Decoding a codable tree of generic classes in Swift 4

Question: Goals
I need a representation of generic objects interconnected in a tree like manner. This tree and their objects should have the following characteristics:

It should be possible to build a tree out of 3 parts: trunk, branch and apple

where it's not possible to add a parent to a trunk
where a trunk can only get multiple branch nodes as child elements
where a branch can only have multiple apple nodes as child elements
where a branch can only have a parent of type trunk or branch
where it's not possible to add a child element to an apple
checks for a valid configuration should be at compile time >> using generics

It should be codable by implementing the Codable protocol

so it can be encoded into a JSON
and decoded from a JSON

As an example at the end of this question I created a playground that fulfills all requirements but one:
decoding the tree from a JSON
Explanation of the example code
A tree consists of nodes, in this case TreePartNodes, which are implementing the TreePartNodeBase protocol.
The tree in this example is an array of AnyTreePartNodes that are also implementing the TreePartNodeBase protocol and wrapping an object implementing the TreePartNodeBase protocol that should be a generic TreePartNode (TreePartNode<Trunk>, TreePartNode<Branch> or TreePartNode<Apple>).
A TreePartNode has the property treePart of type AnyTreePart. AnyTreePart (similar to AnyTreePartNode) wraps an object that implements the TreePart protocol (Trunk, Branch or Apple).
All these classes are implementing Codable and Equatable.
Code ready for pasting inside a Xcode playground
import Foundation

///////////// TreePart -> implemented by Trunk, Branch, Apple and AnyTreePart

protocol TreePart: Codable {
    var name: String { get set }

    func isEqualTo( _ other: TreePart ) -> Bool

    func asEquatable() -> AnyTreePart
}

extension TreePart where Self: Equatable {

    func isEqualTo( _ other: TreePart ) -> Bool {
        guard let otherTreePart = other as? Self else { return false }

        return self == otherTreePart
    }

    func asEquatable() -> AnyTreePart {
        return AnyTreePart( self )
    }
}

///////////// AnyTreePart -> wrapper for Trunk, Branch and Apple

class AnyTreePart: TreePart, Codable {

    var wrappedTreePart: TreePart

    var name: String {
        get {
            return self.wrappedTreePart.name
        }
        set {
            self.wrappedTreePart.name = newValue
        }
    }

    init( _ treePart: TreePart ) {
        self.wrappedTreePart = treePart
    }

    // MARK: Codable

    enum CodingKeys: String, CodingKey {
        case trunk,
             branch,
             apple
    }

    required convenience init( from decoder: Decoder ) throws {
        let container = try decoder.container( keyedBy: CodingKeys.self )

        var treePart: TreePart?

        if let trunk = try container.decodeIfPresent( Trunk.self, forKey: .trunk ) {
            treePart = trunk
        }

        if let branch = try container.decodeIfPresent( Branch.self, forKey: .branch ) {
            treePart = branch
        }

        if let apple = try container.decodeIfPresent( Apple.self, forKey: .apple ) {
            treePart = apple
        }

        guard let foundTreePart = treePart else {
            let context = DecodingError.Context( codingPath: [CodingKeys.trunk, CodingKeys.branch, CodingKeys.apple], debugDescription: "Could not find the treePart key" )
            throw DecodingError.keyNotFound( CodingKeys.trunk, context )
        }

        self.init( foundTreePart )
    }

    func encode( to encoder: Encoder ) throws {
        var container = encoder.container( keyedBy: CodingKeys.self )

        switch self.wrappedTreePart {

        case let trunk as Trunk:
            try container.encode( trunk, forKey: .trunk )

        case let branch as Branch:
            try container.encode( branch, forKey: .branch )

        case let apple as Apple:
            try container.encode( apple, forKey: .apple )

        default:
            fatalError( "Encoding error: No encoding implementation for \( type( of: self.wrappedTreePart ) )" )
        }
    }

}

extension AnyTreePart: Equatable {
    static func ==( lhs: AnyTreePart, rhs: AnyTreePart ) -> Bool {
        return lhs.wrappedTreePart.isEqualTo( rhs.wrappedTreePart )
    }
}

///////////// TreePartNodeBase -> implemented by TreePartNode<T: TreePart> and AnyTreePartNode

protocol TreePartNodeBase: class {

    var treePart: AnyTreePart { get set }

    var uuid: UUID { get }

    var parent: AnyTreePartNode? { get set }

    var weakChildren: NSPointerArray { get }

    func isEqualTo( _ other: TreePartNodeBase ) -> Bool

    func asEquatable() -> AnyTreePartNode
}

extension TreePartNodeBase where Self: Equatable {

    func isEqualTo( _ other: TreePartNodeBase ) -> Bool {
        guard let otherTreePartNode = other as? Self else { return false }

        return self == otherTreePartNode &&
               self.treePart == other.treePart &&
               self.uuid == other.uuid &&
               self.parent == other.parent &&
               self.children == other.children
    }

    func asEquatable() -> AnyTreePartNode {
        return AnyTreePartNode( self )
    }
}

extension TreePartNodeBase {
    var children: [AnyTreePartNode] {
        guard let allNodes = self.weakChildren.allObjects as? [AnyTreePartNode] else {
            fatalError( "The children nodes are not of type \( type( of: AnyTreePartNode.self ) )" )
        }

        return allNodes
    }
}

///////////// AnyTreePartNode -> wrapper of TreePartNode<T: TreePart>

class AnyTreePartNode: TreePartNodeBase, Codable {
    unowned var wrappedTreePartNode: TreePartNodeBase

    var treePart: AnyTreePart {
        get {
            return self.wrappedTreePartNode.treePart
        }
        set {
            self.wrappedTreePartNode.treePart = newValue
        }
    }

    var uuid:                  UUID {
        return self.wrappedTreePartNode.uuid
    }

    /// The parent node
    weak var parent: AnyTreePartNode? {
        get {
            return self.wrappedTreePartNode.parent
        }
        set {
            self.wrappedTreePartNode.parent = newValue
        }
    }

    /// The weak references to the children of this node
    var weakChildren: NSPointerArray {
        return self.wrappedTreePartNode.weakChildren
    }

    init( _ treePartNode: TreePartNodeBase ) {
        self.wrappedTreePartNode = treePartNode
    }

    // MARK: Codable

    enum CodingKeys: String, CodingKey {
        case trunkNode,
             branchNode,
             appleNode
    }

    required convenience init( from decoder: Decoder ) throws {
        let container = try decoder.container( keyedBy: CodingKeys.self )
        // even if an empty Trunk is created, the decoder crashes
        self.init( TreePartNode<Trunk>( Trunk() ) )

        // This attempt of decoding possible nodes doesn't work
        /*
        if let trunkNode: TreePartNode<Trunk> = try container
              .decodeIfPresent( TreePartNode<Trunk>.self, forKey: .trunkNode ) {
            self.init( trunkNode )

        } else if let branchNode: TreePartNode<Branch> = try container
              .decodeIfPresent( TreePartNode<Branch>.self, forKey: .branchNode ) {
            self.init( branchNode )

        } else if let appleNode: TreePartNode<Apple> = try cont«ainer
              .decodeIfPresent( TreePartNode<Apple>.self, forKey: .appleNode ) {
            self.init( appleNode )

        } else {
                let context = DecodingError.Context( codingPath: [CodingKeys.trunkNode,
                                                                                CodingKeys.branchNode,
                                                                                CodingKeys.appleNode],
                                                                                debugDescription: "Could not find the treePart node key" )
                throw DecodingError.keyNotFound( CodingKeys.trunkNode, context )
        }
        */

       // TODO recreating the connections between the nodes should happen after all objects are decoded and will be done based on the UUIDs
    }

    func encode( to encoder: Encoder ) throws {
        var container = encoder.container( keyedBy: CodingKeys.self )

        switch self.wrappedTreePartNode {

        case let trunkNode as TreePartNode<Trunk>:
            try container.encode( trunkNode, forKey: .trunkNode )

        case let branchNode as TreePartNode<Branch>:
            try container.encode( branchNode, forKey: .branchNode )

        case let appleNode as TreePartNode<Apple>:
            try container.encode( appleNode, forKey: .appleNode )

        default:
            fatalError( "Encoding error: No encoding implementation for \( type( of: self.wrappedTreePartNode ) )" )
        }
    }
}

extension AnyTreePartNode: Equatable {
    static func ==( lhs: AnyTreePartNode, rhs: AnyTreePartNode ) -> Bool {
        return lhs.wrappedTreePartNode.isEqualTo( rhs.wrappedTreePartNode )
    }
}

// enables printing of the wrapped tree part and its child elements
extension AnyTreePartNode: CustomStringConvertible {
    var description: String {
        var text = "\( type( of: self.wrappedTreePartNode.treePart.wrappedTreePart ))"

        if !self.children.isEmpty {
            text += " { " + self.children.map { $0.description }.joined( separator: ", " ) + " }"
        }
        return text
    }
}

///////////// TreeParts (Trunk, Branch and Apple)

class Trunk: TreePart, Codable, Equatable {
    var name: String

    var color: String

    init( name: String = "trunk",
              color: String = "#CCC" ) {
        self.name = name
        self.color = color
    }

