问:
iOS Swift: How to recreate a Photos App UICollectionView Layout
I am wondering for quiet a while now how to create the iOS Photos App layout. How can I make it so it looks like zooming in to a collection while at the same time the navigation bar shows a back button?

Is it a new view controller which gets pushed onto a UINavigationController? And if so, how exactly do they manage to match the tiles while expanding.

Is there maybe even a 3rd party library which lets me easily recreate such a layout?

Hope you can help me to understand the concept of how this works.

答:
To answer your first question, "Is it a new view controller which gets pushed onto a UINavigationController?". Yes, it is a new view controller. What Apple is using here is a UIViewControllerTransitioningDelegate which allows you to present a custom animation on how a view controller is presented and dismissed.

Now on the second question, "Hope you can help me to understand the concept of how this works." There is no easy way to put it as quite a lot is involved. I have recreated the effect which I will show below but first I need to explain some core principles.

From Apple's docs,

When implementing your transitioning delegate object, you can return different animator objects depending on whether a view controller is being presented or dismissed. All transitions use a transition animator object—an object that conforms to the UIViewControllerAnimatedTransitioning protocol—to implement the basic animations. A transition animator object performs a set of animations over a finite period of time.

In other words, the UIViewControllerTransitioningDelegate expects an animator object which you create that describes how the view controller should be presented and how it should be dismissed. Only two of these delegates methods are of interest to what you want to achieve and these are:

```<code>    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
    let animator = PresentAnimator()
    return animator
}
</code>```

This asks your delegate for the transition animator object to use when presenting a view controller.

```<code>func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
    let animator = DismissAnimator()
    return animator
}
</code>```

This asks your delegate for the transition animator object to use when dismissing a view controller.

Both the PresentAnimator and DismissAnimator object conform to UIViewControllerAnimatedTransitioning. From Apple's docs:

In your animator object, implement the transitionDuration(using:) method to specify the duration of your transition and implement the animateTransition(using:) method to create the animations themselves. Information about the objects involved in the transition is passed to your animateTransition(using:) method in the form of a context object. Use the information provided by that object to move the target view controller’s view on or off screen over the specified duration.

Basically, each animator object will describe the duration of the view controller's animation and how it will be animated.

Now here is a demonstration of all this. This is what we will achieve:

Create two view controllers in your storyboard. My first view controller is called ViewController which contains a Collection View and a Collection View cell with an identifier "MediaCell" and an image that fills that collection view cell. The collection view cell has a class  called ImageCollectionViewCell with only this:

```<code>    class ImageCollectionViewCell: UICollectionViewCell {

     @IBOutlet weak var image: UIImageView! //links to the collection view cell's image

     }
</code>```

My second view controller is called ImageRevealViewController which simply has a single image view and a grey view at the top that I am using to simulate a navigation bar and a custom back button (I have tried all this with a normal UINavigationController nav bar but the dismiss animator fails to work. There is no shame through is making something that looks and acts like a navigation bar although mine is just for demo).

The Photo Album

This will be the code for your ViewController. Basically this will be the place the user finds a collection of photos just like the Photo Album. I used two test images for mine as you will see.

```<code>    import UIKit

    class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

@IBOutlet weak var collectionView: UICollectionView!

var selectedCell = UICollectionViewCell() //the selected cell, important for the animator

var media: [UIImage] = [UIImage]() //the photo album's images

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    media.append(UIImage(named: "testimage1")!)

    media.append(UIImage(named: "testimage2")!)

    collectionView.delegate = self

    collectionView.dataSource = self
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    selectedCell = collectionView.cellForItem(at: indexPath)!

    let selectedCellImage = selectedCell as! ImageCollectionViewCell

    let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)

    let imageRevealVC = mainStoryboard.instantiateViewController(withIdentifier: "ImageRevealVC") as! ImageRevealViewController

    imageRevealVC.transitioningDelegate = self

    imageRevealVC.imageToReveal = selectedCellImage.image.image

     /*
      This is where I tried using the nav controller but things did not work out for the dismiss animator. I have commented it out.
     */

    //let navController = UINavigationController(rootViewController: imageRevealVC)

    //navController.transitioningDelegate = self

    //navigationController?.pushViewController(imageRevealVC, animated: true)

    present(imageRevealVC, animated: true, completion: nil)

}

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    return media.count

}

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

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

    cell.image.image = media[indexPath.row]

    cell.image.contentMode = .scaleAspectFill

    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let itemsPerRow:CGFloat = 3
    let hardCodedPadding:CGFloat = 2
    let itemWidth = (collectionView.bounds.width / itemsPerRow) - hardCodedPadding
    let itemHeight = itemWidth
    return CGSize(width: itemWidth, height: itemHeight)
}

 }

    extension ViewController: UIViewControllerTransitioningDelegate {

func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
    let animator = PresentAnimator()
    animator.originFrame = selectedCell.frame //the selected cell gives us the frame origin for the reveal animation
    return animator
}

func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
    let animator = DismissAnimator()
    return animator
}

 }
</code>```

The UIViewControllerTransitioningDelegate is at the end alongside the animator objects I talked about. Notice in the didSelect of the collection view that I instantiate the new view controller and make its transitioning delegate equal to self.

The Animators

There are always three steps to making an animator.

Setup the transition

Create the animations

Complete the transitions

Now for the Present Animator. Create a new Swift class called PresentAnimator and add the following:

```<code>    import Foundation

     import UIKit

   class PresentAnimator: NSObject, UIViewControllerAnimatedTransitioning {

let duration = 0.5

var originFrame = CGRect.zero

func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
    return duration
}

func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {

    let containerView = transitionContext.containerView

    let toView = transitionContext.view(forKey: UITransitionContextViewKey.to)!

    //2) create animation
    let finalFrame = toView.frame

    let xScaleFactor = originFrame.width / finalFrame.width
    let yScaleFactor = originFrame.height / finalFrame.height

    let scaleTransform = CGAffineTransform(scaleX: xScaleFactor, y: yScaleFactor)

    toView.transform = scaleTransform
    toView.center = CGPoint(
        x: originFrame.midX,
        y: originFrame.midY
    )

    toView.clipsToBounds = true

    containerView.addSubview(toView)

    UIView.animate(withDuration: duration, delay: 0.0,
                   options: [], animations: {

                    toView.transform = CGAffineTransform.identity
                    toView.center = CGPoint(
                        x: finalFrame.midX,
                        y: finalFrame.midY
                    )

    }, completion: {_ in

        //3 complete the transition
        transitionContext.completeTransition(
            !transitionContext.transitionWasCancelled
        )
    })

}

   }
</code>```

Now for the Dismiss Animator. Create a new class called DismissAnimator and add the following:

```<code>    import Foundation

    import UIKit

    class DismissAnimator: NSObject, UIViewControllerAnimatedTransitioning {

let duration = 0.5

func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
    return duration
}

func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {

    //1) setup the transition
    let containerView = transitionContext.containerView

    let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from)!
    let toView = transitionContext.view(forKey: UITransitionContextViewKey.to)!

    containerView.insertSubview(toView, belowSubview: fromView)

    //2) animations!

    UIView.animate(withDuration: duration, delay: 0.0, options: [], animations: {

        fromView.transform = CGAffineTransform(scaleX: 0.1, y: 0.1)

    }, completion: {_ in

        //3) complete the transition
        transitionContext.completeTransition(
            !transitionContext.transitionWasCancelled
        )
    })

}

    }
</code>```

The Image Revealed

Now for the final step, the view controller that reveals the image. In your ImageRevealController add this:

```<code>    import UIKit

    class ImageRevealViewController: UIViewController {

    var imageToReveal: UIImage!

@IBOutlet weak var imageRevealed: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

    imageRevealed.image = imageToReveal

}

@IBAction func backButton(_ sender: Any) {

    dismiss(animated: true, completion: nil)

}

  }
</code>```

The backButton connects to the button that I added to the view that acts like nav bar. You can add your own back indicator to make it more authentic.

For more info on UIViewControllerTransitioningDelegate there is a section here "From View Controller" disappears using UIViewControllerContextTransitioning, you could look into and to which I have contributed an answer.

Body:
To answer your first question, "Is it a new view controller which gets pushed onto a UINavigationController?". Yes, it is a new view controller. What Apple is using here is a UIViewControllerTransitioningDelegate which allows you to present a custom animation on how a view controller is presented and dismissed.

Now on the second question, "Hope you can help me to understand the concept of how this works." There is no easy way to put it as quite a lot is involved. I have recreated the effect which I will show below but first I need to explain some core principles.

From Apple's docs,

When implementing your transitioning delegate object, you can return different animator objects depending on whether a view controller is being presented or dismissed. All transitions use a transition animator object—an object that conforms to the UIViewControllerAnimatedTransitioning protocol—to implement the basic animations. A transition animator object performs a set of animations over a finite period of time.

In other words, the UIViewControllerTransitioningDelegate expects an animator object which you create that describes how the view controller should be presented and how it should be dismissed. Only two of these delegates methods are of interest to what you want to achieve and these are:

    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
    let animator = PresentAnimator()
    return animator
}

This asks your delegate for the transition animator object to use when presenting a view controller.

func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
    let animator = DismissAnimator()
    return animator
}

This asks your delegate for the transition animator object to use when dismissing a view controller.

Both the PresentAnimator and DismissAnimator object conform to UIViewControllerAnimatedTransitioning. From Apple's docs:

In your animator object, implement the transitionDuration(using:) method to specify the duration of your transition and implement the animateTransition(using:) method to create the animations themselves. Information about the objects involved in the transition is passed to your animateTransition(using:) method in the form of a context object. Use the information provided by that object to move the target view controller’s view on or off screen over the specified duration.

Basically, each animator object will describe the duration of the view controller's animation and how it will be animated.

Now here is a demonstration of all this. This is what we will achieve:

Create two view controllers in your storyboard. My first view controller is called ViewController which contains a Collection View and a Collection View cell with an identifier "MediaCell" and an image that fills that collection view cell. The collection view cell has a class  called ImageCollectionViewCell with only this:

    class ImageCollectionViewCell: UICollectionViewCell {

     @IBOutlet weak var image: UIImageView! //links to the collection view cell's image

     }

My second view controller is called ImageRevealViewController which simply has a single image view and a grey view at the top that I am using to simulate a navigation bar and a custom back button (I have tried all this with a normal UINavigationController nav bar but the dismiss animator fails to work. There is no shame through is making something that looks and acts like a navigation bar although mine is just for demo).

The Photo Album

This will be the code for your ViewController. Basically this will be the place the user finds a collection of photos just like the Photo Album. I used two test images for mine as you will see.

    import UIKit

    class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {

@IBOutlet weak var collectionView: UICollectionView!

var selectedCell = UICollectionViewCell() //the selected cell, important for the animator

var media: [UIImage] = [UIImage]() //the photo album's images

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    media.append(UIImage(named: "testimage1")!)

    media.append(UIImage(named: "testimage2")!)

    collectionView.delegate = self

    collectionView.dataSource = self
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    selectedCell = collectionView.cellForItem(at: indexPath)!

    let selectedCellImage = selectedCell as! ImageCollectionViewCell

    let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)

    let imageRevealVC = mainStoryboard.instantiateViewController(withIdentifier: "ImageRevealVC") as! ImageRevealViewController

    imageRevealVC.transitioningDelegate = self

    imageRevealVC.imageToReveal = selectedCellImage.image.image

     /*
      This is where I tried using the nav controller but things did not work out for the dismiss animator. I have commented it out.
     */

    //let navController = UINavigationController(rootViewController: imageRevealVC)

    //navController.transitioningDelegate = self

    //navigationController?.pushViewController(imageRevealVC, animated: true)

    present(imageRevealVC, animated: true, completion: nil)

}

