问:
UITableView crashes when scrolling / index out of bounds for an array
Index out of bounds exception appears when I scroll UITableView,bug seems to appear in a function named checkTypes.
The problem is in this line:

```<code>listOfAllCells[i].cellTextBox.text = "\(value)"
</code>```

This is my ValuesTableViewController with a custom ValuesCell.

```    //
//  ValuesTableViewController.swift
//  UnitConverter
//
//

import UIKit

protocol Initializable {
    init()
}
//Treba odraditi kalkulaciju unita za svaki treba popraviti bug koji se desi kod nasledjivanja

class ValuesTableViewController: UITableViewController, Initializable, UITextFieldDelegate {

    @IBOutlet var valuesTableView: UITableView!
    var valueName: String?
    var selectedValueObject: Properties?
    var listOfAllUnitObjects = [AnyObject]()
    var doubleTextValue : Double?
    var listOfAllCells = [ValuesCell]()
    var returningCalculatedValue : Double?
   // var testTextField : UITextField
    //"m²","km²","ha","dm²","cm²","mm²","sq mi", "ac", "sq yd","sq ft", "sq in"
   // var areaValues: [String: Area] = ["m²": Acre(), "km²": SquareKilometer(), "ha": Hectare(), "dm²": SquareDecimeter(), ""]
    //var listOfAllUnitsInClass = [Acre,Hectare,SquareCentimeter,SquareDecimeter,SquareFoot,SquareInch,]

    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
         valuesTableView.register(UINib(nibName: "ValuesCell", bundle: nil), forCellReuseIdentifier: "valueCell")

//        let myclass = stringClassFromString(valuesObject.textValue) as! Properties
//        let instance = myclass.init()
       // print("All units in selected Class : \(listOfAllUnitObjects)")
//       let testLista = testCalculation()
//        for object in testLista {
//            print("Ovo pokusavam da napravim : \(object)")
////        object as! Properties
////        let newType = type(of: object)
////        let createObject = createInstance(typeThing: newType)
//        /*
//        let acreTest = Acre()
//        print(acreTest.ConvertFromMainUnitToUnit(entryValue: 200))
//        print(testLista)
//         */

//        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

//    override func numberOfSections(in tableView: UITableView) -> Int {
//        // #warning Incomplete implementation, return the number of sections
//        return 0
//    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        let valuesType = configureTable()
        let valuesObject = createInstance(typeThing: valuesType)

      return valuesObject.listOfMainLabels.count

    }
    func textFieldDidBeginEditing(_ textField: UITextField) {
        textField.text = ""
    }
    func textFieldDidEndEditing(_ textField: UITextField) {
        //Ovde nastaje problem jer uzima prethodno unetu vrednost umesto novu

        //if textField.text != "" {
            if let textInputValue = textField.text {
                if Double(textInputValue) != nil {
                    if let doubleTextValueInput = Double(textInputValue){
                        doubleTextValue = doubleTextValueInput
                        //vratiti vrednost textfielda nakon promene da bi se input iskoristio za racunanje
                        let valuesType = configureTable()
                        let valuesObject = createInstance(typeThing: valuesType)
                        if let returnCalculatedValue = returningCalculatedValue {
                            checkTypes(allCells: listOfAllCells, entryValues: returnCalculatedValue, valuesObject: valuesObject)
                            print("Prolazi unesena vrednost za novo racunanje je \(returnCalculatedValue)")
                            valuesTableView.reloadData()
                        }
                        self.view.endEditing(true)
                    }

                }
            }
        //}
    }
    func configureTable() -> Properties.Type {

        //Check to see if the sent string is equal to any of the existing objects
        //if it is equal then create that object and append all of its values to tableView

        //Napravi listu svih objekata pusti u petlju iteraciju vidi da li je string jednak
        //nekom od objekata.text ako jeste stopiraj je i kraj
        if let valueNameUnwrapped = valueName {
        let valueNamesTrimmed = valueNameUnwrapped.trimmingCharacters(in: .whitespaces)
//            print("This is 2nd step: \(valueNamesTrimmed)")
        let allValuesList = AllValues()
        for value in allValuesList.listValues {
            //print("Vrednosti \(value.textValue)")
            switch valueNamesTrimmed {
            case value.textValue:
//                print("Izabrano je \(value.textValue)")
                selectedValueObject = value
                if let selectedObject = selectedValueObject{
                    selectedValueObject?.textValue = value.textValue
                   // selectedValueObject?.colorValue = value.colorValue
                    selectedValueObject?.tagValue = value.tagValue
                    let typeOfObject = type(of: selectedObject)
                    return typeOfObject
                }
            default:
                if let selectedObject = selectedValueObject{
                    selectedValueObject?.textValue = value.textValue
                   // selectedValueObject?.colorValue = value.colorValue
                    selectedValueObject?.tagValue = value.tagValue
                    let typeOfObject = type(of: selectedObject)
                    return typeOfObject
                }
            }
        }
        }
        return type(of: selectedValueObject) as! Properties.Type
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "valueCell", for: indexPath) as! ValuesCell
        if indexPath.row == 0 {
            cell.cellView.backgroundColor = UIColor.white
        }
        let valuesType = configureTable()
        let valuesObject = createInstance(typeThing: valuesType)

        let currentClassName = valuesObject.listOfAllUnits[indexPath.row]
        let unitObject = stringClassFromString(currentClassName)

        //Napraviti da u izabranom Unitu Navigacija bude iste boje kao na prethodnom screenu
        cell.cellMainLbl.text = valuesObject.listOfMainLabels[indexPath.row]
        cell.cellSmallLbl.text = valuesObject.listofSmallLabels[indexPath.row]
//            cell.valueLabel.textColor = UIColor.init(red: CGFloat(rColorValue[indexPath.row]), green: CGFloat(gColorValue[indexPath.row]), blue: CGFloat(bColorValue[indexPath.row]), alpha: 1.0)
//            cell.leftColorView.backgroundColor = UIColor.init(red: CGFloat(rColorValue[indexPath.row]), green: CGFloat(gColorValue[indexPath.row]), blue: CGFloat(bColorValue[indexPath.row]), alpha: 1.0)
        cell.tag = indexPath.row
        listOfAllCells.append(cell)
        //listOfAllUnitObjects.append(unitObject)
        if let unitObjectUnwrapped = unitObject {
            listOfAllUnitObjects.append(unitObjectUnwrapped)
        }
//        for unit in valuesObject.listOfAllUnits {
//            let unitObject = stringClassFromString(unit)
//            if let unitObjectUnwrapped = unitObject {
//                listOfAllUnitObjects.append(unitObjectUnwrapped)
//            }
//
//
//        }

//        //cell.imageView?.image = UIImage(named: fruitName)
//        cell.rightValueImage.image = UIImage(named: "\(indexPath.row)")

        // Configure the cell...
        return cell
    }
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        let valuesType = configureTable()
        let valuesObject = createInstance(typeThing: valuesType)
        checkTypes(allCells: listOfAllCells,entryValues: 1, valuesObject: valuesObject)
        valuesTableView.tableFooterView = UIView()
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let valuesType = configureTable()
        let valuesObject = createInstance(typeThing: valuesType)
        let cell = tableView.cellForRow(at: indexPath) as! ValuesCell
        if indexPath.row != 0 {
           //let changeFirstCellColor = getCellsData()
         //   changeFirstCellColor[0].cellView.backgroundColor = UIColor.init(red: 232, green: 232, blue: 232, alpha: 1)

        }
        cell.cellView.backgroundColor = UIColor.white
//        print("Ovo su glavne vrednosti za racunanje \(listOfAllUnitObjects)")
//        let finalList = listOfAllUnitObjects as? [Properties]
//        print("Ovde je bio pucao program: \(String(describing: finalList))")
//        let mainToUnit = finalList[indexPath.row].ConvertFromMainUnitToUnit(entryValue: 20)
//        let unitToMain = finalList[indexPath.row].ConvertFromUnitToMainUnit(entryValue: 20)
//        cell.cellTextBox.value(forKey: "\(mainToUnit)")
        cell.cellTextBox.delegate = self
        if let doubleValue = doubleTextValue{
            //Ovde nastaje problem jer samo vrati unetu vrednost
            let entryValueReturned = checkTypesForSelected(indexPath: indexPath, cell: cell, entryValues: doubleValue, valuesObject: valuesObject)
            returningCalculatedValue = entryValueReturned
            if let returnCalculatedValue = returningCalculatedValue {
                print("Vracam vrednost od rezultata checkTypes funkcije za uneti broj \(doubleValue) rezultat je : \(returnCalculatedValue)")
            }

        }
        self.view.endEditing(true)

    }
    func checkTypes<T>(allCells: [ValuesCell],entryValues: Double, valuesObject: T){
        if valuesObject is Area {

        let classValues: [Area.Type] = [SquareMeter.self, SquareKilometer.self, Hectare.self, SquareDecimeter.self,
                                        SquareCentimeter.self, SquareMillimeter.self, SquareMile.self, Acre.self,
                                        SquareYard.self, SquareFoot.self, SquareInch.self]

            for i in 0...(listOfAllCells.count - 1){
                let object = classValues[i].init()
                let value = object.ConvertFromMainUnitToUnit(entryValue: entryValues)
                print("Vracam vrednost druge metode za \(i) element je : \(value)")
                listOfAllCells[i].cellTextBox.text = "\(value)"
            }
        }

    }
    func checkTypesForSelected<T>(indexPath: IndexPath, cell: ValuesCell,entryValues: Double, valuesObject: T) -> Double{
        if valuesObject is Area {

            let classValues: [Area.Type] = [SquareMeter.self, SquareKilometer.self, Hectare.self, SquareDecimeter.self,
                                            SquareCentimeter.self, SquareMillimeter.self, SquareMile.self, Acre.self,
                                            SquareYard.self, SquareFoot.self, SquareInch.self]
            if listOfAllUnitObjects[indexPath.row] is SquareMeter.Type {
                var testObject = classValues[indexPath.row].init()
                testObject = createInstance(typeThing: (listOfAllUnitObjects[indexPath.row] as? SquareMeter.Type)!)
                print("Zavrseno RADI! \(testObject)")
                let value = testObject.ConvertFromUnitToMainUnit(entryValue: entryValues)
                cell.cellTextBox.text = "\(value)"
                return value
            } else if listOfAllUnitObjects[indexPath.row] is SquareKilometer.Type {
                var testObject = classValues[indexPath.row].init()
                testObject = createInstance(typeThing: (listOfAllUnitObjects[indexPath.row] as? SquareKilometer.Type)!)
                print("Zavrseno RADI! \(testObject)")
                let value = testObject.ConvertFromUnitToMainUnit(entryValue: entryValues)
                cell.cellTextBox.text = "\(value)"
                return value
            }else if listOfAllUnitObjects[indexPath.row] is Hectare.Type{
                var testObject = classValues[indexPath.row].init()
                testObject = createInstance(typeThing: (listOfAllUnitObjects[indexPath.row] as? Hectare.Type)!)
                print("Zavrseno RADI! \(testObject)")
                let value = testObject.ConvertFromUnitToMainUnit(entryValue: entryValues)
                cell.cellTextBox.text = "\(value)"
                return value
            }else if listOfAllUnitObjects[indexPath.row] is SquareDecimeter.Type{
                var testObject = classValues[indexPath.row].init()
                testObject = createInstance(typeThing: (listOfAllUnitObjects[indexPath.row] as? SquareDecimeter.Type)!)
                print("Zavrseno RADI! \(testObject)")
                let value = testObject.ConvertFromUnitToMainUnit(entryValue: entryValues)
                cell.cellTextBox.text = "\(value)"
                return value
            }else if listOfAllUnitObjects[indexPath.row] is SquareCentimeter.Type{
                var testObject = classValues[indexPath.row].init()
                testObject = createInstance(typeThing: (listOfAllUnitObjects[indexPath.row] as? SquareCentimeter.Type)!)
                print("Zavrseno RADI! \(testObject)")
                let value = testObject.ConvertFromUnitToMainUnit(entryValue: entryValues)
                cell.cellTextBox.text = "\(value)"
                return value
            }else if listOfAllUnitObjects[indexPath.row] is SquareMillimeter.Type{
                var testObject = classValues[indexPath.row].init()
                testObject = createInstance(typeThing: (listOfAllUnitObjects[indexPath.row] as? SquareMillimeter.Type)!)
                print("Zavrseno RADI! \(testObject)")
                let value = testObject.ConvertFromUnitToMainUnit(entryValue: entryValues)
                cell.cellTextBox.text = "\(value)"
                return value
            }else if listOfAllUnitObjects[indexPath.row] is SquareCentimeter.Type{
                var testObject = classValues[indexPath.row].init()
                testObject = createInstance(typeThing: (listOfAllUnitObjects[indexPath.row] as? SquareCentimeter.Type)!)
                print("Zavrseno RADI! \(testObject)")
                let value = testObject.ConvertFromUnitToMainUnit(entryValue: entryValues)
                cell.cellTextBox.text = "\(value)"
                return value
            }else if listOfAllUnitObjects[indexPath.row] is SquareMile.Type{
                var testObject = classValues[indexPath.row].init()
                testObject = createInstance(typeThing: (listOfAllUnitObjects[indexPath.row] as? SquareMile.Type)!)
                print("Zavrseno RADI! \(testObject)")
                let value = testObject.ConvertFromUnitToMainUnit(entryValue: entryValues)
                cell.cellTextBox.text = "\(value)"
                return value
            }else if listOfAllUnitObjects[indexPath.row] is Acre.Type{
                var testObject = classValues[indexPath.row].init()
                testObject = createInstance(typeThing: (listOfAllUnitObjects[indexPath.row] as? Acre.Type)!)
                print("Zavrseno RADI! \(testObject)")
                let value = testObject.ConvertFromUnitToMainUnit(entryValue: entryValues)
                cell.cellTextBox.text = "\(value)"
                return value
            }else if listOfAllUnitObjects[indexPath.row] is SquareYard.Type{
                var testObject = classValues[indexPath.row].init()
                testObject = createInstance(typeThing: (listOfAllUnitObjects[indexPath.row] as? SquareYard.Type)!)
                print("Zavrseno RADI! \(testObject)")
                let value = testObject.ConvertFromUnitToMainUnit(entryValue: entryValues)
                cell.cellTextBox.text = "\(value)"
                return value
            }else if listOfAllUnitObjects[indexPath.row] is SquareFoot.Type{
                var testObject = classValues[indexPath.row].init()
                testObject = createInstance(typeThing: (listOfAllUnitObjects[indexPath.row] as? SquareFoot.Type)!)
                print("Zavrseno RADI! \(testObject)")
                let value = testObject.ConvertFromUnitToMainUnit(entryValue: entryValues)
                cell.cellTextBox.text = "\(value)"
                return value
            }else if listOfAllUnitObjects[indexPath.row] is SquareInch.Type{
                var testObject = classValues[indexPath.row].init()
                testObject = createInstance(typeThing: (listOfAllUnitObjects[indexPath.row] as? SquareInch.Type)!)
                print("Zavrseno RADI! \(testObject)")
                let value = testObject.ConvertFromUnitToMainUnit(entryValue: entryValues)
                cell.cellTextBox.text = "\(value)"
                return value
            }

        }
        return 0
    }
//    func calculateAllUnits(){
//        let allCells = getCellsData()
//        for cell in allCells {
//            cell.cellTextBox.text = ""
//        }
//    }
    //Pravi objekat od typa Klase
    func createInstance<T>(typeThing:T.Type) -> T where T:Initializable {
        return typeThing.init()
    }

    func stringClassFromString(_ className: String) -> AnyClass! {

        /// get namespace
        let namespace = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String;

        /// get 'anyClass' with classname and namespace
        let cls: AnyClass = NSClassFromString("\(namespace).\(className)")!;

        // return AnyClass!
        return cls;
    }
//    func getCellsData() -> [ValuesCell] {
//        var dataArray: [ValuesCell] = []
//        for section in 0 ..< self.valuesTableView.numberOfSections {
//            for row in 0 ..< self.valuesTableView.numberOfRows(inSection: section) {
//                let indexPath = NSIndexPath(row: row, section: section)
//                let cell = self.valuesTableView.cellForRow(at: indexPath as IndexPath) as! ValuesCell
//                dataArray.append(cell)
//            }
//        }
//        return dataArray
//    }

    //Neka prikaze ne keyboard sa slovima nego samo sa brojkama da ogranicimo korisnika
//    func textFieldDidBeginEditing(_ textField: UITextField) {
//
//    }
//    func textFieldDidEndEditing(_ textField: UITextField) {
//        <#code#>
//    }
//    func testCalculation() -> [AnyObject]{
//        let valuesType = configureTable()
//        let valuesObject = createInstance(typeThing: valuesType)
//        let list = valuesObject.listOfAllUnits
//        var listOfAllUnitValues = [AnyObject]()
//        print("Broj koliko ima elementa u listi : \(list.count)")
//        for i in 0...(list.count - 1) {
//            let object1 = stringClassFromString(list[i]) as AnyObject
//            listOfAllUnitValues.append(object1)
//        }
//        return listOfAllUnitValues
//
//    }
    //Napraviti Dictionary key value da bude labela iz celije, a vrednost da bude ta klasa, posle povezati
//    func makeAllUnitObjects() -> [Properties] {
//       let listOfAllCells = getCellsData()
//        for i in 0...listOfAllCells.count {
//            let test = listOfAllCells[i]
//        }
//    }
    /*
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
```

