问:
Swift 3 Protocol Oriented Programming results in random SIGBUS crashes
I am responsible of a complete Swift 3 application and one of the crashes that occurs regularly is a SIGBUS signal that I can't understand at all:

```<code>Thread 0 Crashed:
0   libswiftCore.dylib    0x00000001009b4ac8 0x1007b8000 +2083528
1   LeadingBoards         @objc PageView.prepareForReuse() -> () (in LeadingBoards) (PageView.swift:0) +1114196
2   LeadingBoards         specialized ReusableContentView<A where ...>.reuseOrInsertView(first : Int, last : Int) -> () (in LeadingBoards) (ReusableView.swift:101) +1730152
3   LeadingBoards         DocumentViewerViewController.reuseOrInsertPages() -> () (in LeadingBoards) (DocumentViewerViewController.swift:0) +1036080
4   LeadingBoards         specialized DocumentViewerViewController.scrollViewDidScroll(UIScrollView) -> () (in LeadingBoards) (DocumentViewerViewController.swift:652) +1089744
5   LeadingBoards         @objc DocumentViewerViewController.scrollViewDidScroll(UIScrollView) -> () (in LeadingBoards) +1028252
6   UIKit                 0x000000018c2a68d4 0x18bf85000 +3283156
7   UIKit                 0x000000018bfb2c08 0x18bf85000 +187400
8   UIKit                 0x000000018c143e5c 0x18bf85000 +1830492
9   UIKit                 0x000000018c143b4c 0x18bf85000 +1829708
10  QuartzCore            0x00000001890755dc 0x18906b000 +42460
11  QuartzCore            0x000000018907548c 0x18906b000 +42124
12  IOKit                 0x00000001860d7b9c 0x1860d2000 +23452
13  CoreFoundation        0x0000000185e01960 0x185d3e000 +801120
14  CoreFoundation        0x0000000185e19ae4 0x185d3e000 +899812
15  CoreFoundation        0x0000000185e19284 0x185d3e000 +897668
16  CoreFoundation        0x0000000185e16d98 0x185d3e000 +888216
17  CoreFoundation        0x0000000185d46da4 0x185d3e000 +36260
18  GraphicsServices      0x00000001877b0074 0x1877a4000 +49268
19  UIKit                 0x000000018bffa058 0x18bf85000 +479320
20  LeadingBoards         main (in LeadingBoards) (AppDelegate.swift:13) +77204
21  libdyld.dylib         0x0000000184d5559c 0x184d51000 +17820
</code>```