    static func ==(lhs: Trunk, rhs: Trunk) -> Bool {
        return lhs.name == rhs.name &&
                     lhs.color == rhs.color
    }
}

class Branch: TreePart, Codable, Equatable {
    var name: String

    var length: Int

    init( name: String = "branch",
                length: Int = 4 ) {
        self.name = name
        self.length = length
    }

    static func ==(lhs: Branch, rhs: Branch) -> Bool {
        return lhs.name == rhs.name &&
                     lhs.length == rhs.length
    }
}

class Apple: TreePart, Codable, Equatable {
    var name: String

    var size: Int

    init( name: String = "apple",
                size: Int = 2 ) {
        self.name = name
        self.size = size
    }

    static func ==(lhs: Apple, rhs: Apple) -> Bool {
        return lhs.name == rhs.name &&
                     lhs.size == rhs.size
    }
}

///////////// TreePartNode -> The node in the tree that contains the TreePart

class TreePartNode<T: TreePart>: TreePartNodeBase, Codable {

    var equatableSelf: AnyTreePartNode!

    var uuid: UUID

    var treePart: AnyTreePart

    var weakChildren = NSPointerArray.weakObjects()

    private var parentUuid : UUID?

    private var childrenUuids : [UUID]?

    weak var parent: AnyTreePartNode? {
        willSet {
            if newValue == nil {
                // unrelated code
                // ... removes the references to this object in the parent node, if it exists
            }
        }
    }

    init( _ treePart: AnyTreePart,
                uuid: UUID = UUID() ) {
        self.treePart = treePart
        self.uuid = uuid
        self.equatableSelf = self.asEquatable()
    }

    convenience init( _ treePart: T,
                uuid: UUID = UUID() ) {
        self.init( treePart.asEquatable(),
                             uuid: uuid )
    }

    init( _ treePart: AnyTreePart,
                uuid: UUID,
                parentUuid: UUID?,
                childrenUuids: [UUID]?) {

        self.treePart = treePart
        self.uuid = uuid
        self.parentUuid = parentUuid
        self.childrenUuids = childrenUuids
        self.equatableSelf = self.asEquatable()
    }

    private func add( child: AnyTreePartNode ) {
        child.parent = self.equatableSelf
        self.weakChildren.addObject( child )
    }

    private func set( parent: AnyTreePartNode ) {
        self.parent = parent
        parent.weakChildren.addObject( self.equatableSelf )
    }

    // MARK: Codable

    enum CodingKeys: String, CodingKey {
        case treePart,
             uuid,
             parent,
             children,
             parentPort
    }

    required convenience init( from decoder: Decoder ) throws {
        let container         = try decoder.container( keyedBy: CodingKeys.self )

        // non-optional values
        let uuid:   UUID      = try container.decode( UUID.self, forKey: .uuid )
        let treePart: AnyTreePart = try container.decode( AnyTreePart.self, forKey: .treePart )

        // optional values
        let childrenUuids: [UUID]?     = try container.decodeIfPresent( [UUID].self, forKey: .children )
        let parentUuid:    UUID?       = try container.decodeIfPresent( UUID.self, forKey: .parent )

        self.init( treePart,
                             uuid: uuid,
                             parentUuid: parentUuid,
                             childrenUuids: childrenUuids)
    }

    func encode( to encoder: Encoder ) throws {
        var container = encoder.container( keyedBy: CodingKeys.self )

        // non-optional values
        try container.encode( self.treePart, forKey: .treePart )
        try container.encode( self.uuid, forKey: .uuid )

        // optional values
        if !self.children.isEmpty {
            try container.encode( self.children.map { $0.uuid }, forKey: .children )
        }

        try container.encodeIfPresent( self.parent?.uuid, forKey: .parent )
    }
}

extension TreePartNode: Equatable {
    static func ==( lhs: TreePartNode, rhs: TreePartNode ) -> Bool {
        return lhs.treePart == rhs.treePart &&
                     lhs.parent == rhs.parent &&
                     lhs.children == rhs.children
    }
}

// enables printing of the wrapped tree part and its child elements
extension TreePartNode: CustomStringConvertible {
    var description: String {
        var text = "\( type( of: self.treePart.wrappedTreePart ))"

        if !self.children.isEmpty {
            text += " { " + self.children.map { $0.description }.joined( separator: ", " ) + " }"
        }
        return text
    }
}

// MARK: functions for adding connections to other TreeParts for each specific TreePart type

extension TreePartNode where T: Trunk {
    func add( child branch: TreePartNode<Branch> ) {
        self.add( child: branch.equatableSelf )
    }
}

extension TreePartNode where T: Branch {
    func add( child apple: TreePartNode<Apple> ) {
        self.add( child: apple.equatableSelf )
    }

    func add( child branch: TreePartNode<Branch> ) {
        self.add( child: branch.equatableSelf )
    }

    func set( parent branch: TreePartNode<Branch> ) {
        self.set( parent: branch.equatableSelf )
    }

    func set( parent trunk: TreePartNode<Trunk> ) {
        self.set( parent: trunk.equatableSelf )
    }
}

extension TreePartNode where T: Apple {
    func set( parent branch: TreePartNode<Branch> ) {
        self.set( parent: branch.equatableSelf )
    }
}

////////////// Helper

extension NSPointerArray {

    func addObject( _ object: AnyObject? ) {
        guard let strongObject = object else { return }
        let pointer = Unmanaged.passUnretained( strongObject ).toOpaque()
        self.addPointer( pointer )
    }

}

////////////// Test (The actual usage of the implementation above)

let trunk = Trunk()
let branch1 = Branch()
let branch2 = Branch()
let branch3 = Branch()
let apple1 = Apple()
let apple2 = Apple()

let trunkNode = TreePartNode<Trunk>( trunk )
let branchNode1 = TreePartNode<Branch>( branch1 )
let branchNode2 = TreePartNode<Branch>( branch2 )
let branchNode3 = TreePartNode<Branch>( branch3 )
let appleNode1 = TreePartNode<Apple>( apple1 )
let appleNode2 = TreePartNode<Apple>( apple2 )

trunkNode.add( child: branchNode1 )
trunkNode.add( child: branchNode2 )
branchNode2.add( child: branchNode3 )
branchNode1.add( child: appleNode1 )
branchNode3.add( child: appleNode2 )

let tree = [trunkNode.equatableSelf,
            branchNode1.equatableSelf,
            branchNode2.equatableSelf,
            branchNode3.equatableSelf,
            appleNode1.equatableSelf,
            appleNode2.equatableSelf]

print( "expected result when printing the decoded trunk node: \(trunkNode)" )

let encoder = JSONEncoder()
let decoder = JSONDecoder()

encoder.outputFormatting = [.prettyPrinted, .sortedKeys]

// This is how the encoded tree looks like
let jsonTree = """
[
  {
    "trunkNode" : {
      "children" : [
        "399B35A7-3307-4EF6-8B4C-1B83A8F734CD",
        "60582654-13B9-40D0-8275-3C6649614069"
      ],
      "treePart" : {
        "trunk" : {
          "color" : "#CCC",
          "name" : "trunk"
        }
      },
      "uuid" : "55748AEB-271E-4560-9EE8-F00C670C8896"
    }
  },
  {
    "branchNode" : {
      "children" : [
        "0349C0DF-FE58-4D8E-AA72-7466749EB1D6"
      ],
      "parent" : "55748AEB-271E-4560-9EE8-F00C670C8896",
      "treePart" : {
        "branch" : {
          "length" : 4,
          "name" : "branch"
        }
      },
      "uuid" : "399B35A7-3307-4EF6-8B4C-1B83A8F734CD"
    }
  },
  {
    "branchNode" : {
      "children" : [
        "6DB14BD5-3E4A-40C4-8EBF-FBD3CC6050C7"
      ],
      "parent" : "55748AEB-271E-4560-9EE8-F00C670C8896",
      "treePart" : {
        "branch" : {
          "length" : 4,
          "name" : "branch"
        }
      },
      "uuid" : "60582654-13B9-40D0-8275-3C6649614069"
    }
  },
  {
    "branchNode" : {
      "children" : [
        "9FCCDBF6-27A7-4E21-8681-5F3E63330504"
      ],
      "parent" : "60582654-13B9-40D0-8275-3C6649614069",
      "treePart" : {
        "branch" : {
          "length" : 4,
          "name" : "branch"
        }
      },
      "uuid" : "6DB14BD5-3E4A-40C4-8EBF-FBD3CC6050C7"
    }
  },
  {
    "appleNode" : {
      "parent" : "399B35A7-3307-4EF6-8B4C-1B83A8F734CD",
      "treePart" : {
        "apple" : {
          "name" : "apple",
          "size" : 2
        }
      },
      "uuid" : "0349C0DF-FE58-4D8E-AA72-7466749EB1D6"
    }
  },
  {
    "appleNode" : {
      "parent" : "6DB14BD5-3E4A-40C4-8EBF-FBD3CC6050C7",
      "treePart" : {
        "apple" : {
          "name" : "apple",
          "size" : 2
        }
      },
      "uuid" : "9FCCDBF6-27A7-4E21-8681-5F3E63330504"
    }
  }
]
""".data(using: .utf8)!

