问:
How can I access an array outside of a closure?
I am a beginning developer using Cloud Firestore for data in my iOS app and want to read the data and store it in arrays. I declared the arrays outside of the function to read the data, but I cannot access the arrays inside of the function without using "self". However, then the data is not stored in the arrays. I was wondering how to store the values inside arrays while also being able to access them outside the function. I know this is probably a very simple problem, but I would greatly appreciate if anyone could help me. This is the code. </p>

```<code>struct PlasticCellData {
    let image: UIImage?
    let message: String?
}
struct PlasticAlphaHeader {
    let label: String?
}

class PlasticMaterial: UITableViewController {

    var rowHeight: CGFloat = 50
    var headerheight: CGFloat = 100
    var ref: DatabaseReference?
    var databaseHandle: DatabaseHandle?

    var alphaHeaderArray = [PlasticAlphaHeader]()
    var aData = [PlasticCellData]()
    var bData = [PlasticCellData]()
    var cData = [PlasticCellData]()
    var dData = [PlasticCellData]()
    var eData = [PlasticCellData]()
    var fData = [PlasticCellData]()
    var gData = [PlasticCellData]()
    var hData = [PlasticCellData]()
    var iData = [PlasticCellData]()
    var jData = [PlasticCellData]()
    var kData = [PlasticCellData]()
    var lData = [PlasticCellData]()
    var mData = [PlasticCellData]()
    var nData = [PlasticCellData]()
    var oData = [PlasticCellData]()
    var pData = [PlasticCellData]()
    var qData = [PlasticCellData]()
    var rData = [PlasticCellData]()
    var sData = [PlasticCellData]()
    var tData = [PlasticCellData]()
    var uData = [PlasticCellData]()
    var vData = [PlasticCellData]()
    var wData = [PlasticCellData]()
    var xData = [PlasticCellData]()
    var yData = [PlasticCellData]()
    var zData = [PlasticCellData]()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        setupNavBar()
        let db = Firestore.firestore()

        alphaHeaderArray =
            [PlasticAlphaHeader.init(label: "A"), PlasticAlphaHeader.init(label: "B"),
            PlasticAlphaHeader.init(label: "C"), PlasticAlphaHeader.init(label: "D"),
            PlasticAlphaHeader.init(label: "E"), PlasticAlphaHeader.init(label: "F"),
            PlasticAlphaHeader.init(label: "G"), PlasticAlphaHeader.init(label: "H"),
            PlasticAlphaHeader.init(label: "I"), PlasticAlphaHeader.init(label: "J"),
            PlasticAlphaHeader.init(label: "K"), PlasticAlphaHeader.init(label: "L"),
            PlasticAlphaHeader.init(label: "M"), PlasticAlphaHeader.init(label: "N"),
            PlasticAlphaHeader.init(label: "O"), PlasticAlphaHeader.init(label: "P"),
            PlasticAlphaHeader.init(label: "Q"), PlasticAlphaHeader.init(label: "R"),
            PlasticAlphaHeader.init(label: "S"), PlasticAlphaHeader.init(label: "T"),
            PlasticAlphaHeader.init(label: "U"), PlasticAlphaHeader.init(label: "V"),
            PlasticAlphaHeader.init(label: "W"), PlasticAlphaHeader.init(label: "X"),
            PlasticAlphaHeader.init(label: "Y"), PlasticAlphaHeader.init(label: "Z")]

        db.collection("plastic").getDocuments { (snapshot, error) in
            if let error = error {

            }
            else {
                for document in snapshot!.documents {
                    let data = document.data()
                    let name = data["name"] as? String ?? ""
                    let firstLetter = name.prefix(1)
                    if firstLetter == "A" {
                        self.aData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "B" {
                        self.bData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "C" {
                        self.cData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "D" {
                        self.dData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "E" {
                        self.eData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "F" {
                        self.fData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "G" {
                        self.gData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "H" {
                        self.hData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "I" {
                        self.iData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "J" {
                        self.jData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "K" {
                        self.kData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "L" {
                        self.lData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "M" {
                        self.mData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "N" {
                        self.nData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "O" {
                        self.oData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "P" {
                        self.pData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "Q" {
                        self.qData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "R" {
                        self.rData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "S" {
                        self.sData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "T" {
                        self.tData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "U" {
                        self.uData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "V" {
                        self.vData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "W" {
                        self.wData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "X" {
                        self.xData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "Y" {
                        self.yData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "Z" {
                        self.zData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                }
            }
        }

        self.tableView.register(ItemCustomCell.self, forCellReuseIdentifier: "custom")
    }

func setupNavBar() {
        navigationItem.title = "Select Item"
        navigationController?.navigationBar.prefersLargeTitles = true
    }

    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let alphaHeader = Bundle.main.loadNibNamed("AlphaHeaderView", owner: self, options: nil)?.first as! AlphaHeaderView

        alphaHeader.headerLabel.text = alphaHeaderArray[section].label
        return alphaHeader
    }
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return headerheight
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCell(withIdentifier: "custom") as! ItemCustomCell
        cell.itemImage = aData[indexPath.row].image // Fatal error: Index out of range
        cell.message = aData[indexPath.row].message
        cell.itemImage = bData[indexPath.row].image
        cell.message = bData[indexPath.row].message
        cell.itemImage = cData[indexPath.row].image
        cell.message = cData[indexPath.row].message
        cell.itemImage = dData[indexPath.row].image
        cell.message = dData[indexPath.row].message
        cell.itemImage = eData[indexPath.row].image
        cell.message = eData[indexPath.row].message
        cell.itemImage = fData[indexPath.row].image
        cell.message = fData[indexPath.row].message
        cell.itemImage = hData[indexPath.row].image
        cell.message = hData[indexPath.row].message
        cell.itemImage = iData[indexPath.row].image
        cell.message = iData[indexPath.row].message
        cell.itemImage = jData[indexPath.row].image
        cell.message = jData[indexPath.row].message
        cell.itemImage = kData[indexPath.row].image
        cell.message = kData[indexPath.row].message
        cell.itemImage = lData[indexPath.row].image
        cell.message = lData[indexPath.row].message
        cell.itemImage = mData[indexPath.row].image
        cell.message = mData[indexPath.row].message
        cell.itemImage = nData[indexPath.row].image
        cell.message = nData[indexPath.row].message
        cell.itemImage = oData[indexPath.row].image
        cell.message = oData[indexPath.row].message
        cell.itemImage = pData[indexPath.row].image
        cell.message = pData[indexPath.row].message
        cell.itemImage = qData[indexPath.row].image
        cell.message = qData[indexPath.row].message
        cell.itemImage = rData[indexPath.row].image
        cell.message = rData[indexPath.row].message
        cell.itemImage = sData[indexPath.row].image
        cell.message = sData[indexPath.row].message
        cell.itemImage = tData[indexPath.row].image
        cell.message = tData[indexPath.row].message
        cell.itemImage = uData[indexPath.row].image
        cell.message = uData[indexPath.row].message
        cell.itemImage = vData[indexPath.row].image
        cell.message = vData[indexPath.row].message
        cell.itemImage = wData[indexPath.row].image
        cell.message = wData[indexPath.row].message
        cell.itemImage = xData[indexPath.row].image
        cell.message = xData[indexPath.row].message
        cell.itemImage = yData[indexPath.row].image
        cell.message = yData[indexPath.row].message
        cell.itemImage = zData[indexPath.row].image
        cell.message = zData[indexPath.row].message
        return cell
    }
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return rowHeight
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 26
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return aData.count
        }
        if section == 1 {
            return bData.count
        }
        if section == 2 {
            return cData.count
        }
        if section == 3 {
            return dData.count
        }
        if section == 4 {
            return eData.count
        }
        if section == 5 {
            return fData.count
        }
        if section == 6 {
            return gData.count
        }
        if section == 7 {
            return hData.count
        }
        if section == 8 {
            return iData.count
        }
        if section == 9 {
            return jData.count
        }
        if section == 10 {
            return kData.count
        }
        if section == 11 {
            return lData.count
        }
        if section == 12 {
            return mData.count
        }
        if section == 13 {
            return nData.count
        }
        if section == 14 {
            return oData.count
        }
        if section == 15 {
            return pData.count
        }
        if section == 16 {
            return qData.count
        }
        if section == 17 {
            return rData.count
        }
        if section == 18{
            return sData.count
        }
        if section == 19 {
            return tData.count
        }
        if section == 20 {
            return uData.count
        }
        if section == 21 {
            return vData.count
        }
        if section == 22 {
            return wData.count
        }
        if section == 23 {
            return xData.count
        }
        if section == 24 {
            return yData.count
        }
        return zData.count
    }
}

</code>```

答:
After the last line where you set the data, tell the table view to reload.

```<code>if firstLetter == "Z" {
    self.zData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
}
tableView.reloadData()
</code>```

Now there will be data and the table will be able to show it.