The logic behind that is the logic for reusing views in a scrollview, as described by Apple in a WWDC video (can't find the year and the video...):

PageView is a class that implement ReusableView and Indexed:

```<code>class PageView: UIView {

    enum Errors: Error {
        case badConfiguration
        case noImage
    }

    enum Resolution: String {
        case high
        case low

        static var emptyGeneratingTracker: [PageView.Resolution: Set<String>] {
            return [.high:Set(),
                    .low:Set()]
        }

        /// SHOULD NOT BE 0
        var quality: CGFloat {
            switch self {
            case .high:
                return 1
            case .low:
                return 0.3
            }
        }

        var JPEGQuality: CGFloat {
            switch self {
            case .high:
                return 0.8
            case .low:
                return 0.25
            }
        }

        var atomicWrite: Bool {
            switch self {
            case .high:
                return false
            case .low:
                return true
            }
        }

        var interpolationQuality: CGInterpolationQuality {
            switch self {
            case .high:
                return .high
            case .low:
                return .low
            }
        }

        var dispatchQueue: OperationQueue {
            switch self {
            case .high:
                return DocumentBridge.highResOperationQueue
            case .low:
                return DocumentBridge.lowResOperationQueue
            }
        }
    }

    @IBOutlet weak var imageView: UIImageView!

    // Loading
    @IBOutlet weak var loadingStackView: UIStackView!
    @IBOutlet weak var pageNumberLabel: UILabel!

    // Error
    @IBOutlet weak var errorStackView: UIStackView!

    // Zoom
    @IBOutlet weak var zoomView: PageZoomView!

    fileprivate weak var bridge: DocumentBridge?

    var displaying: Resolution?
    var pageNumber = 0

    override func layoutSubviews() {
        super.layoutSubviews()

        refreshImageIfNeeded()
    }

    func configure(_ pageNumber: Int, zooming: Bool, bridge: DocumentBridge) throws {
        if pageNumber > 0 && pageNumber <= bridge.numberOfPages {
            self.bridge = bridge
            self.pageNumber = pageNumber
            self.zoomView.configure(bridge: bridge, pageNumber: pageNumber)
        } else {
            throw Errors.badConfiguration
        }

        NotificationCenter.default.addObserver(self, selector: #selector(self.pageRendered(_:)), name: .pageRendered, object: bridge)
        NotificationCenter.default.addObserver(self, selector: #selector(self.pageFailedRendering(_:)), name: .pageFailedRendering, object: bridge)

        pageNumberLabel.text = "PAGE".localized + " \(pageNumber)"

        if displaying == nil {
            loadingStackView.isHidden = false
            errorStackView.isHidden = true
        }
        if displaying != .high {
            refreshImage()
        }

        if zooming {
            startZooming()
        } else {
            stopZooming()
        }
    }

    fileprivate func isNotificationRelated(notification: Notification) -> Bool {
        guard let userInfo = notification.userInfo else {
            return false
        }

        guard pageNumber == userInfo[DocumentBridge.PageNotificationKey.PageNumber.rawValue] as? Int else {
            return false
        }

        guard Int(round(bounds.width)) == userInfo[DocumentBridge.PageNotificationKey.Width.rawValue] as? Int else {
            return false
        }

        guard userInfo[DocumentBridge.PageNotificationKey.Notes.rawValue] as? Bool == false else {
            return false
        }

        return true
    }

    func pageRendered(_ notification: Notification) {
        guard isNotificationRelated(notification: notification) else {
            return
        }

        if displaying == nil || (displaying == .low && notification.userInfo?[DocumentBridge.PageNotificationKey.Resolution.rawValue] as? String == Resolution.high.rawValue) {
            refreshImage()
        }
    }

    func pageFailedRendering(_ notification: Notification) {
        guard isNotificationRelated(notification: notification) else {
            return
        }

        if displaying == nil {
            imageView.image = nil
            loadingStackView.isHidden = true
            errorStackView.isHidden = false
        }
    }

    func refreshImageIfNeeded() {
        if displaying != .high {
            refreshImage()
        }
    }

    fileprivate func refreshImage() {
        let pageNumber = self.pageNumber
        let width = Int(round(bounds.width))
        DispatchQueue.global(qos: .userInitiated).async(execute: { [weak self] () in
            do {
                try self?.setImage(pageNumber, width: width, resolution: .high)
            } catch {
                _ = try? self?.setImage(pageNumber, width: width, resolution: .low)
            }
        })
    }

    func setImage(_ pageNumber: Int, width: Int, resolution: Resolution) throws {
        if let image = try self.bridge?.getImage(page: pageNumber, width: width, resolution: resolution) {
            DispatchQueue.main.async(execute: { [weak self] () in
                if pageNumber == self?.pageNumber {
                    self?.imageView?.image = image
                    self?.displaying = resolution
                    self?.loadingStackView.isHidden = true
                    self?.errorStackView.isHidden = true
                }
            })
        } else {
            throw Errors.noImage
        }
    }
}

extension PageView: ReusableView, Indexed {
    static func instanciate() -> PageView {
        return UINib(nibName: "PageView", bundle: nil).instantiate(withOwner: nil, options: nil).first as! PageView
    }

    var index: Int {
        return pageNumber
    }

    func hasBeenAddedToSuperview() { }

    func willBeRemovedFromSuperview() { }

    func prepareForReuse() {
        NotificationCenter.default.removeObserver(self, name: .pageRendered, object: nil)
        NotificationCenter.default.removeObserver(self, name: .pageFailedRendering, object: nil)

        bridge = nil
        imageView?.image = nil
        displaying = nil
        pageNumber = 0
        zoomView?.prepareForReuse()
    }

    func prepareForRelease() { }
}

// MARK: - Zoom
extension PageView {
    func startZooming() {
        bringSubview(toFront: zoomView)
        zoomView.isHidden = false
        setNeedsDisplay()
    }

    func stopZooming() {
        zoomView.isHidden = true
    }
}
</code>```

where ReusableView and Indexed are protocols defined that way :

```<code>protocol Indexed {
    var index: Int { get }
}

protocol ReusableView {
    associatedtype A

    static func instanciate() -> A

    func hasBeenAddedToSuperview()
    func willBeRemovedFromSuperview()
    func prepareForReuse()
    func prepareForRelease()
}

// Make some func optionals
extension ReusableView {
    func hasBeenAddedToSuperview() {}
    func willBeRemovedFromSuperview() {}
    func prepareForReuse() {}
    func prepareForRelease() {}
}
</code>```

ReusableContentView is a view that manage the view that are inserted, or reused. It's implemented depending of the containing view type :

```<code>class ReusableContentView<T: ReusableView>: UIView where T: UIView {
    var visible = Set<T>()
    var reusable = Set<T>()

    ...
}

extension ReusableContentView where T: Indexed {
    /// To insert view using a range of ids
    func reuseOrInsertView(first: Int, last: Int) {
        // Removing no longer needed views
        for view in visible {
            if view.index < first || view.index > last {
                reusable.insert(view)
                view.willBeRemovedFromSuperview()
                view.removeFromSuperview()
                view.prepareForReuse()
            }
        }
        // Removing reusable pages from visible pages array
        visible.subtract(reusable)

        // Add the missing views
        for index in first...last {
            if !visible.map({ $0.index }).contains(index) {
                let view = dequeueReusableView() ?? T.instanciate() as! T // Getting a new page, dequeued or initialized
                if configureViewWithIndex?(view, index) == true {
                    addSubview(view)
                    view.hasBeenAddedToSuperview()
                    visible.insert(view)
                }
            }
        }
    }
}
</code>```

Witch is called by DocumentViewerViewController.reuseOrInsertPages(), triggered by scrollviewDidScroll delegate.

What can provoque my SIGBUS signal here? Is that the default implementation of func prepareForReuse() {} I use to make the protocol function optional? Any other ideas?

Of course, this crash is completly random and I wasn't able to reproduice it. I just receive crash reports about it from prod version of the app.
Thanks for your help !

答:
For me it looks like something went wrong in PageView.prepareForReuse(). I'm not aware of the properties but from the prepareForReuse function it looks like your are accessing properties which maybe are @IBOutlets:

```<code>bridge = nil
imageView.image = nil
displaying = nil
pageNumber = 0
zoomView.prepareForReuse()
</code>```

Could it be that imageView or zoomView are nil when you try to access them? If so, this could be the most simplistic fix:

```<code>func prepareForReuse() {
    NotificationCenter.default.removeObserver(self, name: .pageRendered, object: nil)
    NotificationCenter.default.removeObserver(self, name: .pageFailedRendering, object: nil)

    bridge = nil
    imageView?.image = nil
    displaying = nil
    pageNumber = 0
    zoomView?.prepareForReuse()
}
</code>```

Again, I am not sure about the implementation details of your PageView and I am only guessing this because it looks like you are instantiating it from a Nib and therefore my guess is you are using for example @IBOutlet weak var imageView: UIImageView!.

If for whatever reason this imageView becomes nil, accessing it will crash your app.

Body:
I am responsible of a complete Swift 3 application and one of the crashes that occurs regularly is a SIGBUS signal that I can't understand at all:

Thread 0 Crashed:
0   libswiftCore.dylib    0x00000001009b4ac8 0x1007b8000 +2083528
1   LeadingBoards         @objc PageView.prepareForReuse() -> () (in LeadingBoards) (PageView.swift:0) +1114196
2   LeadingBoards         specialized ReusableContentView.reuseOrInsertView(first : Int, last : Int) -> () (in LeadingBoards) (ReusableView.swift:101) +1730152
3   LeadingBoards         DocumentViewerViewController.reuseOrInsertPages() -> () (in LeadingBoards) (DocumentViewerViewController.swift:0) +1036080
4   LeadingBoards         specialized DocumentViewerViewController.scrollViewDidScroll(UIScrollView) -> () (in LeadingBoards) (DocumentViewerViewController.swift:652) +1089744
5   LeadingBoards         @objc DocumentViewerViewController.scrollViewDidScroll(UIScrollView) -> () (in LeadingBoards) +1028252
6   UIKit                 0x000000018c2a68d4 0x18bf85000 +3283156
7   UIKit                 0x000000018bfb2c08 0x18bf85000 +187400
8   UIKit                 0x000000018c143e5c 0x18bf85000 +1830492
9   UIKit                 0x000000018c143b4c 0x18bf85000 +1829708
10  QuartzCore            0x00000001890755dc 0x18906b000 +42460
11  QuartzCore            0x000000018907548c 0x18906b000 +42124
12  IOKit                 0x00000001860d7b9c 0x1860d2000 +23452
13  CoreFoundation        0x0000000185e01960 0x185d3e000 +801120
14  CoreFoundation        0x0000000185e19ae4 0x185d3e000 +899812
15  CoreFoundation        0x0000000185e19284 0x185d3e000 +897668
16  CoreFoundation        0x0000000185e16d98 0x185d3e000 +888216
17  CoreFoundation        0x0000000185d46da4 0x185d3e000 +36260
18  GraphicsServices      0x00000001877b0074 0x1877a4000 +49268
19  UIKit                 0x000000018bffa058 0x18bf85000 +479320
20  LeadingBoards         main (in LeadingBoards) (AppDelegate.swift:13) +77204
21  libdyld.dylib         0x0000000184d5559c 0x184d51000 +17820

The logic behind that is the logic for reusing views in a scrollview, as described by Apple in a WWDC video (can't find the year and the video...):

PageView is a class that implement ReusableView and Indexed:

class PageView: UIView {

    enum Errors: Error {
        case badConfiguration
        case noImage
    }

    enum Resolution: String {
        case high
        case low

        static var emptyGeneratingTracker: [PageView.Resolution: Set<String>] {
            return [.high:Set(),
                    .low:Set()]
        }

        /// SHOULD NOT BE 0
        var quality: CGFloat {
            switch self {
            case .high:
                return 1
            case .low:
                return 0.3
            }
        }

        var JPEGQuality: CGFloat {
            switch self {
            case .high:
                return 0.8
            case .low:
                return 0.25
            }
        }

        var atomicWrite: Bool {
            switch self {
            case .high:
                return false
            case .low:
                return true
            }
        }

        var interpolationQuality: CGInterpolationQuality {
            switch self {
            case .high:
                return .high
            case .low:
                return .low
            }
        }

        var dispatchQueue: OperationQueue {
            switch self {
            case .high:
                return DocumentBridge.highResOperationQueue
            case .low:
                return DocumentBridge.lowResOperationQueue
            }
        }
    }

    @IBOutlet weak var imageView: UIImageView!

    // Loading
    @IBOutlet weak var loadingStackView: UIStackView!
    @IBOutlet weak var pageNumberLabel: UILabel!

    // Error
    @IBOutlet weak var errorStackView: UIStackView!

    // Zoom
    @IBOutlet weak var zoomView: PageZoomView!

    fileprivate weak var bridge: DocumentBridge?

    var displaying: Resolution?
    var pageNumber = 0

    override func layoutSubviews() {
        super.layoutSubviews()

        refreshImageIfNeeded()
    }

    func configure(_ pageNumber: Int, zooming: Bool, bridge: DocumentBridge) throws {
        if pageNumber > 0 && pageNumber <= bridge.numberOfPages {
            self.bridge = bridge
            self.pageNumber = pageNumber
            self.zoomView.configure(bridge: bridge, pageNumber: pageNumber)
        } else {
            throw Errors.badConfiguration
        }

        NotificationCenter.default.addObserver(self, selector: #selector(self.pageRendered(_:)), name: .pageRendered, object: bridge)
        NotificationCenter.default.addObserver(self, selector: #selector(self.pageFailedRendering(_:)), name: .pageFailedRendering, object: bridge)

        pageNumberLabel.text = "PAGE".localized + " \(pageNumber)"

        if displaying == nil {
            loadingStackView.isHidden = false
            errorStackView.isHidden = true
        }
        if displaying != .high {
            refreshImage()
        }

        if zooming {
            startZooming()
        } else {
            stopZooming()
        }
    }

    fileprivate func isNotificationRelated(notification: Notification) -> Bool {
        guard let userInfo = notification.userInfo else {
            return false
        }

        guard pageNumber == userInfo[DocumentBridge.PageNotificationKey.PageNumber.rawValue] as? Int else {
            return false
        }

        guard Int(round(bounds.width)) == userInfo[DocumentBridge.PageNotificationKey.Width.rawValue] as? Int else {
            return false
        }

        guard userInfo[DocumentBridge.PageNotificationKey.Notes.rawValue] as? Bool == false else {
            return false
        }

        return true
    }

    func pageRendered(_ notification: Notification) {
        guard isNotificationRelated(notification: notification) else {
            return
        }

        if displaying == nil || (displaying == .low && notification.userInfo?[DocumentBridge.PageNotificationKey.Resolution.rawValue] as? String == Resolution.high.rawValue) {
            refreshImage()
        }
    }

    func pageFailedRendering(_ notification: Notification) {
        guard isNotificationRelated(notification: notification) else {
            return
        }

        if displaying == nil {
            imageView.image = nil
            loadingStackView.isHidden = true
            errorStackView.isHidden = false
        }
    }

    func refreshImageIfNeeded() {
        if displaying != .high {
            refreshImage()
        }
    }

    fileprivate func refreshImage() {
        let pageNumber = self.pageNumber
        let width = Int(round(bounds.width))
        DispatchQueue.global(qos: .userInitiated).async(execute: { [weak self] () in
            do {
                try self?.setImage(pageNumber, width: width, resolution: .high)
            } catch {
                _ = try? self?.setImage(pageNumber, width: width, resolution: .low)
            }
        })
    }

    func setImage(_ pageNumber: Int, width: Int, resolution: Resolution) throws {
        if let image = try self.bridge?.getImage(page: pageNumber, width: width, resolution: resolution) {
            DispatchQueue.main.async(execute: { [weak self] () in
                if pageNumber == self?.pageNumber {
                    self?.imageView?.image = image
                    self?.displaying = resolution
                    self?.loadingStackView.isHidden = true
                    self?.errorStackView.isHidden = true
                }
            })
        } else {
            throw Errors.noImage
        }
    }
}

extension PageView: ReusableView, Indexed {
    static func instanciate() -> PageView {
        return UINib(nibName: "PageView", bundle: nil).instantiate(withOwner: nil, options: nil).first as! PageView
    }

    var index: Int {
        return pageNumber
    }

    func hasBeenAddedToSuperview() { }

    func willBeRemovedFromSuperview() { }

    func prepareForReuse() {
        NotificationCenter.default.removeObserver(self, name: .pageRendered, object: nil)
        NotificationCenter.default.removeObserver(self, name: .pageFailedRendering, object: nil)

        bridge = nil
        imageView?.image = nil
        displaying = nil
        pageNumber = 0
        zoomView?.prepareForReuse()
    }

    func prepareForRelease() { }
}

// MARK: - Zoom
extension PageView {
    func startZooming() {
        bringSubview(toFront: zoomView)
        zoomView.isHidden = false
        setNeedsDisplay()
    }

    func stopZooming() {
        zoomView.isHidden = true
    }
}

where ReusableView and Indexed are protocols defined that way :

protocol Indexed {
    var index: Int { get }
}

protocol ReusableView {
    associatedtype A

    static func instanciate() -> A

    func hasBeenAddedToSuperview()
    func willBeRemovedFromSuperview()
    func prepareForReuse()
    func prepareForRelease()
}

// Make some func optionals
extension ReusableView {
    func hasBeenAddedToSuperview() {}
    func willBeRemovedFromSuperview() {}
    func prepareForReuse() {}
    func prepareForRelease() {}
}

ReusableContentView is a view that manage the view that are inserted, or reused. It's implemented depending of the containing view type :

class ReusableContentView<T: ReusableView>: UIView where T: UIView {
    var visible = Set<T>()
    var reusable = Set<T>()

    ...
}

extension ReusableContentView where T: Indexed {
    /// To insert view using a range of ids
    func reuseOrInsertView(first: Int, last: Int) {
        // Removing no longer needed views
        for view in visible {
            if view.index < first || view.index > last {
                reusable.insert(view)
                view.willBeRemovedFromSuperview()
                view.removeFromSuperview()
                view.prepareForReuse()
            }
        }
        // Removing reusable pages from visible pages array
        visible.subtract(reusable)

        // Add the missing views
        for index in first...last {
            if !visible.map({ $0.index }).contains(index) {
                let view = dequeueReusableView() ?? T.instanciate() as! T // Getting a new page, dequeued or initialized
                if configureViewWithIndex?(view, index) == true {
                    addSubview(view)
                    view.hasBeenAddedToSuperview()
                    visible.insert(view)
                }
            }
        }
    }
}

Witch is called by DocumentViewerViewController.reuseOrInsertPages(), triggered by scrollviewDidScroll delegate.

What can provoque my SIGBUS signal here? Is that the default implementation of func prepareForReuse() {} I use to make the protocol function optional? Any other ideas?

Of course, this crash is completly random and I wasn't able to reproduice it. I just receive crash reports about it from prod version of the app.
Thanks for your help !

Body:
For me it looks like something went wrong in PageView.prepareForReuse(). I'm not aware of the properties but from the prepareForReuse function it looks like your are accessing properties which maybe are @IBOutlets:

bridge = nil
imageView.image = nil
displaying = nil
pageNumber = 0
zoomView.prepareForReuse()

Could it be that imageView or zoomView are nil when you try to access them? If so, this could be the most simplistic fix:

func prepareForReuse() {
    NotificationCenter.default.removeObserver(self, name: .pageRendered, object: nil)
    NotificationCenter.default.removeObserver(self, name: .pageFailedRendering, object: nil)

    bridge = nil
    imageView?.image = nil
    displaying = nil
    pageNumber = 0
    zoomView?.prepareForReuse()
}

Again, I am not sure about the implementation details of your PageView and I am only guessing this because it looks like you are instantiating it from a Nib and therefore my guess is you are using for example @IBOutlet weak var imageView: UIImageView!.

If for whatever reason this imageView becomes nil, accessing it will crash your app.


来源: stackexchange

问:
How do I get F12 to break into the debugger on Vista x64 with VS 2008?
F12 is a wonder for tracking down UI blocking operations, but I can't figure out how to make it work with VS 2008 and managed code.

Help! Or not...

Edit: turns out it doesn't work in VS 2005 either on Vista x64, so I guess that either widens or narrows it down, depending on your perspective :(

MSN

答:
While I did not know about the F12 functionality in x86 Windows XP, the following instructions describe how I'm breaking into already running programs (this technique works in both x86 and x64 Windows operating systems).

First, run Visual Studio (2008, 2005, 2003... doesn't really matter as they all support attaching to running processes; they inherit this functionality from the ultimate debugger, WinDbg, available at Debugging Tools for Windows)

From the Tools menu, choose "Attach to Processs..." command:

Attach to process menu http://img297.imageshack.us/img297/2369/attachmenuhe7.png

I find this functionality so helpful I even added this command to the main Visual Studio toolbar:

Attach to process in toolbar http://img440.imageshack.us/img440/1232/vstoolbarmainaw4.png

"Attach to Process" dialog will show up. It will list all the currently running processes (if your process is not listed, try enabling "Show processes from all users" or "Show processes in all sessions" checkmarks at the bottom of the dialog). Simply select the process you'd like to break into and hit the "Attach" button:

Attach to process dialog http://img231.imageshack.us/img231/8415/vsdialogattachoq5.png

Note: the debugger can work in different modes, debugging native code, managed code, scripts (in Internet Explorer) or even T-SQL and WF workflow. Whatever your choices, the "attach to process" dialog will remember them for the next time you open it.

After Visual Studio successfully attaches to the process you're trying to break into, use the Debug -> Break All command to stop all the threads in this process:

Break all menu http://img297.imageshack.us/img297/8579/vsmenubreakallrb1.png

This command is also available from the debug toolbar:

Break all in toolbar http://img440.imageshack.us/img440/248/vstoolbardebugwt4.png

After breaking, you can explore all the currently running threads, their stacks, memory, local and global variables, etc. This should allow you to troubleshoot long-running operations even from x64 operating systems where the F12 functionality you were using is not readily available.

OwnerDisplayName: MSN

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: MSN

OwnerDisplayName: Milan Gardian

LastEditorDisplayName: Milan Gardian


问:
Map dynamically array to nested object
I want to retrieve the form content on a submit and map that data into an object.

```<code>let userData = $(e.currentTarget).serializeArray();
let userDataObject = this.serializedToObject(userData);
</code>```

--
Template objects to send through POST

```<code>serializedToObject(serializedArray) {
        let templateObject = {
            privider: '',
            pop3: {
                host: '',
                port: 110,
                ssl: false
            },
            imap: {
                host: '',
                port: 993
            },

            email: '',
            password: ''
        };

        for (let data in serializedArray) {
        }

        return templateObject;
    }
</code>```

--
The form of the userData is

```<code>[Object, Object, Object, Object, Object, Object, Object]
</code>```

-- While on object is of form

```<code>Object: {
  name: 'provider',
  value: 'Aladin'
}

Object: {
  name: 'imap-host',
  value: '955'
}

Object: {
  name: 'imap-port',
  value:
}

Object: {
  email: 'test@gmail.com',
  value:
}
</code>```

So I need some help to map that array of objects to the templateObject.
AnyHelp will be highly appreciated.

Update

```<code>[{"name":"name","value":"Nicholas Barbaros"},{"name":"email","value":"george@google.com"},{"name":"password","value":"nicu121-mujik"},{"name":"imap","value":"imap.server.com"},{"name":"imap-port","value":"ad"},{"name":"pop3-host","value":"pop.server.com"},{"name":"pop3-port","value":"465"}, {"name":"pop3-ssl","value":"false"}]
</code>```

答:
There is too much overhead to iterate serialized array and map it to the nested object.

Please consider this approach, which is less complicated:

```<code>let userData = new FormData($(e.currentTarget)[0]);
let userDataObject = serializedToObject(userData);

function serializedToObject(data) {
    return {
        provider: data.get('provider'),
        pop3: {
            host: data.get('pop3-host'),
            port: data.get('pop3-port'),
            ssl:  data.get('pop3-ssl')
        },
        imap: {
            host: data.get('imap-host'),
            port: data.get('imap-port')
        },

        email: data.get('email'),
        password: data.get('password')
    };
}
</code>```

I guessed some fields here. Please correct them if needed.

ContentLicense: CC BY-SA 3.0

Title: Map dynamically array to nested object

Body:
I want to retrieve the form content on a submit and map that data into an object.

let userData = $(e.currentTarget).serializeArray();
let userDataObject = this.serializedToObject(userData);

--
Template objects to send through POST

serializedToObject(serializedArray) {
        let templateObject = {
            privider: '',
            pop3: {
                host: '',
                port: 110,
                ssl: false
            },
            imap: {
                host: '',
                port: 993
            },

            email: '',
            password: ''
        };

        for (let data in serializedArray) {
        }

        return templateObject;
    }

--
The form of the userData is

[Object, Object, Object, Object, Object, Object, Object]

-- While on object is of form

Object: {
  name: 'provider',
  value: 'Aladin'
}

Object: {
  name: 'imap-host',
  value: '955'
}

Object: {
  name: 'imap-port',
  value:
}

Object: {
  email: 'test@gmail.com',
  value:
}

So I need some help to map that array of objects to the templateObject.
AnyHelp will be highly appreciated.

Update

[{"name":"name","value":"Nicholas Barbaros"},{"name":"email","value":"george@google.com"},{"name":"password","value":"nicu121-mujik"},{"name":"imap","value":"imap.server.com"},{"name":"imap-port","value":"ad"},{"name":"pop3-host","value":"pop.server.com"},{"name":"pop3-port","value":"465"}, {"name":"pop3-ssl","value":"false"}]

Body:
There is too much overhead to iterate serialized array and map it to the nested object.

Please consider this approach, which is less complicated:

let userData = new FormData($(e.currentTarget)[0]);
let userDataObject = serializedToObject(userData);

function serializedToObject(data) {
    return {
        provider: data.get('provider'),
        pop3: {
            host: data.get('pop3-host'),
            port: data.get('pop3-port'),
            ssl:  data.get('pop3-ssl')
        },
        imap: {
            host: data.get('imap-host'),
            port: data.get('imap-port')
        },

        email: data.get('email'),
        password: data.get('password')
    };
}

I guessed some fields here. Please correct them if needed.


问:
composer generate [JsonSchema\Exception\ResourceNotFoundException] while executing any command
I am using composer with php 7.1.5 on Windows 10 (x64), I am able to update composer itself if the current folder is empty but as soon as I create composer.json for the project (composer init) then any composer command will fail with the same error. Deleting composer.json will make that error disappear.

```<code>[JsonSchema\Exception\ResourceNotFoundException]
  file_get_contents(phar://Y:/Programs cache/PHP/):
  failed to open stream: phar error: no directory in "phar://Y:/Programs cache/PHP/",
  must have at least phar://Y:/Programs cache/PHP// for root directory
  (always use full path to a new phar
</code>```

答: I have figured out the issue, I just have a "#" in the paths, I know that this char cause a lot of issues when used in folder names but the problem is that composer worked normally for the update but stopped when I tried composer init

Body:
I am using composer with php 7.1.5 on Windows 10 (x64), I am able to update composer itself if the current folder is empty but as soon as I create composer.json for the project (composer init) then any composer command will fail with the same error. Deleting composer.json will make that error disappear.

[JsonSchema\Exception\ResourceNotFoundException]
  file_get_contents(phar://Y:/Programs cache/PHP/):
  failed to open stream: phar error: no directory in "phar://Y:/Programs cache/PHP/",
  must have at least phar://Y:/Programs cache/PHP// for root directory
  (always use full path to a new phar


问:
pygame looping round array to work out where to draw
I am quite new to pygame and am trying to loop round my array to check that when drawing out the sprite's inventory, it will draw the items from the top down. For example,

```<code>[empty]
[empty]
[empty]
</code>```

In this case, if the player picked up an item it would draw it in the first slot.

```<code>[wood]
[empty]
[empty]
</code>```

Now, if the player picked up another item, it would draw it in the second slot.

```<code>inventory = {"logs": 10, "stones": 0, "sword": "none", "pickaxe": "none"}

slots = [False, False, False, False, False, False, False, False, False, False]

if inventory["logs"] > 0:
    y = 90 #coordinate to draw the logs
    for i in slots:
        if i == "logs":
            break
        elif i == True:
            y += 90
        else:
            slots[i] = "logs"
    screen.blit(pygame.image.load("logs.png"), (invX, y)) '''draws the image
    into the inventory area'''

if inventory["stones"] > 0:
        y = 90
        for i in slots:
            if i == "stones":
                break
            elif i == True:
                y += 90
            else:
                slots[i] = "stones"
        screen.blit(pygame.image.load("stones.png"), (invX, y))
</code>```

This is not all the code but hopefully all that is needed. Firstly I am given the error list indices must be integers or slices, not str and secondly, it will draw the stones and logs image on top of each other.

答:
When you use for i in slots: each i is an actual element of your list and not just a number index. You should change the brackets to this:

```<code>else:
    slots[slots.index(i)] = "logs"
</code>```

Body:
I am quite new to pygame and am trying to loop round my array to check that when drawing out the sprite's inventory, it will draw the items from the top down. For example,

[empty]
[empty]
[empty]

In this case, if the player picked up an item it would draw it in the first slot.

[wood]
[empty]
[empty]

Now, if the player picked up another item, it would draw it in the second slot.

inventory = {"logs": 10, "stones": 0, "sword": "none", "pickaxe": "none"}

slots = [False, False, False, False, False, False, False, False, False, False]

if inventory["logs"] > 0:
    y = 90 #coordinate to draw the logs
    for i in slots:
        if i == "logs":
            break
        elif i == True:
            y += 90
        else:
            slots[i] = "logs"
    screen.blit(pygame.image.load("logs.png"), (invX, y)) '''draws the image
    into the inventory area'''

if inventory["stones"] > 0:
        y = 90
        for i in slots:
            if i == "stones":
                break
            elif i == True:
                y += 90
            else:
                slots[i] = "stones"
        screen.blit(pygame.image.load("stones.png"), (invX, y))

This is not all the code but hopefully all that is needed. Firstly I am given the error list indices must be integers or slices, not str and secondly, it will draw the stones and logs image on top of each other.

Body:
When you use for i in slots: each i is an actual element of your list and not just a number index. You should change the brackets to this:

else:
    slots[slots.index(i)] = "logs"


问:
How do I create a list of numpy subarrays from an original array and then apply a function over said list?
Good Morning.  Right now I am working with a csv of numerical data and have converted it into a numpy matrix.  The CSV is rather large (10000x5) and is constructed as follows (the acronyms for the column vectors arn't super important I suppose, but I'll include them) : name of subject, Blood Pressure, PDAC, GSIC, TDAP

What I would like to do is take this create a list of numpy matrices such that each matrix contains the values associated with a unique subject name, as a simple example Edit( at suggestion I changed the "subject name column" to "subject id" by creating a mapping from names to id.  In this example carl has id 1, and doug has id 2):

```<code>Original=np.matrix['1 17 28 32 79; 1 89 72 46 22; 1 91 93 88 90; 2 21 57 73 68; 2 43 32 21 22']

Carl = np.matrix['1 17 28 32 79; 1 89 72 46 22; 1 91 93 88 90']
Doug = ['2 21 57 73 68 ;2 43 32 21 22']

matrixlist = [ Doug, Carl]
</code>```

For a few matrices this wouldn't be too tough of a problem-but there are a lot of subjects spread out in the parent csv, and not every subject has the same number of entries.  I have tried converting all the data into a list and then using list comprehension but I'm running into some issues.

Lastly, I was wondering if there was a way to apply a function to each element in the list of matrices.  As another simple example: I wrote a function that computes the correlation matrix of a numpy array using its svd.  Is it possible to apply it to every element in the list?

```<code>def correlation_matrix(x):
    covariance_matrix = np.cov(x, y=None, rowvar=False, bias=False, ddof=None, fweights=None, aweights=None)
    correlation_matrix =np.matmul(np.matmul(fractional_matrix_power(np.diag(np.diag(covariance_matrix)),-1/2),covariance_matrix),(fractional_matrix_power(np.diag(np.diag(covariance_matrix)),-1/2)))
    return correlation_matrix
</code>```

thanks in advance!

答:
Good evening. A very nice way to do this is to use pandas DataFrame. To read your data and to sort for subjects, do the following:

```<code>import pandas as pd
my_df = pd.read_csv(your_filename, names=['subject','0','1','2','3'])
grouped_output = my_df.groupby('subject').get_group('Carl')
</code>```

This will return just the Carl Data from your DataFrame. After this you could loop through all group subjects and do whatever you'd like to do with them. A loop could look like this:

```<code>for key, subject in my_df.groupby('subject').groups.items():
    print(my_df.groupby('subject').get_group(subject))
</code>```

Body:
Good Morning.  Right now I am working with a csv of numerical data and have converted it into a numpy matrix.  The CSV is rather large (10000x5) and is constructed as follows (the acronyms for the column vectors arn't super important I suppose, but I'll include them) : name of subject, Blood Pressure, PDAC, GSIC, TDAP

What I would like to do is take this create a list of numpy matrices such that each matrix contains the values associated with a unique subject name, as a simple example Edit( at suggestion I changed the "subject name column" to "subject id" by creating a mapping from names to id.  In this example carl has id 1, and doug has id 2):

Original=np.matrix['1 17 28 32 79; 1 89 72 46 22; 1 91 93 88 90; 2 21 57 73 68; 2 43 32 21 22']

Carl = np.matrix['1 17 28 32 79; 1 89 72 46 22; 1 91 93 88 90']
Doug = ['2 21 57 73 68 ;2 43 32 21 22']

matrixlist = [ Doug, Carl]

For a few matrices this wouldn't be too tough of a problem-but there are a lot of subjects spread out in the parent csv, and not every subject has the same number of entries.  I have tried converting all the data into a list and then using list comprehension but I'm running into some issues.

Lastly, I was wondering if there was a way to apply a function to each element in the list of matrices.  As another simple example: I wrote a function that computes the correlation matrix of a numpy array using its svd.  Is it possible to apply it to every element in the list?

def correlation_matrix(x):
    covariance_matrix = np.cov(x, y=None, rowvar=False, bias=False, ddof=None, fweights=None, aweights=None)
    correlation_matrix =np.matmul(np.matmul(fractional_matrix_power(np.diag(np.diag(covariance_matrix)),-1/2),covariance_matrix),(fractional_matrix_power(np.diag(np.diag(covariance_matrix)),-1/2)))
    return correlation_matrix

thanks in advance!

Body:
Good evening. A very nice way to do this is to use pandas DataFrame. To read your data and to sort for subjects, do the following:

import pandas as pd
my_df = pd.read_csv(your_filename, names=['subject','0','1','2','3'])
grouped_output = my_df.groupby('subject').get_group('Carl')

This will return just the Carl Data from your DataFrame. After this you could loop through all group subjects and do whatever you'd like to do with them. A loop could look like this:

for key, subject in my_df.groupby('subject').groups.items():
    print(my_df.groupby('subject').get_group(subject))


问:
TypeScript Obfuscation
Are there any tools or forks of TypeScript to support public namespace obfuscation? I.e. to turn:

```<code>class MyUtil {
   print(): void { ... }
}
</code>```

Into something like:

```<code>class xxy {
   aab(): void { ... }
}
</code>```

If not, would be be straight forward to fork the compiler to provide this? Perhaps with some type of class annotation indication what should / shouldn't be obfuscated.

(Obviously public obfuscation has to be used carefully, no good for libraries! But great if used consistently across your project)

答:
I had the exact same question, and it was instantly deleted by SO.

https://github.com/angular/ts-minify

This is exactly the tool you (and I) are looking for, it seems to work pretty well, I needed to comment out a few parts where the the author was taking precautions I don't think are applicable.

Title: TypeScript Obfuscation

Body:
Are there any tools or forks of TypeScript to support public namespace obfuscation? I.e. to turn:

class MyUtil {
   print(): void { ... }
}

Into something like:

class xxy {
   aab(): void { ... }
}

If not, would be be straight forward to fork the compiler to provide this? Perhaps with some type of class annotation indication what should / shouldn't be obfuscated.

(Obviously public obfuscation has to be used carefully, no good for libraries! But great if used consistently across your project)


问:
Using a Document Listener to display search results in real time?
I've a list of 'people' displayed in a JTable and stored in a database. I'd quite like users to have the results narrowed in that table as they type into a search area.

So for example typing 'S' would narrow the displayed names to 'Susan', 'Stephen', 'Steve', which would be narrowed down to just 'Susan' as soon as you type 'Su'

I was thinking of using the DocumentListener methods .removeUpdate(e) and .insertUpdate(e) to call the method that searches the underlying database and updates the table view - but this seems pretty wasteful.

In effect I'd be creating a new database connection, and other db objects, and refreshing the table every time any character was typed. I'm not sure if this is just poor design, or something that will actively cause me problems? Is there a better way of approaching this? or should I just stick to a normal search button?

答:
The decision depends on your application and user requirements. There are a lot of application that provide Autocomplete functionality that is similar to yours.

Start without any optimization and see how it performs. Then you can try different optimization steps like:

1) Add wait period in between what user typed and search request. For example knowing that user will most likely search for more specific text than just 'S', wait until they type a few more characters within second or two.

2) Run the search in different thread and then update the table from there. You can have previous search thread being canceled when making next search as the user types.

3) Keep the DB connection open while user types and close after a some defined amount of time (5 sec for example). But no too long.


问:
Django Rest-Framework: How to cross object in ModelSerializer
So, I know ModelSerializer supports nested model object based on the foreign key in the current object. However, I am wondering how to do a cross join models with specific the field equals to another object?

i.e.

```<code>class classroom(models.Model):
    id = models.AutoField(primary_key = True, editable = False)

class student(models.Model):
    id = models.AutoField(primary_key = True, editable = False)
    classroom = models.ForeignKey(classroom, on_delete=models.CASCADE)
</code>```

Now I would like to do a ModelSerializer with classroom model. The idea I would like to archive is returning student.objects.filter(classroom = self.id) [self is classrom]

How can I get the data from the student as well? (There is no ForeignKey in classroom targeting student)

```<code>class classroomSerializer(ModelSerializer):
# students = ??
class Meta:
    model = classroom
    fields = [
        'id',
        'students',
    ]
</code>```

答:
You can define another serializer for your student model and refer to it in your classroom serializer.

```<code>class classroomSerializer(ModelSerializer):
students = studentserializer(many=True)
class Meta:
    model = classroom
    fields = [
      'id',
      'students'
    ]
</code>```

And add a related_name in your student model

```<code>class student(models.Model):
    id = models.AutoField(primary_key = True, editable = False)
    classroom = models.ForeignKey(classroom, on_delete=models.CASCADE, related_name='students')
</code>```

Body:
So, I know ModelSerializer supports nested model object based on the foreign key in the current object. However, I am wondering how to do a cross join models with specific the field equals to another object?

i.e.

class classroom(models.Model):
    id = models.AutoField(primary_key = True, editable = False)

class student(models.Model):
    id = models.AutoField(primary_key = True, editable = False)
    classroom = models.ForeignKey(classroom, on_delete=models.CASCADE)

Now I would like to do a ModelSerializer with classroom model. The idea I would like to archive is returning student.objects.filter(classroom = self.id) [self is classrom]

How can I get the data from the student as well? (There is no ForeignKey in classroom targeting student)

class classroomSerializer(ModelSerializer):
# students = ??
class Meta:
    model = classroom
    fields = [
        'id',
        'students',
    ]

Body:
You can define another serializer for your student model and refer to it in your classroom serializer.

class classroomSerializer(ModelSerializer):
students = studentserializer(many=True)
class Meta:
    model = classroom
    fields = [
      'id',
      'students'
    ]

And add a related_name in your student model

class student(models.Model):
    id = models.AutoField(primary_key = True, editable = False)
    classroom = models.ForeignKey(classroom, on_delete=models.CASCADE, related_name='students')


问:
Bing Map v7 to v8 migration
I am working on a project to migrate bing map from version7( v7)  to v8 and following the procedure mentioned in the document

https://social.technet.microsoft.com/wiki/contents/articles/34563.bing-maps-v7-to-v8-migration-guide.aspx

Our bing map application (v7) is using getTargetBounds() method in map class  (as per below code) to navigate the map to show the location selected. As per the document (above link), this method has been depricated in the v8. Could you please advise what would be the work around to achieve this in bing map v8?

```<code>var targetBounds = bingMap.getTargetBounds();
                        var isView = targetBounds.contains(newLocaton);

                        if (!isView) {
                            bingMap.setView({ center: newLocaton });
                        }
</code>```

Thanks

答: Simply use map.getBounds() after the view has changed.</p>

Title: Bing Map v7 to v8 migration

Body:
I am working on a project to migrate bing map from version7( v7)  to v8 and following the procedure mentioned in the document

https://social.technet.microsoft.com/wiki/contents/articles/34563.bing-maps-v7-to-v8-migration-guide.aspx

Our bing map application (v7) is using getTargetBounds() method in map class  (as per below code) to navigate the map to show the location selected. As per the document (above link), this method has been depricated in the v8. Could you please advise what would be the work around to achieve this in bing map v8?

var targetBounds = bingMap.getTargetBounds();
                        var isView = targetBounds.contains(newLocaton);

                        if (!isView) {
                            bingMap.setView({ center: newLocaton });
                        }

Thanks


问:
ID selector isn't working in CSS
I have this html code sample. When I write an internal css as follows it works fine. But when I implement it with a ID selector it won't.

The problem is picture size is more than it should be.

Here's the code without ID selector

```<code><!DOCTYPE html>
<html>
<head>
    <title>Omicron.com</title>
</head>
<body>
    <div>
        <img src="Header.png" alt="Header not Found" style="width:100%;min-width:10px;height:auto;position:relative;top:50px;">
    </div>
</body>
</html>
</code>```

and here's the code with ID selector and here's its preview

```<code><!DOCTYPE html>
<html>
<head>
    <title>Omicron.com</title>
<style>
#headerImage{
    width: 100%;
    min-width: 10px;
    height: 50px;
    position: relative;
    top: 50px;
}
</style>
</head>
<body>
    <div id="headerImage">
        <img src="Header.png" alt="Header not Found">
    </div>
</body>
</html>
</code>```

Can anyone tell me  what am I doing wrong?

答:
Your div with id="headerImage" is the #headerImage element. In the first example, you applied styles to the img. So in the second example, you're applying styles to the div. To apply styles to the img inside of #headerImage use #headerImage img as your selector.

<!DOCTYPE html>

    <title>Omicron.com</title>

```

Title: ID selector isn't working in CSS

Body:
I have this html code sample. When I write an internal css as follows it works fine. But when I implement it with a ID selector it won't.

The problem is picture size is more than it should be.

Here's the code without ID selector

<!DOCTYPE html>

    <title>Omicron.com</title>

and here's the code with ID selector and here's its preview

<!DOCTYPE html>

    <title>Omicron.com</title>

Can anyone tell me  what am I doing wrong?

Body:
Your div with id="headerImage" is the #headerImage element. In the first example, you applied styles to the img. So in the second example, you're applying styles to the div. To apply styles to the img inside of #headerImage use #headerImage img as your selector.

<!DOCTYPE html>
<html>
<head>
    <title>Omicron.com</title>
<style>
#headerImage img {
    width: 100%;
    min-width: 10px;
    height: 50px;
    position: relative;
    top: 50px;
}
</style>
</head>
<body>
    <div id="headerImage">
        <img src="http://kenwheeler.github.io/slick/img/fonz1.png" alt="Header not Found">
    </div>
</body>
</html>


问:
Refresh chart data
I just started using KendoUI for Angular.

What I'm trying to do is refreshing a chart view when I click a button.
This is my code:

My html:

```<code><kendo-chart [categoryAxis]="{ categories: categories }" (seriesClick)="onSeriesClick($event)">
    <kendo-chart-title text="Gross domestic product growth /GDP annual %/"></kendo-chart-title>
    <kendo-chart-legend position="bottom" orientation="horizontal"></kendo-chart-legend>
    <kendo-chart-tooltip format="{0}%"></kendo-chart-tooltip>
    <kendo-chart-series>
        <kendo-chart-series-item *ngFor="let item of series" type="line" style="smooth" [data]="item.data" [name]="item.name">
        </kendo-chart-series-item>
    </kendo-chart-series>
</kendo-chart>
</code>```

My Component:

```<code>@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  private series: any[] = [{
    name: "India",
    data: [3.907, 7.943, ...]
  },{
    name: "World",
    data: [1.988, 2.733, ...]
  }];
  private categories: number[] = [2002, 2003, ...];

    public onSeriesClick(e): void {
        this.series[0].data[0] = this.series[0].data[0] + 4;
        // TODO update the chart view
    }
}
</code>```

How can I reference the view to update it?
Thanks a lot!

答:
kendo-chart will use two day data binding so if you update any thing in the component class it will automatically reflect in the view.
so if you update anything in the series variable it will automatically reflect in the charts.

plnkr will delete india from the chart.
http://plnkr.co/edit/LdJOrU7oLOqB8e9RpNsc?p=preview

```<code>   onClickMe() {
     this.series = [ {
    name: "Russian Federation",
    data: [4.743, 7.295, 7.175, 6.376, 8.153, 8.535, 5.247, -7.832, 4.3, 4.3]
  }, {
    name: "Germany",
    data: [0.010, -0.375, 1.161, 0.684, 3.7, 3.269, 1.083, -5.127, 3.690, 2.995]
  },{
    name: "World",
    data: [1.988, 2.733, 3.994, 3.464, 4.001, 3.939, 1.333, -2.245, 4.339, 2.727]
  }];
  }
</code>```

Title: Refresh chart data

Body:
I just started using KendoUI for Angular.

What I'm trying to do is refreshing a chart view when I click a button.
This is my code:

My html:

<kendo-chart [categoryAxis]="{ categories: categories }" (seriesClick)="onSeriesClick($event)">
    <kendo-chart-title text="Gross domestic product growth /GDP annual %/"></kendo-chart-title>
    <kendo-chart-legend position="bottom" orientation="horizontal"></kendo-chart-legend>
    <kendo-chart-tooltip format="{0}%"></kendo-chart-tooltip>
    <kendo-chart-series>
        <kendo-chart-series-item *ngFor="let item of series" type="line" style="smooth" [data]="item.data" [name]="item.name">
        </kendo-chart-series-item>
    </kendo-chart-series>
</kendo-chart>

My Component:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  private series: any[] = [{
    name: "India",
    data: [3.907, 7.943, ...]
  },{
    name: "World",
    data: [1.988, 2.733, ...]
  }];
  private categories: number[] = [2002, 2003, ...];

    public onSeriesClick(e): void {
        this.series[0].data[0] = this.series[0].data[0] + 4;
        // TODO update the chart view
    }
}

How can I reference the view to update it?
Thanks a lot!

Body:
kendo-chart will use two day data binding so if you update any thing in the component class it will automatically reflect in the view.
so if you update anything in the series variable it will automatically reflect in the charts.

plnkr will delete india from the chart.
http://plnkr.co/edit/LdJOrU7oLOqB8e9RpNsc?p=preview

   onClickMe() {
     this.series = [ {
    name: "Russian Federation",
    data: [4.743, 7.295, 7.175, 6.376, 8.153, 8.535, 5.247, -7.832, 4.3, 4.3]
  }, {
    name: "Germany",
    data: [0.010, -0.375, 1.161, 0.684, 3.7, 3.269, 1.083, -5.127, 3.690, 2.995]
  },{
    name: "World",
    data: [1.988, 2.733, 3.994, 3.464, 4.001, 3.939, 1.333, -2.245, 4.339, 2.727]
  }];
  }


问:
Prime number in java 8
I was trying to write a simple prime number program in Java 8. Below is the program. I wanted to reduce the code in isPrime() as well. Is there something that filters the elements from 2 to n/2, and then apply filter for n%i == 0 which would make isPrime irrelevant?

```<code>import static java.util.stream.Collectors.toList;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class Stream1 {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 20);
        // Prime number
        System.out.println(numbers.stream()
                             .filter(Stream1::isPrime)
                             .collect(toList()));
    }

    public static boolean isPrime(int number) {
        for (int i = 2; i <= number / 2; i++) {
            if (number % i == 0) {
                return false;
            }
        }
        return true;
    }
}
</code>```

答:
As suggest by @rossum you can use the famous Sieve of Eratosthenes for this and it will compute the primes pretty fast.</p>

```<code> private static BitSet primes(int limit) {
    BitSet bitSet = new BitSet(limit);
    bitSet.set(0, false);
    bitSet.set(1, false);
    bitSet.set(2, limit, true);

    for (int i = 2; i * i < limit; ++i) {

        if (bitSet.get(i)) {
            int j = i;
            int x = 2;
            while (j < limit) {
                j = i * x;
                bitSet.set(j, false);
                ++x;
            }
        }

    }

    return bitSet;
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: Prime number in java 8

Body:
I was trying to write a simple prime number program in Java 8. Below is the program. I wanted to reduce the code in isPrime() as well. Is there something that filters the elements from 2 to n/2, and then apply filter for n%i == 0 which would make isPrime irrelevant?

import static java.util.stream.Collectors.toList;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class Stream1 {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 20);
        // Prime number
        System.out.println(numbers.stream()
                             .filter(Stream1::isPrime)
                             .collect(toList()));
    }

    public static boolean isPrime(int number) {
        for (int i = 2; i <= number / 2; i++) {
            if (number % i == 0) {
                return false;
            }
        }
        return true;
    }
}

