问:
Reloading TableViewCell inside CollectionViewCell
I tried viewWillAppear, tableView.reloadData(), and collectionView.reloadData() but the data array never seems to show up

```<code>import UIKit

class yearOne: UICollectionViewController, coursesDelegate {

    let customCellIdentifier = "cellID"
    let customCellIdentifier2 = "cellID2"
    let customCellIdentifier3 = "cellID3"
    let customCellIdentifier4 = "cellID4"

    let quarters = [
        customLabel (title: "Fall Quarter"),
        customLabel (title: "Winter Quarter"),
        customLabel (title: "Spring Quarter"),
        customLabel (title: "Summer Quarter")
    ]

    func sendDataBackFall(data: String) {
        fallQuarterCell.data.append(data)
        //UserDefaults.standard.set(fallQuarterCell.data, forKey: "SavedArray")
    }
    func sendDataBackWinter(data2: String) {
        winterQuarterCell.data.append(data2)
        //UserDefaults.standard.set(winterQuarterCell.data, forKey: "SavedArray")
    }
    func sendDataBackSpring(data3: String) {
        springQuarterCell.data.append(data3)
        //UserDefaults.standard.set(springQuarterCell.data, forKey: "SavedArray")
    }
    func sendDataBackSummer(data4: String) {
        summerQuarterCell.data.append(data4)
        //UserDefaults.standard.set(summerQuarterCell.data, forKey: "SavedArray")
    }

    let vc = fallQuarterCell()

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        print("1")
        print(fallQuarterCell.data)
        vc.tableView.reloadData()
        collectionView.reloadData()
        print("2")
        print(fallQuarterCell.data)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView.dataSource = self
        collectionView.delegate = self

        self.collectionView!.register(fallQuarterCell.self, forCellWithReuseIdentifier: customCellIdentifier)
        self.collectionView!.register(winterQuarterCell.self, forCellWithReuseIdentifier: customCellIdentifier2)
        self.collectionView!.register(springQuarterCell.self, forCellWithReuseIdentifier: customCellIdentifier3)
        self.collectionView!.register(summerQuarterCell.self, forCellWithReuseIdentifier: customCellIdentifier4)

        navigationItem.title = "Year One"
        navigationController?.navigationBar.prefersLargeTitles = true
        collectionView?.backgroundColor = .lightGray
        //navigationItem.prompt = "Click the + button to add courses, Swipe left on a course to delete."

    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return quarters.count
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        if (indexPath.row == 0){
            let cell1 = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier, for: indexPath) as! fallQuarterCell
            cell1.layer.borderColor = UIColor.orange.cgColor
            cell1.layer.borderWidth = 2
            cell1.layer.cornerRadius = 5
            cell1.quarters = self.quarters[0]
            return cell1
        }
        else if (indexPath.row == 1){
            let cell2 = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier2, for: indexPath) as! winterQuarterCell
            cell2.layer.borderColor = UIColor.blue.cgColor
            cell2.layer.borderWidth = 2
            cell2.layer.cornerRadius = 5
            cell2.quarters = self.quarters[1]
            return cell2
        }
        else if (indexPath.row == 2){
            let cell3 = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier3, for: indexPath) as! springQuarterCell
            cell3.layer.borderColor = UIColor.green.cgColor
            cell3.layer.borderWidth = 2
            cell3.layer.cornerRadius = 5
            cell3.quarters = self.quarters[2]
            return cell3
        }
        else if (indexPath.row == 3){
            let cell4 = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier4, for: indexPath) as! summerQuarterCell
            cell4.layer.borderColor = UIColor.red.cgColor
            cell4.layer.borderWidth = 2
            cell4.layer.cornerRadius = 5
            cell4.quarters = self.quarters[3]
            return cell4
        }
        else{
            return UICollectionViewCell()
        }
    }

    @objc func buttonAction(sender: UIButton!) {
        switch sender.tag {
        case 0:
            let destination = SearchPage()
            destination.delegate = self
            destination.tag = sender.tag
            navigationController?.pushViewController(destination, animated: true)
        case 1:
            let destination = SearchPage()
            destination.delegate = self
            destination.tag = sender.tag
            navigationController?.pushViewController(destination, animated: true)
        case 2:
            let destination = SearchPage()
            destination.delegate = self
            destination.tag = sender.tag
            navigationController?.pushViewController(destination, animated: true)
        case 3:
            let destination = SearchPage()
            destination.delegate = self
            destination.tag = sender.tag
            navigationController?.pushViewController(destination, animated: true)
        default:
            let destination = SearchPage()
            destination.delegate = self
            destination.tag = sender.tag
            navigationController?.pushViewController(destination, animated: true)
        }

    }
}

extension yearOne : UICollectionViewDelegateFlowLayout{

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = (view.frame.width - 30)
        return CGSize(width: width, height: 200)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 8
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        UIEdgeInsets(top: 30, left: 10, bottom: 30, right: 10)
    }

}

class fallQuarterCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource {

//    var data = UserDefaults.standard.object(forKey: "SavedArray") as? [String] ?? [String](){
//        didSet{
//            self.tableView.reloadData()
//        }
//    }

    static var data: [String] = []

//    func load(){
//        if let loadeddata: [String] = UserDefaults.standard.object(forKey: "SavedArray") as? [String] {
//            data = loadeddata
//            tableView.reloadData()
//        }
//    }

    let cellId = "coursesName"

    let tableView:UITableView = {
        let tableView = UITableView()
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.backgroundColor = UIColor.white
        return tableView
    }()

    override init(frame: CGRect){
        super.init(frame: frame)
        addSubview(tableView)
        setupView()
    }

    func setupView(){

        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
        tableView.delegate = self
        tableView.dataSource = self

        self.backgroundColor = UIColor.white
        contentView.addSubview(quarterLabel)
        contentView.addSubview(addButton)

        quarterLabel.translatesAutoresizingMaskIntoConstraints = false
        quarterLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10).isActive = true
        quarterLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 10).isActive = true

        addButton.translatesAutoresizingMaskIntoConstraints = false
        addButton.topAnchor.constraint(equalTo: quarterLabel.topAnchor, constant: -5).isActive = true
        addButton.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -10).isActive = true
        addButton.heightAnchor.constraint(equalToConstant: 25).isActive = true
        addButton.widthAnchor.constraint(equalToConstant: 25).isActive = true

        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 35).isActive = true
        tableView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 5).isActive = true
        tableView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -10).isActive = true
        tableView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -5).isActive = true

    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return fallQuarterCell.data.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
        let stringLabel = fallQuarterCell.data[indexPath.row]
        cell.textLabel?.text = stringLabel
        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 40
    }

    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if (editingStyle == .delete) {
            if (indexPath.row == 0){
                fallQuarterCell.data.remove(at: 0)
                self.tableView.reloadData()
                //UserDefaults.standard.set(fallQuarterCell.data, forKey: "SavedArray")
            }
            else if (indexPath.row == 1){
                fallQuarterCell.data.remove(at: 1)
                self.tableView.reloadData()
                //UserDefaults.standard.set(fallQuarterCell.data, forKey: "SavedArray")
            }
            else if (indexPath.row == 2){
                fallQuarterCell.data.remove(at: 2)
                self.tableView.reloadData()
                //UserDefaults.standard.set(fallQuarterCell.data, forKey: "SavedArray")
            }
            else if (indexPath.row == 3){
                fallQuarterCell.data.remove(at: 3)
                self.tableView.reloadData()
                //UserDefaults.standard.set(fallQuarterCell.data, forKey: "SavedArray")
            }
            else if (indexPath.row == 4){
                fallQuarterCell.data.remove(at: 4)
                self.tableView.reloadData()
                //UserDefaults.standard.set(fallQuarterCell.data, forKey: "SavedArray")
            }
        }
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)

        //add class information???
    }

    var quarters: customLabel? {
        didSet {
            guard let quarters = quarters else {return}
            quarterLabel.text = quarters.title
        }
    }

    let quarterLabel : UILabel = {
        let label = UILabel()//frame: CGRect(x: 15, y: -75, width: 300, height: 50))
        label.translatesAutoresizingMaskIntoConstraints = false
        label.textColor = UIColor.black
        label.font = UIFont.boldSystemFont(ofSize: 16)
        //label.textAlignment = .center
        return label
    }()

    let addButton : UIButton = {
        let button = UIButton()//frame: CGRect(x: 345, y: 10, width: 30, height: 30))
        button.setImage(UIImage(named: "addicon"), for: .normal)
        button.imageEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
        button.tag = 0
        button.addTarget(self, action: #selector(yearOne.buttonAction), for: .touchUpInside)
        return button
    }()

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
</code>```