答:
I managed to figure out what was the problem, because uitableview generates cells depending on how many cells u can see, my listOfAllCells was appending constantly. Fix was in cellForRowAt:

```<code>if valuesObject.listOfMainLabels.count - 1 >= listOfAllCells.count {
            listOfAllCells.append(cell)
}
</code>```

As you can see 1 if statement fixed the issue thanks for responding to this thread, if anyone has any suggestions about my code I'm gladly to hear cause I just started developing I'm a beginner and every suggestion makes me better.

Body:
Index out of bounds exception appears when I scroll UITableView,bug seems to appear in a function named checkTypes.
The problem is in this line:

listOfAllCells[i].cellTextBox.text = "\(value)"

This is my ValuesTableViewController with a custom ValuesCell.

    //
//  ValuesTableViewController.swift
//  UnitConverter
//
//

import UIKit

protocol Initializable {
    init()
}
//Treba odraditi kalkulaciju unita za svaki treba popraviti bug koji se desi kod nasledjivanja

class ValuesTableViewController: UITableViewController, Initializable, UITextFieldDelegate {

    @IBOutlet var valuesTableView: UITableView!
    var valueName: String?
    var selectedValueObject: Properties?
    var listOfAllUnitObjects = [AnyObject]()
    var doubleTextValue : Double?
    var listOfAllCells = [ValuesCell]()
    var returningCalculatedValue : Double?
   // var testTextField : UITextField
    //"m²","km²","ha","dm²","cm²","mm²","sq mi", "ac", "sq yd","sq ft", "sq in"
   // var areaValues: [String: Area] = ["m²": Acre(), "km²": SquareKilometer(), "ha": Hectare(), "dm²": SquareDecimeter(), ""]
    //var listOfAllUnitsInClass = [Acre,Hectare,SquareCentimeter,SquareDecimeter,SquareFoot,SquareInch,]

    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
         valuesTableView.register(UINib(nibName: "ValuesCell", bundle: nil), forCellReuseIdentifier: "valueCell")

//        let myclass = stringClassFromString(valuesObject.textValue) as! Properties
//        let instance = myclass.init()
       // print("All units in selected Class : \(listOfAllUnitObjects)")
//       let testLista = testCalculation()
//        for object in testLista {
//            print("Ovo pokusavam da napravim : \(object)")
////        object as! Properties
////        let newType = type(of: object)
////        let createObject = createInstance(typeThing: newType)
//        /*
//        let acreTest = Acre()
//        print(acreTest.ConvertFromMainUnitToUnit(entryValue: 200))
//        print(testLista)
//         */

//        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

//    override func numberOfSections(in tableView: UITableView) -> Int {
//        // #warning Incomplete implementation, return the number of sections
//        return 0
//    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        let valuesType = configureTable()
        let valuesObject = createInstance(typeThing: valuesType)