Body:
As suggest by @rossum you can use the famous Sieve of Eratosthenes for this and it will compute the primes pretty fast.

 private static BitSet primes(int limit) {
    BitSet bitSet = new BitSet(limit);
    bitSet.set(0, false);
    bitSet.set(1, false);
    bitSet.set(2, limit, true);

    for (int i = 2; i * i < limit; ++i) {

        if (bitSet.get(i)) {
            int j = i;
            int x = 2;
            while (j < limit) {
                j = i * x;
                bitSet.set(j, false);
                ++x;
            }
        }

    }

    return bitSet;
}


问:
Powershell advance through an array in a ForEach loop (or nested Foreach)
Folks,

I found a few answers, but they seem to be for manual arrays, or when you know the definite number.  I'll have an array that I dont know how many will be in there.  Was wondering if I could get help.

Basically - I want it to go thru each server, get the OCX and DLL name, version, and date, and put it in a spreadsheet.

It seems to work fine...only once.  It doesnt go on to the next file in my array.

Im so close, can someone help me tell it (OK, dont advance to the next server until you are done getting ALL the files)

Here's my code so far.  Works great - but only for one file per server.

Many thanks in advance.

```<code>$Servers = Get-Content C:\temp\Servers.txt

$objExcel=New-Object -ComObject Excel.Application
$objExcel.Visible=-1
$WorkBook=$objExcel.WorkBooks.Add()
$sheet=$workbook.worksheets.item(1)
$class = "win32_Share"

$sheet.Cells.item(1,1)=("Server")
$sheet.Cells.item(1,2)=("File Name")
$sheet.Cells.Item(1,3)=("File Version")
$sheet.Cells.Item(1,4)=("Date")
$sheet.Range("A1:D1").interior.colorindex = 43
$x=2

$i = 0

foreach ($Server in $Servers) {

    $infos = Invoke-Command -computername $Server {Get-ChildItem "V:\Service\*" -File -Include *.dll, *.ocx | Select-Object name,@{label="FileVersion";expression={$_.versioninfo.fileversion}},@{label="Date";expression={$_.LastWriteTime}}}

    $info = $infos[$i]

$sheet.Cells.item($x, 1)=($Server)
$sheet.Cells.item($x, 2)=($info.name)
$sheet.Cells.item($x, 3)=($info.FileVersion)
$sheet.Cells.item($x, 4)=($info.Date)
$x++
$i++
}

#Autofit columns when completed
$range = $sheet.usedRange
$range.EntireColumn.Autofit()
</code>```