do {
    print( "begin decoding" )
    /* This currently produces an error: Playground execution aborted: error: Execution was interrupted, reason: signal SIGABRT. The process has been left at the point where it was interrupted, use "thread return -x" to return to the state before expression evaluation.
    let decodedTree = try decoder.decode( [AnyTreePartNode].self, from: jsonTree )
    print( decodedTree.first( where: { $0.wrappedTreePartNode.treePart.wrappedTreePart is Trunk } )! )
    */
} catch let error {
    print( error )
}

How the decode function in AnyTreePartNode should decode the JSON? What am I missing?
Comment: What's the error?
Comment: @MikeTaverne I added the error message from playground as a comment at the end. But I don't think, this is helpful.
Comment: are you getting "Truck" as a resultant while decoding ?
Comment: @MAhipalSingh no, even if a call `self.init( TreePartNode( Trunk() ) )` inside the decoder init, the error appears in the line, where the JSON is decoded (at the bottom).
Comment: @SebKas, I'm getting    --> expected result when printing the decoded trunk node: Trunk { Branch { Apple }, Branch { Branch { Apple } } }
begin decoding
[Trunk, Branch, Branch, Branch, Apple, Apple]
Comment: @MAhipalSingh did you just uncomment my `if else` block in `AnyTreePartNode.init( from decoder: Decoder )`? I'm still getting a compile error when I do this. Did you change something else?
Comment: @SebKas yes i uncomment your code. i'm pasting code i had tried pls wait .
Answer: i have change just remove unowned from unowned var wrappedTreePartNode: TreePartNodeBase line
and compiled same code.
RESULT:
expected result when printing the decoded trunk node: Trunk { Branch { Apple }, Branch { Branch { Apple } } }
begin decoding
[Trunk, Branch, Branch, Branch, Apple, Apple]
Code:
//
//  ViewController.swift
//  TestDrive
//
//  Created by Mahipal on 25/04/18.
//  Copyright © 2018 Vandana. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        ////////////// Test (The actual usage of the implementation above)

        let trunk = Trunk()
        let branch1 = Branch()
        let branch2 = Branch()
        let branch3 = Branch()
        let apple1 = Apple()
        let apple2 = Apple()

        let trunkNode = TreePartNode<Trunk>( trunk )
        let branchNode1 = TreePartNode<Branch>( branch1 )
        let branchNode2 = TreePartNode<Branch>( branch2 )
        let branchNode3 = TreePartNode<Branch>( branch3 )
        let appleNode1 = TreePartNode<Apple>( apple1 )
        let appleNode2 = TreePartNode<Apple>( apple2 )

        trunkNode.add( child: branchNode1 )
        trunkNode.add( child: branchNode2 )
        branchNode2.add( child: branchNode3 )
        branchNode1.add( child: appleNode1 )
        branchNode3.add( child: appleNode2 )

        let tree = [trunkNode.equatableSelf,
                    branchNode1.equatableSelf,
                    branchNode2.equatableSelf,
                    branchNode3.equatableSelf,
                    appleNode1.equatableSelf,
                    appleNode2.equatableSelf]

        print( "expected result when printing the decoded trunk node: \(trunkNode)" )

        let encoder = JSONEncoder()
        let decoder = JSONDecoder()

        encoder.outputFormatting = [.prettyPrinted, .sortedKeys]

        // This is how the encoded tree looks like
        let jsonTree = """
[
  {
    "trunkNode" : {
      "children" : [
        "399B35A7-3307-4EF6-8B4C-1B83A8F734CD",
        "60582654-13B9-40D0-8275-3C6649614069"
      ],
      "treePart" : {
        "trunk" : {
          "color" : "#CCC",
          "name" : "trunk"
        }
      },
      "uuid" : "55748AEB-271E-4560-9EE8-F00C670C8896"
    }
  },
  {
    "branchNode" : {
      "children" : [
        "0349C0DF-FE58-4D8E-AA72-7466749EB1D6"
      ],
      "parent" : "55748AEB-271E-4560-9EE8-F00C670C8896",
      "treePart" : {
        "branch" : {
          "length" : 4,
          "name" : "branch"
        }
      },
      "uuid" : "399B35A7-3307-4EF6-8B4C-1B83A8F734CD"
    }
  },
  {
    "branchNode" : {
      "children" : [
        "6DB14BD5-3E4A-40C4-8EBF-FBD3CC6050C7"
      ],
      "parent" : "55748AEB-271E-4560-9EE8-F00C670C8896",
      "treePart" : {
        "branch" : {
          "length" : 4,
          "name" : "branch"
        }
      },
      "uuid" : "60582654-13B9-40D0-8275-3C6649614069"
    }
  },
  {
    "branchNode" : {
      "children" : [
        "9FCCDBF6-27A7-4E21-8681-5F3E63330504"
      ],
      "parent" : "60582654-13B9-40D0-8275-3C6649614069",
      "treePart" : {
        "branch" : {
          "length" : 4,
          "name" : "branch"
        }
      },
      "uuid" : "6DB14BD5-3E4A-40C4-8EBF-FBD3CC6050C7"
    }
  },
  {
    "appleNode" : {
      "parent" : "399B35A7-3307-4EF6-8B4C-1B83A8F734CD",
      "treePart" : {
        "apple" : {
          "name" : "apple",
          "size" : 2
        }
      },
      "uuid" : "0349C0DF-FE58-4D8E-AA72-7466749EB1D6"
    }
  },
  {
    "appleNode" : {
      "parent" : "6DB14BD5-3E4A-40C4-8EBF-FBD3CC6050C7",
      "treePart" : {
        "apple" : {
          "name" : "apple",
          "size" : 2
        }
      },
      "uuid" : "9FCCDBF6-27A7-4E21-8681-5F3E63330504"
    }
  }
]
""".data(using: .utf8)!

        do {
            print( "begin decoding" )
            // This currently produces an error: Playground execution aborted: error: Execution was interrupted, reason: signal SIGABRT. The process has been left at the point where it was interrupted, use "thread return -x" to return to the state before expression evaluation.
             let decodedTree = try decoder.decode( [AnyTreePartNode].self, from: jsonTree )
            print( decodedTree )

        } catch let error {
            print( error )
        }
    }

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

}

import Foundation

///////////// TreePart -> implemented by Trunk, Branch, Apple and AnyTreePart

protocol TreePart: Codable {
    var name: String { get set }

    func isEqualTo( _ other: TreePart ) -> Bool

    func asEquatable() -> AnyTreePart
}

extension TreePart where Self: Equatable {

    func isEqualTo( _ other: TreePart ) -> Bool {
        guard let otherTreePart = other as? Self else { return false }

        return self == otherTreePart
    }

    func asEquatable() -> AnyTreePart {
        return AnyTreePart( self )
    }
}

///////////// AnyTreePart -> wrapper for Trunk, Branch and Apple

class AnyTreePart: TreePart, Codable {

    var wrappedTreePart: TreePart

    var name: String {
        get {
            return self.wrappedTreePart.name
        }
        set {
            self.wrappedTreePart.name = newValue
        }
    }

    init( _ treePart: TreePart ) {
        self.wrappedTreePart = treePart
    }

    // MARK: Codable

    enum CodingKeys: String, CodingKey {
        case trunk,
        branch,
        apple
    }

    required convenience init( from decoder: Decoder ) throws {
        let container = try decoder.container( keyedBy: CodingKeys.self )

        var treePart: TreePart?

        if let trunk = try container.decodeIfPresent( Trunk.self, forKey: .trunk ) {
            treePart = trunk
        }

        if let branch = try container.decodeIfPresent( Branch.self, forKey: .branch ) {
            treePart = branch
        }

        if let apple = try container.decodeIfPresent( Apple.self, forKey: .apple ) {
            treePart = apple
        }

        guard let foundTreePart = treePart else {
            let context = DecodingError.Context( codingPath: [CodingKeys.trunk, CodingKeys.branch, CodingKeys.apple], debugDescription: "Could not find the treePart key" )
            throw DecodingError.keyNotFound( CodingKeys.trunk, context )
        }

        self.init( foundTreePart )
    }

    func encode( to encoder: Encoder ) throws {
        var container = encoder.container( keyedBy: CodingKeys.self )

        switch self.wrappedTreePart {

        case let trunk as Trunk:
            try container.encode( trunk, forKey: .trunk )

        case let branch as Branch:
            try container.encode( branch, forKey: .branch )

        case let apple as Apple:
            try container.encode( apple, forKey: .apple )

        default:
            fatalError( "Encoding error: No encoding implementation for \( type( of: self.wrappedTreePart ) )" )
        }
    }

}

extension AnyTreePart: Equatable {
    static func ==( lhs: AnyTreePart, rhs: AnyTreePart ) -> Bool {
        return lhs.wrappedTreePart.isEqualTo( rhs.wrappedTreePart )
    }
}

///////////// TreePartNodeBase -> implemented by TreePartNode<T: TreePart> and AnyTreePartNode

protocol TreePartNodeBase: class {

    var treePart: AnyTreePart { get set }

    var uuid: UUID { get }

    var parent: AnyTreePartNode? { get set }

    var weakChildren: NSPointerArray { get }

    func isEqualTo( _ other: TreePartNodeBase ) -> Bool

    func asEquatable() -> AnyTreePartNode
}