I also have the

class winterQuarterCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource

class springQuarterCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource

class summerQuarterCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource

similar to that of fallQuarterCell(). I used the print(fallQuarterCell.data) to see whether the delegation works and data string appends, and it does seem to append to the array, just that it won't appear on the fallQuarterCell tableView when backed out from the SearchPage()

Here is the 'SearchPage()where the user clicks on an element from the tableView to append to thefallQuarterCell.datathrough delegation and automatically pop backs toyearOne()`:

```<code>import UIKit

protocol coursesDelegate {
    func sendDataBackFall(data: String)
    func sendDataBackWinter(data2: String)
    func sendDataBackSpring(data3: String)
    func sendDataBackSummer(data4: String)
}

class SearchPage: UITableViewController {

    var delegate: coursesDelegate?

    let cellId = "course"

    var allCourses : NSArray = NSArray()
    var filteredCourses = [String]()
    var resultSearchController = UISearchController()

    var tag: Int?

    @objc func addTapped(sender: UIBarButtonItem!) {
        let addAlert = UIAlertController(title: "Create New Course", message: "Enter a course name", preferredStyle: .alert)

        addAlert.addTextField {(textfield:UITextField) in textfield.placeholder = "Course"}

        addAlert.addAction(UIAlertAction(title: "Create", style: .default, handler: { (action:UIAlertAction) in
            var _customCourse = String()

            if let courseTextField = addAlert.textFields?.first, let customCourse = courseTextField.text{
                _customCourse = customCourse
            }

        }))

        addAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

        self.present(addAlert, animated: true, completion: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let courses : CourseList = CourseList()
        allCourses = courses.coursesList

        navigationItem.title = "Select Courses"
        navigationController?.navigationBar.prefersLargeTitles = true

        let button1 = UIBarButtonItem(title: "Add Course", style: .plain, target: self, action: #selector(addTapped))
        self.navigationItem.rightBarButtonItem = button1

        self.view.backgroundColor = .systemBackground

        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
        tableView.delegate = self
        tableView.dataSource = self

        self.tableView.tableFooterView = UIView()

        resultSearchController = ({
            let controller = UISearchController(searchResultsController: nil)
            controller.searchResultsUpdater = self
            controller.obscuresBackgroundDuringPresentation = false
            controller.searchBar.placeholder = "Search Courses"
            controller.searchBar.sizeToFit()

            tableView.tableHeaderView = controller.searchBar

            return controller
        })()

    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if  (resultSearchController.isActive) {
            return filteredCourses.count
        }
        else{
            return allCourses.count
        }
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)

        if (resultSearchController.isActive) {
            cell.textLabel?.text = filteredCourses[indexPath.row]
            return cell
         }
         else {
            let courses = self.allCourses[indexPath.row]
            cell.textLabel?.text = courses as? String
            return cell
         }
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){

        tableView.deselectRow(at: indexPath, animated: true)

        if (tag == 0){
            if (resultSearchController.isActive){
//                fallQuarterCelll.data.append(filteredCourses[indexPath.row])
//                UserDefaults.standard.set(fallQuarterCelll.data, forKey: "SavedArray")
//                self.navigationController?.popViewController(animated: true)
                let data = filteredCourses[indexPath.row]
                delegate?.sendDataBackFall(data: data)
                self.navigationController?.popViewController(animated: true)

            }
            else{
//                fallQuarterCelll.data.append(allCourses[indexPath.row] as! String)
//                UserDefaults.standard.set(fallQuarterCelll.data, forKey: "SavedArray")
//                self.navigationController?.popViewController(animated: true)
                let data = allCourses[indexPath.row] as! String
                delegate?.sendDataBackFall(data: data)
                self.navigationController?.popViewController(animated: true)

            }
        }
    }

    var isSearchBarEmpty: Bool {
      return resultSearchController.searchBar.text?.isEmpty ?? true
    }
}

extension SearchPage: UISearchResultsUpdating {

  func updateSearchResults(for searchController: UISearchController) {
      filteredCourses.removeAll(keepingCapacity: false)

      let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!)
      let array = (allCourses as NSArray).filtered(using: searchPredicate)
      filteredCourses = array as! [String]

      self.tableView.reloadData()
  }

}
</code>```

Ignore the UsersDefault... I'm trying to make the data appear on the fallQuarterCell tableView first.

答:
All you have to do is create a separate cell class for collection view cell, and create an outlet of your table view into that cell class.

In your cellForItemAt method of the collection view do below code:

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TabelCell", for: indexPath) as! MyTabelCell