It never seems to advance thru the $info[$i] array.

答:
What I would suggest is to get all of that info at once, sort it by server, select what you need, convert it to a tab delimited csv, copy it to the clipboard, and paste it to the spreadsheet.</p>

```<code>$Servers = Get-Content C:\temp\Servers.txt

$objExcel=New-Object -ComObject Excel.Application
$objExcel.Visible=-1
$WorkBook=$objExcel.WorkBooks.Add()
$sheet=$workbook.worksheets.item(1)
$class = "win32_Share"
$infos = Invoke-Command -ComputerName $Servers -ScriptBlock { Get-ChildItem "V:\Service\*" -File -Include *.dll, *.ocx }
$infos |
    Sort PSComputerName |
    Select-Object  @{l='Name';e={$_.PSComputerName}},@{l='File Name';e={$_.Name}},@{label="File Version";expression={$_.versioninfo.fileversion}},@{label="Date";expression={$_.LastWriteTime}} |
    ConvertTo-CSV -Del "`t" |
    | Clip
$sheet.cells.item(1,1).PasteSpecial() | Out-Null

$sheet.Range("A1:D1").interior.colorindex = 43
#Autofit columns when completed
$range = $sheet.usedRange
$range.EntireColumn.Autofit()
</code>```

Body:
Folks,

I found a few answers, but they seem to be for manual arrays, or when you know the definite number.  I'll have an array that I dont know how many will be in there.  Was wondering if I could get help.

Basically - I want it to go thru each server, get the OCX and DLL name, version, and date, and put it in a spreadsheet.

It seems to work fine...only once.  It doesnt go on to the next file in my array.

Im so close, can someone help me tell it (OK, dont advance to the next server until you are done getting ALL the files)

Here's my code so far.  Works great - but only for one file per server.

Many thanks in advance.

$Servers = Get-Content C:\temp\Servers.txt

$objExcel=New-Object -ComObject Excel.Application
$objExcel.Visible=-1
$WorkBook=$objExcel.WorkBooks.Add()
$sheet=$workbook.worksheets.item(1)
$class = "win32_Share"

$sheet.Cells.item(1,1)=("Server")
$sheet.Cells.item(1,2)=("File Name")
$sheet.Cells.Item(1,3)=("File Version")
$sheet.Cells.Item(1,4)=("Date")
$sheet.Range("A1:D1").interior.colorindex = 43
$x=2

$i = 0

foreach ($Server in $Servers) {

    $infos = Invoke-Command -computername $Server {Get-ChildItem "V:\Service\*" -File -Include *.dll, *.ocx | Select-Object name,@{label="FileVersion";expression={$_.versioninfo.fileversion}},@{label="Date";expression={$_.LastWriteTime}}}

    $info = $infos[$i]

$sheet.Cells.item($x, 1)=($Server)
$sheet.Cells.item($x, 2)=($info.name)
$sheet.Cells.item($x, 3)=($info.FileVersion)
$sheet.Cells.item($x, 4)=($info.Date)
$x++
$i++
}

#Autofit columns when completed
$range = $sheet.usedRange
$range.EntireColumn.Autofit()

It never seems to advance thru the $info[$i] array.

Body:
What I would suggest is to get all of that info at once, sort it by server, select what you need, convert it to a tab delimited csv, copy it to the clipboard, and paste it to the spreadsheet.

$Servers = Get-Content C:\temp\Servers.txt

$objExcel=New-Object -ComObject Excel.Application
$objExcel.Visible=-1
$WorkBook=$objExcel.WorkBooks.Add()
$sheet=$workbook.worksheets.item(1)
$class = "win32_Share"
$infos = Invoke-Command -ComputerName $Servers -ScriptBlock { Get-ChildItem "V:\Service\*" -File -Include *.dll, *.ocx }
$infos |
    Sort PSComputerName |
    Select-Object  @{l='Name';e={$_.PSComputerName}},@{l='File Name';e={$_.Name}},@{label="File Version";expression={$_.versioninfo.fileversion}},@{label="Date";expression={$_.LastWriteTime}} |
    ConvertTo-CSV -Del "`t" |
    | Clip