extension TreePartNodeBase where Self: Equatable {

    func isEqualTo( _ other: TreePartNodeBase ) -> Bool {
        guard let otherTreePartNode = other as? Self else { return false }

        return self == otherTreePartNode &&
            self.treePart == other.treePart &&
            self.uuid == other.uuid &&
            self.parent == other.parent &&
            self.children == other.children
    }

    func asEquatable() -> AnyTreePartNode {
        return AnyTreePartNode( self )
    }
}

extension TreePartNodeBase {
    var children: [AnyTreePartNode] {
        guard let allNodes = self.weakChildren.allObjects as? [AnyTreePartNode] else {
            fatalError( "The children nodes are not of type \( type( of: AnyTreePartNode.self ) )" )
        }

        return allNodes
    }
}

///////////// AnyTreePartNode -> wrapper of TreePartNode<T: TreePart>

class AnyTreePartNode: TreePartNodeBase, Codable {
     var wrappedTreePartNode: TreePartNodeBase

    var treePart: AnyTreePart {
        get {
            return self.wrappedTreePartNode.treePart
        }
        set {
            self.wrappedTreePartNode.treePart = newValue
        }
    }

    var uuid:                  UUID {
        return self.wrappedTreePartNode.uuid
    }

    /// The parent node
    weak var parent: AnyTreePartNode? {
        get {
            return self.wrappedTreePartNode.parent
        }
        set {
            self.wrappedTreePartNode.parent = newValue
        }
    }

    /// The weak references to the children of this node
    var weakChildren: NSPointerArray {
        return self.wrappedTreePartNode.weakChildren
    }

    init( _ treePartNode: TreePartNodeBase ) {
        self.wrappedTreePartNode = treePartNode
    }

    // MARK: Codable

    enum CodingKeys: String, CodingKey {
        case trunkNode,
        branchNode,
        appleNode
    }

    required convenience init( from decoder: Decoder ) throws {
        let container = try decoder.container( keyedBy: CodingKeys.self)

        // This attempt of decoding possible nodes doesn't work

         if let trunkNode: TreePartNode<Trunk> = try container.decodeIfPresent( TreePartNode<Trunk>.self, forKey: .trunkNode ) {
         self.init( trunkNode )

         } else if let branchNode: TreePartNode<Branch> = try container
         .decodeIfPresent( TreePartNode<Branch>.self, forKey: .branchNode ) {
         self.init( branchNode )

         } else if let appleNode: TreePartNode<Apple> = try container
         .decodeIfPresent( TreePartNode<Apple>.self, forKey: .appleNode ) {
         self.init( appleNode )

         } else {
         let context = DecodingError.Context( codingPath: [CodingKeys.trunkNode,
         CodingKeys.branchNode,
         CodingKeys.appleNode],
         debugDescription: "Could not find the treePart node key" )
         throw DecodingError.keyNotFound( CodingKeys.trunkNode, context )
         }

        // TODO recreating the connections between the nodes should happen after all objects are decoded and will be done based on the UUIDs
    }

    func encode( to encoder: Encoder ) throws {
        var container = encoder.container( keyedBy: CodingKeys.self )

        switch self.wrappedTreePartNode {

        case let trunkNode as TreePartNode<Trunk>:
            try container.encode( trunkNode, forKey: .trunkNode )

        case let branchNode as TreePartNode<Branch>:
            try container.encode( branchNode, forKey: .branchNode )

        case let appleNode as TreePartNode<Apple>:
            try container.encode( appleNode, forKey: .appleNode )

        default:
            fatalError( "Encoding error: No encoding implementation for \( type( of: self.wrappedTreePartNode ) )" )
        }
    }
}

extension AnyTreePartNode: Equatable {
    static func ==( lhs: AnyTreePartNode, rhs: AnyTreePartNode ) -> Bool {
        return lhs.wrappedTreePartNode.isEqualTo( rhs.wrappedTreePartNode )
    }
}

// enables printing of the wrapped tree part and its child elements
extension AnyTreePartNode: CustomStringConvertible {
    var description: String {
        var text = "\( type( of: self.wrappedTreePartNode.treePart.wrappedTreePart ))"

        if !self.children.isEmpty {
            text += " { " + self.children.map { $0.description }.joined( separator: ", " ) + " }"
        }
        return text
    }
}

///////////// TreeParts (Trunk, Branch and Apple)

class Trunk: TreePart, Codable, Equatable {
    var name: String

    var color: String

    init( name: String = "trunk",
          color: String = "#CCC" ) {
        self.name = name
        self.color = color
    }

    static func ==(lhs: Trunk, rhs: Trunk) -> Bool {
        return lhs.name == rhs.name &&
            lhs.color == rhs.color
    }
}

class Branch: TreePart, Codable, Equatable {
    var name: String

    var length: Int

    init( name: String = "branch",
          length: Int = 4 ) {
        self.name = name
        self.length = length
    }

    static func ==(lhs: Branch, rhs: Branch) -> Bool {
        return lhs.name == rhs.name &&
            lhs.length == rhs.length
    }
}

class Apple: TreePart, Codable, Equatable {
    var name: String

    var size: Int

    init( name: String = "apple",
          size: Int = 2 ) {
        self.name = name
        self.size = size
    }

    static func ==(lhs: Apple, rhs: Apple) -> Bool {
        return lhs.name == rhs.name &&
            lhs.size == rhs.size
    }
}

///////////// TreePartNode -> The node in the tree that contains the TreePart

class TreePartNode<T: TreePart>: TreePartNodeBase, Codable {

    var equatableSelf: AnyTreePartNode!

    var uuid: UUID

    var treePart: AnyTreePart

    var weakChildren = NSPointerArray.weakObjects()

    private var parentUuid : UUID?

    private var childrenUuids : [UUID]?

    weak var parent: AnyTreePartNode? {
        willSet {
            if newValue == nil {
                // unrelated code
                // ... removes the references to this object in the parent node, if it exists
            }
        }
    }

    init( _ treePart: AnyTreePart,
          uuid: UUID = UUID() ) {
        self.treePart = treePart
        self.uuid = uuid
        self.equatableSelf = self.asEquatable()
    }

    convenience init( _ treePart: T,
                      uuid: UUID = UUID() ) {
        self.init( treePart.asEquatable(),
                   uuid: uuid )
    }

    init( _ treePart: AnyTreePart,
          uuid: UUID,
          parentUuid: UUID?,
          childrenUuids: [UUID]?) {

        self.treePart = treePart
        self.uuid = uuid
        self.parentUuid = parentUuid
        self.childrenUuids = childrenUuids
        self.equatableSelf = self.asEquatable()
    }

    private func add( child: AnyTreePartNode ) {
        child.parent = self.equatableSelf
        self.weakChildren.addObject( child )
    }

    private func set( parent: AnyTreePartNode ) {
        self.parent = parent
        parent.weakChildren.addObject( self.equatableSelf )
    }

    // MARK: Codable

    enum CodingKeys: String, CodingKey {
        case treePart,
        uuid,
        parent,
        children,
        parentPort
    }

    required convenience init( from decoder: Decoder ) throws {
        let container         = try decoder.container( keyedBy: CodingKeys.self )

        // non-optional values
        let uuid:   UUID      = try container.decode( UUID.self, forKey: .uuid )
        let treePart: AnyTreePart = try container.decode( AnyTreePart.self, forKey: .treePart )

        // optional values
        let childrenUuids: [UUID]?     = try container.decodeIfPresent( [UUID].self, forKey: .children )
        let parentUuid:    UUID?       = try container.decodeIfPresent( UUID.self, forKey: .parent )

        self.init( treePart,
                   uuid: uuid,
                   parentUuid: parentUuid,
                   childrenUuids: childrenUuids)
    }

    func encode( to encoder: Encoder ) throws {
        var container = encoder.container( keyedBy: CodingKeys.self )

        // non-optional values
        try container.encode( self.treePart, forKey: .treePart )
        try container.encode( self.uuid, forKey: .uuid )

        // optional values
        if !self.children.isEmpty {
            try container.encode( self.children.map { $0.uuid }, forKey: .children )
        }

        try container.encodeIfPresent( self.parent?.uuid, forKey: .parent )
    }
}

extension TreePartNode: Equatable {
    static func ==( lhs: TreePartNode, rhs: TreePartNode ) -> Bool {
        return lhs.treePart == rhs.treePart &&
            lhs.parent == rhs.parent &&
            lhs.children == rhs.children
    }
}

// enables printing of the wrapped tree part and its child elements
extension TreePartNode: CustomStringConvertible {
    var description: String {
        var text = "\( type( of: self.treePart.wrappedTreePart ))"

        if !self.children.isEmpty {
            text += " { " + self.children.map { $0.description }.joined( separator: ", " ) + " }"
        }
        return text
    }
}

// MARK: functions for adding connections to other TreeParts for each specific TreePart type

extension TreePartNode where T: Trunk {
    func add( child branch: TreePartNode<Branch> ) {
        self.add( child: branch.equatableSelf )
    }
}

extension TreePartNode where T: Branch {
    func add( child apple: TreePartNode<Apple> ) {
        self.add( child: apple.equatableSelf )
    }