func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    return media.count

}

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

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

    cell.image.image = media[indexPath.row]

    cell.image.contentMode = .scaleAspectFill

    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let itemsPerRow:CGFloat = 3
    let hardCodedPadding:CGFloat = 2
    let itemWidth = (collectionView.bounds.width / itemsPerRow) - hardCodedPadding
    let itemHeight = itemWidth
    return CGSize(width: itemWidth, height: itemHeight)
}

 }

    extension ViewController: UIViewControllerTransitioningDelegate {

func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
    let animator = PresentAnimator()
    animator.originFrame = selectedCell.frame //the selected cell gives us the frame origin for the reveal animation
    return animator
}

func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
    let animator = DismissAnimator()
    return animator
}

 }

The UIViewControllerTransitioningDelegate is at the end alongside the animator objects I talked about. Notice in the didSelect of the collection view that I instantiate the new view controller and make its transitioning delegate equal to self.

The Animators

There are always three steps to making an animator.

Setup the transition

Create the animations

Complete the transitions

Now for the Present Animator. Create a new Swift class called PresentAnimator and add the following:

    import Foundation

     import UIKit

   class PresentAnimator: NSObject, UIViewControllerAnimatedTransitioning {

let duration = 0.5

var originFrame = CGRect.zero

func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
    return duration
}

func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {

    let containerView = transitionContext.containerView

    let toView = transitionContext.view(forKey: UITransitionContextViewKey.to)!

    //2) create animation
    let finalFrame = toView.frame

    let xScaleFactor = originFrame.width / finalFrame.width
    let yScaleFactor = originFrame.height / finalFrame.height

    let scaleTransform = CGAffineTransform(scaleX: xScaleFactor, y: yScaleFactor)

    toView.transform = scaleTransform
    toView.center = CGPoint(
        x: originFrame.midX,
        y: originFrame.midY
    )

    toView.clipsToBounds = true

    containerView.addSubview(toView)

    UIView.animate(withDuration: duration, delay: 0.0,
                   options: [], animations: {

                    toView.transform = CGAffineTransform.identity
                    toView.center = CGPoint(
                        x: finalFrame.midX,
                        y: finalFrame.midY
                    )

    }, completion: {_ in

        //3 complete the transition
        transitionContext.completeTransition(
            !transitionContext.transitionWasCancelled
        )
    })

}

   }

Now for the Dismiss Animator. Create a new class called DismissAnimator and add the following:

    import Foundation

    import UIKit

    class DismissAnimator: NSObject, UIViewControllerAnimatedTransitioning {

let duration = 0.5

func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
    return duration
}

func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {

    //1) setup the transition
    let containerView = transitionContext.containerView

    let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from)!
    let toView = transitionContext.view(forKey: UITransitionContextViewKey.to)!

    containerView.insertSubview(toView, belowSubview: fromView)

    //2) animations!

    UIView.animate(withDuration: duration, delay: 0.0, options: [], animations: {

        fromView.transform = CGAffineTransform(scaleX: 0.1, y: 0.1)

    }, completion: {_ in

        //3) complete the transition
        transitionContext.completeTransition(
            !transitionContext.transitionWasCancelled
        )
    })

}

    }

The Image Revealed

Now for the final step, the view controller that reveals the image. In your ImageRevealController add this:

    import UIKit

    class ImageRevealViewController: UIViewController {

    var imageToReveal: UIImage!

@IBOutlet weak var imageRevealed: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()

    imageRevealed.image = imageToReveal

}

@IBAction func backButton(_ sender: Any) {

    dismiss(animated: true, completion: nil)

}

  }

The backButton connects to the button that I added to the view that acts like nav bar. You can add your own back indicator to make it more authentic.

For more info on UIViewControllerTransitioningDelegate there is a section here "From View Controller" disappears using UIViewControllerContextTransitioning, you could look into and to which I have contributed an answer.


来源: stackexchange

问:
arc4random Random Number Generator
```<code>int randomNumber = (arc4random() % 83) + 1;
</code>```

Is this the best way to generate "the most random" number? Or is there a better way to generate a random number?

答:
When you use arc4random you avoid one pitfall of using % with linear congruential generators (which is the usual algorithm used by rand): the low-order bits aren't less random.

However, you still have truncation issues: i.e., because (1 << 32) % 83 is 77, that means that numbers between 0 and 76 appear (slightly) more frequently than numbers between 77 and 82. To avoid this, you should throw away the incoming value (i.e., call arc4random again) if it's above (1 << 32) / 83 * 83.

(I assume the range of arc4random is from 0 to 232-1. Adjust the above explanation accordingly.)

ContentLicense: CC BY-SA 2.5

Title: arc4random Random Number Generator

Body:
int randomNumber = (arc4random() % 83) + 1;

Is this the best way to generate "the most random" number? Or is there a better way to generate a random number?


问:
how to show nested JSON in angular 2?
I am new to angular 2. i am facing problem in showing nested JSON in my html view. I have following json.

```<code>{
    "totalItems": 347,
    "totalPages": 35,
    "results": [
        {
            "SNR_Title": "Apple - iPhone 6s 128GB - Gold (AT&T)",
            "SNR_Brand": "Apple",
            "SNR_ModelNo": "MKRP2LL/A",
            "SNR_Description": "A 4.7-inch Retina HD display with 3D Touch. 7000 series aluminum and stronger cover glass. An A9 chip with 64-bit desktop-class architecture. All new 12MP iSight camera with Live Photos. Touch ID. Faster LTE and Wi-Fi. Long battery life and iOS 10 and iCloud. All in a smooth, continuous unibody design.",
            "SNR_SKU": "BB5580428",
            "SNR_ImageURL": "https://img.bbystatic.com/BestBuy_US/images/products/5580/5580428_sa.jpg",
            "SNR_ProductURL": "https://api.bestbuy.com/click/-/5580428/pdp",
            "SNR_UPC": "400055804286",
            "SNR_Price": "699.99",
            "SNR_Available": "BESTBUY"
        },
        {
            "SNR_Title": "Apple - iPhone 6s 128GB - Gold (Sprint)",
            "SNR_Brand": "Apple",
            "SNR_ModelNo": "MKRP2LL/A",
            "SNR_Description": "A 4.7-inch Retina HD display with 3D Touch. 7000 series aluminum and stronger cover glass. An A9 chip with 64-bit desktop-class architecture. All new 12MP iSight camera with Live Photos. Touch ID. Faster LTE and Wi-Fi. Long battery life and iOS 10 and iCloud. All in a smooth, continuous unibody design.",
            "SNR_SKU": "BB5580908",
            "SNR_ImageURL": "https://img.bbystatic.com/BestBuy_US/images/products/5580/5580908_sa.jpg",
            "SNR_ProductURL": "https://api.bestbuy.com/click/-/5580908/pdp",
            "SNR_UPC": "400055809083",
            "SNR_Price": "699.99",
            "SNR_Available": "BESTBUY"
        },
        {
            "SNR_Title": "Apple - iPhone 6s 128GB - Gold (Verizon)",
            "SNR_Brand": "Apple",
            "SNR_ModelNo": "MKRP2LL/A",
            "SNR_Description": "A 4.7-inch Retina HD display with 3D Touch. 7000 series aluminum and stronger cover glass. An A9 chip with 64-bit desktop-class architecture. All new 12MP iSight camera with Live Photos. Touch ID. Faster LTE and Wi-Fi. Long battery life and iOS 10 and iCloud. All in a smooth, continuous unibody design.",
            "SNR_SKU": "BB5581618",
            "SNR_ImageURL": "https://img.bbystatic.com/BestBuy_US/images/products/5581/5581618_sa.jpg",
            "SNR_ProductURL": "https://api.bestbuy.com/click/-/5581618/pdp",
            "SNR_UPC": "400055816180",
            "SNR_Price": "699.99",
            "SNR_Available": "BESTBUY"
        },
        {
            "SNR_Title": "Apple - iPhone 6s 128GB - Silver (AT&T)",
            "SNR_Brand": "Apple",
            "SNR_ModelNo": "MKRM2LL/A",
            "SNR_Description": "A 4.7-inch Retina HD display with 3D Touch. 7000 series aluminum and stronger cover glass. An A9 chip with 64-bit desktop-class architecture. All new 12MP iSight camera with Live Photos. Touch ID. Faster LTE and Wi-Fi. Long battery life and iOS 10 and iCloud. All in a smooth, continuous unibody design.",
            "SNR_SKU": "BB5580429",
            "SNR_ImageURL": "https://img.bbystatic.com/BestBuy_US/images/products/5580/5580429_sa.jpg",
            "SNR_ProductURL": "https://api.bestbuy.com/click/-/5580429/pdp",
            "SNR_UPC": "400055804293",
            "SNR_Price": "699.99",
            "SNR_Available": "BESTBUY"
        },
        {
            "SNR_Title": "Apple - iPhone 6s 128GB - Silver (Sprint)",
            "SNR_Brand": "Apple",
            "SNR_ModelNo": "MKRM2LL/A",
            "SNR_Description": "A 4.7-inch Retina HD display with 3D Touch. 7000 series aluminum and stronger cover glass. An A9 chip with 64-bit desktop-class architecture. All new 12MP iSight camera with Live Photos. Touch ID. Faster LTE and Wi-Fi. Long battery life and iOS 10 and iCloud. All in a smooth, continuous unibody design.",
            "SNR_SKU": "BB5580909",
            "SNR_ImageURL": "https://img.bbystatic.com/BestBuy_US/images/products/5580/5580909_sa.jpg",
            "SNR_ProductURL": "https://api.bestbuy.com/click/-/5580909/pdp",
            "SNR_UPC": "400055809090",
            "SNR_Price": "699.99",
            "SNR_Available": "BESTBUY"
        },
        {
            "SNR_Title": "Apple - iPhone 6s 128GB - Silver (Verizon)",
            "SNR_Brand": "Apple",
            "SNR_ModelNo": "MKRM2LL/A",
            "SNR_Description": "A 4.7-inch Retina HD display with 3D Touch. 7000 series aluminum and stronger cover glass. An A9 chip with 64-bit desktop-class architecture. All new 12MP iSight camera with Live Photos. Touch ID. Faster LTE and Wi-Fi. Long battery life and iOS 10 and iCloud. All in a smooth, continuous unibody design.",
            "SNR_SKU": "BB5581619",
            "SNR_ImageURL": "https://img.bbystatic.com/BestBuy_US/images/products/5581/5581619_sa.jpg",
            "SNR_ProductURL": "https://api.bestbuy.com/click/-/5581619/pdp",
            "SNR_UPC": "400055816197",
            "SNR_Price": "699.99",
            "SNR_Available": "BESTBUY"
        },
        {
            "SNR_Title": "Apple - iPhone 6s 128GB - Space Gray (AT&T)",
            "SNR_Brand": "Apple",
            "SNR_ModelNo": "MKRL2LL/A",
            "SNR_Description": "A 4.7-inch Retina HD display with 3D Touch. 7000 series aluminum and stronger cover glass. An A9 chip with 64-bit desktop-class architecture. All new 12MP iSight camera with Live Photos. Touch ID. Faster LTE and Wi-Fi. Long battery life and iOS 10 and iCloud. All in a smooth, continuous unibody design.",
            "SNR_SKU": "BB5580426",
            "SNR_ImageURL": "https://img.bbystatic.com/BestBuy_US/images/products/5580/5580426_sa.jpg",
            "SNR_ProductURL": "https://api.bestbuy.com/click/-/5580426/pdp",
            "SNR_UPC": "400055804262",
            "SNR_Price": "699.99",
            "SNR_Available": "BESTBUY"
        },
        {
            "SNR_Title": "Apple - iPhone 6s 16GB - Space Gray (Sprint)",
            "SNR_Brand": "Apple",
            "SNR_ModelNo": "MKRC2LL/A",
            "SNR_Description": "A 4.7-inch Retina HD display with 3D Touch. 7000 Series aluminum and stronger cover glass. An A9 chip with 64-bit desktop-class architecture. 12MP iSight camera with Live Photos. Touch ID. Faster LTE¹ and Wi-Fi. Long battery life.² And iOS 9 and iCloud. All in a smooth continuous unibody design.",
            "SNR_SKU": "BB5440400",
            "SNR_ImageURL": "https://img.bbystatic.com/BestBuy_US/images/products/5440/5440400_sa.jpg",
            "SNR_ProductURL": "https://api.bestbuy.com/click/-/5440400/pdp",
            "SNR_UPC": "400054404005",
            "SNR_Price": "549.99",
            "SNR_Available": "BESTBUY"
        },
        {
            "SNR_Title": "Apple - iPhone 6s 32GB - Gold (AT&T)",
            "SNR_Brand": "Apple",
            "SNR_ModelNo": "MN1K2LL/A",
            "SNR_Description": "A 4.7-inch Retina HD display with 3D Touch. 7000 series aluminum and stronger cover glass. An A9 chip with 64-bit desktop-class architecture. All new 12MP iSight camera with Live Photos. Touch ID. Faster LTE and Wi-Fi. Long battery life and iOS 10 and iCloud. All in a smooth, continuous unibody design.",
            "SNR_SKU": "BB5580395",
            "SNR_ImageURL": "https://img.bbystatic.com/BestBuy_US/images/products/5580/5580395_sa.jpg",
            "SNR_ProductURL": "https://api.bestbuy.com/click/-/5580395/pdp",
            "SNR_UPC": "400055803951",
            "SNR_Price": "599.99",
            "SNR_Available": "BESTBUY"
        },
        {
            "SNR_Title": "Apple - iPhone 6s 32GB - Gold (Sprint)",
            "SNR_Brand": "Apple",
            "SNR_ModelNo": "MN1K2LL/A",
            "SNR_Description": "A 4.7-inch Retina HD display with 3D Touch. 7000 series aluminum and stronger cover glass. An A9 chip with 64-bit desktop-class architecture. All new 12MP iSight camera with Live Photos. Touch ID. Faster LTE and Wi-Fi. Long battery life and iOS 10 and iCloud. All in a smooth, continuous unibody design.",
            "SNR_SKU": "BB5580737",
            "SNR_ImageURL": "https://img.bbystatic.com/BestBuy_US/images/products/5580/5580737_sa.jpg",
            "SNR_ProductURL": "https://api.bestbuy.com/click/-/5580737/pdp",
            "SNR_UPC": "400055807379",
            "SNR_Price": "599.99",
            "SNR_Available": "BESTBUY"
        }
    ]
}
</code>```