      return valuesObject.listOfMainLabels.count

    }
    func textFieldDidBeginEditing(_ textField: UITextField) {
        textField.text = ""
    }
    func textFieldDidEndEditing(_ textField: UITextField) {
        //Ovde nastaje problem jer uzima prethodno unetu vrednost umesto novu

        //if textField.text != "" {
            if let textInputValue = textField.text {
                if Double(textInputValue) != nil {
                    if let doubleTextValueInput = Double(textInputValue){
                        doubleTextValue = doubleTextValueInput
                        //vratiti vrednost textfielda nakon promene da bi se input iskoristio za racunanje
                        let valuesType = configureTable()
                        let valuesObject = createInstance(typeThing: valuesType)
                        if let returnCalculatedValue = returningCalculatedValue {
                            checkTypes(allCells: listOfAllCells, entryValues: returnCalculatedValue, valuesObject: valuesObject)
                            print("Prolazi unesena vrednost za novo racunanje je \(returnCalculatedValue)")
                            valuesTableView.reloadData()
                        }
                        self.view.endEditing(true)
                    }

                }
            }
        //}
    }
    func configureTable() -> Properties.Type {

        //Check to see if the sent string is equal to any of the existing objects
        //if it is equal then create that object and append all of its values to tableView

        //Napravi listu svih objekata pusti u petlju iteraciju vidi da li je string jednak
        //nekom od objekata.text ako jeste stopiraj je i kraj
        if let valueNameUnwrapped = valueName {
        let valueNamesTrimmed = valueNameUnwrapped.trimmingCharacters(in: .whitespaces)
//            print("This is 2nd step: \(valueNamesTrimmed)")
        let allValuesList = AllValues()
        for value in allValuesList.listValues {
            //print("Vrednosti \(value.textValue)")
            switch valueNamesTrimmed {
            case value.textValue:
//                print("Izabrano je \(value.textValue)")
                selectedValueObject = value
                if let selectedObject = selectedValueObject{
                    selectedValueObject?.textValue = value.textValue
                   // selectedValueObject?.colorValue = value.colorValue
                    selectedValueObject?.tagValue = value.tagValue
                    let typeOfObject = type(of: selectedObject)
                    return typeOfObject
                }
            default:
                if let selectedObject = selectedValueObject{
                    selectedValueObject?.textValue = value.textValue
                   // selectedValueObject?.colorValue = value.colorValue
                    selectedValueObject?.tagValue = value.tagValue
                    let typeOfObject = type(of: selectedObject)
                    return typeOfObject
                }
            }
        }
        }
        return type(of: selectedValueObject) as! Properties.Type
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "valueCell", for: indexPath) as! ValuesCell
        if indexPath.row == 0 {
            cell.cellView.backgroundColor = UIColor.white
        }
        let valuesType = configureTable()
        let valuesObject = createInstance(typeThing: valuesType)

        let currentClassName = valuesObject.listOfAllUnits[indexPath.row]
        let unitObject = stringClassFromString(currentClassName)

        //Napraviti da u izabranom Unitu Navigacija bude iste boje kao na prethodnom screenu
        cell.cellMainLbl.text = valuesObject.listOfMainLabels[indexPath.row]
        cell.cellSmallLbl.text = valuesObject.listofSmallLabels[indexPath.row]
//            cell.valueLabel.textColor = UIColor.init(red: CGFloat(rColorValue[indexPath.row]), green: CGFloat(gColorValue[indexPath.row]), blue: CGFloat(bColorValue[indexPath.row]), alpha: 1.0)
//            cell.leftColorView.backgroundColor = UIColor.init(red: CGFloat(rColorValue[indexPath.row]), green: CGFloat(gColorValue[indexPath.row]), blue: CGFloat(bColorValue[indexPath.row]), alpha: 1.0)
        cell.tag = indexPath.row
        listOfAllCells.append(cell)
        //listOfAllUnitObjects.append(unitObject)
        if let unitObjectUnwrapped = unitObject {
            listOfAllUnitObjects.append(unitObjectUnwrapped)
        }
//        for unit in valuesObject.listOfAllUnits {
//            let unitObject = stringClassFromString(unit)
//            if let unitObjectUnwrapped = unitObject {
//                listOfAllUnitObjects.append(unitObjectUnwrapped)
//            }
//
//
//        }

//        //cell.imageView?.image = UIImage(named: fruitName)
//        cell.rightValueImage.image = UIImage(named: "\(indexPath.row)")

        // Configure the cell...
        return cell
    }
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        let valuesType = configureTable()
        let valuesObject = createInstance(typeThing: valuesType)
        checkTypes(allCells: listOfAllCells,entryValues: 1, valuesObject: valuesObject)
        valuesTableView.tableFooterView = UIView()
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let valuesType = configureTable()
        let valuesObject = createInstance(typeThing: valuesType)
        let cell = tableView.cellForRow(at: indexPath) as! ValuesCell
        if indexPath.row != 0 {
           //let changeFirstCellColor = getCellsData()
         //   changeFirstCellColor[0].cellView.backgroundColor = UIColor.init(red: 232, green: 232, blue: 232, alpha: 1)

        }
        cell.cellView.backgroundColor = UIColor.white
//        print("Ovo su glavne vrednosti za racunanje \(listOfAllUnitObjects)")
//        let finalList = listOfAllUnitObjects as? [Properties]
//        print("Ovde je bio pucao program: \(String(describing: finalList))")
//        let mainToUnit = finalList[indexPath.row].ConvertFromMainUnitToUnit(entryValue: 20)
//        let unitToMain = finalList[indexPath.row].ConvertFromUnitToMainUnit(entryValue: 20)
//        cell.cellTextBox.value(forKey: "\(mainToUnit)")
        cell.cellTextBox.delegate = self
        if let doubleValue = doubleTextValue{
            //Ovde nastaje problem jer samo vrati unetu vrednost
            let entryValueReturned = checkTypesForSelected(indexPath: indexPath, cell: cell, entryValues: doubleValue, valuesObject: valuesObject)
            returningCalculatedValue = entryValueReturned
            if let returnCalculatedValue = returningCalculatedValue {
                print("Vracam vrednost od rezultata checkTypes funkcije za uneti broj \(doubleValue) rezultat je : \(returnCalculatedValue)")
            }

        }
        self.view.endEditing(true)

    }
    func checkTypes<T>(allCells: [ValuesCell],entryValues: Double, valuesObject: T){
        if valuesObject is Area {

        let classValues: [Area.Type] = [SquareMeter.self, SquareKilometer.self, Hectare.self, SquareDecimeter.self,
                                        SquareCentimeter.self, SquareMillimeter.self, SquareMile.self, Acre.self,
                                        SquareYard.self, SquareFoot.self, SquareInch.self]

            for i in 0...(listOfAllCells.count - 1){
                let object = classValues[i].init()
                let value = object.ConvertFromMainUnitToUnit(entryValue: entryValues)
                print("Vracam vrednost druge metode za \(i) element je : \(value)")
                listOfAllCells[i].cellTextBox.text = "\(value)"
            }
        }

    }
    func checkTypesForSelected<T>(indexPath: IndexPath, cell: ValuesCell,entryValues: Double, valuesObject: T) -> Double{
        if valuesObject is Area {

            let classValues: [Area.Type] = [SquareMeter.self, SquareKilometer.self, Hectare.self, SquareDecimeter.self,
                                            SquareCentimeter.self, SquareMillimeter.self, SquareMile.self, Acre.self,
                                            SquareYard.self, SquareFoot.self, SquareInch.self]
            if listOfAllUnitObjects[indexPath.row] is SquareMeter.Type {
                var testObject = classValues[indexPath.row].init()
                testObject = createInstance(typeThing: (listOfAllUnitObjects[indexPath.row] as? SquareMeter.Type)!)
                print("Zavrseno RADI! \(testObject)")
                let value = testObject.ConvertFromUnitToMainUnit(entryValue: entryValues)
                cell.cellTextBox.text = "\(value)"
                return value
            } else if listOfAllUnitObjects[indexPath.row] is SquareKilometer.Type {
                var testObject = classValues[indexPath.row].init()
                testObject = createInstance(typeThing: (listOfAllUnitObjects[indexPath.row] as? SquareKilometer.Type)!)
                print("Zavrseno RADI! \(testObject)")
                let value = testObject.ConvertFromUnitToMainUnit(entryValue: entryValues)
                cell.cellTextBox.text = "\(value)"
                return value
            }else if listOfAllUnitObjects[indexPath.row] is Hectare.Type{
                var testObject = classValues[indexPath.row].init()
                testObject = createInstance(typeThing: (listOfAllUnitObjects[indexPath.row] as? Hectare.Type)!)
                print("Zavrseno RADI! \(testObject)")
                let value = testObject.ConvertFromUnitToMainUnit(entryValue: entryValues)
                cell.cellTextBox.text = "\(value)"
                return value
            }else if listOfAllUnitObjects[indexPath.row] is SquareDecimeter.Type{
                var testObject = classValues[indexPath.row].init()
                testObject = createInstance(typeThing: (listOfAllUnitObjects[indexPath.row] as? SquareDecimeter.Type)!)
                print("Zavrseno RADI! \(testObject)")
                let value = testObject.ConvertFromUnitToMainUnit(entryValue: entryValues)
                cell.cellTextBox.text = "\(value)"
                return value
            }else if listOfAllUnitObjects[indexPath.row] is SquareCentimeter.Type{
                var testObject = classValues[indexPath.row].init()
                testObject = createInstance(typeThing: (listOfAllUnitObjects[indexPath.row] as? SquareCentimeter.Type)!)
                print("Zavrseno RADI! \(testObject)")
                let value = testObject.ConvertFromUnitToMainUnit(entryValue: entryValues)
                cell.cellTextBox.text = "\(value)"
                return value
            }else if listOfAllUnitObjects[indexPath.row] is SquareMillimeter.Type{
                var testObject = classValues[indexPath.row].init()
                testObject = createInstance(typeThing: (listOfAllUnitObjects[indexPath.row] as? SquareMillimeter.Type)!)
                print("Zavrseno RADI! \(testObject)")
                let value = testObject.ConvertFromUnitToMainUnit(entryValue: entryValues)
                cell.cellTextBox.text = "\(value)"
                return value
            }else if listOfAllUnitObjects[indexPath.row] is SquareCentimeter.Type{
                var testObject = classValues[indexPath.row].init()
                testObject = createInstance(typeThing: (listOfAllUnitObjects[indexPath.row] as? SquareCentimeter.Type)!)
                print("Zavrseno RADI! \(testObject)")
                let value = testObject.ConvertFromUnitToMainUnit(entryValue: entryValues)
                cell.cellTextBox.text = "\(value)"
                return value
            }else if listOfAllUnitObjects[indexPath.row] is SquareMile.Type{
                var testObject = classValues[indexPath.row].init()
                testObject = createInstance(typeThing: (listOfAllUnitObjects[indexPath.row] as? SquareMile.Type)!)
                print("Zavrseno RADI! \(testObject)")
                let value = testObject.ConvertFromUnitToMainUnit(entryValue: entryValues)
                cell.cellTextBox.text = "\(value)"
                return value
            }else if listOfAllUnitObjects[indexPath.row] is Acre.Type{
                var testObject = classValues[indexPath.row].init()
                testObject = createInstance(typeThing: (listOfAllUnitObjects[indexPath.row] as? Acre.Type)!)
                print("Zavrseno RADI! \(testObject)")
                let value = testObject.ConvertFromUnitToMainUnit(entryValue: entryValues)
                cell.cellTextBox.text = "\(value)"
                return value
            }else if listOfAllUnitObjects[indexPath.row] is SquareYard.Type{
                var testObject = classValues[indexPath.row].init()
                testObject = createInstance(typeThing: (listOfAllUnitObjects[indexPath.row] as? SquareYard.Type)!)
                print("Zavrseno RADI! \(testObject)")
                let value = testObject.ConvertFromUnitToMainUnit(entryValue: entryValues)
                cell.cellTextBox.text = "\(value)"
                return value
            }else if listOfAllUnitObjects[indexPath.row] is SquareFoot.Type{
                var testObject = classValues[indexPath.row].init()
                testObject = createInstance(typeThing: (listOfAllUnitObjects[indexPath.row] as? SquareFoot.Type)!)
                print("Zavrseno RADI! \(testObject)")
                let value = testObject.ConvertFromUnitToMainUnit(entryValue: entryValues)
                cell.cellTextBox.text = "\(value)"
                return value
            }else if listOfAllUnitObjects[indexPath.row] is SquareInch.Type{
                var testObject = classValues[indexPath.row].init()
                testObject = createInstance(typeThing: (listOfAllUnitObjects[indexPath.row] as? SquareInch.Type)!)
                print("Zavrseno RADI! \(testObject)")
                let value = testObject.ConvertFromUnitToMainUnit(entryValue: entryValues)
                cell.cellTextBox.text = "\(value)"
                return value
            }

        }
        return 0
    }