    func add( child branch: TreePartNode<Branch> ) {
        self.add( child: branch.equatableSelf )
    }

    func set( parent branch: TreePartNode<Branch> ) {
        self.set( parent: branch.equatableSelf )
    }

    func set( parent trunk: TreePartNode<Trunk> ) {
        self.set( parent: trunk.equatableSelf )
    }
}

extension TreePartNode where T: Apple {
    func set( parent branch: TreePartNode<Branch> ) {
        self.set( parent: branch.equatableSelf )
    }
}

////////////// Helper

extension NSPointerArray {

    func addObject( _ object: AnyObject? ) {
        guard let strongObject = object else { return }
        let pointer = Unmanaged.passUnretained( strongObject ).toOpaque()
        self.addPointer( pointer )
    }

}

Comment: I see, but this is really inconvenient. In the following example an added `Branch` is set to nil, but its `deinit` function is not called, because it's wrapper stil has a reference to it:

`trunkNode.add( child: branchNodeA )`
`trunkNode.add( child: branchNodeB )`

`branchNodeA = nil // deinit is not called` but with
`branchNodeA.equatableSelf = nil // deinit is called and object is removed from tree`

If there is no better solution, I guess I have to define a `remove()` function.
Comment: This works for this case. But wouldn't a strong reference to the wrapped `TreePartNode` create an unwanted memory leak? I mean if afterwards one `TreePartNode` is deallocated (e.g. by setting it to `nil`), the `AnyTreePartNode` wrapper still exists, right?
Comment: @SebKas you need to remove wrapper object, when its not in use


VB6 Using DataControl

Question:
Hello guys, just want you to ask something about my code... I have 5 records n my database with the UserID of A02-0005... I want to get it all using DataControl and display into TextBoxes respectively... My problem is I get only a single set of record and when I click the NextButton of DataControl, nothing happens. At the design time, I'd set the DatabaseName, RecourdSource, and RecordSetType of my DataControl... Where then the problem possibly occurs? I am using VB6... Thanks in advance.
Comment: Can you bind a filtered recordset to a grid control?
Comment: Perhaps... pls give me any suggestion to get it.
Answer: The problem here is with the Seek method. The method takes another argument called SeekOption and by default it will just find the first match.
Instead you could use the Find method on the Recordset as follows. You need to specify your search criteria and also where in the recordset to begin searching from.
Data1.Recordset.Find Criteria:="idxid= 'A02-0005'", Start:=adBookmarkFirst

Finally if you want your text boxes to update automatically when the user clicks the data control then you can just set the DataSource & DataField properties of the text box controls at design time.

VB6 Using DataControl


what is null hypothesis in a simple term?