and i am receiving this in GetAllMobile array.
my service look like this.

```<code>this.httpService.getAllMobiles().subscribe(
    data => {
      const myArray = [];

      for (let key in data) {
        myArray.push(data[key]);
        this.GetAllMobile.push(data[key])

      }
      console.log(this.GetAllMobile)
    }, () => this.loading = false
  );
</code>```

and what i have tried this.

```<code><div *ngFor="let item of GetAllMobile">
    <h2>
        Total {{item.totalItems}} {{item.totalPages}} AMAD
    </h2>
</div>
</code>```

but it does not showing me simple totalItems and Total pages. and to show results i am trying this.

```<code><div *ngFor="let test of GetAllMobile">
    <div *ngFor="let x of test.results">
  <p>
      {{x.SNR_Title}}
  </p>
    </div>
</div>
</code>```

it is also showing me nothing.

can anybody give me hint or code that how can i show it in angular 2 with typescript.
Any help will be highly appreciated.

答:
If GetAllMobile is an array, then the JSON you posted is an object in GetAllMobile and can be displayed following way:

```<code><div *ngFor="let item of GetAllMobile">
  <h2>
      Total {{item.totalItems}} {{item.totalPages}} AMAD
  </h2>

  <div *ngFor="let x of item.results">
    <p>
        {{x.SNR_Title}}
    </p>
  </div>
</div>
</code>```

But if you set the JSON to GetAllMobile, then it becomes an object, and values become directly accessible:

```<code><div>
  <h2>
      Total {{GetAllMobileObject.totalItems}} {{GetAllMobileObject.totalPages}} AMAD
  </h2>
</div>
<div *ngFor="let x of GetAllMobileObject.results">
    <p>
        {{x.SNR_Title}}
    </p>
</div>
</code>```

I have created this demo for both cases using your code example. Hope this helps.

ContentLicense: CC BY-SA 3.0

Title: how to show nested JSON in angular 2?

Body:
I am new to angular 2. i am facing problem in showing nested JSON in my html view. I have following json.

{
    "totalItems": 347,
    "totalPages": 35,
    "results": [
        {
            "SNR_Title": "Apple - iPhone 6s 128GB - Gold (AT&T)",
            "SNR_Brand": "Apple",
            "SNR_ModelNo": "MKRP2LL/A",
            "SNR_Description": "A 4.7-inch Retina HD display with 3D Touch. 7000 series aluminum and stronger cover glass. An A9 chip with 64-bit desktop-class architecture. All new 12MP iSight camera with Live Photos. Touch ID. Faster LTE and Wi-Fi. Long battery life and iOS 10 and iCloud. All in a smooth, continuous unibody design.",
            "SNR_SKU": "BB5580428",
            "SNR_ImageURL": "https://img.bbystatic.com/BestBuy_US/images/products/5580/5580428_sa.jpg",
            "SNR_ProductURL": "https://api.bestbuy.com/click/-/5580428/pdp",
            "SNR_UPC": "400055804286",
            "SNR_Price": "699.99",
            "SNR_Available": "BESTBUY"
        },
        {
            "SNR_Title": "Apple - iPhone 6s 128GB - Gold (Sprint)",
            "SNR_Brand": "Apple",
            "SNR_ModelNo": "MKRP2LL/A",
            "SNR_Description": "A 4.7-inch Retina HD display with 3D Touch. 7000 series aluminum and stronger cover glass. An A9 chip with 64-bit desktop-class architecture. All new 12MP iSight camera with Live Photos. Touch ID. Faster LTE and Wi-Fi. Long battery life and iOS 10 and iCloud. All in a smooth, continuous unibody design.",
            "SNR_SKU": "BB5580908",
            "SNR_ImageURL": "https://img.bbystatic.com/BestBuy_US/images/products/5580/5580908_sa.jpg",
            "SNR_ProductURL": "https://api.bestbuy.com/click/-/5580908/pdp",
            "SNR_UPC": "400055809083",
            "SNR_Price": "699.99",
            "SNR_Available": "BESTBUY"
        },
        {
            "SNR_Title": "Apple - iPhone 6s 128GB - Gold (Verizon)",
            "SNR_Brand": "Apple",
            "SNR_ModelNo": "MKRP2LL/A",
            "SNR_Description": "A 4.7-inch Retina HD display with 3D Touch. 7000 series aluminum and stronger cover glass. An A9 chip with 64-bit desktop-class architecture. All new 12MP iSight camera with Live Photos. Touch ID. Faster LTE and Wi-Fi. Long battery life and iOS 10 and iCloud. All in a smooth, continuous unibody design.",
            "SNR_SKU": "BB5581618",
            "SNR_ImageURL": "https://img.bbystatic.com/BestBuy_US/images/products/5581/5581618_sa.jpg",
            "SNR_ProductURL": "https://api.bestbuy.com/click/-/5581618/pdp",
            "SNR_UPC": "400055816180",
            "SNR_Price": "699.99",
            "SNR_Available": "BESTBUY"
        },
        {
            "SNR_Title": "Apple - iPhone 6s 128GB - Silver (AT&T)",
            "SNR_Brand": "Apple",
            "SNR_ModelNo": "MKRM2LL/A",
            "SNR_Description": "A 4.7-inch Retina HD display with 3D Touch. 7000 series aluminum and stronger cover glass. An A9 chip with 64-bit desktop-class architecture. All new 12MP iSight camera with Live Photos. Touch ID. Faster LTE and Wi-Fi. Long battery life and iOS 10 and iCloud. All in a smooth, continuous unibody design.",
            "SNR_SKU": "BB5580429",
            "SNR_ImageURL": "https://img.bbystatic.com/BestBuy_US/images/products/5580/5580429_sa.jpg",
            "SNR_ProductURL": "https://api.bestbuy.com/click/-/5580429/pdp",
            "SNR_UPC": "400055804293",
            "SNR_Price": "699.99",
            "SNR_Available": "BESTBUY"
        },
        {
            "SNR_Title": "Apple - iPhone 6s 128GB - Silver (Sprint)",
            "SNR_Brand": "Apple",
            "SNR_ModelNo": "MKRM2LL/A",
            "SNR_Description": "A 4.7-inch Retina HD display with 3D Touch. 7000 series aluminum and stronger cover glass. An A9 chip with 64-bit desktop-class architecture. All new 12MP iSight camera with Live Photos. Touch ID. Faster LTE and Wi-Fi. Long battery life and iOS 10 and iCloud. All in a smooth, continuous unibody design.",
            "SNR_SKU": "BB5580909",
            "SNR_ImageURL": "https://img.bbystatic.com/BestBuy_US/images/products/5580/5580909_sa.jpg",
            "SNR_ProductURL": "https://api.bestbuy.com/click/-/5580909/pdp",
            "SNR_UPC": "400055809090",
            "SNR_Price": "699.99",
            "SNR_Available": "BESTBUY"
        },
        {
            "SNR_Title": "Apple - iPhone 6s 128GB - Silver (Verizon)",
            "SNR_Brand": "Apple",
            "SNR_ModelNo": "MKRM2LL/A",
            "SNR_Description": "A 4.7-inch Retina HD display with 3D Touch. 7000 series aluminum and stronger cover glass. An A9 chip with 64-bit desktop-class architecture. All new 12MP iSight camera with Live Photos. Touch ID. Faster LTE and Wi-Fi. Long battery life and iOS 10 and iCloud. All in a smooth, continuous unibody design.",
            "SNR_SKU": "BB5581619",
            "SNR_ImageURL": "https://img.bbystatic.com/BestBuy_US/images/products/5581/5581619_sa.jpg",
            "SNR_ProductURL": "https://api.bestbuy.com/click/-/5581619/pdp",
            "SNR_UPC": "400055816197",
            "SNR_Price": "699.99",
            "SNR_Available": "BESTBUY"
        },
        {
            "SNR_Title": "Apple - iPhone 6s 128GB - Space Gray (AT&T)",
            "SNR_Brand": "Apple",
            "SNR_ModelNo": "MKRL2LL/A",
            "SNR_Description": "A 4.7-inch Retina HD display with 3D Touch. 7000 series aluminum and stronger cover glass. An A9 chip with 64-bit desktop-class architecture. All new 12MP iSight camera with Live Photos. Touch ID. Faster LTE and Wi-Fi. Long battery life and iOS 10 and iCloud. All in a smooth, continuous unibody design.",
            "SNR_SKU": "BB5580426",
            "SNR_ImageURL": "https://img.bbystatic.com/BestBuy_US/images/products/5580/5580426_sa.jpg",
            "SNR_ProductURL": "https://api.bestbuy.com/click/-/5580426/pdp",
            "SNR_UPC": "400055804262",
            "SNR_Price": "699.99",
            "SNR_Available": "BESTBUY"
        },
        {
            "SNR_Title": "Apple - iPhone 6s 16GB - Space Gray (Sprint)",
            "SNR_Brand": "Apple",
            "SNR_ModelNo": "MKRC2LL/A",
            "SNR_Description": "A 4.7-inch Retina HD display with 3D Touch. 7000 Series aluminum and stronger cover glass. An A9 chip with 64-bit desktop-class architecture. 12MP iSight camera with Live Photos. Touch ID. Faster LTE¹ and Wi-Fi. Long battery life.² And iOS 9 and iCloud. All in a smooth continuous unibody design.",
            "SNR_SKU": "BB5440400",
            "SNR_ImageURL": "https://img.bbystatic.com/BestBuy_US/images/products/5440/5440400_sa.jpg",
            "SNR_ProductURL": "https://api.bestbuy.com/click/-/5440400/pdp",
            "SNR_UPC": "400054404005",
            "SNR_Price": "549.99",
            "SNR_Available": "BESTBUY"
        },
        {
            "SNR_Title": "Apple - iPhone 6s 32GB - Gold (AT&T)",
            "SNR_Brand": "Apple",
            "SNR_ModelNo": "MN1K2LL/A",
            "SNR_Description": "A 4.7-inch Retina HD display with 3D Touch. 7000 series aluminum and stronger cover glass. An A9 chip with 64-bit desktop-class architecture. All new 12MP iSight camera with Live Photos. Touch ID. Faster LTE and Wi-Fi. Long battery life and iOS 10 and iCloud. All in a smooth, continuous unibody design.",
            "SNR_SKU": "BB5580395",
            "SNR_ImageURL": "https://img.bbystatic.com/BestBuy_US/images/products/5580/5580395_sa.jpg",
            "SNR_ProductURL": "https://api.bestbuy.com/click/-/5580395/pdp",
            "SNR_UPC": "400055803951",
            "SNR_Price": "599.99",
            "SNR_Available": "BESTBUY"
        },
        {
            "SNR_Title": "Apple - iPhone 6s 32GB - Gold (Sprint)",
            "SNR_Brand": "Apple",
            "SNR_ModelNo": "MN1K2LL/A",
            "SNR_Description": "A 4.7-inch Retina HD display with 3D Touch. 7000 series aluminum and stronger cover glass. An A9 chip with 64-bit desktop-class architecture. All new 12MP iSight camera with Live Photos. Touch ID. Faster LTE and Wi-Fi. Long battery life and iOS 10 and iCloud. All in a smooth, continuous unibody design.",
            "SNR_SKU": "BB5580737",
            "SNR_ImageURL": "https://img.bbystatic.com/BestBuy_US/images/products/5580/5580737_sa.jpg",
            "SNR_ProductURL": "https://api.bestbuy.com/click/-/5580737/pdp",
            "SNR_UPC": "400055807379",
            "SNR_Price": "599.99",
            "SNR_Available": "BESTBUY"
        }
    ]
}