//    func calculateAllUnits(){
//        let allCells = getCellsData()
//        for cell in allCells {
//            cell.cellTextBox.text = ""
//        }
//    }
    //Pravi objekat od typa Klase
    func createInstance<T>(typeThing:T.Type) -> T where T:Initializable {
        return typeThing.init()
    }

    func stringClassFromString(_ className: String) -> AnyClass! {

        /// get namespace
        let namespace = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String;

        /// get 'anyClass' with classname and namespace
        let cls: AnyClass = NSClassFromString("\(namespace).\(className)")!;

        // return AnyClass!
        return cls;
    }
//    func getCellsData() -> [ValuesCell] {
//        var dataArray: [ValuesCell] = []
//        for section in 0 ..< self.valuesTableView.numberOfSections {
//            for row in 0 ..< self.valuesTableView.numberOfRows(inSection: section) {
//                let indexPath = NSIndexPath(row: row, section: section)
//                let cell = self.valuesTableView.cellForRow(at: indexPath as IndexPath) as! ValuesCell
//                dataArray.append(cell)
//            }
//        }
//        return dataArray
//    }

    //Neka prikaze ne keyboard sa slovima nego samo sa brojkama da ogranicimo korisnika
//    func textFieldDidBeginEditing(_ textField: UITextField) {
//
//    }
//    func textFieldDidEndEditing(_ textField: UITextField) {
//        <#code#>
//    }
//    func testCalculation() -> [AnyObject]{
//        let valuesType = configureTable()
//        let valuesObject = createInstance(typeThing: valuesType)
//        let list = valuesObject.listOfAllUnits
//        var listOfAllUnitValues = [AnyObject]()
//        print("Broj koliko ima elementa u listi : \(list.count)")
//        for i in 0...(list.count - 1) {
//            let object1 = stringClassFromString(list[i]) as AnyObject
//            listOfAllUnitValues.append(object1)
//        }
//        return listOfAllUnitValues
//
//    }
    //Napraviti Dictionary key value da bude labela iz celije, a vrednost da bude ta klasa, posle povezati