$sheet.cells.item(1,1).PasteSpecial() | Out-Null

$sheet.Range("A1:D1").interior.colorindex = 43
#Autofit columns when completed
$range = $sheet.usedRange
$range.EntireColumn.Autofit()


问:
Unable to send JSON object to XMLHttpRequest
I am unable to send JSON object to XMLHttpRequest(). However, if I send string data through send(), it works. For example, the following code works:

```<code>var xhr = new XMLHttpRequest();
var url = 'https://xyz.info/api/contacts';
xhr.open("POST", url,true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

xhr.onreadystatechange = function() {//Call a function when the state changes.
     if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
                // Request finished. Do processing here.
     }
}
xhr.send("apikey=ee694eabf9e3&firstname=Raja1&lastname=Kumars&phone=123456");
</code>```

However, if I try to send data using JSON, it posts nothing to the url. The following code does not work.

```<code>var xhr = new XMLHttpRequest();
var url = 'https://xyz.info/api/contacts';
    xhr.open("POST", url,true);
    //xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.setRequestHeader("Content-Type", "application/json");

    xhr.onreadystatechange = function() {//Call a function when the state changes.
    if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
            // Request finished. Do processing here.
        }
    }
    xhr.send(JSON.stringify({
                    'apikey' :'ee6915d4ee4b4df66bba82277e3',
                    'firstname' : 'Kumar',
                    'lastname' : 'Sunder',
                    'phone':'5557773334'
    }));
</code>```