and i am receiving this in GetAllMobile array.
my service look like this.

this.httpService.getAllMobiles().subscribe(
    data => {
      const myArray = [];

      for (let key in data) {
        myArray.push(data[key]);
        this.GetAllMobile.push(data[key])

      }
      console.log(this.GetAllMobile)
    }, () => this.loading = false
  );

and what i have tried this.

        Total {{item.totalItems}} {{item.totalPages}} AMAD

but it does not showing me simple totalItems and Total pages. and to show results i am trying this.

      {{x.SNR_Title}}

it is also showing me nothing.

can anybody give me hint or code that how can i show it in angular 2 with typescript.
Any help will be highly appreciated.

Body:
If GetAllMobile is an array, then the JSON you posted is an object in GetAllMobile and can be displayed following way:

<div *ngFor="let item of GetAllMobile">
  <h2>
      Total {{item.totalItems}} {{item.totalPages}} AMAD
  </h2>

  <div *ngFor="let x of item.results">
    <p>
        {{x.SNR_Title}}
    </p>
  </div>
</div>

But if you set the JSON to GetAllMobile, then it becomes an object, and values become directly accessible:

<div>
  <h2>
      Total {{GetAllMobileObject.totalItems}} {{GetAllMobileObject.totalPages}} AMAD
  </h2>
</div>
<div *ngFor="let x of GetAllMobileObject.results">
    <p>
        {{x.SNR_Title}}
    </p>
</div>

I have created this demo for both cases using your code example. Hope this helps.


问:
Writing a function to split a data set into two

First, split the max_hf data set into two groups, Y and N.

def split_data_hf(old_data, new_data, variable, category):
    new_data = old_data[old_data.variable == category]

split_data_hf(max_hf, max_hf1, inducted, 'Y')
split_data_hf(max_hf, max_hf2, inducted, 'N')

When I try to run this, I get the error that the variable inducted (which I am trying to pass through) is not defined. Can anyone explain why this is the case?

Theoretically it should work, and if I remove the variable input from the split_data_hf function and then add inducted in place of variable, then it runs just fine.

答:
Anyways, I think I figured it out myself.

Instead of having

old_data[old_data.variable == category]

One should write:

old_data[old_data[variable] == category]

Then, when the input variable is passed, write "...." to pass the argument through.

Thanks!


问:
How to cluster a highly dense graph
I have this highly dense graph I want to cluster, I was wondering which is the best algorithm for this case scenario. I'd like to generate a considerable amount of subgroups.

I'm using Python's library Networkx to generate the graph.

答: I finally went for the Louvain method since it was the best fit for my problem and also there was a library already implemented that speaks with Networkx.</p>

Title: How to cluster a highly dense graph


问:
getting System.InvalidOperationException: Listbox DataSource VB.net
This is the error I am getting

```<code>System.InvalidOperationException: 'List that this enumerator is bound to has been modified. An enumerator can only be used if the list does not change.'
</code>```

I have a Listbox that is databound The list of items are stored days table the saved value is stored in a record table. The List is a Comma Separated List E.G: 1,2,3,4,5
Would equate to Items with values of 1 -5 being selected on load.

This is the save Routine which Works perfectly

```<code>Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.Leave
    Dim listboxItems As New List(Of String)

    For Each row As DataRowView In ListBox1.SelectedItems
        listboxItems.Add(row("IDNum"))

    Next row
    selectLoad = True
    lblDays.Text = String.Join(",", listboxItems.ToArray())

End Sub
</code>```

This is Routine Which is Throwing the error.

```<code>Private Sub BGWLoadData_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BGWLoadData.RunWorkerCompleted

        Dim TextBoxStrings() As String = {""}

    Try
        Dim TempStr() As String = lblDays.Text.Split(",")
        ReDim TextBoxStrings(TempStr.Count - 1)
        TextBoxStrings = TempStr
    Catch ex As Exception

    End Try
    Dim TextBoxDoubles(TextBoxStrings.Count - 1) As Double
    For a As Integer = 0 To TextBoxStrings.Count - 1
        Try
            TextBoxDoubles(a) = TextBoxStrings(a)
        Catch ex As Exception
            TextBoxDoubles(a) = 0
        End Try
    Next

    Do While DaysBound = False
        Application.DoEvents()
    Loop

    ListBox1.SelectedItems.Clear()
    Dim TempIndex As Integer = 0
    For Each row As DataRowView In ListBox1.Items
        For a As Integer = 0 To TextBoxDoubles.Count - 1
            If row("IDNum") = TextBoxDoubles(a) Then
                ListBox1.SetSelected(TempIndex, True)
            End If
        Next
        TempIndex = TempIndex + 1
    Next row
End Sub
</code>```

What am I doing wrong or what can be done to make the code more efficient.

Edit:
Error Occurs at Next Row.
Also telling me I have done something wrong isn't helpful I know something is Wrong because I am getting errors. I am asking for is how to fix this with a code snippet or something.

答:
This Has been Solved by Adding a second arrary           </p>

```<code>If selectLoad = False Then

        ' convert CSV of IDNums of selected items in listbox into string array
        Dim TextBoxStrings() As String = {""}
        Try
            Dim TempStr() As String = lblDays.Text.Split(",")
            ReDim TextBoxStrings(TempStr.Count - 1)
            TextBoxStrings = TempStr
        Catch ex As Exception
        End Try

        ' convert string array to double array
        Dim TextBoxDoubles(TextBoxStrings.Count - 1) As Double
        For a As Integer = 0 To TextBoxStrings.Count - 1
            Try
                TextBoxDoubles(a) = TextBoxStrings(a)
            Catch ex As Exception
                TextBoxDoubles(a) = -1
            End Try
        Next

        ' load underlying IDNums into temporary array
        Dim TempIndex As Integer = 0
        Dim TempIDNums(ListBox1.Items.Count - 1) As Integer
        For Each row As DataRowView In ListBox1.Items
            TempIDNums(TempIndex) = row("IDNum")
            TempIndex = TempIndex + 1
        Next row

        ' if any of the underlying IDNums are found in the CSV, select that item in the listbox
        ListBox1.SelectedItems.Clear()
        For ListItemCounter As Integer = 0 To TempIDNums.Count - 1
            For SelectedItemCounter As Integer = 0 To TextBoxDoubles.Count - 1
                If TempIDNums(ListItemCounter) = TextBoxDoubles(SelectedItemCounter) Then
                    ListBox1.SetSelected(ListItemCounter, True)
                End If
            Next
        Next
    End If
</code>```

Body:
This is the error I am getting

System.InvalidOperationException: 'List that this enumerator is bound to has been modified. An enumerator can only be used if the list does not change.'

I have a Listbox that is databound The list of items are stored days table the saved value is stored in a record table. The List is a Comma Separated List E.G: 1,2,3,4,5
Would equate to Items with values of 1 -5 being selected on load.

This is the save Routine which Works perfectly

Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.Leave
    Dim listboxItems As New List(Of String)

    For Each row As DataRowView In ListBox1.SelectedItems
        listboxItems.Add(row("IDNum"))

    Next row
    selectLoad = True
    lblDays.Text = String.Join(",", listboxItems.ToArray())

End Sub

This is Routine Which is Throwing the error.