//    func makeAllUnitObjects() -> [Properties] {
//       let listOfAllCells = getCellsData()
//        for i in 0...listOfAllCells.count {
//            let test = listOfAllCells[i]
//        }
//    }
    /*
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

Body:
I managed to figure out what was the problem, because uitableview generates cells depending on how many cells u can see, my listOfAllCells was appending constantly. Fix was in cellForRowAt:

if valuesObject.listOfMainLabels.count - 1 >= listOfAllCells.count {
            listOfAllCells.append(cell)
}

As you can see 1 if statement fixed the issue thanks for responding to this thread, if anyone has any suggestions about my code I'm gladly to hear cause I just started developing I'm a beginner and every suggestion makes me better.


来源: stackexchange

问:
Google Tag Manager Trigger equals multiple classes
I have a lookup table set up for a variable.

What's working is when I do a trigger for something like:

Variable Name equals Lookup Table Value 1

But what I need is something like:

Variable Name equals Lookup Table Value 1 or Lookup Table Value 2

I tried what amounts to:

Variable Name equals Lookup Table Value 1, Lookup Table Value 2 but that didn't work.

Is there basically a way to do an "or" for triggers using variables like this?

答:
Instead of using Variable Name equals Lookup Table Value 1 or Lookup Table Value 2

you should use Variable Name matches regEx(ignore case) Lookup Table Value 1 | Lookup Table Value 2

Notice the |

ContentLicense: CC BY-SA 3.0


问:
Binary tree inorder traversal using Prolog
I am trying to implement an inorder traversal which in every stage I'll get the current node.
For example:

```<code>?- getnodesinorder(tree(1,nil,nil),X).
X = 1 ;
false.

?- getnodesinorder(tree(5,tree(4,tree(1,nil,tree(3,tree(2,nil,nil),nil)),nil),tree(6,nil,nil)),X).
X = 1 ;
X = 2 ;
X = 3 ;
X = 4 ;
X = 5 ;
X = 6 ;
false.
</code>```

I've tried the next code:

```<code>getnodesinorder(tree(CurrentNode,nil,nil), CurrentNode).
getnodesinorder(tree(X, Left, nil), CurrentNode) :-
    getnodesinorder(Left, _ ),
    CurrentNode is X.
getnodesinorder(tree(X, nil, Right), CurrentNode) :-
    CurrentNode is X,
    getnodesinorder(Right, _ ).
getnodesinorder(tree(X, Left, Right), CurrentNode) :-
    getnodesinorder(Left, _ ),
    CurrentNode is X,
    getnodesinorder(Right, _ ).
</code>```

So of course the base (1st example works) but when trying to run the 2nd one I  get

```<code>X=5;
false
</code>```

as result. Why is that?

答:
```<code>[test] λ = cat test.pl
append([], Ys, Ys).
append([X|Xs], Ys, [X|Zs]) :- append(Xs, Ys, Zs).

getnodesinorder(nil, []).

getnodesinorder(tree(X, Left, Right), R) :-
   getnodesinorder(Left,R1),
   getnodesinorder(Right,R2),
   append(R1,[X|R2],R).
</code>```

Works for me

```<code>?-getnodesinorder(tree(5,tree(4,tree(1,nil,tree(3,tree(2,nil,nil),nil)),nil),tree(6,nil,nil)),X).
X = [1,2,3,4,5,6] ?
yes
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am trying to implement an inorder traversal which in every stage I'll get the current node.
For example:

?- getnodesinorder(tree(1,nil,nil),X).
X = 1 ;
false.

?- getnodesinorder(tree(5,tree(4,tree(1,nil,tree(3,tree(2,nil,nil),nil)),nil),tree(6,nil,nil)),X).
X = 1 ;
X = 2 ;
X = 3 ;
X = 4 ;
X = 5 ;
X = 6 ;
false.

I've tried the next code:

getnodesinorder(tree(CurrentNode,nil,nil), CurrentNode).
getnodesinorder(tree(X, Left, nil), CurrentNode) :-
    getnodesinorder(Left, _ ),
    CurrentNode is X.
getnodesinorder(tree(X, nil, Right), CurrentNode) :-
    CurrentNode is X,
    getnodesinorder(Right, _ ).
getnodesinorder(tree(X, Left, Right), CurrentNode) :-
    getnodesinorder(Left, _ ),
    CurrentNode is X,
    getnodesinorder(Right, _ ).

So of course the base (1st example works) but when trying to run the 2nd one I  get

X=5;
false

as result. Why is that?

Body:
[test] λ = cat test.pl
append([], Ys, Ys).
append([X|Xs], Ys, [X|Zs]) :- append(Xs, Ys, Zs).

getnodesinorder(nil, []).

getnodesinorder(tree(X, Left, Right), R) :-
   getnodesinorder(Left,R1),
   getnodesinorder(Right,R2),
   append(R1,[X|R2],R).

Works for me

?-getnodesinorder(tree(5,tree(4,tree(1,nil,tree(3,tree(2,nil,nil),nil)),nil),tree(6,nil,nil)),X).
X = [1,2,3,4,5,6] ?
yes


问:
How to set the value and text in a Spinner from a string list?
i am working on android spinner control. i already have populate list of string to show in spinner like

```<code>String[] items = new String[]{ "Office", "Home", "College", "Uncle's Home", "CoDebuggers"};
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items);
        SpinnerName.setAdapter(adapter);
</code>```

this is working well but i need to add unique id for my list like

Office = 4

Home = 8

College = 9

Uncle's Home = 10

CoDebiggers = 55

how can i set there value with String list?
and how can i get these values by selected item change?

答:
Create another array, maintain sizes of both arrays same. One is for items and another one is for itemIds. inside OnclickLisener of spinner call itemsId array like below. </p>

```<code>String[] itemsId = new String[]{ "4", "8", "9", "10","55"};
String[] items = new String[]{ "Office", "Home", "College", "Uncle's Home", "CoDebuggers"};
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items);
    SpinnerName.setAdapter(adapter);
SpinnerName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

           String id = itemsId.get(i);
        }
        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });
</code>```

Body:
i am working on android spinner control. i already have populate list of string to show in spinner like

String[] items = new String[]{ "Office", "Home", "College", "Uncle's Home", "CoDebuggers"};
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items);
        SpinnerName.setAdapter(adapter);

this is working well but i need to add unique id for my list like

Office = 4

Home = 8

College = 9

Uncle's Home = 10

CoDebiggers = 55

how can i set there value with String list?
and how can i get these values by selected item change?

Body:
Create another array, maintain sizes of both arrays same. One is for items and another one is for itemIds. inside OnclickLisener of spinner call itemsId array like below.

String[] itemsId = new String[]{ "4", "8", "9", "10","55"};
String[] items = new String[]{ "Office", "Home", "College", "Uncle's Home", "CoDebuggers"};
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items);
    SpinnerName.setAdapter(adapter);
SpinnerName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

           String id = itemsId.get(i);
        }
        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });


问:
How can I import a 72GB dump file into git?
I have migrated an old cvs repository with cvs2git (cvs2svn). The resulted dump file is now 72GB big and my trials to import the dump via git fast-import always fail because of an out-of-memory error:

fatal: Out of memory, malloc failed (tried to allocate 6196691 bytes)

      fast-import: dumping crash report to fast_import_crash_13097

      error: git-fast-import died of signal 11

Whereby my System has 32GB RAM and 50GB swap. I am running the import on a Red Hat 5.3 with Git 1.8.3.4 (gcc44, python2.6.8, cvs2svn2.4.0). I have also tried to unlimit stack size and file descriptors, but the memory error is still there.

Has anybody any idea?

答:
I also had faced the same issue but it is solved now. Please download the latest cvs2svn which has the fix to reduce the size of the dump considerably. It reduces the metadata for symbol commits.Version is cvs2git version 2.5 or later. </p>

<p>(You can view the change made in https://github.com/mhagger/cvs2svn/commit/fd177d0151f00b028b4a0df21e0c8b7096f4246b)</p>

Body:
I also had faced the same issue but it is solved now. Please download the latest cvs2svn which has the fix to reduce the size of the dump considerably. It reduces the metadata for symbol commits.Version is cvs2git version 2.5 or later.

(You can view the change made in https://github.com/mhagger/cvs2svn/commit/fd177d0151f00b028b4a0df21e0c8b7096f4246b)


问:
Sharing manager list with threads and process creates seperate copies
I want to share a list between the processes and threads. So I found the multiprocessing.Manager() for creating a list. I wrote the following piece of code:

```<code>import multiprocessing
import threading
import time

def consumer(l):
    counter = 0
    while counter < 20:
        time.sleep(5)
        l = l[len(l)/2:]
        print "consumer l: {}".format(l)
        counter += 5

def producer(l):
    for i in range(10):
        time.sleep(i)
        l.append(i)
        print "producer l: {}".format(l)

if __name__=="__main__":
    mgr = multiprocessing.Manager()
    l = mgr.list()

    p = threading.Thread(target=producer, args=(l,))
    c = multiprocessing.Process(target=consumer, args=(l,))

    p.start()
    c.start()

    p.join()
    c.join()
    print "done"
</code>```

It creates a process and a thread sharing a list created by manager. Producer appends to the list after every i seconds while consumer halves the list every 5 seconds. I expected that the lists would be same and both will be operating on it. But I observe that consumer and producer share the list only once and next time the lists are seperated.

Output observed:

```<code>producer l: [0]
producer l: [0, 1]
producer l: [0, 1, 2]
consumer l: [1, 2]
producer l: [0, 1, 2, 3]
producer l: [0, 1, 2, 3, 4]
consumer l: [2]
producer l: [0, 1, 2, 3, 4, 5]
consumer l: [2]
consumer l: [2]
producer l: [0, 1, 2, 3, 4, 5, 6]
producer l: [0, 1, 2, 3, 4, 5, 6, 7]
producer l: [0, 1, 2, 3, 4, 5, 6, 7, 8]
producer l: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
done
</code>```

What should be done so that both of them uses same list throughout?

答:
I changed the program to:

```<code>import multiprocessing
import threading
import time

def consumer(l):
    counter = 0
    while counter < 20:
        time.sleep(5)
        del l[0 : len(l)/2+1]
        print("consumer l address {}".format(hex(id(l))))
        print "consumer l: {}".format(l)
        counter += 5

def producer(l):
    for i in range(10):
        time.sleep(i)
        print("producer l address {}".format(hex(id(l))))
        l.append(i)
        print "producer l: {}".format(l)

if __name__=="__main__":
    mgr = multiprocessing.Manager()
    l = mgr.list()

    print("list address {}".format(hex(id(l))))
    p = multiprocessing.Process(target=producer, args=(l,))
    c = multiprocessing.Process(target=consumer, args=(l,))

    p.start()
    c.start()

    p.join()
    c.join()
    print "done"
</code>```

Notice that I have used del instead of creating a new list and assigning it to the old one. I have also added address printing statements in the above code. If you run it as it is, you should see that the address of the list remains same everywhere as we are not recreating the list. If you change line number 9 back to l = l[len(l)/2:] and run the program, you should notice that the address of the lists for the consumer and producer changes after the first operation.

Body:
I want to share a list between the processes and threads. So I found the multiprocessing.Manager() for creating a list. I wrote the following piece of code:

import multiprocessing
import threading
import time

def consumer(l):
    counter = 0
    while counter < 20:
        time.sleep(5)
        l = l[len(l)/2:]
        print "consumer l: {}".format(l)
        counter += 5

def producer(l):
    for i in range(10):
        time.sleep(i)
        l.append(i)
        print "producer l: {}".format(l)

if __name__=="__main__":
    mgr = multiprocessing.Manager()
    l = mgr.list()

    p = threading.Thread(target=producer, args=(l,))
    c = multiprocessing.Process(target=consumer, args=(l,))

    p.start()
    c.start()

    p.join()
    c.join()
    print "done"

It creates a process and a thread sharing a list created by manager. Producer appends to the list after every i seconds while consumer halves the list every 5 seconds. I expected that the lists would be same and both will be operating on it. But I observe that consumer and producer share the list only once and next time the lists are seperated.

Output observed:

producer l: [0]
producer l: [0, 1]
producer l: [0, 1, 2]
consumer l: [1, 2]
producer l: [0, 1, 2, 3]
producer l: [0, 1, 2, 3, 4]
consumer l: [2]
producer l: [0, 1, 2, 3, 4, 5]
consumer l: [2]
consumer l: [2]
producer l: [0, 1, 2, 3, 4, 5, 6]
producer l: [0, 1, 2, 3, 4, 5, 6, 7]
producer l: [0, 1, 2, 3, 4, 5, 6, 7, 8]
producer l: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
done

What should be done so that both of them uses same list throughout?

Body:
I changed the program to:

import multiprocessing
import threading
import time

def consumer(l):
    counter = 0
    while counter < 20:
        time.sleep(5)
        del l[0 : len(l)/2+1]
        print("consumer l address {}".format(hex(id(l))))
        print "consumer l: {}".format(l)
        counter += 5

def producer(l):
    for i in range(10):
        time.sleep(i)
        print("producer l address {}".format(hex(id(l))))
        l.append(i)
        print "producer l: {}".format(l)

if __name__=="__main__":
    mgr = multiprocessing.Manager()
    l = mgr.list()

    print("list address {}".format(hex(id(l))))
    p = multiprocessing.Process(target=producer, args=(l,))
    c = multiprocessing.Process(target=consumer, args=(l,))

    p.start()
    c.start()

    p.join()
    c.join()
    print "done"

Notice that I have used del instead of creating a new list and assigning it to the old one. I have also added address printing statements in the above code. If you run it as it is, you should see that the address of the list remains same everywhere as we are not recreating the list. If you change line number 9 back to l = l[len(l)/2:] and run the program, you should notice that the address of the lists for the consumer and producer changes after the first operation.


问:
date time format null values return default time in PHP
i am currently working on codeigniter project.i have a database name is "student_detail" the table value have like this

```<code>  payment_date
1 NULL
2 NULL
3 2017-12-06 08:47:40

payment_date column is a DATETIME format
</code>```

. when i print this column it returns like this

```<code>payment_date
1 1970-01-01 00:00:00
2 1970-01-01 00:00:00
3 2017-12-06 08:47:40
</code>```

but i need to return as NULL not default time format.

答:
Update your payment date field in database. Setit default to null.</p>

```<code>ALTER TABLE `table_name` CHANGE `payment_date` `payment_date` DATETIME NULL DEFAULT NULL;
</code>```

Body:
i am currently working on codeigniter project.i have a database name is "student_detail" the table value have like this

  payment_date
1 NULL
2 NULL
3 2017-12-06 08:47:40

payment_date column is a DATETIME format

. when i print this column it returns like this

payment_date
1 1970-01-01 00:00:00
2 1970-01-01 00:00:00
3 2017-12-06 08:47:40

but i need to return as NULL not default time format.

Body:
Update your payment date field in database. Setit default to null.

ALTER TABLE `table_name` CHANGE `payment_date` `payment_date` DATETIME NULL DEFAULT NULL;


问:
Multiple images are uploading in server folder but only one record is inserted in mysql
The below code is successfully uploading mutiple images to web/images/album but the only one record is updated in mysql.
So while displaying the images only one image is being displayed.
Since I am new to symfony I don't know how to do.
Can any one guide me how to get all the name of the images and insert their names in mysql??

Entity

```<code>class album
{
/**
 * @var int
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @var string
 *
 * @ORM\Column(name="albumName", type="string", length=255)
 */
private $albumName;

/**
 * @var string
 *
 * @ORM\Column(name="imageName", type="string", length=255)
 */
private $imageName;

/**
 * Get id
 *
 * @return int
 */
public function getId()
{
    return $this->id;
}

/**
 * Set albumName
 *
 * @param string $albumName
 *
 * @return album
 */