Question: I am new here, reading a lot what null hypothesis is but not quite get clear picture. Could someone give me a simple explanatation or example please.
Comment: It might make more sense to try to figure out what particular parts of what you're reading are remaining unclear and focus attention on those. If you've read a lot you'll likely have read explanations people would give here also (in what you're reading almost everyone is attempting to give you simple explanations already), so identifying your specific concerns would improve people's ability to give helpful answers rather than more of the same explanations.
Answer: Imagine someone proposes a research question, like 'electric car sales are increasing'. Now they must test it with a hypothesis test.
The null hypothesis can be thought of as the hypothesis of no change. For example, 'electric car sales are the same as last year'
The alternative hypothesis usually links to the research question. For example, 'electric car sales have increased since last year'
Now, we need evidence (data) to reject the null hypothesis, which would allow us to conclude that electric car sales are not the same as last year. If we did not have strong enough evidence to reject the null hypothesis, we can't say that it's necessarily true, we just conclude that we 'fail to reject the null hypothesis'.
Answer: The null hypothesis is the hypothesis you want to reject. Usually, but not always, it is "no change" or "no relationship" or something similar.
In statistical hypothesis inference testing, you test the null by gathering data and running a test (which kind depends on what data you have and what you are trying to show) and then seeing if the results are unlikely if the null is true. How unlikely they have to be is up to you, but common levels are 5% and 1%.
We then either reject the null (yippee!) or fail to reject (we don't accept it). This is similar to a criminal trial (at least in the US and many other places) where we can find the defendant "guilty" or "not guilty" but not "innocent".  The prosecution has to prove its case.
In statistics, the researchers are the prosecution and they have to prove their case.
In my opinion, nulls other than the usual are not used enough and unconventional levels of doubt to reject are also not used enough. But that's an aside.
Comment: IMO null hypotheses can be useful, but often I find that a null effect is already out of the question and rather it is a matter of deciding which of a set of alternative hypotheses are the best reflection of the data generating process. Outside of NHST, for me, it often becomes a matter of comparing models whether they are null or not.
Answer: Consider the frequentist approach: you repeat an experiment N times, you record a value of interest and with those N measures you create a distribution. This distribution tells how frequent each value you may later observd is. In a general setting this distribution is already available (say, the t-distribution), so for the purpose of this explanation we might call it "the theoretical distribution".
Now you come in with the value you observed on your data, and you compare it to the theoretical distribution. Where it lands? If it lands on the extremes than you might conclude that your value does not come from that theoretical distribution.
The null hypothesis is the hypothesis you assume to be true when generating the theoretical distribution we mentioned above. So when your value "fits in" the theoretical distribution, you cannot reject your assumptions - that is, the null hypothesis. If your value is very extreme then you conclude that probably your value does not come from that distribution and you have yo reject your initial hypothesis/assumptions.
Probably is not a very precise explanation but I think the intuition is there.


Combo Box with option that can only be selected programatically and not by the user in VBA Access

Question: I have a combobox that has a special requirement. It needs to have an item that can only be selected by the program (based on certain criteria detected) and cannot be selected by the user itself. Is there any way to do this in VBA Access?
I found  this solution but it is somewhat of a workaround which I will do if there is not a better alternative. What I want is for the option to not even be visible.
Comment: Why even make it a combobox if the user shouldn't access it or be able to change the value. Just use a TextBox and present the value you want displayed?
Comment: why should it be in the combo box then?
Comment: Well there are a variety of options the user can select. There is just this one that it cannot that the program has to detect. If this option were to be set, then it will be locked and can only be unset programatically.
Comment: I suppose I could add the item, select it immediately, then lock it. When it needs to be unset I can unlock it, set the value to the default, and remove the item from the combobox.
Comment: If you know that the program has to use a certain value, just ignore whatever value is in the combobox and use the value you need to use instead.
Comment: I do not want this one particular option to be visible from the drop down menu. It should just be automatically selected based on certain criteria of the form but in no way should the user be able to select it himself.
Comment: It sounds like you just want an `If` statement in your code - i.e. `If need_to_use_specific_value Then use_value = specific_value Else use_value = combobox.Value` (or something like that)
Comment: @jsotola It needs to be in the combo box because it is related to all the other items in the combo box. When this particular value is set, I want it to be "illegal" to try and select another value for the combobox.
Comment: @YowE3K Can I give a value that does not exist inside of the combobox? How would I make it a two column value?
Comment: does that mean that the combo box is disabled completely when the value is set?
Comment: Yeah the value is locked in
Comment: It would really help if you showed the code you are using that is making use of the combobox's value.
Comment: set the combobox `enabled` property to false to disable the combobox
Answer: You could add an "on change" event to the combo box. Lets say the option which can only be chosen programmatically is "Program only item". I have also assumed that you have a previous field in the form which we can move the focus back to. You haven't mentioned what the criteria for this option is so for arguments sake I will presume that the previous field has to be 1 not 0 (you will have to alter the if...then clause to suit your criteria).
private sub cbo_list_change()

if me.cbo_list.value "Program  only item" then
  if me.chk_previous.value = 0 then
    msgbox "This item cannot be selected. Please select an alternative item", vbOKOnly
    me.cbo_list.value =""
    chk_previous.setFocus
  end if
end if

End sub

You will be able to use me.cbo_list.value="program only option" in a different event when the criteria is met.
Answer: You should try to move business logic out of your forms. You need two functions for this task.
Function SelectAndLock(ByRef SelectPicker As ComboBox, Id As Long)

    Dim SQL_GET As String
    SQL_GET = "SELECT ID, Text From ComboBoxValues WHERE [ID] = " & Id

    SelectPicker.RowSourceType = "Table/Query"
    SelectPicker.RowSource = SQL_GET
    SelectPicker.Value = Id
    SelectPicker.enabled = False

End Function

Function PopulateSelectPicker(ByRef SelectPicker As ComboBox)

    Dim SQL_GET As String
    SQL_GET = "SELECT ID, Text From ComboBoxValues WHERE [ID] not in (your system ids);"

    SelectPicker.RowSourceType = "Table/Query"
    SelectPicker.RowSource = SQL_GET
    SelectPicker.Value = "" ' or null if your field is nullable
    SelectPicker.enabled = True

End Function

Now if your model has dedected the "system" condition, you would call
call SelectAndLock(SelectPicker,id)

Which would select the id that the system choses and locks the combobox.
any other condition or by default, simply call
call PopulateSelectPicker(SelectPicker)

Which would list all options except the system ids user shouldn't see.
This is just a concept. Adapt it as you require.
Answer: This situation seems very strange, and I would never want it in my app... but accepting for the moment that the approach desired is correct and good, and a solution is needed...
You can bind to the data source table field (since you're in MS Access I assume bound forms, though that's not guaranteed) via a hidden control (textbox, I'll assume) that we'll call txtYouNoSeeMe.
Let's refer to the value you want to let the system select (but not the user) as NoPickMe.
Now you need to give your user the ability to select "most options" -- set up that combobox (cboYesYouSeeMe) as necessary and leave it unbound. NoPickMe is not an option on that list.
Finally, you will sadly have to wrap some logic into handling AfterUpdate events for cboYesYouSeeMe. When you wish to permit the user to select an option in cboYesYouSeeMe, you need to then transport the value selected over to your HIDDEN bound control txtYouNoSeeMe. Do that in the AfterUpdate event.
When you wish to have the system pick that "hidden" value NoPickMe (that the user should not see) so be it... place that value into the hidden txtYouNoSeeMe. I have no idea what you're going want to display (in such cases) in cboYesYouSeeMe.
When the record saves, txtYouNoSeeMe drives the value saved to the database. If no database is involved, then just ignore my references to data binding.
This solution works, though I may have forgotten to explain a detail or two. Hopefully you get the idea.


Why aren't the options in my dynamically inserted webform showing up?

Question: I've created a webform with one question that includes a list of checkboxes.
I made the webform available as a block, and am rendering the block in my template using:
<code><?php
$block = module_invoke('webform', 'block_view', 'client-block-#####');
print render($block['content']);
?>
</code>
However, when the form renders, I see the title of the question and the submit button, but the options are not visible. How can I debug why the checkbox options aren't showing up?
Answer: I checked admin/reports/dblog and it turns out the select_or_other plugin wasn't properly installed, stopping the options from showing up at all.


Showing torsion of a curve is constant

Question: I tried to simply find the torsion first by computing $- \frac{{\mathbf N\times B'}}{||\mathbf{r'(t)}||} $ and I was hoping to obtain a constant, but the algebra was too messy and so gave up on that method. I also tried to parametrise the curve with its natural parametrise but I couldn't find this due to t>0.
So I was wondering how this can be done.
Answer: I'll write $\;r(t)=\left(\,1+t\log t,\,-t\log t,\,t^2\,\right) , \;t>0\;$ , so the torsion at any point is given by
$$\tau(t)=\frac{\left(r'\times r''\right)\cdot r'''}{\left\|r'\times r''\right\|^2}$$
and
$$\begin{cases}&r'=(\,\log t+1,\,-\log t-1,\,2t\,)\\{}\\
&r''=\left(\,\frac1t,\,-\frac1t,\,2\,\right)\\{}\\
&r'''=\left(\,-\frac1{t^2},\,\frac1{t^2},\,0\,\right)\end{cases}\;\;\;\;\implies $$
$$\implies r'\times r''=\begin{vmatrix}i&j&k\\
1+\log t&-1-\log t&2t\\
\frac1t&-\frac1t&2\end{vmatrix}=\left(\,-2\log t,\,-2\log t,\,0\,\right)$$
and
$$ \tau(t)=\frac1{8\log^2t}\left(\,\frac{2\log t}{t^2}-\frac{2\log t}{t^2}\,\right)=0$$

Showing torsion of a curve is constant


easyprocess.EasyProcessCheckInstalledError: cmd=['Xvfb', '-help'] OSError=[Errno 2] No such file or directory

Question: I'm trying to setup a display but it's telling me No such file or directory.
Traceback (most recent call last):
  File "/var/www/envs/venv/proj/scripts/my_file.py", line 44, in click
    display = Display(visible=0, size=(800,600))
  File "/usr/lib/python2.6/site-packages/pyvirtualdisplay/display.py", line 33, in __init__
    self._obj = self.display_class(
  File "/usr/lib/python2.6/site-packages/pyvirtualdisplay/display.py", line 51, in display_class
    cls.check_installed()
  File "/usr/lib/python2.6/site-packages/pyvirtualdisplay/xvfb.py", line 38, in check_installed
    ubuntu_package=PACKAGE).check_installed()
  File "/usr/lib/python2.6/site-packages/easyprocess/__init__.py", line 209, in check_installed
    raise EasyProcessCheckInstalledError(self)
easyprocess.EasyProcessCheckInstalledError: cmd=['Xvfb', '-help']
OSError=[Errno 2] No such file or directory
Program install error!

Comment: it was shell path problem: https://stackoverflow.com/a/74157376/8108684
Answer: You likely need to install either the xvfb package, or possibly the xvfbwrapper:
First check and see if xvfb is installed:
Xvfb -help

If the command is not found then you can usually install the xvfb package with the following command (or whichever package manager you generally use):
sudo apt-get install xvfb

xvfbwrapper is  Python wrapper for running a display inside X virtual framebuffer (Xvfb).
You can install it with:
pip install xvfbwrapper

The error you are getting seems to be a result of either the command or module not being found.
Comment: @rojas, windows doesn't run X11.
Comment: @BartekR. Just remove anything related to pyvirtualdisplay on Windows. You don't need it because of Windows graphics engine
Comment: Hi, `pip install xvfbwrapper` does not seem to cut it on windows. Any ideas?
Comment: Hi, I installed xvfb through Xquartz and I made sure it was correctly installed by `Xvfb - help`, but it still says it can't detect xvfb. Thanks
Comment: @li.SQ: How have you installed Xquartz? It uses its own window system, and in order to use xvfb with it I believe you would need to compile it from source using particular options which it would require.
Comment: @I'L'l Yes, I have installed Xquartz by installing the .pkg file. Can you explain "compile it from source"?
Comment: @li.SQ: Check the following link where it mentions `xorg-server`: https://www.xquartz.org/Developer-Info.html. If you can't figure it out then I would recommend posting a new question as your issue isn't really related to this question.
Answer: I encountered this error on a Mac and (finally) solved it by install Xquartz: https://www.xquartz.org/ (reboot after install!)


including javascript via theme.info doesn't work.

Question: I'm trying to include a simple javascript into my theme using the theme.info
It works like a charm on my home-setup but when I try to load in on a real page it doesn't include the .js-files (not even an empty


Box shadow around column of CSS grid

Question: I currently have a CSS grid with a dynamic number of rows where there are subsets of the rows that should be grouped together. I'd like to wrap the first column of those groups together with a drop shadow, but I can't figure out how to do this. I'm able to accomplish what I want with a border, because I'm able to drop the top and bottom border of the middle elements.
Is there a way to do this with or without a grid layout?

.grid {
  display: grid;
  grid-template-columns: 250px 250px 250px;
  grid-column-gap: 20px;
}

.top,
.middle,
.bottom {
  border: 2px solid black;
}

.top {
  border-bottom: none;
}

.middle {
  border-top: none;
  border-bottom: none;
}

.bottom {
  border-top: none;
}

.title {
  text-align: center;

  padding: 5px 20px;
}

.title span {
  margin: 0 20px;
}

.title,
.details,
.actions {
  text-align: center;
  vertical-align: middle;
  margin: auto 0;
}

    row 1 title

  row 1 details
  row 1 actions

    row 2 title

  row 2 details
  row 2 actions

    row 3 has an extra long tile that wraps around

row 3 details

  row 3 actions

    row 4 title

  row 4 details
  row 4 actions

    row 5 title

  row 5 details
  row 5 actions

    row 6 title

  row 6 details
  row 6 actions

Answer: There is no way to apply styles to all grid items in a specific column or row or group them for that matter. You are already doing the possible option to target the elements directly.

Hacky solution
Here I'm going to use the fact that you are using top, middle and bottom clases and creating and effect of box shadow:

use a convenient box-shadow to a pseudo element placed behind the grid items  in the first column,

use background on the grid item to match the column and therefore hiding from view the shadow in between rows,

now use a margin to separate at the bottom class.

.grid {
  display: grid;
  grid-template-columns: 250px 250px 250px;
  grid-column-gap: 20px;
}

.top:after,
.middle:after,
.bottom:after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
  box-shadow: 0 0px 10px 2px #ddd;
  background: #fff;
}

.title.bottom {
  margin-bottom: 15px;
  background: transparent;
}

.title {
  text-align: center;
  position: relative;
  padding: 5px 20px;
  background: #fff;
}

.title span {
  margin: 0 20px;
}

.title,
.details,
.actions {
  text-align: center;
  vertical-align: middle;
  margin: auto 0;
}

    row 1 title

  row 1 details
  row 1 actions

    row 2 title

  row 2 details
  row 2 actions

    row 3 has an extra long tile that wraps around

row 3 details

  row 3 actions

    row 4 title

  row 4 details
  row 4 actions

    row 5 title

  row 5 details
  row 5 actions

    row 6 title

  row 6 details
  row 6 actions

Comment: I tried so many things like this, but couldn't quite get it to work, so thanks! FWIW, if anyone else comes across this, there were additional steps needed to make this work in my setup. This other SO answer was crucial to figuring it out: https://stackoverflow.com/a/9072467/681081.

Essentially, the shadows weren't showing up, so I needed to set the psuedo selector's parent (.grid) to be relative positioned with a z-index of 1 in order for the shadows to appear.

Box shadow around column of CSS grid


Alternate tempo indications in Janáček's Mládí

Question: What is the reason for the alternate tempo markings in Janáček's Mládí here and elsewhere? Is one of them aimed at players who are no longer in the first flush of 'Youth' maybe?
Comment: It looks as if it's reflecting two sources. I would think there would be an explanatory note somewhere. What edition is this and where did you find it?
Comment: It's the one on IMSLP as mentioned in @Aaron's answer.
Answer: The edition on IMSLP (which appears to be the one in the original question) is the second edition. And the introductory notes explain that the tempi in the second edition are different from those in the first.

The first performance of the suite took place at Brno, on 21st October 1924, to celebrate Janáček's seventieth birthday; the concert was arranged by the State Conservatoire of Music. The Hudební Matice Umělecké Besedy published the score, parts and a piano reduction of the suite for the first time in 1925. This new, second edition of the score has been revised to match the copy rewritten under the guidance of the composer after the first performance of the work at Brno, but not in accordance with the original manuscript.

From the Czech portion of the introduction:

Th[is] new edition in the Collection of pocket scores is based on the same principle as was applied in the printing of the score when it was first published, with the difference that, in the movement rules, it first respects Janáček's original data from Sedláček's copy[,] and everything that was ... in the first [edition] changed or added to are marked with brackets. The first of these data preserves as an image the composer's own ideas, interesting even if perhaps not always accurately expressed (although, for example, the Moderato designation at the beginning of the second movement seems to describe that idea better than the confused Andante sostenuto), the second group of data is maintained because it was printed during the composer's lifetime, and therefore probably with his consent.•) Otherwise, in places where it was desirable, the new edition according to the printed voices is supplemented with a few force marks, which are also indicated by brackets for differentiation, and further the printed ones are corrected [for] errors and [deletion of] superfluous shift signs, as always with Janáček and here in the original wording very common.1

The footnote also gives an example of Janáček's changes in tempo. It translates:

For comparison, I also list here the metronomic numbers in which he performed them with the Pralsky Wind Quintet, different from those in the first edition of the score....

1 Original text

Nové vydání ve Sbírce kapesních partitur vychází ze stejné zásady, jaká byla v tisku partitury uplatněna při prvním jejím vydání, s tím však rozdílem, že v pohybových předpisech respektuje na prvém místě původní Janáčkovy údaje ze Sedláčkova opisu a všechno, co v nich bylo v prvém vydání změněno nebo k nim přidáno, má označeno uzávorkoviním. První z těchto údajů zachovává jako obraz vlastní představy skladatelovy, zajímavé i když snad ne všady přesně vyjádřené (ačkoliv na př. označení Moderato na začátku druhé věty zdá se onu představu lépe vystihovati, než zaměněné Andante sostenuto), druhou skupinu údajů podržuje proto, že byla otištěná za skladatelova života a tedy patrně s jeho souhlasem.•) Jinak v místech, v nichž to bylo žádoucí, je nové vydání podle tistěných hlasů doplněno několika znaménky silovými, která pro odlišení jsou rovněž označena uzávorkováním, a dále jsou v něm opraveny tiskové chyby a vypuštěna přebytečná znaménka posuvná, jako vždy u Janáčka i zde v původním znění velmi častá.


Banco Consumindo toda memoria

Question: Bom dia estou com um problema , os usuários de um determinado sistema estão com problemas na hora de consultar um nome no sistema "uma pesquisa simples" , entrei no banco e notei que no sql tem vários bancos e um deles que não o do sistema que os usuários reclama esta consumindo 97% do total de memoria RAM do meu servidor , ele esta sempre assim não importa a hora ou quantas pessoas estão usando, gostaria de saber se isso esta errado  e se tem algo que eu possa fazer segue os dados
Comment: precisa de mais informação antes de até dar uma direção. A primeira coisa que eu diria é fazer um profile e identificar se alguma query está fazendo com que o banco consuma tanta memória, as vezes um aparentemente inocente `OR` ou um campo null fazem estragos. Verifique primeiro se um query está causando isso, e se não for, dá pra idetificar os processos, mas sugiro começar por ai
Comment: como eu teria que proceder para verificar as query e ver o tanto que elas estão consumindo , desculpa a falta de informação mais sou desenvolverdor junior e nunca tive que controlar banco desse jeito , antes quem fazia isso era um dba
Answer: Abra o SQL Management Studio, conecte-se ao servidor que ocupa toda a memória, com um usuário administrador.
Clique com o direito sobre o servidor na janela Object Explorer e selecione Propriedades.

Ajuste a memória e clique em OK.
Comment: obrigado Marcelo novamente
Comment: muito obrigado marcelo , sera que isso pode dar algum problema de lentidão no banco que esta ocupando muita memoria ou sera que ele esta ocupando essa memoria sem necessidade . pq atem nos finais de semana que não tem nenhum usuario ele fica desse jeito
Comment: O normal do SQL Server *é* alocar toda a memória disponível. Se você diminuir os valores na instrução que te passei, ele vai alocar menos.
Comment: Não há de quê, @FlavioSs!

Banco Consumindo toda memoria


Jetty Vs Tomcat for a JSF based social networking & sharing website

Question: I need to host my JavaServerFaces application which is a sort of networking & sharing website.
Which amongst Jetty & Tomcat is recommended for my app? Need easy scalability, better performance & low costs.
Comment: Keeping in mind that there is no license costs for both and that the scalability and performances will be more a function of your application code than anything else, my advice is to choose the one you're most familiar with. If you've developed your application on Tomcat, then keep using Tomcat for production, and the same thing about Jetty.
Answer: We run multiple Java web apps on Tomcat with no issues. And we run them all on CentOS.


Should I report z-score, p-value or both for Mann-Whitney U test under APA guidelines?

Question: As titled, I ran a MWU test on my test results but I'm not sure what I'm supposed to report. My results section currently looks like this. Help?
Comment: Have you checked whether this particular test is covered in the *APA Publication Manual*?
Comment: Here is an incantation to ward off close-voters: https://stats.meta.stackexchange.com/q/3132/1352
Answer: I would suggest you report the statistic ($U$) and the $p$ value. That is usually sufficient. If the reviewers want $z$ scores or anything else as well, they will tell you. But that should be enough information to get past the first hurdle.
And of course, I would recommend that you check the APA Publication Manual, which I don't have with me, but which may indeed cover this particular test in its sheer comprehensiveness.
Answer: Stephan's answer is pretty good, but APA also recommends reporting standardized effect sizes, even though sometimes they're not as important as they seem to be. Looks like you have the $r$ value that pertains to the $z$ approximation to the $U$ statistic, which is discussed in this paper by Fritz, Morris, & Richler (2012) as a good effect size measure to use.


Oque é uma API Rest para comunicação com front e backend?

Question: Não consegui entender oque é uma API Rest para fazer a comunicação  front e backend
Answer: A Representational State Transfer (REST), em português Transferência de Estado Representacional, é uma abstração da arquitetura da World Wide Web, mais precisamente, é um estilo arquitetural que consiste de um conjunto coordenado de restrições arquiteturais aplicadas a componentes, conectores e elementos de dados dentro de um sistema de hipermídia distribuído.
O REST ignora os detalhes da implementação de componente e a sintaxe de protocolo com o objetivo de focar nos papéis dos componentes, nas restrições sobre sua interação com outros componentes e na sua interpretação de elementos de dados significantes.
Ele foi definido oficialmente pela W3C.
Ele é frequentemente aplicado à web services fornecendo APIs para acesso a um serviço qualquer na web. Ele usa integralmente as mensagens HTTP para se comunicar através do que já é definido no protocolo sem precisar "inventar" novos protocolos específicos para aquela aplicação.
Você trabalha essencialmente com componentes, conectores e dados.
Ele usa o protocolo HTTP (verbos, accept headers, códigos de estado HTTP, Content-Type) de forma explícita e representativa para se comunicar. URIs são usados para expor a estrutura do serviço. Utiliza uma notação comum para transferência de dados como XML ou JSON.
Não possui estado entre essas comunicações, ou seja, cada comunicação é independente e uniforme (padronizada) precisando passar toda informação necessária.
Ele deve facilitar o cache de conteúdo no cliente.
Deve ter clara definição do que faz parte do cliente e do servidor. O cliente não precisa saber como o servidor armazena dados, por exemplo. Assim cada implementação não depende da outra e se torna mais escalável.
Permite o uso em camadas também facilitando a escalabilidade, confiabilidade e segurança.
Frequentemente é criado com alguma forma de extensibilidade.
Exemplo:
http://example.com/apagar/produto/1234
significa que você está pedindo para apagar o produto de ID 1234.
Há quem diga que isto está errado e já que a ênfase é em cima dos recursos e não das operações. Deveria usar assim:
http://example.com/produto/1234 (utilizando o verbo DELETE)
Convenhamos que isto pode servir para CRUD, mas existem tantas variações do que precisa ser feito que não é possível representar tudo só com os verbos HTTP. Ok, é possível fazer tudo parecer CRUD, mas talvez exija informações adicionais em nome do formalismo.
Tudo isto é pensado para proporcionar melhor performance, escalabilidade, simplicidade, flexibilidade, visibilidade, portabilidade e confiabilidade.
Cada um define como quiser sua API, ao contrário de SOAP onde tudo é definido oficialmente.


How to check whether QTP is launched in remote machine using VBS

Question: I am trying to launch QTP on a remote server using VBS. I am running VBS file using C# code. When I am running my C# application from local machine it's giving me VBS error messages if there is any error in VBS file. But when I am running the same C# application after deploying to our server it's not giving me any error messages even if there is an error in my VBS file. Can some one please help me with this?
C# Code
protected void btnExecuteScript_Click(object sender, EventArgs e)
{
     System.Diagnostics.Process.Start(@"C:\test1.vbs");
}

VBS Code
Dim qtApp
Dim qtTest
Dim qtResultsOpt

Set qtApp = CreateObject("QuickTest.Application","Server Name")

If Window("HP Unified Functional Testing") _
    .Dialog("HP Unified Functional Testing").Exist(60) = False Then

  MsgBox("Hello world")

End If

qtApp.Launch
qtApp.Visible = True

Answer: The best way to see if QTP is running is to use the automation model directly. The qtApp object supports the boolean Launched property which:

Indicates whether QuickTest is currently open.
Comment: Hi Motti, Can you please let me know whether we can initiate QTP in a remote machine using C# code. I know we can do it through VBS. Below is the code i used in C# for invoking QTP in my local machine. Can you please tell me where to add the remote machine IP address in this C# code.                                                           QuickTest.Application QTPInstance = new QuickTest.Application();
QTPInstance.Launch();
QTPInstance.Visible = true;
Comment: @user545359, I didn't notice the `"Server Name"` part of your question, in any case the `Launched` property is available in VBS too (it's the same interface exposed to different environments).


Viewing the lower right from a selected Range in Excel via VBA

Question: If you select a "large" range via VBA (e.g. range.Select) which is bigger then the screen size and bring the window/worksheet to the front (e.g. workbook.Activate) you will see the top left part of the selected range and whatever else fits on the screen.
Is it possible to show "the opposite" side, the lower right + whatever fits on the screen?
I thought about using something like
ActiveWindow.ScrollRow = tmpLastRowNr
ActiveWindow.ScrollColumn = tmpLastColumnNr

But then I will need some kind of solution to determine how much of the table to the upper left of it and set this as an offset...  I found a way to set/check the windowsize with Application.Height etc. but I actually need the size of the "table area". Did I miss a command or is this just not possible to do it "directly" (without calculating the visible area "manually" similar to this)?
Answer: Try the next code, please:
Sub testLastVisColRow()
  Dim LastVisCol As Long, lastVisRow As Long, selLastRow As Long, selLastCol As Long
  Range("A2:Z32").Select 'use here any range...
    lastVisRow = ActiveWindow.VisibleRange.Rows(ActiveWindow.VisibleRange.Rows.count).Row
    LastVisCol = ActiveWindow.VisibleRange.Columns(ActiveWindow.VisibleRange.Columns.count).Column

    selLastRow = Selection.Rows(Selection.Rows.count).Row
    selLastCol = Selection.Columns(Selection.Columns.count).Column

    ActiveWindow.SmallScroll Down:=selLastRow - lastVisRow + 1
    ActiveWindow.SmallScroll ToRight:=selLastCol - LastVisCol + 1

    If selLastRow > lastVisRow Or selLastCol > LastVisCol Then
        ActiveWindow.SmallScroll Down:=selLastRow - lastVisRow + 1
        ActiveWindow.SmallScroll ToRight:=selLastCol - LastVisCol + 1
        cells(selLastRow, selLastCol).Activate 'in order to perfectly simulate the reverse of the normal behavior :)
    End If
End Sub

Comment: VisibleRange, seems this is what I was looking for...  I give it a try right away! Thanks!
Comment: @Albin: Glad I could help! But didn't my above code answer your question?
Comment: Unfortunately it doesn't. In my test the range is sized 5 rows and around 100 columns (different sizes but the biggest around 1/10 of the screen width). Applying your procedure creates a "split screen" with the 100th column roughly being in the middle of the screen. But don't worry I can take it from here... If not I'll let you know.
Comment: And I didn't know about "ActiveWindow.SmallScroll" either... thats helpfull as well.
Comment: I got it to work just scrolling all the way to the right and then via a loop in 1 column increments. Not the most elegant way, it might have problems if you have hidden columns, but it works in my specific case since there is a max. of 30 columns on the screen at any time.


main program of console application is called twice in c# when called from web application

Question: i have console application and web application.
i am calling the main program of console from web application like this
Web
 public void RunconsoleApplication(string CanpaignId) {
        // Get the file path of your Application (exe)
        string filePath = @"E:/ConsoleApplication1/ConsoleApplication1/bin/Debug/ConsoleApplication1.exe";

        System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo(filePath, CanpaignId);

        System.Diagnostics.Process p = System.Diagnostics.Process.Start(info);
        p.Start();
    }

Console
Class program {
    static void Main(string[] args) {
        Console.WriteLine("start without arg");
        if (args.Length > 0) {
            Program p = new Program();
            // This is another function in the class, not copied here
            p.CreateCanpaign(Convert.ToInt64(args[0]));

            Console.WriteLine("stop");
        }
    }
}

now can someone explain why this function 'CreateCanpaign(a)' is called twice. i am new to console applications. thanks in advance.
Answer: Because of these two lines, you are starting it twice
System.Diagnostics.Process p = System.Diagnostics.Process.Start(info);
p.Start();

Remove p.Start();
Comment: so p.start() should not be included??
Comment: ahh.. i know that was simple thing to ask.. but sometimes these little things are difficult to find out.. thankyou very much .. :)
Comment: plz can you tell me one thing more.. i am calling this function as a user. how can i call it as an administrator with username and password.. i have tried some code but it is not working..
Comment: @DollyDar, see this thread http://stackoverflow.com/questions/2532769/how-to-start-a-process-as-administrator-mode-in-c-sharp


multiple function within routes in express js

Question: Hi I'm newbie to express js i want to put multiple functions within routes, kindly explain me how to add multiple function within route, i have 2 functions in company.js but i don't know how to export it and add it in index.js
index.js
var router = require('express').Router();
var path = require('path');

// Rest API
require(path.join(__dirname, './', 'company'))(router);

// Homepage/Client
router.get('/', function(req, res, next) {
  res.sendFile(path.join(__dirname, '../', 'client', 'index.html'));
});

module.exports = function(app, passport) {
    // set authentication routes
    require('./authentication.js')(app, passport);

    // set other routes
    app.use('/', router);
};

company.js
  var sockets = require('../utilities/socket');
  var authenticationMiddleware =
  require('../middlewares/authentication.js');
  var companyModel = require('../models/company.js');

var getCompanyProfile = function(router){

  router.post('/api/v1/profile/fetchCompany', authenticationMiddleware.isLoggedIn,
        function(req, res) {
            companyModel.getCompanyProfile(req['user'].id_user,
                                            function(result){
                                                return res.json(result);
                                            });
          }
    );

},
var saveCompanyProfile = function(router){

  router.post('/api/v1/profile/saveCompany', authenticationMiddleware.isLoggedIn,
      function(req, res) {
        companyModel.saveCompanyProfile(req,
                        function(result){
                          return res.json(result);
                        });
      }
  );

}

module.exports = getCompanyProfile;

Answer: You can export those two functions as follows
module.exports = {
   getCompanyProfile: getCompanyProfile,
   saveCompanyProfile: saveCompanyProfile
}

and import in index.js as follows
const company = require('./company.js');
company.getCompanyProfile(router);
company.saveCompanyProfile(router);

Comment: raises error like
      router.post('/api/v1/profile/getCompanyProfile',authenticationMiddleware.isLoggedIn,
        ^

TypeError: Cannot read property 'post' of undefined
Comment: You need to pass the router param to those functions like `company.getCompanyProfile(router);`
Comment: I just gave a general approach of exporting and importing exported functions @veeran I just forgot to edit it as per your question.. Hope you got an idea cheers


How do I properly chroot Nginx and uwsgi?

Question: I have a pretty good idea of how to do this, I just wanted to make sure I wasn't going to be seriously screwing stuff up before I deployed it.  I have a web application which uses uwsgi and nginx, and I wanted to chroot the app to a specific directory.  I was planning on chrooting both nginx and uwsgi to the same directory.  Now, I know how to do this, but would this be all I need to do to make it secure (in terms of jailing it), or is there anything else I should do?  Alternatively, is chrooting one of them unnecessary?  i.e., should I just chroot uwsgi or nginx and leave the other alone?
Comment: Did you find a way for this?
Answer: chroot is a good start in securing your webserver, but it only works correctly when uwsgi is working/configured correctly.
If you are really looking for a secure environment you would also want to configure selinux/apparmour to restrict what your web server has access to. In this way even if your web server is compromised and/or mis-configured the damage would be limited to only being able to access what the web server had access to.
You still aren't really secure in the strictest sense. Other things that you would be interested in are things like what user the web server is running as, what permissions the web server has, what permissions you are allowing to applications your web server is running, how updates are being applied, what other processes are running, and so on.
Once you are comfortable with all of those things you would look more into social engineering aspects of things, like, are your passwords secure, what about users using your system, are you securing data to/from your web server.
In short you can probably never do enough to make something secure depending on your definition of secure, but chroot is probably fine for what you are doing.