答: You are sending via a POST action, but then sending the data via a url string.  If you want to send it that way you need to set it to GET.</p>

Body:
I am unable to send JSON object to XMLHttpRequest(). However, if I send string data through send(), it works. For example, the following code works:

var xhr = new XMLHttpRequest();
var url = 'https://xyz.info/api/contacts';
xhr.open("POST", url,true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

xhr.onreadystatechange = function() {//Call a function when the state changes.
     if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
                // Request finished. Do processing here.
     }
}
xhr.send("apikey=ee694eabf9e3&firstname=Raja1&lastname=Kumars&phone=123456");

However, if I try to send data using JSON, it posts nothing to the url. The following code does not work.

var xhr = new XMLHttpRequest();
var url = 'https://xyz.info/api/contacts';
    xhr.open("POST", url,true);
    //xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.setRequestHeader("Content-Type", "application/json");

    xhr.onreadystatechange = function() {//Call a function when the state changes.
    if(xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
            // Request finished. Do processing here.
        }
    }
    xhr.send(JSON.stringify({
                    'apikey' :'ee6915d4ee4b4df66bba82277e3',
                    'firstname' : 'Kumar',
                    'lastname' : 'Sunder',
                    'phone':'5557773334'
    }));


问:
What is wrong with my Grails deploy to Tomcat container?
I am seeing an issue where my Grails 3 web application does not start up correctly on an EC2 instance that we have successfully deployed a Grails 2 web application to. This same Grails 2 application has been upgraded to Grails 3, and is now causing the issue.

The version of Grails I am using is 3.2.4. The version of Tomcat that is being used on the EC2 instance is 8.0.20. Also, the JVM version is 1.8.0_31.

The war file is built using the Grails command grails package (I'm not sure if there's a difference between this and grails war as other Grails 3.2.4 applications package and deploy just fine using this command), and the file is subsequently placed into the Tomcat webapps directory.

This is the issue I see when starting up Tomcat:

```<code>Caused by: org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'grailsCacheFilter': Cannot create inner bean '(inner bean)#2fb114b8' of type [grails.plugin.cache.web.filter.simple.MemoryPageFragmentCachingFilter] while setting bean property 'filter'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name '(inner bean)#2fb114b8': Unsatisfied dependency expressed through method 'setUrlMappingsHandlerMapping' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'urlMappingsHandlerMapping': Unsatisfied dependency expressed through method 'setWebRequestInterceptors' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'openSessionInViewInterceptor': Cannot resolve reference to bean 'hibernateDatastore' while setting bean property 'hibernateDatastore'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateDatastore': Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.grails.orm.hibernate.HibernateDatastore]: Constructor threw exception; nested exception is java.lang.NullPointerException
</code>```

This happens when I package, deploy, and start up the application using production mode only. I have tried setting the project up in a Tomcat 8 container locally, in qa mode on a different EC2 instance, and also in qa mode on an EC2 instance that was launched from an image that I made of the production instance I am trying to deploy to. I could not reproduce the issue on any of these.