cell.MyTableView.reloadData()

}
</code>```

Now you have to reload collection view and it will automatically reload the table view. That's the best and easiest way to approach TableView in CollectionView

Body:
I tried viewWillAppear, tableView.reloadData(), and collectionView.reloadData() but the data array never seems to show up

import UIKit

class yearOne: UICollectionViewController, coursesDelegate {

    let customCellIdentifier = "cellID"
    let customCellIdentifier2 = "cellID2"
    let customCellIdentifier3 = "cellID3"
    let customCellIdentifier4 = "cellID4"

    let quarters = [
        customLabel (title: "Fall Quarter"),
        customLabel (title: "Winter Quarter"),
        customLabel (title: "Spring Quarter"),
        customLabel (title: "Summer Quarter")
    ]

    func sendDataBackFall(data: String) {
        fallQuarterCell.data.append(data)
        //UserDefaults.standard.set(fallQuarterCell.data, forKey: "SavedArray")
    }
    func sendDataBackWinter(data2: String) {
        winterQuarterCell.data.append(data2)
        //UserDefaults.standard.set(winterQuarterCell.data, forKey: "SavedArray")
    }
    func sendDataBackSpring(data3: String) {
        springQuarterCell.data.append(data3)
        //UserDefaults.standard.set(springQuarterCell.data, forKey: "SavedArray")
    }
    func sendDataBackSummer(data4: String) {
        summerQuarterCell.data.append(data4)
        //UserDefaults.standard.set(summerQuarterCell.data, forKey: "SavedArray")
    }

    let vc = fallQuarterCell()

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        print("1")
        print(fallQuarterCell.data)
        vc.tableView.reloadData()
        collectionView.reloadData()
        print("2")
        print(fallQuarterCell.data)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView.dataSource = self
        collectionView.delegate = self

        self.collectionView!.register(fallQuarterCell.self, forCellWithReuseIdentifier: customCellIdentifier)
        self.collectionView!.register(winterQuarterCell.self, forCellWithReuseIdentifier: customCellIdentifier2)
        self.collectionView!.register(springQuarterCell.self, forCellWithReuseIdentifier: customCellIdentifier3)
        self.collectionView!.register(summerQuarterCell.self, forCellWithReuseIdentifier: customCellIdentifier4)

        navigationItem.title = "Year One"
        navigationController?.navigationBar.prefersLargeTitles = true
        collectionView?.backgroundColor = .lightGray
        //navigationItem.prompt = "Click the + button to add courses, Swipe left on a course to delete."

    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return quarters.count
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        if (indexPath.row == 0){
            let cell1 = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier, for: indexPath) as! fallQuarterCell
            cell1.layer.borderColor = UIColor.orange.cgColor
            cell1.layer.borderWidth = 2
            cell1.layer.cornerRadius = 5
            cell1.quarters = self.quarters[0]
            return cell1
        }
        else if (indexPath.row == 1){
            let cell2 = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier2, for: indexPath) as! winterQuarterCell
            cell2.layer.borderColor = UIColor.blue.cgColor
            cell2.layer.borderWidth = 2
            cell2.layer.cornerRadius = 5
            cell2.quarters = self.quarters[1]
            return cell2
        }
        else if (indexPath.row == 2){
            let cell3 = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier3, for: indexPath) as! springQuarterCell
            cell3.layer.borderColor = UIColor.green.cgColor
            cell3.layer.borderWidth = 2
            cell3.layer.cornerRadius = 5
            cell3.quarters = self.quarters[2]
            return cell3
        }
        else if (indexPath.row == 3){
            let cell4 = collectionView.dequeueReusableCell(withReuseIdentifier: customCellIdentifier4, for: indexPath) as! summerQuarterCell
            cell4.layer.borderColor = UIColor.red.cgColor
            cell4.layer.borderWidth = 2
            cell4.layer.cornerRadius = 5
            cell4.quarters = self.quarters[3]
            return cell4
        }
        else{
            return UICollectionViewCell()
        }
    }

    @objc func buttonAction(sender: UIButton!) {
        switch sender.tag {
        case 0:
            let destination = SearchPage()
            destination.delegate = self
            destination.tag = sender.tag
            navigationController?.pushViewController(destination, animated: true)
        case 1:
            let destination = SearchPage()
            destination.delegate = self
            destination.tag = sender.tag
            navigationController?.pushViewController(destination, animated: true)
        case 2:
            let destination = SearchPage()
            destination.delegate = self
            destination.tag = sender.tag
            navigationController?.pushViewController(destination, animated: true)
        case 3:
            let destination = SearchPage()
            destination.delegate = self
            destination.tag = sender.tag
            navigationController?.pushViewController(destination, animated: true)
        default:
            let destination = SearchPage()
            destination.delegate = self
            destination.tag = sender.tag
            navigationController?.pushViewController(destination, animated: true)
        }

    }
}

extension yearOne : UICollectionViewDelegateFlowLayout{

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = (view.frame.width - 30)
        return CGSize(width: width, height: 200)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 8
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 1
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        UIEdgeInsets(top: 30, left: 10, bottom: 30, right: 10)
    }

}

class fallQuarterCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource {

//    var data = UserDefaults.standard.object(forKey: "SavedArray") as? [String] ?? [String](){
//        didSet{
//            self.tableView.reloadData()
//        }
//    }

    static var data: [String] = []

//    func load(){
//        if let loadeddata: [String] = UserDefaults.standard.object(forKey: "SavedArray") as? [String] {
//            data = loadeddata
//            tableView.reloadData()
//        }
//    }

    let cellId = "coursesName"

    let tableView:UITableView = {
        let tableView = UITableView()
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.backgroundColor = UIColor.white
        return tableView
    }()

    override init(frame: CGRect){
        super.init(frame: frame)
        addSubview(tableView)
        setupView()
    }

    func setupView(){

        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
        tableView.delegate = self
        tableView.dataSource = self

        self.backgroundColor = UIColor.white
        contentView.addSubview(quarterLabel)
        contentView.addSubview(addButton)

        quarterLabel.translatesAutoresizingMaskIntoConstraints = false
        quarterLabel.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10).isActive = true
        quarterLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 10).isActive = true

        addButton.translatesAutoresizingMaskIntoConstraints = false
        addButton.topAnchor.constraint(equalTo: quarterLabel.topAnchor, constant: -5).isActive = true
        addButton.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -10).isActive = true
        addButton.heightAnchor.constraint(equalToConstant: 25).isActive = true
        addButton.widthAnchor.constraint(equalToConstant: 25).isActive = true

        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 35).isActive = true
        tableView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 5).isActive = true
        tableView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -10).isActive = true
        tableView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -5).isActive = true

    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return fallQuarterCell.data.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
        let stringLabel = fallQuarterCell.data[indexPath.row]
        cell.textLabel?.text = stringLabel
        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 40
    }

    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if (editingStyle == .delete) {
            if (indexPath.row == 0){
                fallQuarterCell.data.remove(at: 0)
                self.tableView.reloadData()
                //UserDefaults.standard.set(fallQuarterCell.data, forKey: "SavedArray")
            }
            else if (indexPath.row == 1){
                fallQuarterCell.data.remove(at: 1)
                self.tableView.reloadData()
                //UserDefaults.standard.set(fallQuarterCell.data, forKey: "SavedArray")
            }
            else if (indexPath.row == 2){
                fallQuarterCell.data.remove(at: 2)
                self.tableView.reloadData()
                //UserDefaults.standard.set(fallQuarterCell.data, forKey: "SavedArray")
            }
            else if (indexPath.row == 3){
                fallQuarterCell.data.remove(at: 3)
                self.tableView.reloadData()
                //UserDefaults.standard.set(fallQuarterCell.data, forKey: "SavedArray")
            }
            else if (indexPath.row == 4){
                fallQuarterCell.data.remove(at: 4)
                self.tableView.reloadData()
                //UserDefaults.standard.set(fallQuarterCell.data, forKey: "SavedArray")
            }
        }
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)

        //add class information???
    }

    var quarters: customLabel? {
        didSet {
            guard let quarters = quarters else {return}
            quarterLabel.text = quarters.title
        }
    }

    let quarterLabel : UILabel = {
        let label = UILabel()//frame: CGRect(x: 15, y: -75, width: 300, height: 50))
        label.translatesAutoresizingMaskIntoConstraints = false
        label.textColor = UIColor.black
        label.font = UIFont.boldSystemFont(ofSize: 16)
        //label.textAlignment = .center
        return label
    }()

    let addButton : UIButton = {
        let button = UIButton()//frame: CGRect(x: 345, y: 10, width: 30, height: 30))
        button.setImage(UIImage(named: "addicon"), for: .normal)
        button.imageEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
        button.tag = 0
        button.addTarget(self, action: #selector(yearOne.buttonAction), for: .touchUpInside)
        return button
    }()

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

I also have the

class winterQuarterCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource

class springQuarterCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource

class summerQuarterCell: UICollectionViewCell, UITableViewDelegate, UITableViewDataSource

similar to that of fallQuarterCell(). I used the print(fallQuarterCell.data) to see whether the delegation works and data string appends, and it does seem to append to the array, just that it won't appear on the fallQuarterCell tableView when backed out from the SearchPage()

Here is the 'SearchPage()where the user clicks on an element from the tableView to append to thefallQuarterCell.datathrough delegation and automatically pop backs toyearOne()`:

import UIKit

protocol coursesDelegate {
    func sendDataBackFall(data: String)
    func sendDataBackWinter(data2: String)
    func sendDataBackSpring(data3: String)
    func sendDataBackSummer(data4: String)
}

class SearchPage: UITableViewController {

    var delegate: coursesDelegate?

    let cellId = "course"

    var allCourses : NSArray = NSArray()
    var filteredCourses = [String]()
    var resultSearchController = UISearchController()

    var tag: Int?