Body:
I am a beginning developer using Cloud Firestore for data in my iOS app and want to read the data and store it in arrays. I declared the arrays outside of the function to read the data, but I cannot access the arrays inside of the function without using "self". However, then the data is not stored in the arrays. I was wondering how to store the values inside arrays while also being able to access them outside the function. I know this is probably a very simple problem, but I would greatly appreciate if anyone could help me. This is the code.

struct PlasticCellData {
    let image: UIImage?
    let message: String?
}
struct PlasticAlphaHeader {
    let label: String?
}

class PlasticMaterial: UITableViewController {

    var rowHeight: CGFloat = 50
    var headerheight: CGFloat = 100
    var ref: DatabaseReference?
    var databaseHandle: DatabaseHandle?

    var alphaHeaderArray = [PlasticAlphaHeader]()
    var aData = [PlasticCellData]()
    var bData = [PlasticCellData]()
    var cData = [PlasticCellData]()
    var dData = [PlasticCellData]()
    var eData = [PlasticCellData]()
    var fData = [PlasticCellData]()
    var gData = [PlasticCellData]()
    var hData = [PlasticCellData]()
    var iData = [PlasticCellData]()
    var jData = [PlasticCellData]()
    var kData = [PlasticCellData]()
    var lData = [PlasticCellData]()
    var mData = [PlasticCellData]()
    var nData = [PlasticCellData]()
    var oData = [PlasticCellData]()
    var pData = [PlasticCellData]()
    var qData = [PlasticCellData]()
    var rData = [PlasticCellData]()
    var sData = [PlasticCellData]()
    var tData = [PlasticCellData]()
    var uData = [PlasticCellData]()
    var vData = [PlasticCellData]()
    var wData = [PlasticCellData]()
    var xData = [PlasticCellData]()
    var yData = [PlasticCellData]()
    var zData = [PlasticCellData]()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        setupNavBar()
        let db = Firestore.firestore()

        alphaHeaderArray =
            [PlasticAlphaHeader.init(label: "A"), PlasticAlphaHeader.init(label: "B"),
            PlasticAlphaHeader.init(label: "C"), PlasticAlphaHeader.init(label: "D"),
            PlasticAlphaHeader.init(label: "E"), PlasticAlphaHeader.init(label: "F"),
            PlasticAlphaHeader.init(label: "G"), PlasticAlphaHeader.init(label: "H"),
            PlasticAlphaHeader.init(label: "I"), PlasticAlphaHeader.init(label: "J"),
            PlasticAlphaHeader.init(label: "K"), PlasticAlphaHeader.init(label: "L"),
            PlasticAlphaHeader.init(label: "M"), PlasticAlphaHeader.init(label: "N"),
            PlasticAlphaHeader.init(label: "O"), PlasticAlphaHeader.init(label: "P"),
            PlasticAlphaHeader.init(label: "Q"), PlasticAlphaHeader.init(label: "R"),
            PlasticAlphaHeader.init(label: "S"), PlasticAlphaHeader.init(label: "T"),
            PlasticAlphaHeader.init(label: "U"), PlasticAlphaHeader.init(label: "V"),
            PlasticAlphaHeader.init(label: "W"), PlasticAlphaHeader.init(label: "X"),
            PlasticAlphaHeader.init(label: "Y"), PlasticAlphaHeader.init(label: "Z")]