I thought that it was possible that the dataSource in application.groovy production environment block was causing the issue. Since this particular project doesn't rely on a database, I have tried removing that and deploying the web app again in production mode on the production instance, but I still faced the same issue.

I have also tried to replicate the production dataSource configuration in qa mode. The project still started up correctly using qa mode with the same dataSource properties. I didn't see the issue appear in the Tomcat logs.

I have also read the docs a few times (particularly the deployment section), and have made sure to change the line for spring-boot-starter-tomcat dependency to provided "org.springframework.boot:spring-boot-starter-tomcat" in build.gradle since I am not using an embedded Tomcat.

After doing some more research, I am still unsure of what could be causing this issue. Maybe there is some incompatibility with Tomcat that I am overlooking. Does anyone have any ideas? Any help would be greatly appreciated. Thank you.

答: The issue was with my application configuration and an incompatible plugin. Both application.yml and application.groovy contained hibernate blocks in them. I also had an old version of the plugin database-migration (1.4.0). Once I removed the hibernate block in application.yml and removed the database-migration plugin, the application was deployed successfully. If you want to use the database-migration plugin with a Grails 3 project, you can do so with the 2.x version, according to the docs: https://github.com/grails-plugins/grails-database-migration#versions.

Body:
I am seeing an issue where my Grails 3 web application does not start up correctly on an EC2 instance that we have successfully deployed a Grails 2 web application to. This same Grails 2 application has been upgraded to Grails 3, and is now causing the issue.

The version of Grails I am using is 3.2.4. The version of Tomcat that is being used on the EC2 instance is 8.0.20. Also, the JVM version is 1.8.0_31.

The war file is built using the Grails command grails package (I'm not sure if there's a difference between this and grails war as other Grails 3.2.4 applications package and deploy just fine using this command), and the file is subsequently placed into the Tomcat webapps directory.

This is the issue I see when starting up Tomcat:

Caused by: org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'grailsCacheFilter': Cannot create inner bean '(inner bean)#2fb114b8' of type [grails.plugin.cache.web.filter.simple.MemoryPageFragmentCachingFilter] while setting bean property 'filter'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name '(inner bean)#2fb114b8': Unsatisfied dependency expressed through method 'setUrlMappingsHandlerMapping' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'urlMappingsHandlerMapping': Unsatisfied dependency expressed through method 'setWebRequestInterceptors' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'openSessionInViewInterceptor': Cannot resolve reference to bean 'hibernateDatastore' while setting bean property 'hibernateDatastore'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateDatastore': Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.grails.orm.hibernate.HibernateDatastore]: Constructor threw exception; nested exception is java.lang.NullPointerException

This happens when I package, deploy, and start up the application using production mode only. I have tried setting the project up in a Tomcat 8 container locally, in qa mode on a different EC2 instance, and also in qa mode on an EC2 instance that was launched from an image that I made of the production instance I am trying to deploy to. I could not reproduce the issue on any of these.

I thought that it was possible that the dataSource in application.groovy production environment block was causing the issue. Since this particular project doesn't rely on a database, I have tried removing that and deploying the web app again in production mode on the production instance, but I still faced the same issue.

I have also tried to replicate the production dataSource configuration in qa mode. The project still started up correctly using qa mode with the same dataSource properties. I didn't see the issue appear in the Tomcat logs.

I have also read the docs a few times (particularly the deployment section), and have made sure to change the line for spring-boot-starter-tomcat dependency to provided "org.springframework.boot:spring-boot-starter-tomcat" in build.gradle since I am not using an embedded Tomcat.

After doing some more research, I am still unsure of what could be causing this issue. Maybe there is some incompatibility with Tomcat that I am overlooking. Does anyone have any ideas? Any help would be greatly appreciated. Thank you.


问:
Private methods in TypeScript class implementing interface
I have a CPU-constrained project with a large number of classes and I use interfaces to minimize the number of imports I use in each module. However, I've run into some issues when declaring private methods on classes that implement their respective interfaces. Currently, I'm encountering:

index.d.ts:

```<code>interface IColony {
    // (other public properties)
    // instantiateVirtualComponents(): void;
}
</code>```

Colony.ts:

```<code>export class Colony implements IColony {
    // (constructor and other methods)
    private instantiateVirtualComponents(): void {
        // (implementation)
    }
}
</code>```

The issue is that TypeScript won't seem to let me declare private properties on this class. As is, tsc complains:

```<code>Error:(398, 3) TS2322:Type 'IColony' is not assignable to type 'Colony'. Property 'instantiateVirtualComponents' is missing in type 'IColony'.
</code>```

I'm pretty sure that private properties and methods shouldn't be declared in the interface, but just to be safe, if I uncomment the method declaration in IColony, tsc then complains the following (among lots of other errors resulting from this):

```<code>Error:(10, 14) TS2420:Class 'Colony' incorrectly implements interface 'IColony'. Property 'instantiateVirtualComponents' is private in type 'Colony' but not in type 'IColony'.
</code>```

What am I doing wrong here? Can you simply not declare private members on classes that implement an interface?

For reference, Colony.ts is here and the relevant part of index.d.ts is here.

答:
You are probably doing something similar to:

```<code>function fn(): IColony { ... }

let a: Colony = fn(); // error: Type 'IColony' is not assignable to type 'Colony'...
</code>```

This error occurs because you are trying to assign an instance of IColony to a variable of type Colony and it doesn't work that way (only the other way around).

If that's the case then it should be:

```<code>let a: IColony = fn();
</code>```

Body:
I have a CPU-constrained project with a large number of classes and I use interfaces to minimize the number of imports I use in each module. However, I've run into some issues when declaring private methods on classes that implement their respective interfaces. Currently, I'm encountering:

index.d.ts:

interface IColony {
    // (other public properties)
    // instantiateVirtualComponents(): void;
}

Colony.ts:

export class Colony implements IColony {
    // (constructor and other methods)
    private instantiateVirtualComponents(): void {
        // (implementation)
    }
}

The issue is that TypeScript won't seem to let me declare private properties on this class. As is, tsc complains:

Error:(398, 3) TS2322:Type 'IColony' is not assignable to type 'Colony'. Property 'instantiateVirtualComponents' is missing in type 'IColony'.

I'm pretty sure that private properties and methods shouldn't be declared in the interface, but just to be safe, if I uncomment the method declaration in IColony, tsc then complains the following (among lots of other errors resulting from this):

Error:(10, 14) TS2420:Class 'Colony' incorrectly implements interface 'IColony'. Property 'instantiateVirtualComponents' is private in type 'Colony' but not in type 'IColony'.

What am I doing wrong here? Can you simply not declare private members on classes that implement an interface?

For reference, Colony.ts is here and the relevant part of index.d.ts is here.

Body:
You are probably doing something similar to:

function fn(): IColony { ... }

let a: Colony = fn(); // error: Type 'IColony' is not assignable to type 'Colony'...

This error occurs because you are trying to assign an instance of IColony to a variable of type Colony and it doesn't work that way (only the other way around).

If that's the case then it should be:

let a: IColony = fn();


问:
Div with image slider not inheriting height in Safari only
I am using Flickity slider for a single page web store. I have set the height to be 100% of the parent div on desktop screens. This works well on Chrome however does not work on Safari only.

LINK TO PAGE

HTML:

```<code><div class="product__container">
        <div class="product__image--container">
            <div class="main-carousel">
                <div class="carousel-cell img--two"></div>
                <div class="carousel-cell img--four"></div>
                <div class="carousel-cell img--five"></div>
                <div class="carousel-cell img--one"></div>
            </div>
        </div>
        <div class="product__description--container">

            <div class="product__description--aligner">

                <h1 class="product__title" style="margin-bottom: 0px; margin-top: 0px;"><strong>MYSTERY BOX</strong></h1>
                <p class="product__price">$25</p>
                <p><strong>The stuff:</strong> we spend our days working with cool brands with even cooler products.</p>
                <p><strong>The selection:</strong> only the coolest of the coolest products make their way into the HRVST Mystery Box.</p>
                <p><strong>The shipping:</strong> your HRVST Mystery Box will magically show up to your door at the beginning of the month—unless there’s a postal strike.</p>
                <p>Each month we bring local brands together to offer a handpicked box of Montreal-based products to the first 100 shoppers, delivered to your door. Reserve yours today and never look back.</p>
                <p><i>Sourced and packed locally. Not for the faint of heart.</i></p>

                <div id='product-component-83d33f1cc51'></div>

            </div>

</div>
</code>```

CSS:

```<code>    .product__container {display: flex; display: -webkit-flex; flex-direction: column-reverse !important; -webkit-flex-direction: column-reverse !important;}
    .product__image--container, .main-carousel, .flickity-viewport, .carousel-cell {width: 100vw !important; height: 100vw !important;}
    .product__description--container {width: 100vw !important;}
    .flickity-prev-next-button {left: calc(100vw - 140px) !important;}
    div#product-component-83d33f1cc51 {margin: auto !important;}
}

.shop__wrapper {display: flex; display: -webkit-flex; flex-direction: column; -webkit-flex-direction: column; background-color: #FFFFFF; position: relative;}

.product__container {display: flex; display: -webkit-flex; flex-direction: row; -webkit-flex-direction: row;}
.product__image--container {height: inherit;}
.main-carousel {height: 100%;}
.flickity-viewport {height: inherit !important;}
.flickity-viewport, .carousel-cell {width: 50vw; min-height: 50vw;}
.carousel-cell {height: inherit;}
.img--one, .img--two, .img--three, .img--four, .img--five {background-position: center center; background-size: cover;}
.flickity-prev-next-button {
    position: relative !important;
    left: calc(50vw - 140px);
    top: -60px !important;
    background-image: url(images/Asset_9.svg) !important;
    background-position: center center !important;
    background-repeat: no-repeat !important;
    background-color: transparent !important;
    width: 30px !important;
    height: 30px !important;
    margin: 10px !important;
}
.flickity-prev-next-button:hover {opacity: 0.7;}
.next {transform: rotate(0deg) !important;}
.previous {transform: rotate(-180deg) !important;}
.flickity-prev-next-button svg {display: none;}
.img--one {background-image: url("images/shop/1.jpg");}
.img--two {background-image: url("images/shop/2.jpg");}
.img--three {background-image: url("images/shop/3.jpg");}
.img--four {background-image: url("images/shop/4.jpg");}
.img--five {background-image: url("images/shop/5.jpg");}
</code>```

答: This sounds like a browser compatibility error. Especially if the element isn't working at all. (Your question is unclear as to if it doesn't work at all or it is displayed weird.) Try a browser compatibility checker. I like browsershots.com, but there are many other free tools that can check.</p>