    @objc func addTapped(sender: UIBarButtonItem!) {
        let addAlert = UIAlertController(title: "Create New Course", message: "Enter a course name", preferredStyle: .alert)

        addAlert.addTextField {(textfield:UITextField) in textfield.placeholder = "Course"}

        addAlert.addAction(UIAlertAction(title: "Create", style: .default, handler: { (action:UIAlertAction) in
            var _customCourse = String()

            if let courseTextField = addAlert.textFields?.first, let customCourse = courseTextField.text{
                _customCourse = customCourse
            }

        }))

        addAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

        self.present(addAlert, animated: true, completion: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let courses : CourseList = CourseList()
        allCourses = courses.coursesList

        navigationItem.title = "Select Courses"
        navigationController?.navigationBar.prefersLargeTitles = true

        let button1 = UIBarButtonItem(title: "Add Course", style: .plain, target: self, action: #selector(addTapped))
        self.navigationItem.rightBarButtonItem = button1

        self.view.backgroundColor = .systemBackground

        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellId)
        tableView.delegate = self
        tableView.dataSource = self

        self.tableView.tableFooterView = UIView()

        resultSearchController = ({
            let controller = UISearchController(searchResultsController: nil)
            controller.searchResultsUpdater = self
            controller.obscuresBackgroundDuringPresentation = false
            controller.searchBar.placeholder = "Search Courses"
            controller.searchBar.sizeToFit()

            tableView.tableHeaderView = controller.searchBar

            return controller
        })()

    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if  (resultSearchController.isActive) {
            return filteredCourses.count
        }
        else{
            return allCourses.count
        }
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)

        if (resultSearchController.isActive) {
            cell.textLabel?.text = filteredCourses[indexPath.row]
            return cell
         }
         else {
            let courses = self.allCourses[indexPath.row]
            cell.textLabel?.text = courses as? String
            return cell
         }
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){

        tableView.deselectRow(at: indexPath, animated: true)

        if (tag == 0){
            if (resultSearchController.isActive){
//                fallQuarterCelll.data.append(filteredCourses[indexPath.row])
//                UserDefaults.standard.set(fallQuarterCelll.data, forKey: "SavedArray")
//                self.navigationController?.popViewController(animated: true)
                let data = filteredCourses[indexPath.row]
                delegate?.sendDataBackFall(data: data)
                self.navigationController?.popViewController(animated: true)

            }
            else{
//                fallQuarterCelll.data.append(allCourses[indexPath.row] as! String)
//                UserDefaults.standard.set(fallQuarterCelll.data, forKey: "SavedArray")
//                self.navigationController?.popViewController(animated: true)
                let data = allCourses[indexPath.row] as! String
                delegate?.sendDataBackFall(data: data)
                self.navigationController?.popViewController(animated: true)

            }
        }
    }

    var isSearchBarEmpty: Bool {
      return resultSearchController.searchBar.text?.isEmpty ?? true
    }
}

extension SearchPage: UISearchResultsUpdating {

  func updateSearchResults(for searchController: UISearchController) {
      filteredCourses.removeAll(keepingCapacity: false)

      let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!)
      let array = (allCourses as NSArray).filtered(using: searchPredicate)
      filteredCourses = array as! [String]

      self.tableView.reloadData()
  }

}

Ignore the UsersDefault... I'm trying to make the data appear on the fallQuarterCell tableView first.

Body:
All you have to do is create a separate cell class for collection view cell, and create an outlet of your table view into that cell class.

In your cellForItemAt method of the collection view do below code:

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

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TabelCell", for: indexPath) as! MyTabelCell

cell.MyTableView.reloadData()

}

Now you have to reload collection view and it will automatically reload the table view. That's the best and easiest way to approach TableView in CollectionView


来源: stackexchange

问:
JQuery / JavaScript - trigger button click from another button click event
I have this HTML which looks like this:

```<code><input type="submit" name="savebutton" class="first button" />
<input type="submit" name="savebutton" class="second button" />
</code>```

and JS:

```<code>jQuery("input.second").click(function(){
   // trigger second button ?
   return false;
});
</code>```

So how can I trigger the click event from the 2nd button by clicking on the first one?
Note that I don't have any control over the 2nd button, neither on the html or the click event on it...

答:
If it does not work by using the click() method like suggested in the accepted answer, then you can try this:

```<code>//trigger second button
$("#second").mousedown();
$("#second").mouseup();
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have this HTML which looks like this:

<input type="submit" name="savebutton" class="first button" />
<input type="submit" name="savebutton" class="second button" />

and JS:

jQuery("input.second").click(function(){
   // trigger second button ?
   return false;
});

So how can I trigger the click event from the 2nd button by clicking on the first one?
Note that I don't have any control over the 2nd button, neither on the html or the click event on it...

Body:
If it does not work by using the click() method like suggested in the accepted answer, then you can try this:

//trigger second button
$("#second").mousedown();
$("#second").mouseup();

ContentLicense: CC BY-SA 4.0


问:
How to display my background-image in my html/css?
I've seen another topic about my issue, but it doesn't resolve it, I try to put a background image for my portfolio but it doesn't work. I don't understand why, do you have an idea ?

my code:

html:

          Project
          Skills
          Contact

```

```css:

.main{
background-image: url(../img/dev-dots.png);
background-position: center;
background-repeat: no-repeat;
background-size: cover;

}

.navbar{
    height: 10vh;
    background-color: purple;
    position: fixed;
}
```

PS: Sorry for my english, it's not my first language.

答:
you are providing the wrong path. try this

<!DOCTYPE HTML>

          Project
          Skills
          Contact

```

Body:
I've seen another topic about my issue, but it doesn't resolve it, I try to put a background image for my portfolio but it doesn't work. I don't understand why, do you have an idea ?

my code:

html:

          Project
          Skills
          Contact

css:

.main{
background-image: url(../img/dev-dots.png);
background-position: center;
background-repeat: no-repeat;
background-size: cover;

}

.navbar{
    height: 10vh;
    background-color: purple;
    position: fixed;
}

PS: Sorry for my english, it's not my first language.

Body:
you are providing the wrong path. try this

<!DOCTYPE HTML>
<html>
<head>
<style>

.main{
background-image: url(http://www.cagbd.org/assets/upload/logo/1124d2b92e3b8f44b1c8f21cfebc6dae.jpg);
background-position: center;
background-repeat: no-repeat;
background-size: cover;

}

.navbar{
    height: 10vh;
}
</style>
</head>
<body>

 <div class="main">
    <div class="navbar container-fluid d-flex justify-content-center">
        <i class="fab fa-react fa-3x firstIcon mr-4"> <span class="txtIcon"> Project</span></i>
        <i class="fas fa-check-square fa-3x mx-4"> <span class="txtIcon2"> Skills</span></i>
        <i class="fas fa-id-card fa-3x ml-4"> <span class="txtIcon3"> Contact</span></i>
    </div>
</div>

</body>
</html>


问:
Override Navbar in Django base admin page to be same as the base.html
In my django admin pages, I would like to override the navbar (top ribbon) to be the same as the one in my "base.html" template. For different reasons:

Users can navigate through the website even when they are in the admin views.

To keep same style across pages, even in admin pages.

I am using django 2.2.6.

I don't really know how to start and what would be the best approach.

Any advices of how you would do this ?

EDIT1:

I was thinking about creating a base_site.html file within "templates/admin/" folder and just copy paste my base.html.

The problem I am facing is styling. Please see below for more details:

```<code># Content of admin/base_site.html:
{% extends "admin/base_site.html" %}
{% load static %}

{% block extrastyle %}
<!--<link href="{% static 'css/bootstrap.css' %}" rel="stylesheet"/>--> # Uncommenting this line will "fix" style on my navbar but break style of all admin pages ...

<script src="{% static 'js/jquery-1.12.3.min.js' %}"></script>
<script src="{% static 'js/jquery-ui.js' %}"></script>
<script src="{% static 'js/bootstrap.min.js' %}"></script>
{% endblock %}