public function setAlbumName($albumName)
{
    $this->albumName = $albumName;

    return $this;
}

/**
 * Get albumName
 *
 * @return string
 */
public function getAlbumName()
{
    return $this->albumName;
}

/**
 * Set imageName
 *
 * @param string $imageName
 *
 * @return album
 */
public function setImageName($imageName)
{
    $this->imageName = $imageName;

    return $this;
}

/**
 * Get imageName
 *
 * @return string
 */
public function getImageName()
{
    return $this->imageName;
}
 }
</code>```

Form

```<code>     $builder->add('albumName', TextType::class)
               ->add('imageName', FileType::class, array(
                'multiple' => true,
                'data_class' => null
            ))
               ->add('save', SubmitType::class, array('label' => 'Submit',        'attr' => array('class' => 'btn btn-primary')));
</code>```

Controller

```<code>  public function indexAction(Request $request) {

    $albumMember = new album();

    $galleryView = $this->createForm(imageUpload::class, $albumMember);
    $galleryView->handleRequest($request);
    if ($galleryView->isSubmitted() && $galleryView->isValid()) {

        /**
         * @var UploadedFile $file
         */
        $file = $albumMember->getImageName();
        foreach ($file as $count) {
            $fileName = md5(uniqid()) . '.' . $count->guessExtension();

            $count->move(
                    $this->getParameter('image_directory'), $fileName
            );
            $albumMember->setImageName($fileName);

            $albumName = $galleryView['albumName']->getData();
            $albumMember->setAlbumName($albumName);
        }
        $em = $this->getDoctrine()->getManager();
        $em->persist($albumMember);
        $em->flush();

        $this->addFlash('notice', 'Images Added');
        return $this->redirectToRoute('createGallery');
    }

    return $this->render('admin/galleryView.html.twig', [
                'galleryView' => $galleryView->createView()
    ]);
}
</code>```

答:
For how you defined your Album entity it would expect only one image and not many of them. You should revisit your entity for using a one-to-many association between an Album and many Image in it.

```<code>use Doctrine\Common\Collections\ArrayCollection;

/** @Entity */
class Album
{
    // ...
    /**
     * One Album has Many Images.
     * @ORM\OneToMany(targetEntity="Image", mappedBy="album")
     */
    private $images;
    // ...

    public function __construct() {
        $this->images = new ArrayCollection();
    }
}

/** @Entity */
class Image
{
    // ...
    /**
     * Many Images have One Album.
     * @ORM\ManyToOne(targetEntity="Album", inversedBy="images")
     * @ORM\JoinColumn(name="album_id", referencedColumnName="id")
     */
    private $album;
    // ...
}
</code>```

Then when processing the request from the form you should add the images to the ArrayCollection. Something like this:

```<code>$album->getImages->add($image)
</code>```

of course you'll have getters/setters for that.

See more about Doctrine associations here and here.

Body:
The below code is successfully uploading mutiple images to web/images/album but the only one record is updated in mysql.
So while displaying the images only one image is being displayed.
Since I am new to symfony I don't know how to do.
Can any one guide me how to get all the name of the images and insert their names in mysql??

Entity

class album
{
/**
 * @var int
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @var string
 *
 * @ORM\Column(name="albumName", type="string", length=255)
 */
private $albumName;

/**
 * @var string
 *
 * @ORM\Column(name="imageName", type="string", length=255)
 */
private $imageName;

/**
 * Get id
 *
 * @return int
 */
public function getId()
{
    return $this->id;
}

/**
 * Set albumName
 *
 * @param string $albumName
 *
 * @return album
 */
public function setAlbumName($albumName)
{
    $this->albumName = $albumName;

    return $this;
}

/**
 * Get albumName
 *
 * @return string
 */
public function getAlbumName()
{
    return $this->albumName;
}

/**
 * Set imageName
 *
 * @param string $imageName
 *
 * @return album
 */
public function setImageName($imageName)
{
    $this->imageName = $imageName;

    return $this;
}

/**
 * Get imageName
 *
 * @return string
 */
public function getImageName()
{
    return $this->imageName;
}
 }

Form

     $builder->add('albumName', TextType::class)
               ->add('imageName', FileType::class, array(
                'multiple' => true,
                'data_class' => null
            ))
               ->add('save', SubmitType::class, array('label' => 'Submit',        'attr' => array('class' => 'btn btn-primary')));

Controller

  public function indexAction(Request $request) {

    $albumMember = new album();

    $galleryView = $this->createForm(imageUpload::class, $albumMember);
    $galleryView->handleRequest($request);
    if ($galleryView->isSubmitted() && $galleryView->isValid()) {

        /**
         * @var UploadedFile $file
         */
        $file = $albumMember->getImageName();
        foreach ($file as $count) {
            $fileName = md5(uniqid()) . '.' . $count->guessExtension();

            $count->move(
                    $this->getParameter('image_directory'), $fileName
            );
            $albumMember->setImageName($fileName);

            $albumName = $galleryView['albumName']->getData();
            $albumMember->setAlbumName($albumName);
        }
        $em = $this->getDoctrine()->getManager();
        $em->persist($albumMember);
        $em->flush();

        $this->addFlash('notice', 'Images Added');
        return $this->redirectToRoute('createGallery');
    }

    return $this->render('admin/galleryView.html.twig', [
                'galleryView' => $galleryView->createView()
    ]);
}

Body:
For how you defined your Album entity it would expect only one image and not many of them. You should revisit your entity for using a one-to-many association between an Album and many Image in it.

use Doctrine\Common\Collections\ArrayCollection;

/** @Entity */
class Album
{
    // ...
    /**
     * One Album has Many Images.
     * @ORM\OneToMany(targetEntity="Image", mappedBy="album")
     */
    private $images;
    // ...

    public function __construct() {
        $this->images = new ArrayCollection();
    }
}

/** @Entity */
class Image
{
    // ...
    /**
     * Many Images have One Album.
     * @ORM\ManyToOne(targetEntity="Album", inversedBy="images")
     * @ORM\JoinColumn(name="album_id", referencedColumnName="id")
     */
    private $album;
    // ...
}

Then when processing the request from the form you should add the images to the ArrayCollection. Something like this:

$album->getImages->add($image)

of course you'll have getters/setters for that.

See more about Doctrine associations here and here.


问:
Append error messages to form with jQuery
After a jQuery post of my form data, I get a JSON object back. When the form isn't valid, the status is set to "error" and messages are appended where the error exactly occured.

This is my response (fetched from Firebug console)

```<code>"status":"error",
"messages":{
    "email":{
        "emailAddressInvalidFormat":"'asd' is no valid email address in the basic format local-part@hostname"
    }
 }
</code>```

The insertion of the post when the form was valid is working perfectly. Now I use this code to add error messages when a form failed:

```<code>$.each(data.messages, function(element, errors) {
    var ul = $("<ul>").attr("class", "errors");
    $.each(errors, function(name, message) {
        ul.append($("<li>").val(message));
    });

    $("#" + element).after(ul);
});
</code>```

I notice that element and message are fine (checked with console.log()). I think it goes wrong due to the (second) loop, because at other places this similar piece of code works ok. I am sure the html isn't inserted into the DOM, I checked that also with Firebug.

答:
val() method is used to set and retrieve information from form tags. Use the text() method instead of it:

ul.append($("
").text(message));

Body:
After a jQuery post of my form data, I get a JSON object back. When the form isn't valid, the status is set to "error" and messages are appended where the error exactly occured.

This is my response (fetched from Firebug console)

"status":"error",
"messages":{
    "email":{
        "emailAddressInvalidFormat":"'asd' is no valid email address in the basic format local-part@hostname"
    }
 }

The insertion of the post when the form was valid is working perfectly. Now I use this code to add error messages when a form failed:

$.each(data.messages, function(element, errors) {
    var ul = $("
").attr("class", "errors");
    $.each(errors, function(name, message) {
        ul.append($("
").val(message));
    });

    $("#" + element).after(ul);
});

I notice that element and message are fine (checked with console.log()). I think it goes wrong due to the (second) loop, because at other places this similar piece of code works ok. I am sure the html isn't inserted into the DOM, I checked that also with Firebug.

Body:
val() method is used to set and retrieve information from form tags. Use the text() method instead of it:

ul.append($("<li>").text(message));


问:
No webhook calls for deleted draft envelopes
I saw this question Deleted Draft Envelopes have inaccurate status about deleted drafts, but I wanted to check if that's also true for webhooks.

If I create Draft Envelope in DocuSign from my application, and then user deletes that Envelope in DocuSign, will any webhook event fire?

These are the event notifications that I have specified when Draft Envelope is created or Envelope is sent:

```<code>{
  "eventNotification": {
    "envelopeEvents": [
      { "envelopeEventStatusCode": "completed" },
      { "envelopeEventStatusCode": "declined"  },
      { "envelopeEventStatusCode": "voided"    }
    ]
  }
}
</code>```

I receive no webhook calls when draft is deleted.

But I do receive webhook calls from Docusign when Envelope is sent and

completed

declined

voided

答: Can you describe your use case whereby you want your software application to be notified when a draft envelope has been deleted? </p>

Body:
I saw this question Deleted Draft Envelopes have inaccurate status about deleted drafts, but I wanted to check if that's also true for webhooks.

If I create Draft Envelope in DocuSign from my application, and then user deletes that Envelope in DocuSign, will any webhook event fire?

These are the event notifications that I have specified when Draft Envelope is created or Envelope is sent:

{
  "eventNotification": {
    "envelopeEvents": [
      { "envelopeEventStatusCode": "completed" },
      { "envelopeEventStatusCode": "declined"  },
      { "envelopeEventStatusCode": "voided"    }
    ]
  }
}

I receive no webhook calls when draft is deleted.

But I do receive webhook calls from Docusign when Envelope is sent and

completed

declined

voided


问:
Target the same child with two differents parent class
Since few days I'm using SASS to write my css files.
I have two different parents class but this two parents have the same children classes. So I want to build my SCSS tree of this CSS code :

```<code>#header {
    position: relative;
    width: 100%;
}

#header-g {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 300;
    width: 100%;
}