Body:
I am using Flickity slider for a single page web store. I have set the height to be 100% of the parent div on desktop screens. This works well on Chrome however does not work on Safari only.

LINK TO PAGE

HTML:

MYSTERY BOX

$25

The stuff: we spend our days working with cool brands with even cooler products.

The selection: only the coolest of the coolest products make their way into the HRVST Mystery Box.

The shipping: your HRVST Mystery Box will magically show up to your door at the beginning of the month—unless there’s a postal strike.

Each month we bring local brands together to offer a handpicked box of Montreal-based products to the first 100 shoppers, delivered to your door. Reserve yours today and never look back.

Sourced and packed locally. Not for the faint of heart.

CSS:

    .product__container {display: flex; display: -webkit-flex; flex-direction: column-reverse !important; -webkit-flex-direction: column-reverse !important;}
    .product__image--container, .main-carousel, .flickity-viewport, .carousel-cell {width: 100vw !important; height: 100vw !important;}
    .product__description--container {width: 100vw !important;}
    .flickity-prev-next-button {left: calc(100vw - 140px) !important;}
    div#product-component-83d33f1cc51 {margin: auto !important;}
}

.shop__wrapper {display: flex; display: -webkit-flex; flex-direction: column; -webkit-flex-direction: column; background-color: #FFFFFF; position: relative;}

.product__container {display: flex; display: -webkit-flex; flex-direction: row; -webkit-flex-direction: row;}
.product__image--container {height: inherit;}
.main-carousel {height: 100%;}
.flickity-viewport {height: inherit !important;}
.flickity-viewport, .carousel-cell {width: 50vw; min-height: 50vw;}
.carousel-cell {height: inherit;}
.img--one, .img--two, .img--three, .img--four, .img--five {background-position: center center; background-size: cover;}
.flickity-prev-next-button {
    position: relative !important;
    left: calc(50vw - 140px);
    top: -60px !important;
    background-image: url(images/Asset_9.svg) !important;
    background-position: center center !important;
    background-repeat: no-repeat !important;
    background-color: transparent !important;
    width: 30px !important;
    height: 30px !important;
    margin: 10px !important;
}
.flickity-prev-next-button:hover {opacity: 0.7;}
.next {transform: rotate(0deg) !important;}
.previous {transform: rotate(-180deg) !important;}
.flickity-prev-next-button svg {display: none;}
.img--one {background-image: url("images/shop/1.jpg");}
.img--two {background-image: url("images/shop/2.jpg");}
.img--three {background-image: url("images/shop/3.jpg");}
.img--four {background-image: url("images/shop/4.jpg");}
.img--five {background-image: url("images/shop/5.jpg");}


答:
You need to target the image, not its parent div.</p>

```<code>#headerImage img{
    width: 100%;
    min-width: 10px;
    height: 50px;
    position: relative;
    top: 50px;
}
</code>```

Title: ID selector isn't working in CSS

Body:
You need to target the image, not its parent div.

#headerImage img{
    width: 100%;
    min-width: 10px;
    height: 50px;
    position: relative;
    top: 50px;
}


问:
Angular 2 HTTP property retryWhen doesn't exist on type Observable<any>
I am trying to retry my requests so that I can get a refresh token before sending the user to log in again however I am getting an error when I try to use retryWhen on the request and I'm not sure why.

http.service.ts

```<code>import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Http, Headers, RequestOptions, Response } from '@angular/http';

@Injectable()
export class HttpService {

  constructor(
    private http: Http
  ) { }

  public get(url: string, headers?: Headers): Observable<any> {
    return this.http.get(url, this.getHeaders(headers))
      .map(this.extractData)
      .retryWhen((error: any) => { ... }) // [ts] Property 'retryWhen' does not exist on type 'Observable<any>'.
      .catch(this.handleError);
  }
}
</code>```

答:
You must import the operator first before using it(it works the same for other operators)

Put this in your imports at the top of the file:

```<code>import 'rxjs/add/operator/retryWhen';
</code>```

It adds this operator on-top of the Observable prototype.

Body:
I am trying to retry my requests so that I can get a refresh token before sending the user to log in again however I am getting an error when I try to use retryWhen on the request and I'm not sure why.

http.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Http, Headers, RequestOptions, Response } from '@angular/http';

@Injectable()
export class HttpService {

  constructor(
    private http: Http
  ) { }

  public get(url: string, headers?: Headers): Observable<any> {
    return this.http.get(url, this.getHeaders(headers))
      .map(this.extractData)
      .retryWhen((error: any) => { ... }) // [ts] Property 'retryWhen' does not exist on type 'Observable<any>'.
      .catch(this.handleError);
  }
}

Body:
You must import the operator first before using it(it works the same for other operators)

Put this in your imports at the top of the file:

import 'rxjs/add/operator/retryWhen';

It adds this operator on-top of the Observable prototype.


问:
Node Request: Get certain class/id
I am using the Node module Request. I have also used node-fetch in the past but request seems better. I want to be able to log something with a certain ID/Class/Span, you name it. This is my current code which logs the whole body.

```<code>const request = require('request');

request("https://discord.js.org/#/docs/main/stable/class/GuildMember", (err, response, body) => {
    if (err) console.log(err);

    console.log(body)
});
</code>```

I want to log the contents of any Property the user gives, let's say they give bannable I want to log the contents of div#doc-for-bannable.class-prop.class-item but I'm not sure how to do this.

Edit:

I tried using Cheerio as suggested but it is not giving me any sort of response, just a blank space in my console.The code I tried was:

```<code>request("https://discord.js.org/#/docs/main/stable/class/GuildMember", (err, response, body) => {
    if (err) console.log(err);
    const $ = cheerio.load(body);

    const g = $('docs-page'); // this doesn't work either, after trying '#doc-for-bannable`

    const gText = g.text();

    console.log(gText)
});
</code>```

答:
The underlying request page builds the DOM after requesting data from backend using XHR/ajax requests.

So when you use 'request', the page is loaded without XHR being fired

However, if you closely look at the Network tab, you will come across
https://raw.githubusercontent.com/hydrabolt/discord.js/docs/stable.json

This has the data that you are looking for.
You can use the nodejs 'request' for this url and consume the json

Title: Node Request: Get certain class/id

Body:
I am using the Node module Request. I have also used node-fetch in the past but request seems better. I want to be able to log something with a certain ID/Class/Span, you name it. This is my current code which logs the whole body.

const request = require('request');

request("https://discord.js.org/#/docs/main/stable/class/GuildMember", (err, response, body) => {
    if (err) console.log(err);

    console.log(body)
});

I want to log the contents of any Property the user gives, let's say they give bannable I want to log the contents of div#doc-for-bannable.class-prop.class-item but I'm not sure how to do this.

Edit:

I tried using Cheerio as suggested but it is not giving me any sort of response, just a blank space in my console.The code I tried was:

request("https://discord.js.org/#/docs/main/stable/class/GuildMember", (err, response, body) => {
    if (err) console.log(err);
    const $ = cheerio.load(body);

    const g = $('docs-page'); // this doesn't work either, after trying '#doc-for-bannable`

    const gText = g.text();

    console.log(gText)
});


问:
How should I declare a Stateless Functional Component with Typescript in React?
I've seen two ways of declaring a SFC in React with Typescript, which are these two:

```<code>import * as React from 'react'

interface Props {
  message: string
}

const Component = (props: Props) => {
  const { message } = props
  return (
    <div>{message}</div>
  )
}

export default Component
</code>```

and:

```<code>import * as React from 'react'

interface Props {
  message: string
}

const Component: React.StatelessComponent<Props> = props => {
  const { message } = props
  return (
    <div>{message}</div>
  )
}

export default Component
</code>```

From this question I see that with the second way you can omit children from your interface if you are using it in your component.

Are there any more differences? Which one is the preferred one and why?

答:
When you declare that const Component: React.StatelessComponent<Props>
You basically declaring what this function gets, and what it returns:

interface StatelessComponent
 {
        (props: P ... ): ReactElement<any>;

So for readability, I would actually do:

const Component = (props: Props): JSX.Element => {

Because here the developer that looks into this code don't need to know what is the interface of StatelessComponent - he can just read what goes in and what goes out.

And basically, it is all a big:

const Component: React.StatelessComponent<Props> = (props: IProps): JSX.Element =>

Body:
I've seen two ways of declaring a SFC in React with Typescript, which are these two:

import * as React from 'react'

interface Props {
  message: string
}

const Component = (props: Props) => {
  const { message } = props
  return (

{message}

  )
}

export default Component

and:

import * as React from 'react'

interface Props {
  message: string
}

const Component: React.StatelessComponent<Props> = props => {
  const { message } = props
  return (

{message}

  )
}

export default Component

From this question I see that with the second way you can omit children from your interface if you are using it in your component.

Are there any more differences? Which one is the preferred one and why?

Body:
When you declare that const Component: React.StatelessComponent<Props>
You basically declaring what this function gets, and what it returns:

interface StatelessComponent<P> {
        (props: P ... ): ReactElement<any>;

So for readability, I would actually do:

const Component = (props: Props): JSX.Element => {

Because here the developer that looks into this code don't need to know what is the interface of StatelessComponent - he can just read what goes in and what goes out.

And basically, it is all a big:

const Component: React.StatelessComponent<Props> = (props: IProps): JSX.Element =>


问:
Azure Table Service - 409 errors all over the place
On the last 4 hours i've got 200+ requests failing on azure table reporting 409. I've looked around and this means PK duplication. Since this is a table specific for logging, I really don't care about the keys so my RowKey is Guid.NewGuid()...

Is there another reason for azure table to return a 409 or I'm actually seeing UUIDs colliding?

PS: i really hope that there's another reason, because on the last 4 hours I've handled only 50k requests...

答:
Most likely your client didn't see the HTTP 200 response indicating a successful insertion (client timeout, network error, etc), but the insert did successfully happen on the server side.  Then when the client retried the operation it received a 409 since the entity already existed on the server.

You will be able to see evidence of this in the storage analytics logs if you turn those on.

You can try to troubleshoot the initial client failure, but that doesn't ultimately solve the problem since you need to handle this type of failure anyways.  Since you are just writing logging data then you probably don't care about the 409 on the retry so the best solution is to just ignore it.  Other possible solutions are to use the 'Insert Or Replace' or 'Insert Or Merge' operations instead of just an Insert.

For some more context see https://github.com/Azure/azure-storage-java/issues/35 or https://social.msdn.microsoft.com/Forums/azure/en-US/9ab80192-6450-41c2-a964-4ea092c1f6ef/table-storage-handling-retry-error-where-item-already-exists?forum=windowsazuredata.