{% block usertools %}
<div class="dropdown">
    <a id="dLabel" role="button" data-toggle="dropdown" class="btn btn-primary" data-target="#" href="/">
    Dropdown <span class="caret"></span>
    </a>
    <ul class="dropdown-menu multi-level" role="menu" aria-labelledby="dropdownMenu">
        <li><a href="#">Some action</a></li>
        <li><a href="#">Some other action</a></li>
        <li class="divider"></li>
        <li class="dropdown-submenu">
            <a tabindex="-1" href="#">Group</a>
            <ul class="dropdown-menu">
                <li><a tabindex="-1" href="#">Second level</a></li>
            </ul>
        </li>
    </ul>
</div>
{% endblock %}
</code>```

As you may have understood, the navbar in my base.html is using bootstrap which for reason I ignored, when trying to importing boostrap in my admin/base_site.html template is breaking style in general.

Am I missing an important style for admin pages to be working? I was thinking admin page were already using bootstrap.

In that case, how style can be broken just by importing it in base_site.html?

If not, any idea how can I combine bootstrap with the missing css style ?

答:
All admin pages inherit from admin/base_site.html. In order override, you can override this template with your custom code.

Also this template should be loaded before admin app is loaded. Here are a couple of sample app templates that are overriding the base template.

django-admin-env-notice,
 django-admin-ribbon

Body:
In my django admin pages, I would like to override the navbar (top ribbon) to be the same as the one in my "base.html" template. For different reasons:

Users can navigate through the website even when they are in the admin views.

To keep same style across pages, even in admin pages.

I am using django 2.2.6.

I don't really know how to start and what would be the best approach.

Any advices of how you would do this ?

EDIT1:

I was thinking about creating a base_site.html file within "templates/admin/" folder and just copy paste my base.html.

The problem I am facing is styling. Please see below for more details:

# Content of admin/base_site.html:
{% extends "admin/base_site.html" %}
{% load static %}

{% block extrastyle %}
 # Uncommenting this line will "fix" style on my navbar but break style of all admin pages ...

{% endblock %}

{% block usertools %}

    Dropdown

Some action

Some other action

            Group

Second level

{% endblock %}

As you may have understood, the navbar in my base.html is using bootstrap which for reason I ignored, when trying to importing boostrap in my admin/base_site.html template is breaking style in general.

Am I missing an important style for admin pages to be working? I was thinking admin page were already using bootstrap.

In that case, how style can be broken just by importing it in base_site.html?

If not, any idea how can I combine bootstrap with the missing css style ?


问:
Kubelet config yaml is missing when restart work node docker service
When I restart the docker service in work node, the logs of kubelet in master node report a no such file error.</p>

```<code># in work node
# systemctl restart docker service

# in master node
# journalctl -u kubelet
# failed to load Kubelet config file /var/lib/kubelet/config.yaml, error failed to read kubelet config file "/var/lib/kubelet/config.yaml", error: open /var/lib/kubelet/config.yaml: no such file or directory
</code>```

答:
You might have done kubeadm reset which cleans up all files.

Just do kubeadm reset --force to reset the node and then kubeadm init in master node and kubeadm join in woker node thereafter.

Body:
When I restart the docker service in work node, the logs of kubelet in master node report a no such file error.

# in work node
# systemctl restart docker service

# in master node
# journalctl -u kubelet
# failed to load Kubelet config file /var/lib/kubelet/config.yaml, error failed to read kubelet config file "/var/lib/kubelet/config.yaml", error: open /var/lib/kubelet/config.yaml: no such file or directory


问:
Distributing a given amount over a list of negative values from bottom to top in SQL
I have a table of negative values for a given date like this:

```<code>------------------
| date | deficit |    budget: 100
|----------------|
|01.01 |   -5    |
|01.02 |   -7    |
|        .       |
|        .       |
|20.12 |   -8    |
|30.12 |   -6    |
------------------
</code>```

I also have a fixed number, lets just call it budget and say its 100.

Now I want to use my budget to cancel out the negative values, for example I reduce my budget from 100 to 95 and write 0 in the table in the row with date 01.01, instead of 5.

Like this:

```<code>------------------
| date | deficit |    budget: 95
|----------------|
|01.01 |    0    |
|01.02 |   -7    |
|        .       |
|        .       |
|20.12 |   -8    |
|30.12 |   -6    |
------------------
</code>```

I want to do this sequentially from the lowest date to the highest date, and if I run out of budget just leave the negative values at the end that I cannot fill anymore.

In the end, it would look like this, assuming we reached the 20.12 entry with a budget of 6, thus not being able to cancel out the negative value completely and running out of budget

```<code>------------------
| date | deficit |    budget: 0
|----------------|
|01.01 |    0    |
|01.02 |    0    |
|        .       |
|        .       |
|20.12 |   -2    |
|30.12 |   -6    |
------------------
</code>```

How would I do that? I know how I would do this in an imperative language, but how do you ensure in which order it substracts and change the statue of the sum in a mostly declarative language?
I'm using oracle.

EDIT:

Here is what I want to do given in imperative pseudo code:

```<code>*Asuming deficits are already ordered by date
foreach deficit of deficits
  if (budget - deficit) >= 0
    set deficit = 0
    set budget = budget - deficit
  else
    set deficit = budget - deficit
    set budget = 0
  end if
</code>```

So I basically need this but in SQL code.

答:
There are a few ways to approach this, but you can use windowed analytic functions to get a running total of the deficit and how much of the budget has been spent. To get the final number you want you could use something like:

```<code>greatest(deficit,
  sum(deficit) over (order by date_col)
    + least(100, - sum(deficit) over (order by date_col)))
</code>```

or perhaps a bit more clearly:

```<code>case
  when sum(deficit)
    over (order by date_col rows between unbounded preceding and 1 preceding) <= -100
  then
    deficit
  else
    sum(deficit) over (order by date_col)
      + least(100, - sum(deficit) over (order by date_col))
end
</code>```

The sum(deficit) over (order by date_col) gives you the running total, in date order, of the deficits. For the first date that is calculated as -5; for the second as (-5 + -7) = -12; etc.

The least(100, - sum(deficit) over (order by date_col))) gives you budget used up to and including the current date, but capped at 100. For the first date that is least(100, - (-5)) which is 5; for the second it is least(100, - (-5 + -7)) which is 12; by the 20th it is least(100, - (-102)), so you get the lower of 100 and 102 - so capped to 100. (You could do that as greatest(-100, sum(deficit) over (order by date_col))) if you prefer, and then subtract that in the last step instead.)

When that is added to the running total of the deficit, the first few rows cancel out and you get zero. For the 20th, the deficit total is 102 and the capped value is 100, so you end up with -2. For the 30th though, that would give you 100 - 108, so -8 instead of the -6 you actually want. That's where the greatest(deficit, ...) comes in. Up to the 20th that doesn't change the answer; greatest(-8, 100 - 102) is still -2, because -2 > -8. For the 30th you have greatest(-6, 100 - 108) is -6, because -6 > -8.

Demo with some sample data and showing some of the working:

```<code>-- sample data
with your_table (date_col, deficit) as (
            select date '2020-01-01', -5 from dual
  union all select date '2020-01-02', -7 from dual
  union all select date '2020-01-03', -50 from dual
  union all select date '2020-01-04', -32 from dual
  union all select date '2020-01-20', -8 from dual
  union all select date '2020-01-30', -6 from dual
)
-- actual query
select date_col, deficit,
  sum(deficit) over (order by date_col) as sum_deficit,
  least(100, - sum(deficit) over (order by date_col)) as budget_used,
  greatest(0, 100 + sum(deficit) over (order by date_col)) as budget_left_1,
  100 - least(100, - sum(deficit) over (order by date_col)) as budget_left_2,
  greatest(deficit,
    sum(deficit) over (order by date_col)
      + least(100, - sum(deficit) over (order by date_col))) as new_deficit_1,
  case
    when sum(deficit)
      over (order by date_col rows between unbounded preceding and 1 preceding) <= -100
    then
      deficit
    else
      sum(deficit) over (order by date_col)
        + least(100, - sum(deficit) over (order by date_col))
    end as new_deficit_2