Private Sub BGWLoadData_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BGWLoadData.RunWorkerCompleted

        Dim TextBoxStrings() As String = {""}

    Try
        Dim TempStr() As String = lblDays.Text.Split(",")
        ReDim TextBoxStrings(TempStr.Count - 1)
        TextBoxStrings = TempStr
    Catch ex As Exception

    End Try
    Dim TextBoxDoubles(TextBoxStrings.Count - 1) As Double
    For a As Integer = 0 To TextBoxStrings.Count - 1
        Try
            TextBoxDoubles(a) = TextBoxStrings(a)
        Catch ex As Exception
            TextBoxDoubles(a) = 0
        End Try
    Next

    Do While DaysBound = False
        Application.DoEvents()
    Loop

    ListBox1.SelectedItems.Clear()
    Dim TempIndex As Integer = 0
    For Each row As DataRowView In ListBox1.Items
        For a As Integer = 0 To TextBoxDoubles.Count - 1
            If row("IDNum") = TextBoxDoubles(a) Then
                ListBox1.SetSelected(TempIndex, True)
            End If
        Next
        TempIndex = TempIndex + 1
    Next row
End Sub

What am I doing wrong or what can be done to make the code more efficient.

Edit:
Error Occurs at Next Row.
Also telling me I have done something wrong isn't helpful I know something is Wrong because I am getting errors. I am asking for is how to fix this with a code snippet or something.

Body:
This Has been Solved by Adding a second arrary

If selectLoad = False Then

        ' convert CSV of IDNums of selected items in listbox into string array
        Dim TextBoxStrings() As String = {""}
        Try
            Dim TempStr() As String = lblDays.Text.Split(",")
            ReDim TextBoxStrings(TempStr.Count - 1)
            TextBoxStrings = TempStr
        Catch ex As Exception
        End Try

        ' convert string array to double array
        Dim TextBoxDoubles(TextBoxStrings.Count - 1) As Double
        For a As Integer = 0 To TextBoxStrings.Count - 1
            Try
                TextBoxDoubles(a) = TextBoxStrings(a)
            Catch ex As Exception
                TextBoxDoubles(a) = -1
            End Try
        Next

        ' load underlying IDNums into temporary array
        Dim TempIndex As Integer = 0
        Dim TempIDNums(ListBox1.Items.Count - 1) As Integer
        For Each row As DataRowView In ListBox1.Items
            TempIDNums(TempIndex) = row("IDNum")
            TempIndex = TempIndex + 1
        Next row

        ' if any of the underlying IDNums are found in the CSV, select that item in the listbox
        ListBox1.SelectedItems.Clear()
        For ListItemCounter As Integer = 0 To TempIDNums.Count - 1
            For SelectedItemCounter As Integer = 0 To TextBoxDoubles.Count - 1
                If TempIDNums(ListItemCounter) = TextBoxDoubles(SelectedItemCounter) Then
                    ListBox1.SetSelected(ListItemCounter, True)
                End If
            Next
        Next
    End If


问:
Adding Play/Pause to WebGL, in PHP JS only
I am trying to add a Play/Pause button to the Advanced API controls, I have the button.value changing from the ascii #9654 to #9646 but the rest of the code to start the animation and stop it is not working? The sphere will rotate if the 'requestanimationframe' is contained within the 'init()' of the WebGl it's self. You can see the working sphere at No controls and the one I'm adding controls in Placing controls but animation play/pause not working, thanks for any ideas.

I left in //hard coded markers if you need to run it yourself just comment out the php section of DB access.

```<code><!DOCTYPE HTML>
<html>
  <head>
    <script src="http://www.webglearth.com/v2/api.js"></script>
    <script>
      function initialize() {
        var options = {
          sky: true,
          atmosphere: true,
          dragging: true,
          tilting: false
        };//options
        var earth = new WE.map('earth_div');
        earth.setView([30.0, -87.65], 3);
        WE.tileLayer('http://data.webglearth.com/natural-earth-color/{z}/{x}/{y}.jpg', {
          tileSize: 256,
          bounds: [[-85, -180], [85, 180]],
          minZoom: 2,
          maxZoom: 9,
          tms: true
        }).addTo(earth);//tilelayer
        var toner = WE.tileLayer('http://tile.stamen.com/toner/{z}/{x}/{y}.png', {
          opacity: 0.25
        });//toner
        toner.addTo(earth);
        earth.setZoom(3);
          document.getElementById('zoom_level').addEventListener('change', function(e) {
          earth.setZoom(e.target.value);
        });//setZoom

//      earth.setTilt(40);
//        document.getElementById('tilt_level').addEventListener('change', function(e) {
//          earth.setTilt(e.target.value);
//        });//setTilt-not working look at .setview

/*       // Add markers - Hard coded works.
         var marker = WE.marker([48.45, 34.9833], 'http://eagleeye360.com/worldmap/pin.jpg', 4, 4).addTo(earth);
         marker.bindPopup("86.110.118.194", {maxWidth: 90, closeButton: true}).openPopup();
         var marker2 = WE.marker([41.85, -87.65], 'http://eagleeye360.com/worldmap/pin.jpg', 4, 4).addTo(earth);
         marker2.bindPopup("174.221.5.127", {maxWidth: 90, closeButton: true}).openPopup();
         var marker3 = WE.marker([44.3051,-69.977], 'http://eagleeye360.com/worldmap/pin.jpg', 4, 4).addTo(earth);
         marker3.bindPopup("142.105.199.149", {maxWidth: 90, closeButton: true}).openPopup();
*/
        //Get GPS lat/lon from sql Db for markers
        <?php
        include('ts.php');
        // Add markers
        $ct = 0;
        $i = 1;
        $lat1 = ""; $lat2 = "";
        $lon1 = ""; $lon2 = "";
        $row = array();
        $rows = array($row);
        $con = mysql_connect("localhost","User","Password");
        $db_selected = mysql_select_db("DB", $con);
        if (!$db_selected){echo mysql_errno($con) . ": " . mysql_error($con) . "\n";}
        $query = "SELECT `gpslat`, `gpslon`, `ip` FROM `visitor_tracker` ORDER BY `gpslat` DESC";
        $result = mysql_query($query) or die(mysql_error());
        while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
               $lat1 = $row[0];
               //$lon1 = $row[1];
        if ($ct == 0) {$rows[] = $row;
                       $lat2 = $rows[$i][0];
                       //$lon2 = $rows[$i][1];
                       }//if
        Else {if ($lat1 != $lat2){
                  $rows[] = $row;
                  $i = $i+1;
                  $lat2 = $rows[$i][0];
                  //$lon2 = $rows[$i-1][1];
                  }//if
                  }//else
        $ct = $ct+1;
        }//while
        mysql_free_result($result);
        mysql_close($con);
        ?>
        // Populate markers
        var markers = <?php echo json_encode($rows); ?>;
        var ygpslat = <?php echo json_encode($gpslat); ?>;
        var ygpslon = <?php echo json_encode($gpslon); ?>;
        var yip = <?php echo json_encode($ip); ?>;
        for(var i = 1, len = markers.length; i < len; i++) {
        var marker = WE.marker([markers[i][0],markers[i][1]], 'http://eagleeye360.com/worldmap/pin_green.jpg', 4, 4).addTo(earth);
        marker.bindPopup(markers[i][2], {maxWidth: 100, closeButton: true}).closePopup();
        }//for
        //Your marker
        var marker = WE.marker([ygpslat,ygpslon], 'http://eagleeye360.com/worldmap/pin.jpg', 4, 4).addTo(earth);
        marker.bindPopup("<center>You</br>"+yip, {maxWidth: 100, closeButton: true}).openPopup();
    }//init()

        function rotate_play_pause() {
        var status = document.getElementById("rotate_button");
        if (status.value == String.fromCharCode(9654)) {
           document.getElementById("rotate_button").value = String.fromCharCode(9646);
            // Start a simple rotation animation
        var before = null;
        requestAnimationFrame(function animate(now) {
            var c = earth.getPosition();
            var elapsed = before? now - before: 0;
            before = now;
            earth.setCenter([c[0], c[1] - 0.1*(elapsed/30)]);
            requestAnimationFrame(animate);
        });//requestAnimationFrame

        } else {
          document.getElementById("rotate_button").value = String.fromCharCode(9654);
          cancelAnimationFrame(animate);
          }//if else
         }//function rotate_play_pause()

//      document.getElementById('cesium-credit-text').innerHTML = "EagleEye360.com-Visitors/Bots/HackAttempts";

    </script>
    <style type="text/css">
      html, body{padding: 0; margin: 0; background-color: black;}
      #earth_div{top: 0; right: 0; bottom: 0; left: 0; position: absolute !important;}
      #coords{position: absolute; bottom: 10px; right: 10px; z-index: 100000;}
      #buttons {position: absolute; bottom:10px; left: 10px; color: #808080;}
    </style>
    <title>EagleEye360 Test 1</title>
  </head>
  <body onload="initialize()">
    <div id="earth_div"></div>
      <div id="buttons">
      <center><input type="button" id="rotate_button" value="&#9654" class="play" onclick="rotate_play_pause();"><center/><br>
      <center>Zoom</center>
      2<input type="range" id="zoom_level" min="2" max="9" step="1.0" value="3.0">9<br>
      <center>Tilt</center>
      40&#176<input type="range" id="tilt_level" min="40" max="130" step="5" value="40">130&#176<br>
      </div>
  </body>
</html>
</code>```

答:
After 10 days of trying, I have solved the issue with this code :)
The problem was that Java Script does not pass vars as other languages it passes a dynamic of the var so anything done to a var with in a function will leave the original var unchanged - unless it is a Global var.
I added Global vars: Earth and myReq(for canx the request) the entire code is:

```<code>    <!DOCTYPE HTML>
<html>
  <head>
  <link rel="stylesheet" href="CSS/vertical-text.css" type="text/css"/>
    <script src="http://www.webglearth.com/v2/api.js"></script>
    <script>
    var earth = undefined;
    var myReq;
      function initialize() {
        var options = {
          sky: true,
          atmosphere: true,
          dragging: true,
          tilting: false,
          scrollWheelZoom: false
        };//options
        earth = new WE.map('earth_div');
        earth.setView([30.0, -87.65], 3);
        WE.tileLayer('http://data.webglearth.com/natural-earth-color/{z}/{x}/{y}.jpg', {
          tileSize: 256,
          bounds: [[-85, -180], [85, 180]],
          minZoom: 2,
          maxZoom: 9,
          tms: true,
          attribution: '© EagleEye360.com'
        }).addTo(earth);//tilelayer
        var toner = WE.tileLayer('http://tile.stamen.com/toner/{z}/{x}/{y}.png', {
          opacity: 0.15 // or use http://{s}.tile.thunderforest.com/cycle/{z}/{x}/{y}.png
        });//toner
        toner.addTo(earth);
        document.getElementById('opacity2').addEventListener('change', function(e) {
          toner.setOpacity(e.target.value);
        });//set opacity
        earth.setZoom(3);
          document.getElementById('zoom_level').addEventListener('change', function(e) {
          earth.setZoom(e.target.value);
        });//setZoom
        //rotate_play_pause();
        document.getElementById('rotate_button').addEventListener('change', function(e) {
          rotate_play_pause();
          });//rotate_play_pause()

//      earth.setTilt(40);
//        document.getElementById('tilt_level').addEventListener('change', function(e) {
//          earth.setTilt(e.target.value);
//        });//setTilt-not working look at .setview

/*       // Add markers - Hard coded works.
         var marker = WE.marker([48.45, 34.9833], 'http://eagleeye360.com/worldmap/pin.jpg', 4, 4).addTo(earth);
         marker.bindPopup("86.110.118.194", {maxWidth: 90, closeButton: true}).openPopup();
         var marker2 = WE.marker([41.85, -87.65], 'http://eagleeye360.com/worldmap/pin.jpg', 4, 4).addTo(earth);
         marker2.bindPopup("174.221.5.127", {maxWidth: 90, closeButton: true}).openPopup();
         var marker3 = WE.marker([44.3051,-69.977], 'http://eagleeye360.com/worldmap/pin.jpg', 4, 4).addTo(earth);
         marker3.bindPopup("142.105.199.149", {maxWidth: 90, closeButton: true}).openPopup();
*/

        <?php
        include('ts.php');
        // Add markers
        $ct = 0;
        $i = 1;
        $lat1 = ""; $lat2 = "";
        $lon1 = ""; $lon2 = "";
        $row = array();
        $rows = array($row);
        $con = mysql_connect("localhost","hogansba_Jon","Tigger09<>");
        $db_selected = mysql_select_db("hogansba_EagleEye", $con);
        if (!$db_selected){echo mysql_errno($con) . ": " . mysql_error($con) . "\n";}
        $query = "SELECT `gpslat`, `gpslon`, `ip` FROM `visitor_tracker` ORDER BY `gpslat` DESC";
        $result = mysql_query($query) or die(mysql_error());
        while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
               $lat1 = $row[0];
               //$lon1 = $row[1];
        if ($ct == 0) {$rows[] = $row;
                       $lat2 = $rows[$i][0];
                       //$lon2 = $rows[$i][1];
                       }//if
        Else {if ($lat1 != $lat2){
                  $rows[] = $row;
                  $i = $i+1;
                  $lat2 = $rows[$i][0];
                  //$lon2 = $rows[$i-1][1];
                  }//if
                  }//else
        $ct = $ct+1;
        }//while
        mysql_free_result($result);
        mysql_close($con);
        ?>
        // Populate markers
        var markers = <?php echo json_encode($rows); ?>;
        var ygpslat = <?php echo json_encode($gpslat); ?>;
        var ygpslon = <?php echo json_encode($gpslon); ?>;
        var yip = <?php echo json_encode($ip); ?>;
        for(var i = 1, len = markers.length; i < len; i++) {
        var marker = WE.marker([markers[i][0],markers[i][1]], 'http://eagleeye360.com/worldmap/pin_green.jpg', 4, 4).addTo(earth);
        marker.bindPopup(markers[i][2], {maxWidth: 100, closeButton: true}).closePopup();
        }//for
        //Your marker
        var marker = WE.marker([ygpslat,ygpslon], 'http://eagleeye360.com/worldmap/pin.jpg', 4, 4).addTo(earth);
        marker.bindPopup("<div class='container'><div class='rotated-text'><span class='rotated-text__inner'><center><?php echo 'You-',$ip?><center/></span></div></div>", {maxWidth: 14, closeButton: true}).openPopup();
        earth.setView([ygpslat,ygpslon], 3);

    }//init()

        function rotate_play_pause() {
        var before = null;
        var status = document.getElementById("rotate_button");
        if (status.value == String.fromCharCode(9654)) {
           document.getElementById("rotate_button").value = String.fromCharCode(9646);
            // Start a simple rotation animation
        requestAnimationFrame(function animate(now) {
            var c = earth.getPosition();
            var elapsed = before? now - before: 0;
            before = now;
            earth.setCenter([c[0], c[1] - 0.1*(elapsed/30)]);
            myReq = requestAnimationFrame(animate);
        });//requestAnimationFrame

        } else {
          cancelAnimationFrame(myReq);
          document.getElementById("rotate_button").value = String.fromCharCode(9654);
          }//if else
         }//function rotate_play_pause()

//      document.getElementById('cesium-credit-text').innerHTML = "EagleEye360.com-Visitors/Bots/HackAttempts";

    </script>
    <style type="text/css">
      html, body{padding: 0; margin: 0; background-color: black;}
      #earth_div{top: 0; right: 0; bottom: 0; left: 0; position: absolute !important;}
      #coords{position: absolute; bottom: 10px; right: 10px; z-index: 100000;}
      #buttons {position: absolute; bottom:10px; left: 10px; color: #808080;}
    </style>
    <title>EagleEye360 Test 1</title>
  </head>
  <body onload="initialize()">
    <div id="earth_div"></div>
      <div id="buttons">
      <center><input type="button" id="rotate_button" value="&#9654" class="play" onclick="rotate_play_pause();"><center/><br>
      <center>Zoom</center>
      2<input type="range" id="zoom_level" min="2" max="9" step="1.0" value="3.0">9<br>
      <center>Streetmap opacity</center>
      0<input type="range" id="opacity2" min="0" max="1" step="0.05" value="0.15">1<br>
      <center><p>Total Hits: <?php echo $ct ?></br>Unique Visitors: <?php echo $i ?><p/></center>
      </div>
  </body>
</html>
</code>```

You can see it working Here I will leave it up for about a month after that it will no longer be available.
Jon

Body:
I am trying to add a Play/Pause button to the Advanced API controls, I have the button.value changing from the ascii #9654 to #9646 but the rest of the code to start the animation and stop it is not working? The sphere will rotate if the 'requestanimationframe' is contained within the 'init()' of the WebGl it's self. You can see the working sphere at No controls and the one I'm adding controls in Placing controls but animation play/pause not working, thanks for any ideas.

I left in //hard coded markers if you need to run it yourself just comment out the php section of DB access.

<!DOCTYPE HTML>

    <title>EagleEye360 Test 1</title>

      <input type="button" id="rotate_button" value="&#9654" class="play" onclick="rotate_play_pause();">

      Zoom
      2<input type="range" id="zoom_level" min="2" max="9" step="1.0" value="3.0">9

      Tilt
      40&#176<input type="range" id="tilt_level" min="40" max="130" step="5" value="40">130&#176

Body:
After 10 days of trying, I have solved the issue with this code :)
The problem was that Java Script does not pass vars as other languages it passes a dynamic of the var so anything done to a var with in a function will leave the original var unchanged - unless it is a Global var.
I added Global vars: Earth and myReq(for canx the request) the entire code is:

    <!DOCTYPE HTML>
<html>
  <head>
  <link rel="stylesheet" href="CSS/vertical-text.css" type="text/css"/>
    <script src="http://www.webglearth.com/v2/api.js"></script>
    <script>
    var earth = undefined;
    var myReq;
      function initialize() {
        var options = {
          sky: true,
          atmosphere: true,
          dragging: true,
          tilting: false,
          scrollWheelZoom: false
        };//options
        earth = new WE.map('earth_div');
        earth.setView([30.0, -87.65], 3);
        WE.tileLayer('http://data.webglearth.com/natural-earth-color/{z}/{x}/{y}.jpg', {
          tileSize: 256,
          bounds: [[-85, -180], [85, 180]],
          minZoom: 2,
          maxZoom: 9,
          tms: true,
          attribution: '© EagleEye360.com'
        }).addTo(earth);//tilelayer
        var toner = WE.tileLayer('http://tile.stamen.com/toner/{z}/{x}/{y}.png', {
          opacity: 0.15 // or use http://{s}.tile.thunderforest.com/cycle/{z}/{x}/{y}.png
        });//toner
        toner.addTo(earth);
        document.getElementById('opacity2').addEventListener('change', function(e) {
          toner.setOpacity(e.target.value);
        });//set opacity
        earth.setZoom(3);
          document.getElementById('zoom_level').addEventListener('change', function(e) {
          earth.setZoom(e.target.value);
        });//setZoom
        //rotate_play_pause();
        document.getElementById('rotate_button').addEventListener('change', function(e) {
          rotate_play_pause();
          });//rotate_play_pause()

//      earth.setTilt(40);
//        document.getElementById('tilt_level').addEventListener('change', function(e) {
//          earth.setTilt(e.target.value);
//        });//setTilt-not working look at .setview

/*       // Add markers - Hard coded works.
         var marker = WE.marker([48.45, 34.9833], 'http://eagleeye360.com/worldmap/pin.jpg', 4, 4).addTo(earth);
         marker.bindPopup("86.110.118.194", {maxWidth: 90, closeButton: true}).openPopup();
         var marker2 = WE.marker([41.85, -87.65], 'http://eagleeye360.com/worldmap/pin.jpg', 4, 4).addTo(earth);
         marker2.bindPopup("174.221.5.127", {maxWidth: 90, closeButton: true}).openPopup();
         var marker3 = WE.marker([44.3051,-69.977], 'http://eagleeye360.com/worldmap/pin.jpg', 4, 4).addTo(earth);
         marker3.bindPopup("142.105.199.149", {maxWidth: 90, closeButton: true}).openPopup();
*/

        <?php
        include('ts.php');
        // Add markers
        $ct = 0;
        $i = 1;
        $lat1 = ""; $lat2 = "";
        $lon1 = ""; $lon2 = "";
        $row = array();
        $rows = array($row);
        $con = mysql_connect("localhost","hogansba_Jon","Tigger09<>");
        $db_selected = mysql_select_db("hogansba_EagleEye", $con);
        if (!$db_selected){echo mysql_errno($con) . ": " . mysql_error($con) . "\n";}
        $query = "SELECT `gpslat`, `gpslon`, `ip` FROM `visitor_tracker` ORDER BY `gpslat` DESC";
        $result = mysql_query($query) or die(mysql_error());
        while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
               $lat1 = $row[0];
               //$lon1 = $row[1];
        if ($ct == 0) {$rows[] = $row;
                       $lat2 = $rows[$i][0];
                       //$lon2 = $rows[$i][1];
                       }//if
        Else {if ($lat1 != $lat2){
                  $rows[] = $row;
                  $i = $i+1;
                  $lat2 = $rows[$i][0];
                  //$lon2 = $rows[$i-1][1];
                  }//if
                  }//else
        $ct = $ct+1;
        }//while
        mysql_free_result($result);
        mysql_close($con);
        ?>
        // Populate markers
        var markers = <?php echo json_encode($rows); ?>;
        var ygpslat = <?php echo json_encode($gpslat); ?>;
        var ygpslon = <?php echo json_encode($gpslon); ?>;
        var yip = <?php echo json_encode($ip); ?>;
        for(var i = 1, len = markers.length; i < len; i++) {
        var marker = WE.marker([markers[i][0],markers[i][1]], 'http://eagleeye360.com/worldmap/pin_green.jpg', 4, 4).addTo(earth);
        marker.bindPopup(markers[i][2], {maxWidth: 100, closeButton: true}).closePopup();
        }//for
        //Your marker
        var marker = WE.marker([ygpslat,ygpslon], 'http://eagleeye360.com/worldmap/pin.jpg', 4, 4).addTo(earth);
        marker.bindPopup("<div class='container'><div class='rotated-text'><span class='rotated-text__inner'><center><?php echo 'You-',$ip?><center/></span></div></div>", {maxWidth: 14, closeButton: true}).openPopup();
        earth.setView([ygpslat,ygpslon], 3);

    }//init()

        function rotate_play_pause() {
        var before = null;
        var status = document.getElementById("rotate_button");
        if (status.value == String.fromCharCode(9654)) {
           document.getElementById("rotate_button").value = String.fromCharCode(9646);
            // Start a simple rotation animation
        requestAnimationFrame(function animate(now) {
            var c = earth.getPosition();
            var elapsed = before? now - before: 0;
            before = now;
            earth.setCenter([c[0], c[1] - 0.1*(elapsed/30)]);
            myReq = requestAnimationFrame(animate);
        });//requestAnimationFrame

        } else {
          cancelAnimationFrame(myReq);
          document.getElementById("rotate_button").value = String.fromCharCode(9654);
          }//if else
         }//function rotate_play_pause()