#header .l-header-top, #header-g .l-header-top {
    height: 55px;
    line-height: 50px;
    border-top: 5px solid #474747;
    background-color: #f0f1f3;

    font-size: 16px;
}
</code>```

I tried this but I think I forget something :

```<code>    #header {
    position: relative;
    width: 100%;

    &#header-g {
        position: fixed;
        top: 0;
        left: 0;
        z-index: 300;
        width: 100%;

        .l-header-top {
            height: 55px;
            line-height: 50px;
            border-top: 5px solid #474747;
            background-color: #f0f1f3;

            font-size: 16px;
        }
    }
}
</code>```

Thanks

答:
In your code, if you are using & it means that they are in the same element and in a single element there is only 1 ID. You should use a class in that situation.

```<code>#header {
    position: relative;
    width: 100%;

    &#header-g {
        position: fixed;
        top: 0;
        left: 0;
        z-index: 300;
        width: 100%;
</code>```

but it should be something like this. #header and #header-gestion are you ID parents while they have the same children which are .l-header-top.

```<code>#header {
    position: relative;
    width: 100%;
    .l-header-top {
       height: 55px;
       line-height: 50px;
       border-top: 5px solid #474747;
       background-color: #f0f1f3;

       font-size: 16px;
    }
}

#header-g {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 300;
    width: 100%;
    .l-header-top {
       height: 55px;
       line-height: 50px;
       border-top: 5px solid #474747;
       background-color: #f0f1f3;

       font-size: 16px;
    }
}
</code>```

Or you use & in this way which is based on BEM Methodology in class naming conventions. You can check this link: BEM — Block Element Modifier Methodology

```<code>#header {
    position: relative;
    width: 100%;
    &-g {
       position: fixed;
       top: 0;
       left: 0;
       z-index: 300;
       width: 100%;
    }
}

#header,
#header-g {
    .l-header-top {
       height: 55px;
       line-height: 50px;
       border-top: 5px solid #474747;
       background-color: #f0f1f3;
       font-size: 16px;
    }
}
</code>```

Body:
Since few days I'm using SASS to write my css files.
I have two different parents class but this two parents have the same children classes. So I want to build my SCSS tree of this CSS code :

#header {
    position: relative;
    width: 100%;
}

#header-g {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 300;
    width: 100%;
}

#header .l-header-top, #header-g .l-header-top {
    height: 55px;
    line-height: 50px;
    border-top: 5px solid #474747;
    background-color: #f0f1f3;

    font-size: 16px;
}

I tried this but I think I forget something :

    #header {
    position: relative;
    width: 100%;

    &#header-g {
        position: fixed;
        top: 0;
        left: 0;
        z-index: 300;
        width: 100%;

        .l-header-top {
            height: 55px;
            line-height: 50px;
            border-top: 5px solid #474747;
            background-color: #f0f1f3;

            font-size: 16px;
        }
    }
}

Thanks

Body:
In your code, if you are using & it means that they are in the same element and in a single element there is only 1 ID. You should use a class in that situation.

#header {
    position: relative;
    width: 100%;

    &#header-g {
        position: fixed;
        top: 0;
        left: 0;
        z-index: 300;
        width: 100%;

but it should be something like this. #header and #header-gestion are you ID parents while they have the same children which are .l-header-top.

#header {
    position: relative;
    width: 100%;
    .l-header-top {
       height: 55px;
       line-height: 50px;
       border-top: 5px solid #474747;
       background-color: #f0f1f3;

       font-size: 16px;
    }
}

#header-g {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 300;
    width: 100%;
    .l-header-top {
       height: 55px;
       line-height: 50px;
       border-top: 5px solid #474747;
       background-color: #f0f1f3;

       font-size: 16px;
    }
}

Or you use & in this way which is based on BEM Methodology in class naming conventions. You can check this link: BEM — Block Element Modifier Methodology

#header {
    position: relative;
    width: 100%;
    &-g {
       position: fixed;
       top: 0;
       left: 0;
       z-index: 300;
       width: 100%;
    }
}

#header,
#header-g {
    .l-header-top {
       height: 55px;
       line-height: 50px;
       border-top: 5px solid #474747;
       background-color: #f0f1f3;
       font-size: 16px;
    }
}


问:
CSS Animation on hover
I need a little help with CSS animations. How can I make this http://jsfiddle.net/nmsdvid/TdnVs/ just with CSS. So, when I hover over the krab div a css animation will start and going to switch images (vws02.png than vws01.png than vws02.png) while I'm on hover. </p>

答:
here you check

#krab {
        width:335px;
        height:345px;
        background-image:url(https://www.planwallpaper.com/static/images/desktop-year-of-the-tiger-images-wallpaper.jpg);
    }

#krab:hover {
background-image:url(https://image.winudf.com/v2/image/Y29tLnp6d3BuZXcudGlnZXIzRF9zY3JlZW5zaG90c18wX2NhZWNhNzYz/screen-0.jpg?h=355&fakeurl=1&type=.jpg);
    }

demo: http://jsfiddle.net/TdnVs/4/

Title: CSS Animation on hover


问:
Copy and paste a file through access vba
I need to check a folder for a file, if it exists delete it an replace it with an updated version, or if the file doesn't delete then it will copy the file from a path into the individuals personal drive

My Code:

```<code>Dim FileExistsbol As Boolean
Dim stFileName As String
Dim CopyFrom As String
Dim CopyTo As String

stFileName = "H:\Test File.txt"
stFileName = Trim(stFileName)
FileExistsbol = dir(stFileName) <> vbNullString

If FileExistsbol Then
 Kill stFileName
 CopyFrom = "J:\Test File.txt"
 CopyTo = "H:\"
 FileSystemObject.CopyFile CopyFrom, CopyTo
Else
 CopyFrom = "J:\Test File.txt"
 CopyTo = "H:\"
 FileSystemObject.CopyFile CopyFrom, CopyTo
End If
</code>```

What Happens:

The code executes and deletes the existing file as expected, but it appears to be failing on the copy and paste part.

Error:

The debug that comes up is:

Object Required

答:
Bare bones:</p>

```<code>Dim fso As Object       'filesystemobject
Set fso = CreateObject("Scripting.FileSystemObject")
fso.CopyFile strSourcePathWithFileAndExt, strDestPathWithFinalBackslash
Set fso = Nothing
</code>```

Body:
I need to check a folder for a file, if it exists delete it an replace it with an updated version, or if the file doesn't delete then it will copy the file from a path into the individuals personal drive

My Code:

Dim FileExistsbol As Boolean
Dim stFileName As String
Dim CopyFrom As String
Dim CopyTo As String

stFileName = "H:\Test File.txt"
stFileName = Trim(stFileName)
FileExistsbol = dir(stFileName) <> vbNullString

If FileExistsbol Then
 Kill stFileName
 CopyFrom = "J:\Test File.txt"
 CopyTo = "H:\"
 FileSystemObject.CopyFile CopyFrom, CopyTo
Else
 CopyFrom = "J:\Test File.txt"
 CopyTo = "H:\"
 FileSystemObject.CopyFile CopyFrom, CopyTo
End If

What Happens:

The code executes and deletes the existing file as expected, but it appears to be failing on the copy and paste part.

Error:

The debug that comes up is:

Object Required

Body:
Bare bones:

Dim fso As Object       'filesystemobject
Set fso = CreateObject("Scripting.FileSystemObject")
fso.CopyFile strSourcePathWithFileAndExt, strDestPathWithFinalBackslash
Set fso = Nothing


问:
Run two delays at once C++
I want to make a program in which there are two dots blinking (with a break of 10ms) simultaneously, but one with delay 200ms and other with delay of 300ms. How can I play these two dots simultaneously from beginning? Is there a better way to that from following:</p>

```<code>for(int i=1;i<100;i++)
{
  if (i%2==0)
    circle(10,10,2);
  if (i%3==0)
    circle(20,10,2);
  delay(10);
  cleardevice();
  delay(100);
}
</code>```

答:
I would do something like this instead:

int t0=0,t1=0,t=0,s0=0,s1=0,render=1;
for (;;)
 {
 if (some stop condition like keyboard hit ...) break;
 // update time, state
 if (t>=t0) { render=1; s0=!s0; if (s0) t0+=10; else t0+=200; }
 if (t>=t1) { render=1; s1=!s1; if (s1) t1+=10; else t1+=300; }
 // render
 if (render)
  {
  render=0;
  cleardevice();
  if (s0) circle(10,10,2);
  if (s1) circle(20,10,2);
  }
 // update main time
 delay(10); // Sleep(10) would be better but I am not sure it is present in TC++
 t+=10;
 if (t>10000) // make sure overflow is not an issue
  {
  t -=10000;
  t0-=10000;
  t1-=10000;
  }
 }
```

Beware the code is untested as I wrote it directly in here (so there might be syntax errors or typos).

The basic idea is having one global time t with small enough granularity (10ms). And for each object have time of event (t0,t1) state of object (s0,s1) and periods (10/200 , 10/300).

If main time reach the event time swap the state on/off and update event time to next state swap time.

This way you can have any number of objects just make sure your main time step is small enough.

The render flag just ensures that the scene is rendered on change only.

To improve timing you can use RDTSC instead of t+=10 and actually measure how much time has passed with CPU frequency accuracy.

Title: Run two delays at once C++

Body:
I want to make a program in which there are two dots blinking (with a break of 10ms) simultaneously, but one with delay 200ms and other with delay of 300ms. How can I play these two dots simultaneously from beginning? Is there a better way to that from following:

for(int i=1;i<100;i++)
{
  if (i%2==0)
    circle(10,10,2);
  if (i%3==0)
    circle(20,10,2);
  delay(10);
  cleardevice();
  delay(100);
}

Body:
I would do something like this instead:

int t0=0,t1=0,t=0,s0=0,s1=0,render=1;
for (;;)
 {
 if (some stop condition like keyboard hit ...) break;
 // update time, state
 if (t>=t0) { render=1; s0=!s0; if (s0) t0+=10; else t0+=200; }
 if (t>=t1) { render=1; s1=!s1; if (s1) t1+=10; else t1+=300; }
 // render
 if (render)
  {
  render=0;
  cleardevice();
  if (s0) circle(10,10,2);
  if (s1) circle(20,10,2);
  }
 // update main time
 delay(10); // Sleep(10) would be better but I am not sure it is present in TC++
 t+=10;
 if (t>10000) // make sure overflow is not an issue
  {
  t -=10000;
  t0-=10000;
  t1-=10000;
  }
 }