        db.collection("plastic").getDocuments { (snapshot, error) in
            if let error = error {

            }
            else {
                for document in snapshot!.documents {
                    let data = document.data()
                    let name = data["name"] as? String ?? ""
                    let firstLetter = name.prefix(1)
                    if firstLetter == "A" {
                        self.aData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "B" {
                        self.bData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "C" {
                        self.cData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "D" {
                        self.dData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "E" {
                        self.eData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "F" {
                        self.fData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "G" {
                        self.gData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "H" {
                        self.hData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "I" {
                        self.iData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "J" {
                        self.jData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "K" {
                        self.kData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "L" {
                        self.lData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "M" {
                        self.mData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "N" {
                        self.nData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "O" {
                        self.oData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "P" {
                        self.pData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "Q" {
                        self.qData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "R" {
                        self.rData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "S" {
                        self.sData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "T" {
                        self.tData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "U" {
                        self.uData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "V" {
                        self.vData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "W" {
                        self.wData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "X" {
                        self.xData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "Y" {
                        self.yData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                    if firstLetter == "Z" {
                        self.zData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
                    }
                }
            }
        }

        self.tableView.register(ItemCustomCell.self, forCellReuseIdentifier: "custom")
    }

func setupNavBar() {
        navigationItem.title = "Select Item"
        navigationController?.navigationBar.prefersLargeTitles = true
    }

    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let alphaHeader = Bundle.main.loadNibNamed("AlphaHeaderView", owner: self, options: nil)?.first as! AlphaHeaderView

        alphaHeader.headerLabel.text = alphaHeaderArray[section].label
        return alphaHeader
    }
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return headerheight
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCell(withIdentifier: "custom") as! ItemCustomCell
        cell.itemImage = aData[indexPath.row].image // Fatal error: Index out of range
        cell.message = aData[indexPath.row].message
        cell.itemImage = bData[indexPath.row].image
        cell.message = bData[indexPath.row].message
        cell.itemImage = cData[indexPath.row].image
        cell.message = cData[indexPath.row].message
        cell.itemImage = dData[indexPath.row].image
        cell.message = dData[indexPath.row].message
        cell.itemImage = eData[indexPath.row].image
        cell.message = eData[indexPath.row].message
        cell.itemImage = fData[indexPath.row].image
        cell.message = fData[indexPath.row].message
        cell.itemImage = hData[indexPath.row].image
        cell.message = hData[indexPath.row].message
        cell.itemImage = iData[indexPath.row].image
        cell.message = iData[indexPath.row].message
        cell.itemImage = jData[indexPath.row].image
        cell.message = jData[indexPath.row].message
        cell.itemImage = kData[indexPath.row].image
        cell.message = kData[indexPath.row].message
        cell.itemImage = lData[indexPath.row].image
        cell.message = lData[indexPath.row].message
        cell.itemImage = mData[indexPath.row].image
        cell.message = mData[indexPath.row].message
        cell.itemImage = nData[indexPath.row].image
        cell.message = nData[indexPath.row].message
        cell.itemImage = oData[indexPath.row].image
        cell.message = oData[indexPath.row].message
        cell.itemImage = pData[indexPath.row].image
        cell.message = pData[indexPath.row].message
        cell.itemImage = qData[indexPath.row].image
        cell.message = qData[indexPath.row].message
        cell.itemImage = rData[indexPath.row].image
        cell.message = rData[indexPath.row].message
        cell.itemImage = sData[indexPath.row].image
        cell.message = sData[indexPath.row].message
        cell.itemImage = tData[indexPath.row].image
        cell.message = tData[indexPath.row].message
        cell.itemImage = uData[indexPath.row].image
        cell.message = uData[indexPath.row].message
        cell.itemImage = vData[indexPath.row].image
        cell.message = vData[indexPath.row].message
        cell.itemImage = wData[indexPath.row].image
        cell.message = wData[indexPath.row].message
        cell.itemImage = xData[indexPath.row].image
        cell.message = xData[indexPath.row].message
        cell.itemImage = yData[indexPath.row].image
        cell.message = yData[indexPath.row].message
        cell.itemImage = zData[indexPath.row].image
        cell.message = zData[indexPath.row].message
        return cell
    }
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return rowHeight
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 26
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return aData.count
        }
        if section == 1 {
            return bData.count
        }
        if section == 2 {
            return cData.count
        }
        if section == 3 {
            return dData.count
        }
        if section == 4 {
            return eData.count
        }
        if section == 5 {
            return fData.count
        }
        if section == 6 {
            return gData.count
        }
        if section == 7 {
            return hData.count
        }
        if section == 8 {
            return iData.count
        }
        if section == 9 {
            return jData.count
        }
        if section == 10 {
            return kData.count
        }
        if section == 11 {
            return lData.count
        }
        if section == 12 {
            return mData.count
        }
        if section == 13 {
            return nData.count
        }
        if section == 14 {
            return oData.count
        }
        if section == 15 {
            return pData.count
        }
        if section == 16 {
            return qData.count
        }
        if section == 17 {
            return rData.count
        }
        if section == 18{
            return sData.count
        }
        if section == 19 {
            return tData.count
        }
        if section == 20 {
            return uData.count
        }
        if section == 21 {
            return vData.count
        }
        if section == 22 {
            return wData.count
        }
        if section == 23 {
            return xData.count
        }
        if section == 24 {
            return yData.count
        }
        return zData.count
    }
}

Body:
After the last line where you set the data, tell the table view to reload.

if firstLetter == "Z" {
    self.zData = [PlasticCellData.init(image: #imageLiteral(resourceName: "PlasticSilverware"), message: name)]
}
tableView.reloadData()

Now there will be data and the table will be able to show it.


来源: stackexchange

问:
PHP SHA-512 to Python+C SHA-512
I am working on a website for a game. The accounts are created via the php based website, and the game login server is being prototyped in Python, and will be finalized in C. The problem I am having is that when I hash something in PHP, I am unable to reproduce the same result with the same starting data and salt in Python. I looked through the algorithm in PHP here http://www.akkadia.org/drepper/SHA-crypt.txt and compared it to the way I was doing it and noticed that PHP cuts off the null byte at the end. Although, other than that I havent had much luck.

Python:

```<code>def HashPassword(Salt,Password,Rounds=5000):
    passhash=hashlib.sha512(Password+Salt).digest()[:-1]
    for i in xrange(2,Rounds):
        passhash=hashlib.sha512(passhash+Salt).digest()[:-1]
    return passhash
</code>```

PHP:

```<code>function HashPW($password, $salt = "")
{
    if(strlen($salt) == 0) $salt = RandChar(16);
    return crypt($password, '$6$rounds=5000$' . $salt . '$');
}
</code>```

答:
Here is some simpler Python code for you.</p>

```<code>import crypt
def hashPassword(salt, password, rounds=5000):
    return crypt.crypt(password, '$6$rounds={:d}${}$'.format(rounds, salt))
</code>```

ContentLicense: CC BY-SA 3.0

Title: PHP SHA-512 to Python+C SHA-512

Body:
I am working on a website for a game. The accounts are created via the php based website, and the game login server is being prototyped in Python, and will be finalized in C. The problem I am having is that when I hash something in PHP, I am unable to reproduce the same result with the same starting data and salt in Python. I looked through the algorithm in PHP here http://www.akkadia.org/drepper/SHA-crypt.txt and compared it to the way I was doing it and noticed that PHP cuts off the null byte at the end. Although, other than that I havent had much luck.

Python:

def HashPassword(Salt,Password,Rounds=5000):
    passhash=hashlib.sha512(Password+Salt).digest()[:-1]
    for i in xrange(2,Rounds):
        passhash=hashlib.sha512(passhash+Salt).digest()[:-1]
    return passhash

PHP:

function HashPW($password, $salt = "")
{
    if(strlen($salt) == 0) $salt = RandChar(16);
    return crypt($password, '$6$rounds=5000$' . $salt . '$');
}

Body:
Here is some simpler Python code for you.

import crypt
def hashPassword(salt, password, rounds=5000):
    return crypt.crypt(password, '$6$rounds={:d}${}$'.format(rounds, salt))


问:
Dynamically join pivoted table
Maybe the community could advise me on this Postgres question (PostgreSQL 9.5)

There is a big (1.5 mil rows) flightlog table with columns: action type (4 action types), timestamp and user_id.
The users table has 6K rows.

```<code>**flightlog**
user_id, time, action
2301    "2016-10-25 14:13:25.74668" "View"
8   "2016-04-25 15:02:13.916204"    "Download"
8   "2016-04-25 15:01:20.553475"    "Download"
8   "2016-04-25 14:57:02.430493"    "Download"
8   "2016-04-25 14:57:02.160002"    "Download"
8   "2016-04-25 14:57:01.397602"    "Download"
26  "2016-10-25 16:01:25.005285"    "View"
216 "2016-10-24 14:46:16.035242"    "View"
2182    "2016-10-24 14:47:43.713"   "View"
243 "2016-10-24 12:10:12.187181"    "View"
26  "2016-10-24 15:01:26.269981"    "View"
26  "2016-10-24 15:01:28.122361"    "View"

**users**
user_id, email
8 "ndoe@mysite.com"
26  "jdoe@mysite.com"
2301 "kdoe@mysite.com"

**subscriptions**
user_id, expires
8    "2017-08-30 15:48:06.827258"
26   "2017-08-10 00:00:00"
2301 "2017-09-28 09:09:17.56549"
</code>```

I need to have a table with counts for 4 different actions per month for a user,
so it would be user and then 4 actions per month and this is replicated 12 times.
The columns would look the following:

```<code>user1  period1_action1 period1_action2 period1_action3 period1_action4 period2_action1 etc
</code>```

To make it more complicated these 12 months should be dynamic for every user, calculated as +12 months from their subscription date in subscriptions table(10K).

So far I could come with a FILTER-based pivot on actions and join it with cte choosing username and start of the subscription.

```<code>with counters ( <doing counts using windowing functions>),
     pivot1   ( <pivoting counters using FILTER>
              ...sum(times) filter (where action = 'action1')...
              ),
     recent_subscription (<picking latest subscription for a user>),
     titles   (<using previous cte and adding more info from info table>)

select t.user, t.id, t.subscription_starts, t.expires_at, t.title, email,
                p."action1", p."action2", p."action3 ", p."action4"
      from titles t
      join pivot1 p
...
</code>```

Which correctly produces activity data of 12 months for a user in the following format:

```<code>user1 ... 1st_period_4user1 action1 action2 action3 action4
user1 ... 2nd_period_4user1 action1 action2 action3 action4
user2 ... 1st_period_4user2 action1 action2 action3 action4
user2 ... 2nd_period_4user2 action1 action2 action3 action4
user3 ... 1st_period_4user3 action1 action2 action3 action4
user3 ... 2nd_period_4user3 action1 action2 action3 action4
</code>```

etc

But the challenge is now to pivot this again to get 12periods/4actions combinations.
Could be just 12 if as below done
with json_object_aggr as (period: and then 4 actions)

```<code> --using the piece above as another CTE called merged
 --this code does not work :(
select
        email, id, ends, subs, info,
        json_object_aggr(starts, s1,v1,p1,d1 ORDER BY starts) as P1,
        json_object_aggr(starts, s2,v2,p2,d2 ORDER BY starts) as P2,
        json_object_aggr(starts, s3,v3,p3,d3 ORDER BY starts) as P3,
        json_object_aggr(starts, s4,v4,p4,d4 ORDER BY starts) as P4,
        json_object_aggr(starts, s5,v5,p5,d5 ORDER BY starts) as P5,
        json_object_aggr(starts, s6,v6,p6,d6 ORDER BY starts) as P6,
        json_object_aggr(starts, s7,v7,p7,d7 ORDER BY starts) as P7,
        json_object_aggr(starts, s8,v8,p8,d8 ORDER BY starts) as P8,
        json_object_aggr(starts, s9,v9,p9,d9 ORDER BY starts) as P9,
        json_object_aggr(starts, s10,v10,p10,d10 ORDER BY starts) as P10,
        json_object_aggr(starts, s11,v11,p11,d11 ORDER BY starts) as P11,
        json_object_aggr(starts, s12,v12,p12,d12 ORDER BY starts) as P12
    from
            (select email, id,  starts, ends, subs, info, starts,
  sum("action1") as s1,sum("action2") as v1,sum("action3") as
  p1,sum("action4")
  as d1
              from merged
              group by email, id,  starts, ends, subs, info, starts

            ) m
    group by email, id,  starts, ends, subs, info
    order by email, id,  starts, ends, subs, info
</code>```

Could this be json_object_agg for 4 actions per period?
Could I get help on how to pivot this?

Thank you.

答:
Starting from the working query above which produced the results in the following way:

```<code>user1 ... 1st_period_4user1 action1 action2 action3 action4
user1 ... 2nd_period_4user1 action1 action2 action3 action4
</code>```

I had the last 5 columns concatenated into "period+4 actions" string.
Then I had the table ranked so there would be 1 to 12 rankings there.
Then using the concatenated column as value and ranks as columns I pivot again...
Doing this 12 times:

```<code>array_agg(stf) FILTER (where rnk = 1) AS period_1
array_agg(stf) FILTER (where rnk = 2) AS period_2
</code>```

to get user_id with 12 data columns.
The drawback with this approach is that once a month is skipped it still is ranked as next period.

Then I join additional info/organisations tables to add more to user_id.

This took 67 lines of code and 4 CTEs...
Still hope for a more refined solution...

This answer is posted for informational purposes only.

ContentLicense: CC BY-SA 4.0

Title: Dynamically join pivoted table

Body:
Maybe the community could advise me on this Postgres question (PostgreSQL 9.5)

There is a big (1.5 mil rows) flightlog table with columns: action type (4 action types), timestamp and user_id.
The users table has 6K rows.

**flightlog**
user_id, time, action
2301    "2016-10-25 14:13:25.74668" "View"
8   "2016-04-25 15:02:13.916204"    "Download"
8   "2016-04-25 15:01:20.553475"    "Download"
8   "2016-04-25 14:57:02.430493"    "Download"
8   "2016-04-25 14:57:02.160002"    "Download"
8   "2016-04-25 14:57:01.397602"    "Download"
26  "2016-10-25 16:01:25.005285"    "View"
216 "2016-10-24 14:46:16.035242"    "View"
2182    "2016-10-24 14:47:43.713"   "View"
243 "2016-10-24 12:10:12.187181"    "View"
26  "2016-10-24 15:01:26.269981"    "View"
26  "2016-10-24 15:01:28.122361"    "View"

**users**
user_id, email
8 "ndoe@mysite.com"
26  "jdoe@mysite.com"
2301 "kdoe@mysite.com"

**subscriptions**
user_id, expires
8    "2017-08-30 15:48:06.827258"
26   "2017-08-10 00:00:00"
2301 "2017-09-28 09:09:17.56549"

I need to have a table with counts for 4 different actions per month for a user,
so it would be user and then 4 actions per month and this is replicated 12 times.
The columns would look the following:

user1  period1_action1 period1_action2 period1_action3 period1_action4 period2_action1 etc

To make it more complicated these 12 months should be dynamic for every user, calculated as +12 months from their subscription date in subscriptions table(10K).

So far I could come with a FILTER-based pivot on actions and join it with cte choosing username and start of the subscription.

with counters ( <doing counts using windowing functions>),
     pivot1   ( <pivoting counters using FILTER>
              ...sum(times) filter (where action = 'action1')...
              ),
     recent_subscription (<picking latest subscription for a user>),
     titles   (<using previous cte and adding more info from info table>)

select t.user, t.id, t.subscription_starts, t.expires_at, t.title, email,
                p."action1", p."action2", p."action3 ", p."action4"
      from titles t
      join pivot1 p
...

Which correctly produces activity data of 12 months for a user in the following format:

user1 ... 1st_period_4user1 action1 action2 action3 action4
user1 ... 2nd_period_4user1 action1 action2 action3 action4
user2 ... 1st_period_4user2 action1 action2 action3 action4
user2 ... 2nd_period_4user2 action1 action2 action3 action4
user3 ... 1st_period_4user3 action1 action2 action3 action4
user3 ... 2nd_period_4user3 action1 action2 action3 action4

etc

But the challenge is now to pivot this again to get 12periods/4actions combinations.
Could be just 12 if as below done
with json_object_aggr as (period: and then 4 actions)

 --using the piece above as another CTE called merged
 --this code does not work :(
select
        email, id, ends, subs, info,
        json_object_aggr(starts, s1,v1,p1,d1 ORDER BY starts) as P1,
        json_object_aggr(starts, s2,v2,p2,d2 ORDER BY starts) as P2,
        json_object_aggr(starts, s3,v3,p3,d3 ORDER BY starts) as P3,
        json_object_aggr(starts, s4,v4,p4,d4 ORDER BY starts) as P4,
        json_object_aggr(starts, s5,v5,p5,d5 ORDER BY starts) as P5,
        json_object_aggr(starts, s6,v6,p6,d6 ORDER BY starts) as P6,
        json_object_aggr(starts, s7,v7,p7,d7 ORDER BY starts) as P7,
        json_object_aggr(starts, s8,v8,p8,d8 ORDER BY starts) as P8,
        json_object_aggr(starts, s9,v9,p9,d9 ORDER BY starts) as P9,
        json_object_aggr(starts, s10,v10,p10,d10 ORDER BY starts) as P10,
        json_object_aggr(starts, s11,v11,p11,d11 ORDER BY starts) as P11,
        json_object_aggr(starts, s12,v12,p12,d12 ORDER BY starts) as P12
    from
            (select email, id,  starts, ends, subs, info, starts,
  sum("action1") as s1,sum("action2") as v1,sum("action3") as
  p1,sum("action4")
  as d1
              from merged
              group by email, id,  starts, ends, subs, info, starts

            ) m
    group by email, id,  starts, ends, subs, info
    order by email, id,  starts, ends, subs, info

Could this be json_object_agg for 4 actions per period?
Could I get help on how to pivot this?

Thank you.

Body:
Starting from the working query above which produced the results in the following way:

user1 ... 1st_period_4user1 action1 action2 action3 action4
user1 ... 2nd_period_4user1 action1 action2 action3 action4

I had the last 5 columns concatenated into "period+4 actions" string.
Then I had the table ranked so there would be 1 to 12 rankings there.
Then using the concatenated column as value and ranks as columns I pivot again...
Doing this 12 times:

array_agg(stf) FILTER (where rnk = 1) AS period_1
array_agg(stf) FILTER (where rnk = 2) AS period_2

to get user_id with 12 data columns.
The drawback with this approach is that once a month is skipped it still is ranked as next period.

Then I join additional info/organisations tables to add more to user_id.

This took 67 lines of code and 4 CTEs...
Still hope for a more refined solution...

This answer is posted for informational purposes only.


问:
Create-react-app reload on service worker update
I want to modify create-react-app service worker file and implement popup message which will ask user to update app if newer service worker is ready to be activated. I'm almost done with the solution but have one pitfall. I want to reload the app when user confirms service worker update popup, so I've added some coded to the end of register function, see below:

```<code>export default function register(config) {
  if (process.env.NODE_ENV === "production" && "serviceWorker" in navigator) {
    // The URL constructor is available in all browsers that support SW.
    const publicUrl = new URL(process.env.PUBLIC_URL, window.location)
    if (publicUrl.origin !== window.location.origin) {
      // Our service worker won't work if PUBLIC_URL is on a different origin
      // from what our page is served on. This might happen if a CDN is used to
      // serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374
      return
    }

    window.addEventListener("load", () => {
      const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`

      if (isLocalhost) {
        // This is running on localhost. Lets check if a service worker still exists or not.
        checkValidServiceWorker(swUrl, config)

        // Add some additional logging to localhost, pointing developers to the
        // service worker/PWA documentation.
        navigator.serviceWorker.ready.then(() => {
          console.log(
            "This web app is being served cache-first by a service " +
              "worker."
          )
        })
      } else {
        // Is not local host. Just register service worker
        registerValidSW(swUrl, config)
      }

      let preventDevToolsReloadLoop
      navigator.serviceWorker.addEventListener("controllerchange", function() {
        // ensure refresh is called only once
        if (preventDevToolsReloadLoop) {
          return
        }

        preventDevToolsReloadLoop = true
        console.log("reload")
        window.location.reload(true)
      })
    })
  }
}
</code>```

But the problem is that it reloads the app also on first visit, when there doesn't exist any service worker yet. How can I solve it?

答:
Update to react-scripts ^3.2.0.  Verify that you have the new version of serviceWorker.ts or .js.  The old one was called registerServiceWorker.ts and the register function did not accept a configuration object.  Note that this solution only works well if you are Not lazy-loading.

then in index.tsx:

```<code>  serviceWorker.register({
    onUpdate: registration => {
      alert('New version available!  Ready to update?');
      if (registration && registration.waiting) {
        registration.waiting.postMessage({ type: 'SKIP_WAITING' });
      }
      window.location.reload();
    }
  });
</code>```

The latest version of the ServiceWorker.ts register()function accepts a config object with a callback function where we can handle upgrading.  If we post a message SKIP_WAITING this tells the service worker to stop waiting and to go ahead and load the new content after the next refresh.  In this example I am using a javascript alert to inform the user.  Please replace this with a custom toast.

The reason this postMessage function works is because under the hood CRA is using workbox-webpack-plugin which includes a SKIP_WAITING listener.

More About Service Workers

good guide: https://redfin.engineering/how-to-fix-the-refresh-button-when-using-service-workers-a8e27af6df68

CRA issue discussing service worker cache:  https://github.com/facebook/create-react-app/issues/5316

If you are not using CRA, you can use workbox directly: https://developers.google.com/web/tools/workbox

Body:
I want to modify create-react-app service worker file and implement popup message which will ask user to update app if newer service worker is ready to be activated. I'm almost done with the solution but have one pitfall. I want to reload the app when user confirms service worker update popup, so I've added some coded to the end of register function, see below:

export default function register(config) {
  if (process.env.NODE_ENV === "production" && "serviceWorker" in navigator) {
    // The URL constructor is available in all browsers that support SW.
    const publicUrl = new URL(process.env.PUBLIC_URL, window.location)
    if (publicUrl.origin !== window.location.origin) {
      // Our service worker won't work if PUBLIC_URL is on a different origin
      // from what our page is served on. This might happen if a CDN is used to
      // serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374
      return
    }

    window.addEventListener("load", () => {
      const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`

      if (isLocalhost) {
        // This is running on localhost. Lets check if a service worker still exists or not.
        checkValidServiceWorker(swUrl, config)

        // Add some additional logging to localhost, pointing developers to the
        // service worker/PWA documentation.
        navigator.serviceWorker.ready.then(() => {
          console.log(
            "This web app is being served cache-first by a service " +
              "worker."
          )
        })
      } else {
        // Is not local host. Just register service worker
        registerValidSW(swUrl, config)
      }

      let preventDevToolsReloadLoop
      navigator.serviceWorker.addEventListener("controllerchange", function() {
        // ensure refresh is called only once
        if (preventDevToolsReloadLoop) {
          return
        }

        preventDevToolsReloadLoop = true
        console.log("reload")
        window.location.reload(true)
      })
    })
  }
}

But the problem is that it reloads the app also on first visit, when there doesn't exist any service worker yet. How can I solve it?

Body:
Update to react-scripts ^3.2.0.  Verify that you have the new version of serviceWorker.ts or .js.  The old one was called registerServiceWorker.ts and the register function did not accept a configuration object.  Note that this solution only works well if you are Not lazy-loading.

then in index.tsx:

  serviceWorker.register({
    onUpdate: registration => {
      alert('New version available!  Ready to update?');
      if (registration && registration.waiting) {
        registration.waiting.postMessage({ type: 'SKIP_WAITING' });
      }
      window.location.reload();
    }
  });

The latest version of the ServiceWorker.ts register()function accepts a config object with a callback function where we can handle upgrading.  If we post a message SKIP_WAITING this tells the service worker to stop waiting and to go ahead and load the new content after the next refresh.  In this example I am using a javascript alert to inform the user.  Please replace this with a custom toast.

The reason this postMessage function works is because under the hood CRA is using workbox-webpack-plugin which includes a SKIP_WAITING listener.

More About Service Workers

good guide: https://redfin.engineering/how-to-fix-the-refresh-button-when-using-service-workers-a8e27af6df68

CRA issue discussing service worker cache:  https://github.com/facebook/create-react-app/issues/5316

If you are not using CRA, you can use workbox directly: https://developers.google.com/web/tools/workbox


问:
How to show Validation Error in view page where I am sending Model data for drop-down list from controller?
I have a country model(Id, Name), Type(id, type of place) model and place(details) model.
Whenever I want to create a new place I have to send a viewModel that contains country and type lists.
I have to select the country and type from the drop-down list in View page. I am using DATA ANNOTATION to validate data. The problem is when the input form is invalid I have to show red empty field error and also I have to keep ViewModel data. If I redirect to create page then I can't show the error message and if I use return View('Create') then ViewModel becomes empty.

How can I do this?

ViewModel:

```<code>public class DropDownListViewModel
{
    [Required(ErrorMessage = "Address is required")]
    public PlaceModel Place { get; set; }
    public IEnumerable<TypeModel> TypeList { get; set; }
    public IEnumerable<CountryModel> CountryList { get; set; }
    [Required]
    public int SelectedType { get; set;  }
    public int SelectedCountry { get; set; }
}

public class PlaceModel:BaseClassModel
{
    [Required(ErrorMessage ="Address is required")]
    public string Address { get; set; }
    [Range(1, 5, ErrorMessage = "Range must be between 1-5 in years.")]
    public int RatingId { get; set; }
    public string TypeName { get; set; }
    public string CountryName { get; set; }

    public byte[] img { get; set; }
}

[HttpPost]
    public ActionResult SaveNewPlace(DropDownListViewModel EditedModel)
    {
        if(ModelState.IsValid)
        {

            DBhandler db = new DBhandler();

            string Name = EditedModel.Place.Name;
            string Address = EditedModel.Place.Address;
            int RatingId = EditedModel.Place.RatingId;
            int TypeId = EditedModel.SelectedType;
            int CountryId = EditedModel.SelectedCountry;
            if (EditedModel.Place.Id >= 1)
            {
                int Id = EditedModel.Place.Id;
                db.Update(Id, Name, Address, RatingId, TypeId, CountryId);
            }
            else
            {
                db.Insert(Name, Address, RatingId, TypeId, CountryId);
            }
            return Redirect("Index");
        }
        else
        {
            return View("Create");
        }
    }

public ActionResult Create()
    {
        DBhandler manager = new DBhandler();
        DropDownListViewModel list = new DropDownListViewModel();
        list.CountryList = manager.GetCountries();
        list.TypeList = manager.GetTypes();
        return View(list);
    }
</code>```

view:

@model TouristPlace.Models.DropDownListViewModel

@{
    ViewBag.Title = "View";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

View

@using (Html.BeginForm("SaveNewPlace","Home", FormMethod.Post))
{
    @Html.AntiForgeryToken()

PlaceModel

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.Place.Name, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.Place.Name, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Place.Name, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.Place.Address, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.Place.Address, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Place.Address, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.Place.RatingId, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.Place.RatingId, new { htmlAttributes = new { @class = "form-control", min = "1", max = "5", value = "1" } })
            @Html.ValidationMessageFor(model => model.Place.RatingId, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.SelectedType, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.DropDownList("SelectedType", new SelectList(Model.TypeList, "Id", "Name"), new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.SelectedType, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.SelectedCountry, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.DropDownList("SelectedCountry", new SelectList(Model.CountryList, "Id", "Name"), new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.SelectedCountry, "", new { @class = "text-danger" })

            <input type="submit" value="Create" class="btn btn-default" />

}

    @Html.ActionLink("Back to List", "Index")

```

答:
Try it without specifying the return page so:</p>

```<code>else
    {
        return View();
    }
</code>```

Body:
I have a country model(Id, Name), Type(id, type of place) model and place(details) model.
Whenever I want to create a new place I have to send a viewModel that contains country and type lists.
I have to select the country and type from the drop-down list in View page. I am using DATA ANNOTATION to validate data. The problem is when the input form is invalid I have to show red empty field error and also I have to keep ViewModel data. If I redirect to create page then I can't show the error message and if I use return View('Create') then ViewModel becomes empty.

How can I do this?

ViewModel:

public class DropDownListViewModel
{
    [Required(ErrorMessage = "Address is required")]
    public PlaceModel Place { get; set; }
    public IEnumerable<TypeModel> TypeList { get; set; }
    public IEnumerable<CountryModel> CountryList { get; set; }
    [Required]
    public int SelectedType { get; set;  }
    public int SelectedCountry { get; set; }
}

public class PlaceModel:BaseClassModel
{
    [Required(ErrorMessage ="Address is required")]
    public string Address { get; set; }
    [Range(1, 5, ErrorMessage = "Range must be between 1-5 in years.")]
    public int RatingId { get; set; }
    public string TypeName { get; set; }
    public string CountryName { get; set; }

    public byte[] img { get; set; }
}

[HttpPost]
    public ActionResult SaveNewPlace(DropDownListViewModel EditedModel)
    {
        if(ModelState.IsValid)
        {

            DBhandler db = new DBhandler();

            string Name = EditedModel.Place.Name;
            string Address = EditedModel.Place.Address;
            int RatingId = EditedModel.Place.RatingId;
            int TypeId = EditedModel.SelectedType;
            int CountryId = EditedModel.SelectedCountry;
            if (EditedModel.Place.Id >= 1)
            {
                int Id = EditedModel.Place.Id;
                db.Update(Id, Name, Address, RatingId, TypeId, CountryId);
            }
            else
            {
                db.Insert(Name, Address, RatingId, TypeId, CountryId);
            }
            return Redirect("Index");
        }
        else
        {
            return View("Create");
        }
    }

public ActionResult Create()
    {
        DBhandler manager = new DBhandler();
        DropDownListViewModel list = new DropDownListViewModel();
        list.CountryList = manager.GetCountries();
        list.TypeList = manager.GetTypes();
        return View(list);
    }

view:

@model TouristPlace.Models.DropDownListViewModel

@{
    ViewBag.Title = "View";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

View

@using (Html.BeginForm("SaveNewPlace","Home", FormMethod.Post))
{
    @Html.AntiForgeryToken()

PlaceModel

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.Place.Name, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.Place.Name, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Place.Name, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.Place.Address, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.Place.Address, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Place.Address, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.Place.RatingId, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.Place.RatingId, new { htmlAttributes = new { @class = "form-control", min = "1", max = "5", value = "1" } })
            @Html.ValidationMessageFor(model => model.Place.RatingId, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.SelectedType, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.DropDownList("SelectedType", new SelectList(Model.TypeList, "Id", "Name"), new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.SelectedType, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.SelectedCountry, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.DropDownList("SelectedCountry", new SelectList(Model.CountryList, "Id", "Name"), new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.SelectedCountry, "", new { @class = "text-danger" })

            <input type="submit" value="Create" class="btn btn-default" />

}

    @Html.ActionLink("Back to List", "Index")

Body:
Try it without specifying the return page so:

else
    {
        return View();
    }


问:
Detecting change in two consecutive pictures
As a toy project i want to write an application that will take pictures from a web cam and then detect changes in them. I want to detect if someone walked in front of the webcam.

Can you guys, show me some pointers on how can i detect a major change in two consecutive shots?

答: Over at Code Project is a nice article explaining a possible solution.</p>

OwnerDisplayName: Hamza Yerlikaya

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: HS


问:
Where does TeamCity get the value for %system.teamcity.build.workingDir%
We have TeamCity and on the [Runner: Command Line] of the [Build Configuration] page, there is a [Command Parameter] field %system.teamcity.build.workingDir%

My question is where does TeamCity get this value from as when i look at the System Properties of the Agent i do not see it has been set.
%system.teamcity.build.workingDir% does not appear in the list of [System Properties] or [Environment Variables]

答:
Where are you looking? It is listed along with other system properties:

@Snahider - a build at any point runs only on one agent. So %system.teamcity.build.workingDir% will be set to the current build's working dir. It is not same as %system.agent.work.dir% which is the parent of the checkout directory for each build.

For example if you have your agent installed in C:\BuildAgent the %system.agent.work.dir% will be C:\BuildAgent\work whereas %system.teamcity.build.workingDir% will be something like C:\BuildAgent\work\8b0fde2bf2d2efc0 if you have not specified the checkout directory in VCS settings or if you have set it, to say wd it will be C:\BuildAgent\work\wd

One more thing is that, if in the build step step you change the working directory, to say Examples, %system.teamcity.build.workingDir% will, as the name suggests, point to that - C:\BuildAgent\work\wd\Examples So %system.teamcity.build.workingDir% can change depending on what is happening, while %system.agent.work.dir% will remain same for an agent. Hope this explains the difference.


问:
RESTful servive : Unable to return array of object using json
This sample was extracted from one of the many samples found via Google.
The application returns 3 objects but all attributes are NULL.

The following is the Controller Object.

```<code>import java.net.URI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

@RestController
@RequestMapping(path = "/employees")
public class EmployeeController
{
    @Autowired
    private EmployeeDAO employeeDao;

    @GetMapping(path="/", produces = "application/json")
    public Employees getEmployees()
    {
        return employeeDao.getAllEmployees();
    }

    @PostMapping(path= "/", consumes = "application/json", produces = "application/json")
    public ResponseEntity<Object> addEmployee(@RequestBody Employee employee)
    {
        Integer id = employeeDao.getAllEmployees().getEmployeeList().size() + 1;
        employee.setId(id);

        employeeDao.addEmployee(employee);

        URI location = ServletUriComponentsBuilder.fromCurrentRequest()
                                    .path("/{id}")
                                    .buildAndExpand(employee.getId())
                                    .toUri();

        return ResponseEntity.created(location).build();
    }
}
</code>```

Here is the Employees object which gets returned via the getEmployees call.

```<code>import java.util.ArrayList;
import java.util.List;

public class Employees
{
    private List<Employee> employeeList;

    public List<Employee> getEmployeeList() {
        if(employeeList == null) {
            employeeList = new ArrayList<>();
        }
        return employeeList;
    }

    public void setEmployeeList(List<Employee> employeeList) {
        this.employeeList = employeeList;
    }
}
</code>```

In case you need it, here is the DAO.

```<code>import org.springframework.stereotype.Repository;

@Repository
public class EmployeeDAO
{
    private static Employees list = new Employees();

    static
    {
        list.getEmployeeList().add(new Employee(11, "Lokesh", "Gupta", "howtodoinjava@gmail.com"));
        list.getEmployeeList().add(new Employee(22, "Alex", "Kolenchiskey", "abc@gmail.com"));
        list.getEmployeeList().add(new Employee(33, "David", "Kameron", "titanic@gmail.com"));
    }

    public Employees getAllEmployees()
    {
        return list;
    }

    public void addEmployee(Employee employee) {
        list.getEmployeeList().add(employee);
    }
}
</code>```

As requested, here is the Employee class.

```<code>import javax.annotation.ManagedBean;

import org.springframework.web.context.annotation.ApplicationScope;

import lombok.Data;
import lombok.Getter;
import lombok.Setter;

//@ManagedBean
//@ApplicationScope
//@Data

public class Employee {

    public Employee() {

    }
    public Employee(Integer id, String firstName, String lastName, String email) {
        super();
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
    }

    @Setter  @Getter  private Integer id;
    private String firstName;
    private String lastName;
    private String email;

    //Getters and setters

    @Override
    public String toString() {
        return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
    }
}
</code>```

Here is the partial client code....

```<code>    private static void getEmployees()
    {

        // HttpHeaders
        HttpHeaders headers = new HttpHeaders();

        headers.setAccept(Arrays.asList(new MediaType[] { MediaType.APPLICATION_JSON }));
        // Request to return JSON format
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("my_other_key", "my_other_value");

        // HttpEntity<String>: To get result as String.
        HttpEntity<String> entity = new HttpEntity<String>(headers);

        // RestTemplate
        RestTemplate restTemplate = new RestTemplate();

        // Send request with GET method, and Headers.
        ///This works but only prints IDs.
        ResponseEntity<String> response = restTemplate.exchange(URL_EMPLOYEES, HttpMethod.GET, entity, String.class);
        String result = response.getBody();
        System.out.println(result);

        HttpEntity<Employees> entity2 = new HttpEntity<Employees>(headers);
      ResponseEntity<Employees> eResponse = restTemplate.exchange(URL_EMPLOYEES, HttpMethod.GET, entity2, Employees.class);
      List <Employee> eList = eResponse.getBody().getEmployeeList();
      for (Employee e : eList)
      {
          System.out.println(e.toString());
      }
   }
</code>```

From the above, the following call works and prints out the 3 IDs.

```<code>    ResponseEntity<String> response = restTemplate.exchange(URL_EMPLOYEES, HttpMethod.GET, entity, String.class);
    String result = response.getBody();
    System.out.println(result);
</code>```

Once the IDs were returned, the next step was to print out all the attributes for each employee using the next set of calls.

```<code>  ResponseEntity<Employees> eResponse = restTemplate.exchange(URL_EMPLOYEES, HttpMethod.GET, entity, Employees.class);
  List <Employee> eList = eResponse.getBody().getEmployeeList();
  for (Employee e : eList)
  {
      System.out.println(e.toString());
  }
</code>```

I placed a break point on the line doing the LIST call and verified the eResponse object has 3 items in the List BUT all 3 items show each of their associated attributes to be NULL.

Since I confirmed the call seems to be working since the IDs are returned in the first call, what command or setup is missing for the 2nd call to allow for the complete objects to be returned?

答: I think you should remove super(); in the constructor. We use it to access the members of the super class. Your Employee class has no parent class. </p>

Body:
This sample was extracted from one of the many samples found via Google.
The application returns 3 objects but all attributes are NULL.

The following is the Controller Object.

import java.net.URI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

@RestController
@RequestMapping(path = "/employees")
public class EmployeeController
{
    @Autowired
    private EmployeeDAO employeeDao;

    @GetMapping(path="/", produces = "application/json")
    public Employees getEmployees()
    {
        return employeeDao.getAllEmployees();
    }

    @PostMapping(path= "/", consumes = "application/json", produces = "application/json")
    public ResponseEntity<Object> addEmployee(@RequestBody Employee employee)
    {
        Integer id = employeeDao.getAllEmployees().getEmployeeList().size() + 1;
        employee.setId(id);

        employeeDao.addEmployee(employee);

        URI location = ServletUriComponentsBuilder.fromCurrentRequest()
                                    .path("/{id}")
                                    .buildAndExpand(employee.getId())
                                    .toUri();

        return ResponseEntity.created(location).build();
    }
}

Here is the Employees object which gets returned via the getEmployees call.

import java.util.ArrayList;
import java.util.List;

public class Employees
{
    private List<Employee> employeeList;

    public List<Employee> getEmployeeList() {
        if(employeeList == null) {
            employeeList = new ArrayList<>();
        }
        return employeeList;
    }

    public void setEmployeeList(List<Employee> employeeList) {
        this.employeeList = employeeList;
    }
}

In case you need it, here is the DAO.

import org.springframework.stereotype.Repository;

@Repository
public class EmployeeDAO
{
    private static Employees list = new Employees();

    static
    {
        list.getEmployeeList().add(new Employee(11, "Lokesh", "Gupta", "howtodoinjava@gmail.com"));
        list.getEmployeeList().add(new Employee(22, "Alex", "Kolenchiskey", "abc@gmail.com"));
        list.getEmployeeList().add(new Employee(33, "David", "Kameron", "titanic@gmail.com"));
    }

    public Employees getAllEmployees()
    {
        return list;
    }

    public void addEmployee(Employee employee) {
        list.getEmployeeList().add(employee);
    }
}

As requested, here is the Employee class.

import javax.annotation.ManagedBean;

import org.springframework.web.context.annotation.ApplicationScope;

import lombok.Data;
import lombok.Getter;
import lombok.Setter;

//@ManagedBean
//@ApplicationScope
//@Data

public class Employee {

    public Employee() {

    }
    public Employee(Integer id, String firstName, String lastName, String email) {
        super();
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
    }

    @Setter  @Getter  private Integer id;
    private String firstName;
    private String lastName;
    private String email;

    //Getters and setters

    @Override
    public String toString() {
        return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
    }
}

Here is the partial client code....

    private static void getEmployees()
    {

        // HttpHeaders
        HttpHeaders headers = new HttpHeaders();

        headers.setAccept(Arrays.asList(new MediaType[] { MediaType.APPLICATION_JSON }));
        // Request to return JSON format
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("my_other_key", "my_other_value");

        // HttpEntity<String>: To get result as String.
        HttpEntity<String> entity = new HttpEntity<String>(headers);

        // RestTemplate
        RestTemplate restTemplate = new RestTemplate();

        // Send request with GET method, and Headers.
        ///This works but only prints IDs.
        ResponseEntity<String> response = restTemplate.exchange(URL_EMPLOYEES, HttpMethod.GET, entity, String.class);
        String result = response.getBody();
        System.out.println(result);

        HttpEntity<Employees> entity2 = new HttpEntity<Employees>(headers);
      ResponseEntity<Employees> eResponse = restTemplate.exchange(URL_EMPLOYEES, HttpMethod.GET, entity2, Employees.class);
      List <Employee> eList = eResponse.getBody().getEmployeeList();
      for (Employee e : eList)
      {
          System.out.println(e.toString());
      }
   }

From the above, the following call works and prints out the 3 IDs.

    ResponseEntity<String> response = restTemplate.exchange(URL_EMPLOYEES, HttpMethod.GET, entity, String.class);
    String result = response.getBody();
    System.out.println(result);

Once the IDs were returned, the next step was to print out all the attributes for each employee using the next set of calls.

  ResponseEntity<Employees> eResponse = restTemplate.exchange(URL_EMPLOYEES, HttpMethod.GET, entity, Employees.class);
  List <Employee> eList = eResponse.getBody().getEmployeeList();
  for (Employee e : eList)
  {
      System.out.println(e.toString());
  }

I placed a break point on the line doing the LIST call and verified the eResponse object has 3 items in the List BUT all 3 items show each of their associated attributes to be NULL.

Since I confirmed the call seems to be working since the IDs are returned in the first call, what command or setup is missing for the 2nd call to allow for the complete objects to be returned?


问:
How many records can you insert in a redis instance?
I have a list of 100 million strings one on each line. The file size is 1.66 Gb.
Each string is about 20 chars long.

I started inserting the data into small instance and got max memory error. There were only 1million records inserted by then.

```<code>Micro
Micro Cache Node (cache.t1.micro): 213 MB memory, Up to 2 ECU (for short periodic bursts), 64-bit platform, Low I/O Capacity
Standard
Small Cache Node (cache.m1.small): 1.3 GB memory, 1 ECU (1 virtual core with 1 ECU), 64-bit platform, Moderate I/O Capacity
Medium Cache Node (cache.m1.medium): 3.35 GB memory, 2 ECU (1 virtual core with 2 ECUs), 64-bit platform, Moderate I/O Capacity
Large Cache Node (cache.m1.large): 7.1 GB memory, 4 ECUs (2 virtual cores with 2 ECUs each), 64-bit platform, High I/O Capacity
Extra Large Cache Node (cache.m1.xlarge): 14.6 GB of memory, 8 ECUs (4 virtual cores with 2 ECUs each), 64-bit platform, High I/O Capacity
</code>```

Will a small cache node be able to store the data or will I run out of space? How to calculate the number of records that an instance can handle?

答:
2^32 keys

Which equals to 4,294,967,296. Basically You should say how much ram is needed to save this much of data! On average, having 8 characters for every key will take 32GB of ram! Summing with the size of values, you will need much!

Source: https://redis.io/topics/faq

Body:
I have a list of 100 million strings one on each line. The file size is 1.66 Gb.
Each string is about 20 chars long.

I started inserting the data into small instance and got max memory error. There were only 1million records inserted by then.

Micro
Micro Cache Node (cache.t1.micro): 213 MB memory, Up to 2 ECU (for short periodic bursts), 64-bit platform, Low I/O Capacity
Standard
Small Cache Node (cache.m1.small): 1.3 GB memory, 1 ECU (1 virtual core with 1 ECU), 64-bit platform, Moderate I/O Capacity
Medium Cache Node (cache.m1.medium): 3.35 GB memory, 2 ECU (1 virtual core with 2 ECUs), 64-bit platform, Moderate I/O Capacity
Large Cache Node (cache.m1.large): 7.1 GB memory, 4 ECUs (2 virtual cores with 2 ECUs each), 64-bit platform, High I/O Capacity
Extra Large Cache Node (cache.m1.xlarge): 14.6 GB of memory, 8 ECUs (4 virtual cores with 2 ECUs each), 64-bit platform, High I/O Capacity

Will a small cache node be able to store the data or will I run out of space? How to calculate the number of records that an instance can handle?


问:
In a code segment of Hackerrank it was advised to make the string static. Why isn't the code working without static string?
The following code is giving an error. But when I declare the string static then the same code works.</p>

```<code>     char* check(int x1, int x2)
    {
        char str1[]= "YES";
        char str2[]= "NO";
        if((x2-x1)>0)
            return str1;
        else
            return str2;
    }
</code>```

答:
You return pointer to the automatic variables - they do not exist when you leave the scope of the function. So it the Undefined Bahaviour and the code "works" by incident only (as usually UB means - anything may happen)

when you add static keyword you change its storage duration to static and they live as long as the program itself.

Most of the modern compilers will emit the warning.
https://godbolt.org/z/_MiuM5

Body:
The following code is giving an error. But when I declare the string static then the same code works.

     char* check(int x1, int x2)
    {
        char str1[]= "YES";
        char str2[]= "NO";
        if((x2-x1)>0)
            return str1;
        else
            return str2;
    }


问:
Django - Handle Multiple different Level Nest Model
I have some question about django nested model.

As i know, to handle nested data structure, i must de-serialize every data, then create the object that will connected with ForeignKeyField.

I could handle this by override the .create() method by separate every nested data by .pop() and create each object model separately. Here is the example how i handle 2 level nested data
(based on documentation: DRF Documentation)

```<code>def create(self, validated_data):
    child_data = validated_data.pop('child_data')
    parent_obj = ParentModel.objects.create(**validated_data)
    for data in child_data:
        ChildModel.objects.create(parent_id=parent_obj, **data)
    return parent_obj
</code>```

I have some trouble here. I have multiple multi level data structure, maybe like data below:

```<code>    "data_a": [
        {
            "data_a_1": [
                {
                    "data_a_1_1": [
                        {
                            "data_a_1_1_1": "example_a_1_1_1",
                            "data_a_1_1_2": "example_a_1_1_2"
                        }
                    ]
                },
                {
                    "data_a_1_2_1": "Example a-1-2-1",
                    "data_a_1_2_2": "Example a-1-2-2"
                }
            ]
            "data_a_2": [
                {
                    "data_a_2_1": "Example a-2-1"
                },
                {
                    "data_a_2_2": "Example a-2-2"
                }
            ]
        }
    ]
</code>```

My question is:

What is the best way to handle dynamic data structure like this? It will take a long hardcoded script to handle multiple multilevel data structure by override .create() as i mention above.

Any other best practice to handle mentioned data-strucure?

答:
I found solution for this structure.

I read at the the DRF Documentation, there is a third-party package to handle parent-children relation easily drf-writable-nested

It helps me a lot to handle this kind data structure problem with out hardcoded .create() and .update(). This package provide special method to handle parent-child CRUD problem as i mentioned above.

Here is the example:

models.py:

```<code>class GrandChildModel(models.Model):
    name = models.CharField(max_length=32, blank=True, null=True)
    parent_id = models.ForeignKeyField(ChildModel, on_delete=CASCADE, related_name='grandchild')

class ChildModel(models.Model):
    name = models.CharField(max_length=32, blank=True, null=True)
    parent_id = models.ForeignKeyField(ParentModel, on_delete=CASCADE, related_name='child')

class ParentModel(models.Model):
    parent_name = model.CharField(max_length=32, blank=True, null=True)
</code>```

serializer.py

```<code>from drf_writable_nested.serializers import WritableNestedModelSerializer

class GrandChildSerializer(serializers.ModelSerializer):
    class Meta:
        model=GrandChildModel
        fields = ["name"]

class ChildSerializer(WritableModelSerializer):
    grandchild = GrandChildSerializer(many=True)
    class Meta:
        model=ChildModel
        fields = ["name", "grandchild"]

class ParentSerializer(WritableModelSerializer):
    child = ChildSerializer(many=True)
    class Meta:
        model=ChildModelimport
        fields = ["name", "child"]
</code>```

with this, you can process all kind of nested data :)

Body:
I have some question about django nested model.

As i know, to handle nested data structure, i must de-serialize every data, then create the object that will connected with ForeignKeyField.

I could handle this by override the .create() method by separate every nested data by .pop() and create each object model separately. Here is the example how i handle 2 level nested data
(based on documentation: DRF Documentation)

def create(self, validated_data):
    child_data = validated_data.pop('child_data')
    parent_obj = ParentModel.objects.create(**validated_data)
    for data in child_data:
        ChildModel.objects.create(parent_id=parent_obj, **data)
    return parent_obj

I have some trouble here. I have multiple multi level data structure, maybe like data below:

    "data_a": [
        {
            "data_a_1": [
                {
                    "data_a_1_1": [
                        {
                            "data_a_1_1_1": "example_a_1_1_1",
                            "data_a_1_1_2": "example_a_1_1_2"
                        }
                    ]
                },
                {
                    "data_a_1_2_1": "Example a-1-2-1",
                    "data_a_1_2_2": "Example a-1-2-2"
                }
            ]
            "data_a_2": [
                {
                    "data_a_2_1": "Example a-2-1"
                },
                {
                    "data_a_2_2": "Example a-2-2"
                }
            ]
        }
    ]

My question is:

What is the best way to handle dynamic data structure like this? It will take a long hardcoded script to handle multiple multilevel data structure by override .create() as i mention above.

Any other best practice to handle mentioned data-strucure?

Body:
I found solution for this structure.

I read at the the DRF Documentation, there is a third-party package to handle parent-children relation easily drf-writable-nested

It helps me a lot to handle this kind data structure problem with out hardcoded .create() and .update(). This package provide special method to handle parent-child CRUD problem as i mentioned above.

Here is the example:

models.py:

class GrandChildModel(models.Model):
    name = models.CharField(max_length=32, blank=True, null=True)
    parent_id = models.ForeignKeyField(ChildModel, on_delete=CASCADE, related_name='grandchild')

class ChildModel(models.Model):
    name = models.CharField(max_length=32, blank=True, null=True)
    parent_id = models.ForeignKeyField(ParentModel, on_delete=CASCADE, related_name='child')

class ParentModel(models.Model):
    parent_name = model.CharField(max_length=32, blank=True, null=True)

serializer.py

from drf_writable_nested.serializers import WritableNestedModelSerializer

class GrandChildSerializer(serializers.ModelSerializer):
    class Meta:
        model=GrandChildModel
        fields = ["name"]

class ChildSerializer(WritableModelSerializer):
    grandchild = GrandChildSerializer(many=True)
    class Meta:
        model=ChildModel
        fields = ["name", "grandchild"]

class ParentSerializer(WritableModelSerializer):
    child = ChildSerializer(many=True)
    class Meta:
        model=ChildModelimport
        fields = ["name", "child"]

with this, you can process all kind of nested data :)


问:
Package.Dependency has no member Package
I am working on my app, and I keep getting this error when I add a package so I can import it.

```<code>error: type 'Package.Dependency' has no member 'Package'
</code>```

This is my Package.swift code:

```<code>// swift-tools-version:4.0
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
    name: "xHelp",
    dependencies: [
        .Package(url: "https://github.com/onevcat/Hedwig.git",
                 majorVersion: 1)
    ],
    targets: [
        // Targets are the basic building blocks of a package. A target can define a module or a test suite.
        // Targets can depend on other targets in this package, and on products in packages which this package depends on.
        .target(
            name: "xHelp",
            dependencies: ["Hedwig"]),
        .testTarget(
            name: "xHelpTests",
            dependencies: ["xHelp"]),
        ]
)
</code>```

I have tried this SO post, but it didn't work. What should I do here?

答:
Everything its okay only change capital P to p in

.Package(url: "https://github.com/onevcat/Hedwig.git",
                   majorVersion: 1)

to lowercase

.package(url: "https://github.com/onevcat/Hedwig.git",
                   majorVersion: 1)

Body:
I am working on my app, and I keep getting this error when I add a package so I can import it.

error: type 'Package.Dependency' has no member 'Package'

This is my Package.swift code:

// swift-tools-version:4.0
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
    name: "xHelp",
    dependencies: [
        .Package(url: "https://github.com/onevcat/Hedwig.git",
                 majorVersion: 1)
    ],
    targets: [
        // Targets are the basic building blocks of a package. A target can define a module or a test suite.
        // Targets can depend on other targets in this package, and on products in packages which this package depends on.
        .target(
            name: "xHelp",
            dependencies: ["Hedwig"]),
        .testTarget(
            name: "xHelpTests",
            dependencies: ["xHelp"]),
        ]
)

I have tried this SO post, but it didn't work. What should I do here?


答:
You are returning the address of local automatically allocated arrays. Those cease to exist when the function exits, which makes the returned address no longer valid.

Making the strings static keeps them alive all the time, fixing the issue.

Title: In a code segment of Hackerrank it was advised to make the string static. Why isn't the code working without static string?


问:
Image displaying behind the section after using overflow hidden
I am getting the horizontal scroll when using after class.

If I use overflow then my image is displaying behind the first section.

Would you help me out with these issues?

This is the after class which is not working. I am getting scrollbar

section {
  height: 400px;
  position: relative;
}

.test1 {
  overflow: hidden;
}

.test1:after {
  content: "";
  background-image: url('https://www.netclipart.com/pp/m/16-165891_sale-price-tag-png-sale-icon-png.png');
  background-repeat: no-repeat;
  background-size: contain;
  width: 350px;
  height: 308px;
  display: block;
  position: absolute;
  top: -15%;
  right: -10%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section style="background-color: #f8f8f8;">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
    dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</section>
<section class="test1">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
    dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </p>

</section></code>```

I am getting the output

My expected output

答:
Problem is img is relative to that div so it cut, Setting right
  0 and width to actual width of img solved that problem

section {
  height: 400px;
  position: relative;
}

.test1 {

}

.test1:after {
  content: "";
  background-image: url('https://www.netclipart.com/pp/m/16-165891_sale-price-tag-png-sale-icon-png.png');
  background-repeat: no-repeat;
  background-size: contain;
      width: 210px;
    height: 308px;
    display: block;
    position: absolute;
    top: -15%;
    right: 0;
 background-position: 47px center
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section style="background-color: #f8f8f8;">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
    dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</section>
<section class="test1">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
    dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </p>

</section></code>```

Body:
I am getting the horizontal scroll when using after class.

If I use overflow then my image is displaying behind the first section.

Would you help me out with these issues?

This is the after class which is not working. I am getting scrollbar

section {
  height: 400px;
  position: relative;
}

.test1 {
  overflow: hidden;
}

.test1:after {
  content: "";
  background-image: url('https://www.netclipart.com/pp/m/16-165891_sale-price-tag-png-sale-icon-png.png');
  background-repeat: no-repeat;
  background-size: contain;
  width: 350px;
  height: 308px;
  display: block;
  position: absolute;
  top: -15%;
  right: -10%;
}

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
    dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
    dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

I am getting the output

My expected output

Body:
Problem is img is relative to that div so it cut, Setting right
  0 and width to actual width of img solved that problem

section {
  height: 400px;
  position: relative;
}

.test1 {

}

.test1:after {
  content: "";
  background-image: url('https://www.netclipart.com/pp/m/16-165891_sale-price-tag-png-sale-icon-png.png');
  background-repeat: no-repeat;
  background-size: contain;
      width: 210px;
    height: 308px;
    display: block;
    position: absolute;
    top: -15%;
    right: 0;
 background-position: 47px center
}

<section style="background-color: #f8f8f8;">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
    dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</section>
<section class="test1">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
    dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
  </p>

</section>


问:
Facing issues in doing round off in Java
I have to show the fund value to customers for the next 30 years in one of my application , but the issue is there are some decimal values present , so we have to do the round off those values so that we will be calculated properly .e.g we there are values like, 414.598940334717 , it should round off to 414.60 but it is not getting round off with this function till 414.61 according to the spreadsheet.
I have written this method</p>

```<code>BigDecimal bd = new BigDecimal(Double.toString(414.598940334717));

bd = bd.setScale(2,BigDecimal.ROUND_HALF_UP );
</code>```

答:
I don't see your issue...

```<code>BigDecimal bd = new BigDecimal(Double.toString(414.598940334717));
bd = bd.setScale(2,BigDecimal.ROUND_HALF_UP );
System.out.println("" + bd);
</code>```

Output

414.60

My usual trick to do round-ups like this is to just use casting:

```<code>double d = 414.598940334717;
double rounded = (int)(d * 100 + 0.5) / 100.0;
System.out.println("" + rounded);
</code>```

Output

414.6

Body:
I have to show the fund value to customers for the next 30 years in one of my application , but the issue is there are some decimal values present , so we have to do the round off those values so that we will be calculated properly .e.g we there are values like, 414.598940334717 , it should round off to 414.60 but it is not getting round off with this function till 414.61 according to the spreadsheet.
I have written this method

BigDecimal bd = new BigDecimal(Double.toString(414.598940334717));

bd = bd.setScale(2,BigDecimal.ROUND_HALF_UP );

Body:
I don't see your issue...

BigDecimal bd = new BigDecimal(Double.toString(414.598940334717));
bd = bd.setScale(2,BigDecimal.ROUND_HALF_UP );
System.out.println("" + bd);

Output

414.60

My usual trick to do round-ups like this is to just use casting:

double d = 414.598940334717;
double rounded = (int)(d * 100 + 0.5) / 100.0;
System.out.println("" + rounded);

Output

414.6