//      document.getElementById('cesium-credit-text').innerHTML = "EagleEye360.com-Visitors/Bots/HackAttempts";

    </script>
    <style type="text/css">
      html, body{padding: 0; margin: 0; background-color: black;}
      #earth_div{top: 0; right: 0; bottom: 0; left: 0; position: absolute !important;}
      #coords{position: absolute; bottom: 10px; right: 10px; z-index: 100000;}
      #buttons {position: absolute; bottom:10px; left: 10px; color: #808080;}
    </style>
    <title>EagleEye360 Test 1</title>
  </head>
  <body onload="initialize()">
    <div id="earth_div"></div>
      <div id="buttons">
      <center><input type="button" id="rotate_button" value="&#9654" class="play" onclick="rotate_play_pause();"><center/><br>
      <center>Zoom</center>
      2<input type="range" id="zoom_level" min="2" max="9" step="1.0" value="3.0">9<br>
      <center>Streetmap opacity</center>
      0<input type="range" id="opacity2" min="0" max="1" step="0.05" value="0.15">1<br>
      <center><p>Total Hits: <?php echo $ct ?></br>Unique Visitors: <?php echo $i ?><p/></center>
      </div>
  </body>
</html>

You can see it working Here I will leave it up for about a month after that it will no longer be available.
Jon


问:
C# Socket SocketAsyncEventArgs reuse socket - ERRAddrAlreadyInUse
I'm trying to write a high performance lib for Sockets with a lot of preallocating. I am using SocketAsyncEventArgs XXXAsync methods. When I try to re-use the socket for 2nd time after calling

_socket.DisconnectAsync(_socketAsyncEventArgs)

and setting

_socketAsyncEventArgs.DisconnectReuseSocket = true;

Before I make the disconnect call, i get ERRAddrAlreadyInUse on 2nd connect call. I have tried the following options when I create the Socket object, however nothing changes. I am aware I could call Close and create new Socket, but that would allocate new object every time I call my main function, which is bad.

```<code>_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(false, 0));
_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
</code>```

I have also tried to set ReuseAddress to true, but nothing changed
I'm waiting for the first disconnect to finish and then afterwards I call the method which initiates the connection again. I am also not 100% sure if I should be using different SocketAsyncEventArgs for Connect/Disconnect call, since this is a socket client I see no problems with using 1.

```<code>private void SocketConnect()
{
    try
    {
        if(!_init)
        {
            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            {
                UseOnlyOverlappedIO = true,
                ReceiveBufferSize = _receiveBuffer.Length,
                SendBufferSize = _sendBuffer.Length,
            };
            _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(false, 0));
            _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);

            _socketAsyncEventArgs = new SocketAsyncEventArgs();
            _socketAsyncEventArgs.Completed += _socketProc;

            _init = !_init;
         }
         _socketAsyncEventArgs.RemoteEndPoint = _proxy != null ?
         new IPEndPoint(_proxy.IP, _proxy.Port) : new IPEndPoint(Dns.GetHostAddresses(DestinationUri.Host)[0].MapToIPv4(), DestinationUri.Scheme == "https" ? 443 : 80);
         var res = _socket.ConnectAsync(_socketAsyncEventArgs);
         if(!res)
             _socketProc(_socket, _socketAsyncEventArgs);
     }
     catch(SocketException socketException)
     {
         _completedTask.SetResult(false);
         Debug.WriteLine($"SocketConnect: {socketException.Message} : {socketException.ErrorCode} : {socketException.SocketErrorCode}");
     }
}
</code>```

答: There is a TCP setting in registry for TIME_WAIT which is set to 120 by standard. Sad that only C Winsock documentation specifies this and not C# one. Guess I have to force close the socket and recreate.</p>

Body:
I'm trying to write a high performance lib for Sockets with a lot of preallocating. I am using SocketAsyncEventArgs XXXAsync methods. When I try to re-use the socket for 2nd time after calling

_socket.DisconnectAsync(_socketAsyncEventArgs)

and setting

_socketAsyncEventArgs.DisconnectReuseSocket = true;

Before I make the disconnect call, i get ERRAddrAlreadyInUse on 2nd connect call. I have tried the following options when I create the Socket object, however nothing changes. I am aware I could call Close and create new Socket, but that would allocate new object every time I call my main function, which is bad.

_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(false, 0));
_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);

I have also tried to set ReuseAddress to true, but nothing changed
I'm waiting for the first disconnect to finish and then afterwards I call the method which initiates the connection again. I am also not 100% sure if I should be using different SocketAsyncEventArgs for Connect/Disconnect call, since this is a socket client I see no problems with using 1.

private void SocketConnect()
{
    try
    {
        if(!_init)
        {
            _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            {
                UseOnlyOverlappedIO = true,
                ReceiveBufferSize = _receiveBuffer.Length,
                SendBufferSize = _sendBuffer.Length,
            };
            _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(false, 0));
            _socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);

            _socketAsyncEventArgs = new SocketAsyncEventArgs();
            _socketAsyncEventArgs.Completed += _socketProc;

            _init = !_init;
         }
         _socketAsyncEventArgs.RemoteEndPoint = _proxy != null ?
         new IPEndPoint(_proxy.IP, _proxy.Port) : new IPEndPoint(Dns.GetHostAddresses(DestinationUri.Host)[0].MapToIPv4(), DestinationUri.Scheme == "https" ? 443 : 80);
         var res = _socket.ConnectAsync(_socketAsyncEventArgs);
         if(!res)
             _socketProc(_socket, _socketAsyncEventArgs);
     }
     catch(SocketException socketException)
     {
         _completedTask.SetResult(false);
         Debug.WriteLine($"SocketConnect: {socketException.Message} : {socketException.ErrorCode} : {socketException.SocketErrorCode}");
     }
}


问:
Put inside Textarea button with Jsx (react)
Okey small question from junior to pro about Jsx and react:

I have textarea and i wanna put inside button

```<code>    renderButton() {
    const { mod } = this.state
    return (
      <button className={classNames({
        [styles.button]: mod == 'default',
        [styles.fullScreenButton]: mod == 'fullscreen'
      })} onClick={this.fullScreen} >
      {this.renderIcon()}
      </button>
    )
  }

  render() {
    const { text, rows } = this.props
    const { mod } = this.state
    return (
      <div>
        <textarea rows={rows} value='text'
          className={classNames({
            [styles.textArea]: mod == 'default',
            [styles.fullScreen]: mod == 'fullscreen'
          })}>
        </textarea>
        {this.renderButton()}
      </div>
    )
  }
}
</code>```

How i can do that?

Just

```<code><textarea> <button> </button> </textarea>
</code>```

not working
Using position: absolute maybe yes, but have any another way to do that?

答:
As you have discovered, placing an HTML button as a child of a <textarea> will not work. This is not a limitation of React or JSX but of the <textarea> element. If you want the button to be placed inside the <textarea> visually you'll need to use CSS to reposition it. Something like this:

div {
  position: relative;
}

textarea {
  width: 100%;
  height: 300px;
  margin: 0;
  padding: 0;
}