from your_table
order by date_col;
</code>```

which produces:

```<code>DATE_COL      DEFICIT SUM_DEFICIT BUDGET_USED BUDGET_LEFT_1 BUDGET_LEFT_2 NEW_DEFICIT_1 NEW_DEFICIT_2
---------- ---------- ----------- ----------- ------------- ------------- ------------- -------------
2020-01-01         -5          -5           5            95            95             0             0
2020-01-02         -7         -12          12            88            88             0             0
2020-01-03        -50         -62          62            38            38             0             0
2020-01-04        -32         -94          94             6             6             0             0
2020-01-20         -8        -102         100             0             0            -2            -2
2020-01-30         -6        -108         100             0             0            -6            -6
</code>```

Body:
I have a table of negative values for a given date like this:

------------------
| date | deficit |    budget: 100
|----------------|
|01.01 |   -5    |
|01.02 |   -7    |
|        .       |
|        .       |
|20.12 |   -8    |
|30.12 |   -6    |
------------------

I also have a fixed number, lets just call it budget and say its 100.

Now I want to use my budget to cancel out the negative values, for example I reduce my budget from 100 to 95 and write 0 in the table in the row with date 01.01, instead of 5.

Like this:

------------------
| date | deficit |    budget: 95
|----------------|
|01.01 |    0    |
|01.02 |   -7    |
|        .       |
|        .       |
|20.12 |   -8    |
|30.12 |   -6    |
------------------

I want to do this sequentially from the lowest date to the highest date, and if I run out of budget just leave the negative values at the end that I cannot fill anymore.

In the end, it would look like this, assuming we reached the 20.12 entry with a budget of 6, thus not being able to cancel out the negative value completely and running out of budget

------------------
| date | deficit |    budget: 0
|----------------|
|01.01 |    0    |
|01.02 |    0    |
|        .       |
|        .       |
|20.12 |   -2    |
|30.12 |   -6    |
------------------

How would I do that? I know how I would do this in an imperative language, but how do you ensure in which order it substracts and change the statue of the sum in a mostly declarative language?
I'm using oracle.

EDIT:

Here is what I want to do given in imperative pseudo code:

*Asuming deficits are already ordered by date
foreach deficit of deficits
  if (budget - deficit) >= 0
    set deficit = 0
    set budget = budget - deficit
  else
    set deficit = budget - deficit
    set budget = 0
  end if

So I basically need this but in SQL code.

Body:
There are a few ways to approach this, but you can use windowed analytic functions to get a running total of the deficit and how much of the budget has been spent. To get the final number you want you could use something like:

greatest(deficit,
  sum(deficit) over (order by date_col)
    + least(100, - sum(deficit) over (order by date_col)))

or perhaps a bit more clearly:

case
  when sum(deficit)
    over (order by date_col rows between unbounded preceding and 1 preceding) <= -100
  then
    deficit
  else
    sum(deficit) over (order by date_col)
      + least(100, - sum(deficit) over (order by date_col))
end

The sum(deficit) over (order by date_col) gives you the running total, in date order, of the deficits. For the first date that is calculated as -5; for the second as (-5 + -7) = -12; etc.

The least(100, - sum(deficit) over (order by date_col))) gives you budget used up to and including the current date, but capped at 100. For the first date that is least(100, - (-5)) which is 5; for the second it is least(100, - (-5 + -7)) which is 12; by the 20th it is least(100, - (-102)), so you get the lower of 100 and 102 - so capped to 100. (You could do that as greatest(-100, sum(deficit) over (order by date_col))) if you prefer, and then subtract that in the last step instead.)

When that is added to the running total of the deficit, the first few rows cancel out and you get zero. For the 20th, the deficit total is 102 and the capped value is 100, so you end up with -2. For the 30th though, that would give you 100 - 108, so -8 instead of the -6 you actually want. That's where the greatest(deficit, ...) comes in. Up to the 20th that doesn't change the answer; greatest(-8, 100 - 102) is still -2, because -2 > -8. For the 30th you have greatest(-6, 100 - 108) is -6, because -6 > -8.

Demo with some sample data and showing some of the working:

-- sample data
with your_table (date_col, deficit) as (
            select date '2020-01-01', -5 from dual
  union all select date '2020-01-02', -7 from dual
  union all select date '2020-01-03', -50 from dual
  union all select date '2020-01-04', -32 from dual
  union all select date '2020-01-20', -8 from dual
  union all select date '2020-01-30', -6 from dual
)
-- actual query
select date_col, deficit,
  sum(deficit) over (order by date_col) as sum_deficit,
  least(100, - sum(deficit) over (order by date_col)) as budget_used,
  greatest(0, 100 + sum(deficit) over (order by date_col)) as budget_left_1,
  100 - least(100, - sum(deficit) over (order by date_col)) as budget_left_2,
  greatest(deficit,
    sum(deficit) over (order by date_col)
      + least(100, - sum(deficit) over (order by date_col))) as new_deficit_1,
  case
    when sum(deficit)
      over (order by date_col rows between unbounded preceding and 1 preceding) <= -100
    then
      deficit
    else
      sum(deficit) over (order by date_col)
        + least(100, - sum(deficit) over (order by date_col))
    end as new_deficit_2
from your_table
order by date_col;

which produces:

DATE_COL      DEFICIT SUM_DEFICIT BUDGET_USED BUDGET_LEFT_1 BUDGET_LEFT_2 NEW_DEFICIT_1 NEW_DEFICIT_2
---------- ---------- ----------- ----------- ------------- ------------- ------------- -------------
2020-01-01         -5          -5           5            95            95             0             0
2020-01-02         -7         -12          12            88            88             0             0
2020-01-03        -50         -62          62            38            38             0             0
2020-01-04        -32         -94          94             6             6             0             0
2020-01-20         -8        -102         100             0             0            -2            -2
2020-01-30         -6        -108         100             0             0            -6            -6


问:
Can we migrate from Kafka(1.4.0) to RAFT(1.4.3) if channel capabilities are disabled?
While migrating from kafka(Fabric 1.4.0) to RAFT(fabric 1.4.3), in first step I am changing the state of network form NORMAL to MAINTENANCE, after signing the block, when I send to the orderer, getting the following error.

Error: got unexpected status: BAD_REQUEST -- config update for
  existing channel did not pass maintenance checks: config transaction
  inspection failed: next config attempted to change ConsensusType.State
  to STATE_MAINTENANCE, but the capability is disabled

Can we enable channel capabilities for the network with version (1.4.0)?

答: As the latest HLF documentation suggests that Capabilities Requirements need to be set for Channel and Application, these need to be set to the current HLF version which is being migrated. For e.g., if the current Fabric version is 1.4.2, the requirement parameters need to be set as V1_4_2: true. See this link for additional clarification.


问:
Problem generating manifest. Could not load assembly Microsoft.Windows.SDK.Contracts when installing nuget Microsoft.Toolkit.Forms.UI.Controls.Webview
I'm getting the following errors after installing the nuget package Microsoft.Toolkit.Forms.UI.Controls.Webview:

Severity Code    Description Project File    Line    Suppression State
  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Media.MediaControlContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.    OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.ApplicationModel.Activation.ActivationCameraSettingsContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.  OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Perception.Automation.Core.PerceptionAutomationCoreContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.   OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.ApplicationModel.Preview.Notes.PreviewNotesContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.   OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Web.Http.Diagnostics.HttpDiagnosticsContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.  OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Devices.DevicesLowLevelContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.   OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Devices.Scanners.ScannerDeviceContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.    OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.UI.Xaml.Hosting.HostingContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.   OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Media.AppRecording.AppRecordingContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.   OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Management.Deployment.Preview.DeploymentPreviewContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.   OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Devices.Printers.Extensions.ExtensionsContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.    OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Gaming.XboxLive.StorageApiContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.    OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Networking.NetworkOperators.NetworkOperatorsFdnContract.WinMD' or one of its dependencies. An attempt was made to load a program with an incorrect format.   OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Gaming.UI.GamingUIProviderContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.    OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Graphics.Printing3D.Printing3DContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.    OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.ApplicationModel.StartupTaskContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.  OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.UI.Core.AnimationMetrics.AnimationMetricsContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format. OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.System.SystemManagementContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.   OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Services.Maps.LocalSearchContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format. OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.ApplicationModel.Activation.WebUISearchActivatedEventsContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.    OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.UI.ViewManagement.ViewManagementViewScalingContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.   OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Networking.Connectivity.WwanContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.  OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Media.AppBroadcasting.AppBroadcastingContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format. OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Globalization.GlobalizationJapanesePhoneticAnalyzerContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.   OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Services.Maps.GuidanceContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.    OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Security.ExchangeActiveSyncProvisioning.EasContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.   OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.System.Profile.SystemManufacturers.SystemManufacturersContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.    OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.UI.WebUI.Core.WebUICommandBarContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format. OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Media.Capture.CameraCaptureUIContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format. OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Phone.StartScreen.DualSimTileContract.WinMD' or one of its dependencies. An attempt was made to load a program with an incorrect format. OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Media.Devices.CallControlContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format. OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Phone.PhoneContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.   OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.ApplicationModel.Calls.LockScreenCallContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format. OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Gaming.Preview.GamesEnumerationContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.   OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.System.UserProfile.UserProfileLockScreenContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.  OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.AI.MachineLearning.Preview.MachineLearningPreviewContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format. OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.ApplicationModel.Calls.CallsVoipContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.  OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.ApplicationModel.Calls.CallsPhoneContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format. OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Storage.Provider.CloudFilesContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.   OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.ApplicationModel.CommunicationBlocking.CommunicationBlockingContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.  OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Media.Capture.AppCaptureMetadataContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.  OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Foundation.UniversalApiContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.   OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.UI.Shell.SecurityAppManagerContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.   OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.ApplicationModel.Wallet.WalletContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.    OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Devices.SmartCards.SmartCardBackgroundTriggerContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format. OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Gaming.UI.GameChatOverlayContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format. OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Media.Capture.GameBarContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format. OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.AI.MachineLearning.MachineLearningContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.    OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.System.Profile.ProfileHardwareTokenContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.   OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Devices.Sms.LegacySmsApiContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.  OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.ApplicationModel.Preview.InkWorkspace.PreviewInkWorkspaceContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format. OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Networking.XboxLive.XboxLiveSecureSocketsContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format. OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Devices.Custom.CustomDeviceContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.   OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.UI.Core.CoreWindowDialogsContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format. OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.UI.Xaml.Core.Direct.XamlDirectContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.    OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.System.Profile.ProfileRetailInfoContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.  OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Embedded.DeviceLockdown.DeviceLockdownContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.    OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.System.UserProfile.UserProfileContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.    OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Media.Capture.AppBroadcastContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.    OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.UI.ApplicationSettings.ApplicationsSettingsContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.   OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Devices.SmartCards.SmartCardEmulatorContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.  OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.ApplicationModel.FullTrustAppContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format. OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.ApplicationModel.Search.Core.SearchCoreContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.   OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.WinMD' or one of its dependencies. An attempt was made to load a program with an incorrect format.   OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.System.Profile.ProfileSharedModeContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.  OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.ApplicationModel.Background.BackgroundAlarmApplicationContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.    OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.ApplicationModel.Search.SearchContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.    OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Networking.NetworkOperators.LegacyNetworkOperatorsContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.    OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Gaming.Input.GamingInputPreviewContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.   OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Media.Protection.ProtectionRenewalContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.    OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Security.EnterpriseData.EnterpriseDataContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.    OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.ApplicationModel.Calls.Background.CallsBackgroundContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format. OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Networking.Sockets.ControlChannelTriggerContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.  OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.ApplicationModel.Activation.ActivatedEventsContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.   OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.ApplicationModel.SocialInfo.SocialInfoContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.    OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Management.Workplace.WorkplaceSettingsContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.    OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.ApplicationModel.Resources.Management.ResourceIndexerContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format. OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Devices.Portable.PortableDeviceContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.   OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Media.Playlists.PlaylistsContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format. OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Media.Capture.AppCaptureContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.  OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.ApplicationModel.Activation.ContactActivatedEventsContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.    OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Services.TargetedContent.TargetedContentContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.  OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Services.Store.StoreContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format.  OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Devices.Printers.PrintersContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format. OutlookAddIn

  Error       Problem generating manifest. Could not load file or assembly 'C:\Users\Vladimir.nuget\packages\microsoft.windows.sdk.contracts\10.0.18362.2005\ref\netstandard2.0\Windows.Foundation.FoundationContract.winmd' or one of its dependencies. An attempt was made to load a program with an incorrect format. OutlookAddIn

Here's what I have done:

Switch to PackageReference as default. Tools -> Options -> Nuget Package Manager -> General -> Default to PackageReference.

Migrated nuget packages to PackageReference. Right-click reference and selected migrate to packagereference.

Installed nuget for Microsoft Microsoft.Toolkit.Forms.UI.Controls.Webview. I was initially getting the error regarding PackageReference but the previous steps fixed it.

I'm now getting the errors above, and they're all related to the Contracts nuget. I've installed and uninstalled this nuget with no results.

答:
I'm now getting the errors above, and they're all related to the
  Contracts nuget. I've installed and uninstalled this nuget with no
  results.

From your description, I created a wpf framework 4.7.2 project which references microsoft.windows.sdk.contracts with packages.config format in VS2019. After that, right-click the packages.config,migrate to packagereference,install Microsoft.Toolkit.Forms.UI.Controls.Webview without any errors. Quite strange. SO l sugget you could follow these steps to roubleshoot your issue:

1) perhaps you're having a 32-bit / 64-bit conflict. For an example, a 32bit project references a x64 dll. Please right-click on your project-->Build-->set Platform target to Any CPU. Also, uncheck Prefer 32-bit.

2) add these codes in xxxx.csproj file

```<code><PropertyGroup>
  <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
  <GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