Beware the code is untested as I wrote it directly in here (so there might be syntax errors or typos).

The basic idea is having one global time t with small enough granularity (10ms). And for each object have time of event (t0,t1) state of object (s0,s1) and periods (10/200 , 10/300).

If main time reach the event time swap the state on/off and update event time to next state swap time.

This way you can have any number of objects just make sure your main time step is small enough.

The render flag just ensures that the scene is rendered on change only.

To improve timing you can use RDTSC instead of t+=10 and actually measure how much time has passed with CPU frequency accuracy.


问:
Windows Services Error in C#
I using c#. At this time I using Windows 7.My question is ; When I running my code,
that's gives me errors etc 193:0xc1 error , Services started but after stopped , 1053 services  errors.
Here is my code.

```<code>    public RupdaterService()
    {
        InitializeComponent();
        this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);
    }
      protected override void OnStart (string[] args)
    {
        timer1.Enabled=true;
        this.DBEntry("Service Started");
    }
      protected override void OnStop()
    {
        this.timer1.Enabled = false;
        this.DBEntry("Service Stopped");
    }

    private void timer1_Elapsed(object sender,System.Timers.ElapsedEventArgs e)
    {

        this.DBEntry("Service Running");
        }

 Here is my App.Config.

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<configSections>

    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c5***9" >
        <section name="HedefliRUpdater.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5***9" requirePermission="false" />
    </sectionGroup>
</configSections>

<system.serviceModel>

</system.serviceModel>

<applicationSettings>
    <HedefliRUpdater.Properties.Settings>
        <setting name="HedefliRUpdater_srvHedefli_wsrvHermesHedefliMesaj"
            serializeAs="String">
            <value>http://***.com/hedefli/srvHedefli.asmx</value>
        </setting>
    </HedefliRUpdater.Properties.Settings>
</applicationSettings>
</code>```

Thanks in advance,

答:
Some things to check. These happened to me, off the top of my head:

Is there anything in the Event Logs? They can sometimes give you a clue.

Is the Event Log full? If Windows can't write to it, it won't start the service. Try clearing the Application event log and see if it starts.

Are there any syntax errors in the .config file? We once had a problem with an .msi installer that put an <endpoint> tag after the end of </configuration>

It looks like you're writing to a database. Does the user that the service runs under have access to that database?

Try putting Debugger.Break() at the beginning of your OnStart() to prompt Windows to connect an instance of Visual Studio when it starts up. At the very least, it'll tell you if the fault is happening before it gets to your OnStart, or after.

Do you have more than one <endpoint> specified in the app.config/web.config file that matches the same contract? Try removing the superfluous endpoint

Title: Windows Services Error in C#

Body:
I using c#. At this time I using Windows 7.My question is ; When I running my code,
that's gives me errors etc 193:0xc1 error , Services started but after stopped , 1053 services  errors.
Here is my code.

    public RupdaterService()
    {
        InitializeComponent();
        this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);
    }
      protected override void OnStart (string[] args)
    {
        timer1.Enabled=true;
        this.DBEntry("Service Started");
    }
      protected override void OnStop()
    {
        this.timer1.Enabled = false;
        this.DBEntry("Service Stopped");
    }

    private void timer1_Elapsed(object sender,System.Timers.ElapsedEventArgs e)
    {

        this.DBEntry("Service Running");
        }

 Here is my App.Config.

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<configSections>

    <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c5***9" >

    </sectionGroup>
</configSections>

<system.serviceModel>

</system.serviceModel>

<applicationSettings>
    <HedefliRUpdater.Properties.Settings>
        <setting name="HedefliRUpdater_srvHedefli_wsrvHermesHedefliMesaj"
            serializeAs="String">
            <value>http://***.com/hedefli/srvHedefli.asmx</value>
        </setting>
    </HedefliRUpdater.Properties.Settings>
</applicationSettings>

Thanks in advance,


问:
merging my local branch with remote master
I am new to git. I am working on a codebase with a team.
The status of my remote repository is:

```<code>git remote show origin                                # show the status
Remote branches:
....
                     master                             tracked
                     branch_to_be_merged                 tracked
...
Local branches configured for git pull:
master                                                 merges with remote master
branch_to_be_merged                                      merges with remote branch_to_be_merged

Local refs configured for git push:
master                                                 pushes to master
branch_to_be_merged                                       pushes to  branch_to_be_merged
</code>```

I have been working on a feature  on branch_to_be_merged, while master was actively developed.
Now I need to make my feature available to the public, and I would be merging using the following series of git commands.

Is the following correct?

```<code>git fetch origin                #make sure I am updated with latest remote changes
git checkout -b branch_to_be_merged   # the currently checked out branch is the one of interest
git branch                      # check I am on the branch I would like to merge later (it should now show *branch_to_be_merged)
git pull origin master           # apply the latest remote changes to my local branch_to_be_merged [I EXPECT CONFLICTS HERE]
git push branch_to_be_merged     # push the changes to remote
git checkout -b master           # the currently checked out branch is master
git branch                      # check I am on the branch I would like to merge later (it should now show *master)
git pull origin master           # apply the latest remote changes to my local master
git merge branch_to_be_merged    # merge  branch_to_be_merged to local master
git push master                 # publish the updates to master
</code>```

答:
You Version with Comments

# you don't need to put 'origin'. If you have more than one remote, you can use 'git fetch --all'
git fetch origin                #make sure I am updated with latest remote changes
# the '-b' creates a new branch, this is not possible since the branch already exists. Remove '-b'
git checkout -b branch_to_be_merged   # the currently checked out branch is the one of interest
git branch                      # check I am on the branch I would like to merge later (it should now show *branch_to_be_merged)
# I would advice against doing this. Usually, 'pull' is used to update a
# local branch of the same name as the remote branch (it is a shorthand for
# 'git fetch && git merge origin/branch_name'.
# Secondly, 'pull' can be configured to use either 'merge' or 'rebase'
# so the behavior of this command depends on some configuration
git pull origin master           # apply the latest remote changes to my local branch_to_be_merged [I EXPECT CONFLICTS HERE]
# if you are merging the branch back to master you will probably delete
# it afterwards. Hence, you don't need to push it. You'll push your
# commits when you push the updated master branch
git push branch_to_be_merged     # push the changes to remote
# Again, no '-b' for existing branches
git checkout -b master           # the currently checked out branch is master
git branch                      # check I am on the branch I would like to merge later (it should now show *master)
# Simply use git pull, as this will automatically pull in the changes
# from the correct remote branch (so you cannot accidentally pull changes
# from a different branch)
git pull origin master           # apply the latest remote changes to my local master
git merge branch_to_be_merged    # merge  branch_to_be_merged to local master
git push master                 # publish the updates to master
```

<h2>Short Solution</h2>

<p>I would suggest the following commands:</p>

<pre class="lang-sh prettyprint-override"><code>git checkout master
# You don't need a git fetch at all, since pull does a fetch
git pull
git merge branch_to_be_merged # merge conflicts here
git push
# optionally delete the merged branch and its remote
git branch -d branch_to_be_merged
git push origin :branch_to_be_merged
</code>```

Body:
I am new to git. I am working on a codebase with a team.
The status of my remote repository is:

git remote show origin                                # show the status
Remote branches:
....
                     master                             tracked
                     branch_to_be_merged                 tracked
...
Local branches configured for git pull:
master                                                 merges with remote master
branch_to_be_merged                                      merges with remote branch_to_be_merged

Local refs configured for git push:
master                                                 pushes to master
branch_to_be_merged                                       pushes to  branch_to_be_merged

I have been working on a feature  on branch_to_be_merged, while master was actively developed.
Now I need to make my feature available to the public, and I would be merging using the following series of git commands.

Is the following correct?

git fetch origin                #make sure I am updated with latest remote changes
git checkout -b branch_to_be_merged   # the currently checked out branch is the one of interest
git branch                      # check I am on the branch I would like to merge later (it should now show *branch_to_be_merged)
git pull origin master           # apply the latest remote changes to my local branch_to_be_merged [I EXPECT CONFLICTS HERE]
git push branch_to_be_merged     # push the changes to remote
git checkout -b master           # the currently checked out branch is master
git branch                      # check I am on the branch I would like to merge later (it should now show *master)
git pull origin master           # apply the latest remote changes to my local master
git merge branch_to_be_merged    # merge  branch_to_be_merged to local master
git push master                 # publish the updates to master

Body:
You Version with Comments

# you don't need to put 'origin'. If you have more than one remote, you can use 'git fetch --all'
git fetch origin                #make sure I am updated with latest remote changes
# the '-b' creates a new branch, this is not possible since the branch already exists. Remove '-b'
git checkout -b branch_to_be_merged   # the currently checked out branch is the one of interest
git branch                      # check I am on the branch I would like to merge later (it should now show *branch_to_be_merged)
# I would advice against doing this. Usually, 'pull' is used to update a
# local branch of the same name as the remote branch (it is a shorthand for
# 'git fetch && git merge origin/branch_name'.
# Secondly, 'pull' can be configured to use either 'merge' or 'rebase'
# so the behavior of this command depends on some configuration
git pull origin master           # apply the latest remote changes to my local branch_to_be_merged [I EXPECT CONFLICTS HERE]
# if you are merging the branch back to master you will probably delete
# it afterwards. Hence, you don't need to push it. You'll push your
# commits when you push the updated master branch
git push branch_to_be_merged     # push the changes to remote
# Again, no '-b' for existing branches
git checkout -b master           # the currently checked out branch is master
git branch                      # check I am on the branch I would like to merge later (it should now show *master)
# Simply use git pull, as this will automatically pull in the changes
# from the correct remote branch (so you cannot accidentally pull changes
# from a different branch)
git pull origin master           # apply the latest remote changes to my local master
git merge branch_to_be_merged    # merge  branch_to_be_merged to local master
git push master                 # publish the updates to master

Short Solution

I would suggest the following commands:

git checkout master
# You don't need a git fetch at all, since pull does a fetch
git pull
git merge branch_to_be_merged # merge conflicts here
git push
# optionally delete the merged branch and its remote
git branch -d branch_to_be_merged
git push origin :branch_to_be_merged