button {
  position: absolute;
  bottom: 15px;
  right: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <textarea>
  </textarea>
  <button>Submit</button>
</div></code>```

Body:
Okey small question from junior to pro about Jsx and react:

I have textarea and i wanna put inside button

    renderButton() {
    const { mod } = this.state
    return (
      <button className={classNames({
        [styles.button]: mod == 'default',
        [styles.fullScreenButton]: mod == 'fullscreen'
      })} onClick={this.fullScreen} >
      {this.renderIcon()}
      </button>
    )
  }

  render() {
    const { text, rows } = this.props
    const { mod } = this.state
    return (

        <textarea rows={rows} value='text'
          className={classNames({
            [styles.textArea]: mod == 'default',
            [styles.fullScreen]: mod == 'fullscreen'
          })}>
        </textarea>
        {this.renderButton()}

    )
  }
}

How i can do that?

Just

<textarea> <button> </button> </textarea>

not working
Using position: absolute maybe yes, but have any another way to do that?

Body:
As you have discovered, placing an HTML button as a child of a <textarea> will not work. This is not a limitation of React or JSX but of the <textarea> element. If you want the button to be placed inside the <textarea> visually you'll need to use CSS to reposition it. Something like this:

div {
  position: relative;
}

textarea {
  width: 100%;
  height: 300px;
  margin: 0;
  padding: 0;
}

button {
  position: absolute;
  bottom: 15px;
  right: 10px;
}

<div>
  <textarea>
  </textarea>
  <button>Submit</button>
</div>


问:
How to use MMFCreateDXGISurfaceBuffer in MediaFundation.Net?
I've searched in Microsoft Website about MMFCreateDXGISurfaceBuffer but it was all written in c++. I'm trying to use MMFCreateDXGISurfaceBuffer in c# but can't find any reference to how to correctly used the method.

in c++ below is the code.

```<code>MFCreateDXGISurfaceBuffer(__uuidof(ID3D11Texture2D), pAcquiredDesktopImage, 0, FALSE, &pMediaBuffer)
</code>```

I tried converting the above code to c# and below is my code but seems not right because I'm getting E_NOINTERFACE

```<code>MFExtern.MFCreateDXGISurfaceBuffer(typeof(SharpDX.Direct3D11.Texture2D).GUID, texture, 0, false, out buffer);
</code>```

I'm using SharpDX DXGI and MediaFoundation.Net in my application. I'm not sure if

```<code>typeof(SharpDX.Direct3D11.Texture2D).GUID
</code>```

is Equivalent to

```<code>__uuidof(ID3D11Texture2D)
</code>```

Below is the wrapper for MMFCreateDXGISurfaceBuffer

```<code> [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity]
    public static extern HResult MFCreateDXGISurfaceBuffer(
        [In, MarshalAs(UnmanagedType.LPStruct)] Guid riid,
        [MarshalAs(UnmanagedType.Interface)] object punkSurface,
        int uSubresourceIndex,
        [MarshalAs(UnmanagedType.Bool)] bool fBottomUpWhenLinear,
        out IMFMediaBuffer ppBuffer
    );
</code>```

Can someone teach me how to use MFCreateDXGISurfaceBuffer in MediaFOundation.Net. Thanks

Edit: I used MFTrace and below is the log where it failed

```<code>1716,2494 03:19:20.59013 CMFTransformDetours::SetInputType @02E96B4C Failed MT: MF_MT_FRAME_SIZE=5866925327104 (1366,768);MF_MT_MAJOR_TYPE=MEDIATYPE_Video;MF_MT_FRAME_RATE=257698037761 (60,1);MF_MT_PIXEL_ASPECT_RATIO=4294967297 (1,1);MF_MT_INTERLACE_MODE=2;MF_MT_SUBTYPE=MFVideoFormat_RGB32
</code>```

Im not sure if I'm setting the input type correctly since I'm feeding the sink with direct3d surface.

答:
I think this is your post (https://sourceforge.net/p/mfnet/discussion/711229/thread/9814e58b/#c149); I answered over there but saw your question on StackOverflow and thought I should reproduce my answer.

MFCreateDXGISurfaceBuffer accepts an IUnknown as the second parameter, so you can pass it anything that looks like a COM object, whether native or managed. However, internally MFCreateDXGISurfaceBuffer is actually looking for an object that implements the ID3D11Texture2D interface, which is why you have to pass the IID of that interface as the first parameter.

Your code is probably failing because you're passing in the SharpDX Texture2D managed object itself to MFCreateDXGISurfaceBuffer. You'd think this would fail on the .NET side (i.e. compiler or marshalling error), but the .NET interop marshaller actually makes the P/Invoke function call possible. This is because any .NET class can be casted to object, and all .NET objects can be marshalled into a native IUnknown COM object via a CCW (COM callable wrapper).

The reason you're getting an E_NOINTERFACE from MFCreateDXGISurfaceBuffer is because the .NET interop marshaller wraps the SharpDX Texture2D object with a native CCW, hands the CCW off to that function, and then the function tries to see if the object (which it sees as a native IUnknown) supports the ID3D11Texture2D interface. MFCreateDXGISurfaceBuffer does this by using the COM QueryInterface function that IUnknown provides. However, the SharpDX Texture2D class does not implement the ID3D11Texture2D interface, so when the marshalled version of Texture2D is queried the lookup fails and QueryInterface will return E_NOINTERFACE.

To solve this problem you need to get the native COM pointer the SharpDX Texture2D is encapsulating instead of passing in the SharpDX object itself. All the SharpDX objects are derived from a base ComObject class that provides a NativePointer property accessor, which gives you an IntPtr to the actual wrapped COM object. This is the actual COM ID3D11Texture2D pointer in your case, but now we need to get an object out of it rather than an IntPtr. That looks like this:

HResult hr;
IMFMediaBuffer buffer;

// "Marshal" is from the System.Runtime.InteropServices namespace

// This line converts the IntPtr texture.NativePointer in to a .NET RCW
// (runtime callable wrapper) so that it can be used like a native .NET
// object.
object texNativeObject = Marshal.GetObjectForIUnknown(texture.NativePointer);

// When texNativeObject is passed as an argument to MFCreateDXGISurfaceBuffer,
// the .NET marshaller will simply unwrap the RCW and provide a native COM
// pointer to the function.
hr = MFExtern.MFCreateDXGISurfaceBuffer(
    typeof(SharpDX.Direct3D11.Texture2D).GUID,
    texNativeObject,
    0, false, out buffer
);

// check "hr" here for success or failure

// "COMBase" is from the MediaFoundation.Misc namespace
// If this line causes problems at runtime, just remove it. SafeRelease
// forces the .NET runtime to release the RCW now, rather than later when
// a GC happens. It calls Marshal.ReleaseComObject(...) internally.
COMBase.SafeRelease(texNativeObject);
texNativeObject = null;
```

<p>Alternatively, you can add another definition of <code>MFCreateDXGISurfaceBuffer</code> that accepts an <code>IntPtr</code> as the second argument. You can add this to your own code instead of modifying MediaFoundation.NET.</p>

<pre class="lang-cs prettyprint-override"><code>class NativeMethods
{
    // EntryPoint must be provided since we are naming the alternate
    // version MFCreateDXGISurfaceBuffer2 to separate it from the original
    [DllImport("mfplat.dll", ExactSpelling = true, EntryPoint = "MFCreateDXGISurfaceBuffer")]
    public static extern HResult MFCreateDXGISurfaceBuffer2(
        [In, MarshalAs(UnmanagedType.LPStruct)] Guid riid,
        IntPtr punkSurface,
        int uSubresourceIndex,
        [MarshalAs(UnmanagedType.Bool)] bool fBottomUpWhenLinear,
        out IMFMediaBuffer ppBuffer
    );
}
</code>```

It's okay to use an alternate function signature like this, only because the Texture2D.NativePointer is an IntPtr referencing unmanaged memory. In other words, you're handing an unmanaged memory address to an unmanaged function, and that's okay.

Once you have the alternate version in your code, you can use the new MFCreateDXGISurfaceBuffer2 function like this:

HResult hr;
IMFMediaBuffer buffer;
hr = NativeMethods.MFCreateDXGISurfaceBuffer2(
    typeof(SharpDX.Direct3D11.Texture2D).GUID,
    texture.NativePointer,
    0, false, out buffer
);

// check "hr" here
```

Hope this helps!

Body:
I've searched in Microsoft Website about MMFCreateDXGISurfaceBuffer but it was all written in c++. I'm trying to use MMFCreateDXGISurfaceBuffer in c# but can't find any reference to how to correctly used the method.

in c++ below is the code.

MFCreateDXGISurfaceBuffer(__uuidof(ID3D11Texture2D), pAcquiredDesktopImage, 0, FALSE, &pMediaBuffer)

I tried converting the above code to c# and below is my code but seems not right because I'm getting E_NOINTERFACE

MFExtern.MFCreateDXGISurfaceBuffer(typeof(SharpDX.Direct3D11.Texture2D).GUID, texture, 0, false, out buffer);

I'm using SharpDX DXGI and MediaFoundation.Net in my application. I'm not sure if

typeof(SharpDX.Direct3D11.Texture2D).GUID

is Equivalent to

__uuidof(ID3D11Texture2D)

Below is the wrapper for MMFCreateDXGISurfaceBuffer

 [DllImport("mfplat.dll", ExactSpelling = true), SuppressUnmanagedCodeSecurity]
    public static extern HResult MFCreateDXGISurfaceBuffer(
        [In, MarshalAs(UnmanagedType.LPStruct)] Guid riid,
        [MarshalAs(UnmanagedType.Interface)] object punkSurface,
        int uSubresourceIndex,
        [MarshalAs(UnmanagedType.Bool)] bool fBottomUpWhenLinear,
        out IMFMediaBuffer ppBuffer
    );

Can someone teach me how to use MFCreateDXGISurfaceBuffer in MediaFOundation.Net. Thanks

Edit: I used MFTrace and below is the log where it failed

1716,2494 03:19:20.59013 CMFTransformDetours::SetInputType @02E96B4C Failed MT: MF_MT_FRAME_SIZE=5866925327104 (1366,768);MF_MT_MAJOR_TYPE=MEDIATYPE_Video;MF_MT_FRAME_RATE=257698037761 (60,1);MF_MT_PIXEL_ASPECT_RATIO=4294967297 (1,1);MF_MT_INTERLACE_MODE=2;MF_MT_SUBTYPE=MFVideoFormat_RGB32

Im not sure if I'm setting the input type correctly since I'm feeding the sink with direct3d surface.

Body:
I think this is your post (https://sourceforge.net/p/mfnet/discussion/711229/thread/9814e58b/#c149); I answered over there but saw your question on StackOverflow and thought I should reproduce my answer.

MFCreateDXGISurfaceBuffer accepts an IUnknown as the second parameter, so you can pass it anything that looks like a COM object, whether native or managed. However, internally MFCreateDXGISurfaceBuffer is actually looking for an object that implements the ID3D11Texture2D interface, which is why you have to pass the IID of that interface as the first parameter.

Your code is probably failing because you're passing in the SharpDX Texture2D managed object itself to MFCreateDXGISurfaceBuffer. You'd think this would fail on the .NET side (i.e. compiler or marshalling error), but the .NET interop marshaller actually makes the P/Invoke function call possible. This is because any .NET class can be casted to object, and all .NET objects can be marshalled into a native IUnknown COM object via a CCW (COM callable wrapper).

The reason you're getting an E_NOINTERFACE from MFCreateDXGISurfaceBuffer is because the .NET interop marshaller wraps the SharpDX Texture2D object with a native CCW, hands the CCW off to that function, and then the function tries to see if the object (which it sees as a native IUnknown) supports the ID3D11Texture2D interface. MFCreateDXGISurfaceBuffer does this by using the COM QueryInterface function that IUnknown provides. However, the SharpDX Texture2D class does not implement the ID3D11Texture2D interface, so when the marshalled version of Texture2D is queried the lookup fails and QueryInterface will return E_NOINTERFACE.

To solve this problem you need to get the native COM pointer the SharpDX Texture2D is encapsulating instead of passing in the SharpDX object itself. All the SharpDX objects are derived from a base ComObject class that provides a NativePointer property accessor, which gives you an IntPtr to the actual wrapped COM object. This is the actual COM ID3D11Texture2D pointer in your case, but now we need to get an object out of it rather than an IntPtr. That looks like this:

HResult hr;
IMFMediaBuffer buffer;

// "Marshal" is from the System.Runtime.InteropServices namespace

// This line converts the IntPtr texture.NativePointer in to a .NET RCW
// (runtime callable wrapper) so that it can be used like a native .NET
// object.
object texNativeObject = Marshal.GetObjectForIUnknown(texture.NativePointer);

// When texNativeObject is passed as an argument to MFCreateDXGISurfaceBuffer,
// the .NET marshaller will simply unwrap the RCW and provide a native COM
// pointer to the function.
hr = MFExtern.MFCreateDXGISurfaceBuffer(
    typeof(SharpDX.Direct3D11.Texture2D).GUID,
    texNativeObject,
    0, false, out buffer
);

// check "hr" here for success or failure

// "COMBase" is from the MediaFoundation.Misc namespace
// If this line causes problems at runtime, just remove it. SafeRelease
// forces the .NET runtime to release the RCW now, rather than later when
// a GC happens. It calls Marshal.ReleaseComObject(...) internally.
COMBase.SafeRelease(texNativeObject);
texNativeObject = null;

Alternatively, you can add another definition of MFCreateDXGISurfaceBuffer that accepts an IntPtr as the second argument. You can add this to your own code instead of modifying MediaFoundation.NET.

class NativeMethods
{
    // EntryPoint must be provided since we are naming the alternate
    // version MFCreateDXGISurfaceBuffer2 to separate it from the original
    [DllImport("mfplat.dll", ExactSpelling = true, EntryPoint = "MFCreateDXGISurfaceBuffer")]
    public static extern HResult MFCreateDXGISurfaceBuffer2(
        [In, MarshalAs(UnmanagedType.LPStruct)] Guid riid,
        IntPtr punkSurface,
        int uSubresourceIndex,
        [MarshalAs(UnmanagedType.Bool)] bool fBottomUpWhenLinear,
        out IMFMediaBuffer ppBuffer
    );
}

It's okay to use an alternate function signature like this, only because the Texture2D.NativePointer is an IntPtr referencing unmanaged memory. In other words, you're handing an unmanaged memory address to an unmanaged function, and that's okay.

Once you have the alternate version in your code, you can use the new MFCreateDXGISurfaceBuffer2 function like this:

HResult hr;
IMFMediaBuffer buffer;
hr = NativeMethods.MFCreateDXGISurfaceBuffer2(
    typeof(SharpDX.Direct3D11.Texture2D).GUID,
    texture.NativePointer,
    0, false, out buffer
);

// check "hr" here

Hope this helps!