</PropertyGroup>
</code>```

3) set Platform target to Any CPU then click Tools-->Nuget Package Manager--> Package Manager Console-->input update-Package -reinstall

Body:
I'm now getting the errors above, and they're all related to the
  Contracts nuget. I've installed and uninstalled this nuget with no
  results.

From your description, I created a wpf framework 4.7.2 project which references microsoft.windows.sdk.contracts with packages.config format in VS2019. After that, right-click the packages.config,migrate to packagereference,install Microsoft.Toolkit.Forms.UI.Controls.Webview without any errors. Quite strange. SO l sugget you could follow these steps to roubleshoot your issue:

1) perhaps you're having a 32-bit / 64-bit conflict. For an example, a 32bit project references a x64 dll. Please right-click on your project-->Build-->set Platform target to Any CPU. Also, uncheck Prefer 32-bit.

2) add these codes in xxxx.csproj file

<PropertyGroup>
  <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
  <GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
</PropertyGroup>

3) set Platform target to Any CPU then click Tools-->Nuget Package Manager--> Package Manager Console-->input update-Package -reinstall


问:
Collections.sort() Comparison method violates its general contract
I am trying to sort arraylist based on comparing two strings using comparator ,but i end up with Comparison method violates its general contract error. How do i handle if null comparison occurs in the string.

Code

Collections.sort(keyList, new DIMsComparator<DIM>(sortField));

public static class DIMsComparator<T> implements Comparator<T> {
    String sortField = "";

    public DIMsComparator(String sortField) {
        this.sortField = sortField;
    }

    public int compare(T obj1, T obj2) {
        if (!(obj1 instanceof DIM) || !(obj2 instanceof DIM))
            return obj1 instanceof DIM ? -1 : obj2 instanceof DIM ? 1 : 0;
        DIM dim1 = (DIM) obj1;
        DIM dim2 = (DIM) obj2;
        // Changes for Grouping enhancement starts
        /*
         * if(dim1.getGroupName() != "" || dim2.getGroupName() != "") return -1;
         */
        // Changes for Grouping enhancement ends
        if (dim1.isTextLine())
            return 1;
        if (dim2.isTextLine())
            return -1;
        String[] mySortFields = Util.split(this.sortField, ",");
        for (int i = 0; i < mySortFields.length; i++) {
            if (mySortFields[i].equals(""))
                break;
            int value = compare(dim1, dim2, mySortFields[i]);
            if (value == 0)
                continue;
            else
                return value;
        }

        return dim1.dimSeqNo > dim2.dimSeqNo ? 1 : dim1.dimSeqNo < dim2.dimSeqNo ? -1 : 0;
    }
```

<p>Error</p>

```[err] java.lang.IllegalArgumentException: Comparison method violates its general contract!
[err]   at java.util.TimSort.mergeLo(TimSort.java:788)
[err]   at java.util.TimSort.mergeAt(TimSort.java:525)
[err]   at java.util.TimSort.mergeCollapse(TimSort.java:452)
[err]   at java.util.TimSort.sort(TimSort.java:256)
[err]   at java.util.Arrays.sort(Arrays.java:1856)
[err]   at java.util.ArrayList.sort(ArrayList.java:1471)
[err]   at java.util.Collections.sort(Collections.java:186)
```

答:
As explained in https://stackoverflow.com/a/11441813/4090157 the exception message means, that your comparison does not follow the contract for every compare(..) method, which is:

The implementor must ensure that sgn(compare(x, y)) == -sgn(compare(y, x)) for all x and y. (This implies that compare(x, y) must throw an exception if and only if compare(y, x) throws an exception.)

The implementor must also ensure that the relation is transitive: ((compare(x, y)>0) && (compare(y, z)>0)) implies compare(x, z)>0.

Finally, the implementor must ensure that compare(x, y)==0 implies that sgn(compare(x, z))==sgn(compare(y, z)) for all z.

One error in your code is, that you only consider the first dim if it is a textline:

```<code>if (dim1.isTextLine())
    return 1;
if (dim2.isTextLine())
    return -1;
</code>```

So if both dim1 and dim2 are textlines both comparisons compare(dim1,dim2) and compare(dim2,dim1) will return 1, which violates the contract requirement 1.

And there may also be more inconsistancy in compare(dim1, dim2, mySortFields[i]) which is impossible to tell, since you did not add source code for this function.

Body:
I am trying to sort arraylist based on comparing two strings using comparator ,but i end up with Comparison method violates its general contract error. How do i handle if null comparison occurs in the string.

Code

Collections.sort(keyList, new DIMsComparator<DIM>(sortField));

public static class DIMsComparator<T> implements Comparator<T> {
    String sortField = "";

    public DIMsComparator(String sortField) {
        this.sortField = sortField;
    }

    public int compare(T obj1, T obj2) {
        if (!(obj1 instanceof DIM) || !(obj2 instanceof DIM))
            return obj1 instanceof DIM ? -1 : obj2 instanceof DIM ? 1 : 0;
        DIM dim1 = (DIM) obj1;
        DIM dim2 = (DIM) obj2;
        // Changes for Grouping enhancement starts
        /*
         * if(dim1.getGroupName() != "" || dim2.getGroupName() != "") return -1;
         */
        // Changes for Grouping enhancement ends
        if (dim1.isTextLine())
            return 1;
        if (dim2.isTextLine())
            return -1;
        String[] mySortFields = Util.split(this.sortField, ",");
        for (int i = 0; i < mySortFields.length; i++) {
            if (mySortFields[i].equals(""))
                break;
            int value = compare(dim1, dim2, mySortFields[i]);
            if (value == 0)
                continue;
            else
                return value;
        }

        return dim1.dimSeqNo > dim2.dimSeqNo ? 1 : dim1.dimSeqNo < dim2.dimSeqNo ? -1 : 0;
    }

Error

[err] java.lang.IllegalArgumentException: Comparison method violates its general contract!
[err]   at java.util.TimSort.mergeLo(TimSort.java:788)
[err]   at java.util.TimSort.mergeAt(TimSort.java:525)
[err]   at java.util.TimSort.mergeCollapse(TimSort.java:452)
[err]   at java.util.TimSort.sort(TimSort.java:256)
[err]   at java.util.Arrays.sort(Arrays.java:1856)
[err]   at java.util.ArrayList.sort(ArrayList.java:1471)
[err]   at java.util.Collections.sort(Collections.java:186)

Body:
As explained in https://stackoverflow.com/a/11441813/4090157 the exception message means, that your comparison does not follow the contract for every compare(..) method, which is:

The implementor must ensure that sgn(compare(x, y)) == -sgn(compare(y, x)) for all x and y. (This implies that compare(x, y) must throw an exception if and only if compare(y, x) throws an exception.)

The implementor must also ensure that the relation is transitive: ((compare(x, y)>0) && (compare(y, z)>0)) implies compare(x, z)>0.

Finally, the implementor must ensure that compare(x, y)==0 implies that sgn(compare(x, z))==sgn(compare(y, z)) for all z.

One error in your code is, that you only consider the first dim if it is a textline:

if (dim1.isTextLine())
    return 1;
if (dim2.isTextLine())
    return -1;

So if both dim1 and dim2 are textlines both comparisons compare(dim1,dim2) and compare(dim2,dim1) will return 1, which violates the contract requirement 1.

And there may also be more inconsistancy in compare(dim1, dim2, mySortFields[i]) which is impossible to tell, since you did not add source code for this function.


问:
Forcing action right before application termination
I have 2 libraries.

The first one downloads some web pages and stores them in more "parsable" way to some files on disc.

The other relies on the files and therefore it needs some sort of verification that all the files were downloaded and processed correctly.

I couldn't figure out any other solution than the first library creating something like setup.txt where it would append messages such as $"Exception {e.GetType()} - {pathToDirectoryWithCorruptedFiles}" or $"Success - {pathToDirectoryWithCorrectFiles}".

I don't think this is the correct way, because after exceptions like StackOverFlowException or OutOfMemoryException and after termination with Ctrl + C the program is terminated and so there is no time to do something.

Is there any way of writing something or storing some information after these exceptions of after Ctrl + C ? Thank you for your answers.

答:
If I understand correctly - one application downloads the file, and the second processes it. You need to notify the second application that the file download was completed successfully. Correct me if I'm wrong. I think it is better to use a message broker to send a message from the first application to the secondю This message will notify the second one that the work is completed without error and the second application can start working. Rabbitmq or Kafka should do the trick.
Or if there are exactly libraries - you can use events to notify the second library that file was downloaded successfully.</p>