text:
Q: Vigor2925 keeps dropping connectivity For the past few days our router has been dropping all connectivity, mean computers lose connection to the Internet, and to the router itself I believe (we also have a switch in place).
The setup is as follows:

*

*Various PCs connected to the switch

*Switch plugged into Router (Vigor2925)

*Second cheapo router connected to Vigor (acts as a WiFi bridge)

*Vigor setup for two VLANs, one for the PCs, one for the WiFi bridge router

*Bonded pair Internet connection into Vigor Router

I've powered cycled the lot, and still seeing cut-outs.
They only last a few seconds, but happen frequently.
Link to a log file from the Vigor router here
In the log file, there are entries like this (note how the date goes from Oct 14 to Jan 1)
<150>Oct 14 11:37:31 Vigor: Local User (MAC=8C-89-A5-C1-4C-7E): 192.168.1.19:57823 -> 216.58.208.40:443 (UDP)
<150>Oct 14 11:37:31 Vigor: Local User (MAC=8C-89-A5-C1-4C-7E): 192.168.1.19:38444 -> 23.21.49.236:443 (TCP)
<150>Oct 14 11:37:31 Vigor: Local User (MAC=8C-89-A5-C1-4C-7E): 192.168.1.19:38445 -> 23.21.49.236:443 (TCP)
<150>Oct 14 11:37:31 Vigor: Local User (MAC=8C-89-A5-C1-4C-7E): 192.168.1.19:38446 -> 104.16.12.8:443 (TCP)
<150>Oct 14 11:37:31 Vigor: Local User (MAC=8C-89-A5-C1-4C-7E): 192.168.1.19:38447 -> 54.88.71.191:443 (TCP)
<150>Oct 14 11:37:31 Vigor: Local User (MAC=8C-89-A5-C1-4C-7E): 192.168.1.19:38448 -> 54.88.71.191:443 (TCP)
<150>Oct 14 11:37:31 Vigor: Local User (MAC=8C-89-A5-C1-4C-7E): 192.168.1.19:38449 -> 198.41.209.121:443 (TCP)
<150>Oct 14 11:37:31 Vigor: Local User (MAC=90-2B-34-51-F1-12): 192.168.1.17:51114 -> 64.233.166.188:5228 (TCP)
<150>Oct 14 11:37:31 Vigor: [WLAN] AUTH - MBSS(0), Rcv AUTH seq#1, Alg=0, Status=0 from [wcid=255]c0:ee:fb:24:22:b0

<150>Jan  1 00:00:03 Vigor: Local User (MAC=BC-AE-C5-43-AA-17): 192.168.1.18:51332 -> 216.58.209.229:443 (UDP)
<150>Jan  1 00:00:03 Vigor: [WLAN] AUTH - Class 2 error, Send DEAUTH frame to 04:e6:76:5a:d8:1f

<150>Jan  1 00:00:03 Vigor: WLAN_DBG - MLME Associate MAC c0:ee:fb:24:22:b0

<150>Jan  1 00:00:03 Vigor: WLAN_DBG - WPA2 capable client
<150>Jan  1 00:00:03 Vigor: WLAN_DBG - MLME Associate MAC ec:35:86:3d:66:9e

<150>Jan  1 00:00:03 Vigor: WLAN_DBG - WPA2 capable client
<150>Jan  1 00:00:03 Vigor: WLAN_DBG - WPA handshake start for c0:ee:fb:24:22:b0
<150>Jan  1 00:00:03 Vigor: WLAN_DBG - RSN, Send key to: c0:ee:fb:24:22:b0
<150>Jan  1 00:00:03 Vigor: WLAN_DBG - send 1st packet in 4-way handshake
<150>Jan  1 00:00:03 Vigor: WLAN_DBG - WPA handshake start for ec:35:86:3d:66:9e
<150>Jan  1 00:00:03 Vigor: WLAN_DBG - RSN, Send key to: ec:35:86:3d:66:9e
<150>Jan  1 00:00:03 Vigor: WLAN_DBG - send 1st packet in 4-way handshake
<181>Jan  1 00:00:03 Vigor: [DHCP] Vigor DHCP server has given out an IP [MAC: c0-ee-fb-24-22-b0, IP: 192.168.1.15]
<150>Jan  1 00:00:03 Vigor: WLAN_DBG - EAPoL_handler, from ec:35:86:3d:66:9e
<150>Jan  1 00:00:03 Vigor: WLAN_DBG - Wpa_EAPoL_handler, from ec:35:86:3d:66:9e
<150>Jan  1 00:00:03 Vigor: WLAN_DBG - EAPOL_KEY
<150>Jan  1 00:00:03 Vigor: WLAN_DBG - parse_EAPOL_Key
<150>Jan  1 00:00:03 Vigor: WLAN_DBG - Rx message 2 in 4-way handshake
<150>Jan  1 00:00:03 Vigor: WLAN_DBG - RSN, Send key to: ec:35:86:3d:66:9e
<150>Jan  1 00:00:03 Vigor: WLAN_DBG - send 3rd packet in 4-way handshake
<150>Jan  1 00:00:03 Vigor: WLAN_DBG - EAPoL_handler, from c0:ee:fb:24:22:b0
<150>Jan  1 00:00:03 Vigor: WLAN_DBG - Wpa_EAPoL_handler, from c0:ee:fb:24:22:b0
<150>Jan  1 00:00:03 Vigor: WLAN_DBG - EAPOL_KEY
<150>Jan  1 00:00:03 Vigor: WLAN_DBG - parse_EAPOL_Key
<150>Jan  1 00:00:03 Vigor: WLAN_DBG - Rx message 2 in 4-way handshake
<150>Jan  1 00:00:03 Vigor: WLAN_DBG - RSN, Send key to: c0:ee:fb:24:22:b0
<150>Jan  1 00:00:03 Vigor: WLAN_DBG - send 3rd packet in 4-way handshake
<150>Jan  1 00:00:03 Vigor: WLAN_DBG - EAPoL_handler, from ec:35:86:3d:66:9e
<150>Jan  1 00:00:03 Vigor: WLAN_DBG - Wpa_EAPoL_handler, from ec:35:86:3d:66:9e
<150>Jan  1 00:00:03 Vigor: WLAN_DBG - EAPOL_KEY
<150>Jan  1 00:00:03 Vigor: WLAN_DBG - parse_EAPOL_Key
<150>Jan  1 00:00:03 Vigor: WLAN_DBG - Rx message 4 in 4-way handshake
<150>Jan  1 00:00:03 Vigor: WLAN_DBG - WPA handshake finish for ec:35:86:3d:66:9e
<150>Jan  1 00:00:03 Vigor: WLAN_DBG - EAPoL_handler, from c0:ee:fb:24:22:b0
<150>Jan  1 00:00:03 Vigor: WLAN_DBG - Wpa_EAPoL_handler, from c0:ee:fb:24:22:b0
<150>Jan  1 00:00:03 Vigor: WLAN_DBG - EAPOL_KEY
<150>Jan  1 00:00:03 Vigor: WLAN_DBG - parse_EAPOL_Key
<150>Jan  1 00:00:03 Vigor: WLAN_DBG - Rx message 4 in 4-way handshake
<150>Jan  1 00:00:03 Vigor: WLAN_DBG - WPA handshake finish for c0:ee:fb:24:22:b0
<150>Jan  1 00:00:03 Vigor: Local User (MAC=C0-EE-FB-24-22-B0): 192.168.1.15:57744 -> 184.173.161.174:5222 (TCP)
<134>Jan  1 00:00:03 Vigor: [ARP][LAN IP conflict - lan ip conflicts with the one host whose MAC is C4:6E:1F:BF:25:3A, please contact with the administrator]
<150>Jan  1 00:00:03 Vigor: Local User (MAC=D0-E1-40-8A-DE-BA): 192.168.2.13:64161 -> 17.110.224.74:5223 (TCP)
<134>Jan  1 00:00:04 Vigor: [ARP][LAN IP conflict - lan ip conflicts with the one host whose MAC is C4:6E:1F:BF:25:3A, please contact with the administrator]
<181>Jan  1 00:00:04 Vigor: [DHCP] Vigor DHCP server has given out an IP [MAC: ec-35-86-3d-66-9e, IP: 192.168.1.28]
<150>Jan  1 00:00:04 Vigor: Local User (MAC=10-DD-B1-BD-7F-63): 192.168.1.23:28756 -> 52.1.1.135:3000 (UDP)
<150>Jan  1 00:00:04 Vigor: Local User (MAC=10-DD-B1-BD-7F-63): 192.168.1.23:61823 -> 52.0.104.40:3000 (TCP)
<150>Jan  1 00:00:04 Vigor: Local User (MAC=10-DD-B1-BD-7F-63): 192.168.1.23:28756 -> 52.0.104.40:3000 (UDP)
<150>Jan  1 00:00:04 Vigor: Local User (MAC=10-DD-B1-BD-7F-63): 192.168.1.23:61824 -> 52.0.102.230:3000 (TCP)
<150>Jan  1 00:00:04 Vigor: Local User (MAC=10-DD-B1-BD-7F-63): 192.168.1.23:28756 -> 52.0.102.230:3000 (UDP)
<150>Jan  1 00:00:04 Vigor: Local User (MAC=08-60-6E-88-B1-A2): 192.168.1.22:59805 -> 216.58.210.69:443 (UDP)
<150>Jan  1 00:00:04 Vigor: Local User (MAC=10-DD-B1-BD-7F-63): 192.168.1.23:61825 -> 52.1.1.135:3000 (TCP)
<150>Jan  1 00:00:04 Vigor: Local User (MAC=10-DD-B1-BD-7F-63): 192.168.1.23:61826 -> 52.0.102.230:3000 (TCP)
<150>Jan  1 00:00:05 Vigor: Local User (MAC=10-DD-B1-BD-7F-63): 192.168.1.23:61821 -> 52.1.40.103:3000 (TCP)
<134>Jan  1 00:00:05 Vigor: [ARP][LAN IP conflict - lan ip conflicts with the one host whose MAC is C4:6E:1F:BF:25:3A, please contact with the administrator]
<150>Jan  1 00:00:05 Vigor: [WLAN] AUTH - MBSS(0), Rcv AUTH seq#1, Alg=0, Status=0 from [wcid=255]4c:60:de:6f:5c:fb

<150>Jan  1 00:00:05 Vigor: [WLAN] AUTH_RSP - Send AUTH response (SUCCESS)...

<150>Jan  1 00:00:05 Vigor: [WLAN] ASSOC - MBSS(0), receive ASSOC request from 4c:60:de:6f:5c:fb

<150>Jan  1 00:00:05 Vigor: [WLAN] ASSOC - Send ASSOC response (Status=0)...

<150>Jan  1 00:00:05 Vigor: WLAN_DBG - MLME Associate MAC 4c:60:de:6f:5c:fb

<150>Jan  1 00:00:05 Vigor: WLAN_DBG - MLME Associate MAC 78:31:c1:be:1f:ac

<150>Jan  1 00:00:05 Vigor: WLAN_DBG - WPA2 capable client
<150>Jan  1 00:00:05 Vigor: WLAN_DBG - WPA handshake start for 78:31:c1:be:1f:ac
<150>Jan  1 00:00:05 Vigor: WLAN_DBG - RSN, Send key to: 78:31:c1:be:1f:ac
<150>Jan  1 00:00:05 Vigor: WLAN_DBG - send 1st packet in 4-way handshake
<150>Jan  1 00:00:05 Vigor: WLAN_DBG - EAPoL_handler, from 78:31:c1:be:1f:ac
<150>Jan  1 00:00:05 Vigor: WLAN_DBG - Wpa_EAPoL_handler, from 78:31:c1:be:1f:ac
<150>Jan  1 00:00:05 Vigor: WLAN_DBG - EAPOL_KEY
<150>Jan  1 00:00:05 Vigor: WLAN_DBG - parse_EAPOL_Key
<150>Jan  1 00:00:05 Vigor: WLAN_DBG - Rx message 2 in 4-way handshake
<150>Jan  1 00:00:05 Vigor: WLAN_DBG - RSN, Send key to: 78:31:c1:be:1f:ac
<150>Jan  1 00:00:05 Vigor: WLAN_DBG - send 3rd packet in 4-way handshake
<150>Jan  1 00:00:05 Vigor: WLAN_DBG - EAPoL_handler, from 78:31:c1:be:1f:ac
<150>Jan  1 00:00:05 Vigor: WLAN_DBG - Wpa_EAPoL_handler, from 78:31:c1:be:1f:ac
<150>Jan  1 00:00:05 Vigor: WLAN_DBG - EAPOL_KEY
<150>Jan  1 00:00:05 Vigor: WLAN_DBG - parse_EAPOL_Key
<150>Jan  1 00:00:05 Vigor: WLAN_DBG - Rx message 4 in 4-way handshake
<150>Jan  1 00:00:05 Vigor: WLAN_DBG - WPA handshake finish for 78:31:c1:be:1f:ac
<150>Jan  1 00:00:05 Vigor: [WLAN] WPA: send Msg1 of 4-way

<150>Jan  1 00:00:05 Vigor: [WLAN] Receive EAPoL-Key frame from STA 4C-60-DE-6F-5C-FB

<150>Jan  1 00:00:05 Vigor: [WLAN] WPA: recieve Msg2 of 4-way (4C-60-DE-6F-5C-FB)

<150>Jan  1 00:00:05 Vigor: [WLAN] WPA: send Msg3 of 4-way

<181>Jan  1 00:00:05 Vigor: [DHCP] Vigor DHCP server has given out an IP [MAC: 4c-60-de-6f-5c-fb, IP: 192.168.1.59]
<166>Jan  1 00:00:05 Vigor: [DHCPv6s] Received solicit from FE80::F13E:1A54:334C:B475 on LAN1
<166>Jan  1 00:00:05 Vigor: [DHCPv6] Elapsed time: 0
<166>Jan  1 00:00:05 Vigor: [DHCPv6] Client DUID: 00:01:00:01:1b:f5:04:29:c0:4a:00:02:1f:ab
<166>Jan  1 00:00:05 Vigor: [DHCPv6] IA_NA: ID=237036842, T1=0, T2=0
<166>Jan  1 00:00:05 Vigor: [DHCPv6] Requested option: domain search list
<166>Jan  1 00:00:05 Vigor: [DHCPv6] Requested option: DNS
<166>Jan  1 00:00:05 Vigor: [DHCPv6] Requested option: vendor specific info
<166>Jan  1 00:00:05 Vigor: [DHCPv6] Requested option: client FQDN
<150>Jan  1 00:00:05 Vigor: [WLAN] Receive EAPoL-Key frame from STA 4C-60-DE-6F-5C-FB


text:
Q: Passing custom data with map pin segue I've been having trouble figuring out how to pass a custom variable in a map pin to another view controller in Swift. I know that passing the                 coordinates, title, and subtitle are available when you addAnnotation. I would like to try and pass a custom variable but hidden. Is there such a thing? Below I am getting the users location, mapping it, dropping a pin of a couple locations nearby with annotations which goes to another view controller and passes just the title and subtitle. Any insight is greatly appreciated.
import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

var mappedCity = String()
var mappedState = String()

var manager = CLLocationManager()
var annotation:MKAnnotation!
var error:NSError!
var pointAnnotation:MKPointAnnotation!
var pinAnnotationView:MKPinAnnotationView!
var selectedAnnotation: MKPointAnnotation!

private var mapChangedFromUserInteraction = false

@IBOutlet var mapView: MKMapView!

override func viewDidLoad() {
    super.viewDidLoad()

    self.mapView.delegate = self
    self.navigationItem.titleView = searchController.searchBar
    self.definesPresentationContext = true

    if CLLocationManager.locationServicesEnabled(){
        manager.delegate = self
        manager.desiredAccuracy = kCLLocationAccuracyBest
        manager.requestWhenInUseAuthorization()
        manager.startUpdatingLocation()

   }

}

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    let userLocation:CLLocation = locations[0]
    let latitude = userLocation.coordinate.latitude
    let longitude = userLocation.coordinate.longitude

    let latDelta:CLLocationDegrees = 0.05
    let lonDelta:CLLocationDegrees = 0.05
    let span:MKCoordinateSpan = MKCoordinateSpanMake(latDelta, lonDelta)
    let location:CLLocationCoordinate2D = CLLocationCoordinate2DMake(latitude, longitude)
    let region:MKCoordinateRegion = MKCoordinateRegionMake(location, span)

    self.mapView.setRegion(region, animated: true)
    self.mapView.showsUserLocation = true

    CLGeocoder().reverseGeocodeLocation(userLocation) { (placemarks, error) in

        if (error != nil){

            print(error)

        }else {

            if let p = placemarks?[0]{

                let locality = p.locality ?? ""
                let administrativeArea = p.administrativeArea ?? ""

                self.mappedCity = String(locality)
                self.mappedState = String(administrativeArea)

                self.parseJSON("\(locality)", state: "\(administrativeArea)")
            }

        }

    }
 self.manager.stopUpdatingLocation()
}

func parseJSON(city: String, state: String){
    let passedCity = city
    let passedState = state
    let escapedCity = passedCity.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
    let escapedState = passedState.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!

    let url = NSURL(string:"http://www.API.com/api.php?city=\(escapedCity)&stateAbv=\(escapedState)")!

    let session = NSURLSession.sharedSession()

    let task = session.dataTaskWithURL(url) { (items, response, error) -> Void in

        if error != nil {

            print(error)

        }else {

            if let items = items {

                do {
                    let jsonResult = try NSJSONSerialization.JSONObjectWithData(items, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary

                    if jsonResult.count > 0 {

                        if let datas = jsonResult["data"] as? NSArray{

                            for data in datas{

                                if let title = data["title"] as? String {

                                    if let street = data["street"] as? String {

                                        if let city =  data["city"] as? String {

                                            if let stateAbv =  data["stateAbv"] as? String {

                                                if let zip =  data["zip"] as? String {

                                                    self.geoAddress("\(title)", street: "\(street)", city: "\(city)", state: "\(stateAbv)", zip: "\(zip)")

                                                }
                                            }
                                        }

                                    }

                                }

                            }
                        }

                    }
                } catch{}

            }

        }

    }

    task.resume()

}

func geoAddress(title: String, street: String, city: String, state: String, zip: String){
    let storeName = "\(title)"
    let location = "\(street) \(city) \(state) \(zip)"
    let geocoder = CLGeocoder();
    geocoder.geocodeAddressString(location, completionHandler: {(placemarks: [CLPlacemark]?, error: NSError?) -> Void in
        if (error != nil) {
            print("Error \(error!)")
        } else if let placemark = placemarks?[0] {

            let coordinates:CLLocationCoordinate2D = placemark.location!.coordinate

            let pointAnnotation:MKPointAnnotation = MKPointAnnotation()
            pointAnnotation.coordinate = coordinates
            pointAnnotation.title = storeName
            pointAnnotation.subtitle = location

            self.mapView.addAnnotation(pointAnnotation)

        }
    })
}

private func mapViewRegionDidChangeFromUserInteraction() -> Bool {
    let view: UIView = self.mapView.subviews[0] as UIView
    //  Look through gesture recognizers to determine whether this region change is from user interaction
    if let gestureRecognizers = view.gestureRecognizers {
        for recognizer in gestureRecognizers {
            if( recognizer.state == UIGestureRecognizerState.Began || recognizer.state == UIGestureRecognizerState.Ended ) {
                return true
            }
        }
    }
    return false
}

func mapView(mapView: MKMapView, regionWillChangeAnimated animated: Bool) {
    mapChangedFromUserInteraction = mapViewRegionDidChangeFromUserInteraction()
    if (mapChangedFromUserInteraction) {
        // user changed map region

    }
}

func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
    if (mapChangedFromUserInteraction) {
        // user changed map region
        let center = mapView.centerCoordinate

        let mapLatitude = center.latitude
        let mapLongitude = center.longitude

        let locationmove = CLLocation(latitude: mapLatitude, longitude: mapLongitude)
        CLGeocoder().reverseGeocodeLocation(locationmove) { (placemarks, error) in

            if (error != nil){

                print(error)

            }else {

                if let p = placemarks?[0]{

                    let locality = p.locality ?? ""
                    let administrativeArea = p.administrativeArea ?? ""

                     self.mappedCity = String(locality)
                     self.mappedState = String(administrativeArea)
                     self.parseJSON("\(locality)", state: "\(administrativeArea)")
                }

            }

        }
    }
}

func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
    if annotation is MKUserLocation {
        return nil
    }

    let reuseId = "pin"
    var pinView = mapView.dequeueReusableAnnotationViewWithIdentifier(reuseId) as? MKPinAnnotationView
    if pinView == nil {
        pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: reuseId)
        pinView?.animatesDrop = false
        pinView?.canShowCallout = true
        pinView?.draggable = true
        pinView?.pinTintColor = UIColor.greenColor()
        let rightButton: AnyObject! = UIButton(type: UIButtonType.DetailDisclosure)
        pinView?.rightCalloutAccessoryView = rightButton as? UIView
    }
    else {
        pinView?.annotation = annotation
    }

    return pinView
}

func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
    if control == view.rightCalloutAccessoryView {
        selectedAnnotation = view.annotation as? MKPointAnnotation
        performSegueWithIdentifier("Details", sender: self)
    }
}

func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, didChangeDragState newState: MKAnnotationViewDragState, fromOldState oldState: MKAnnotationViewDragState) {
    if newState == MKAnnotationViewDragState.Ending {
        let droppedAt = view.annotation?.coordinate
        print(droppedAt)
    }
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

   if (segue.identifier == "Details"){
   let myDetails = segue.destinationViewController as! DetailViewController
     myDetails.mytitle = selectedAnnotation.title
     myDetails.mysubtitle = selectedAnnotation.subtitle

    }

}

func updateSearchResultsForSearchController(searchController: UISearchController) {

}

}

A: Subclass the "MKPointAnnotation" class and add your custom property in it.
class MyAnnotation : MKPointAnnotation {
    var customProperty : String?
}

And you can use MyAnnotation instead of MKPointAnnotation. Like following
 let pointAnnotation:MyAnnotation = MyAnnotation()
 pointAnnotation.coordinate = coordinates
 pointAnnotation.title = storeName
 pointAnnotation.subtitle = location
 pointAnnotation.customProperty = "your value"
 self.mapView.addAnnotation(pointAnnotation)

redpajama_set_name: RedPajamaStackExchange


text:
Q: In the ending, what happens to the boy and the girl?
Possible Duplicate:
Can someone formulate a clear description of the ending of Limbo?

Did both the boy and the girl die in the end?
After the animation where he found the girl ended, the game menu appeared. The scene behind it looked similar to the previous one. But there only were swarms of flies above the two patches of grass approximately where the kids stood just a moment before.

A: There are many theories about the ending of Limbo. This article gives a good summary.


text:
Q: Android adding views in a for loop hi i'm trying to create an list from a json feed that has a header for each date and then the content in underneath. however the json feed i have coming in arent organised in date order i have created a for loop that gets all the dates then checks for duplicates which gives me an array of dates from the feed. I then want to add a header view to my adapter for each date and i presume i then need to add another for loop to get the content under each date? problem is at the moment my header views
so my question is how can i create a list that adds header views based on a for loop and then adds other views underneath each header?
here is my function i'm running after an AsyncTask
public void FillData() throws JSONException{

      ListView list = getListView();
        list.scrollTo(0, 0);
        list.setVerticalFadingEdgeEnabled(false);

           list.setTextFilterEnabled(true);

           LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE );
            View header = inflater.inflate( R.layout.homeheader, list, false);

       fixturesView = LayoutInflater.from(getBaseContext()).inflate(R.layout.fixturescell,
                 null);

       //Log.v("MyFix", "fixturesArray = " + fixturesArray);
       if(fixturesArray.length() < 1){

             TextView emptytext = (TextView) fixturesView.findViewById(R.id.TextView02);
             emptytext.setText("No Upcoming Fixtures Available");

       }else{
        try{

            for(int t = 0; t < fixturesArray.length(); t++){
               JSONObject matchDateDict = fixturesArray.getJSONObject(t);
               String matchDate = matchDateDict.getString("matchdate");

               if(matchDatesArray.length() != 0){

                   int lm = t - 1;
                   JSONObject lastDateDict = fixturesArray.getJSONObject(lm);
                   String lastMatchDate = lastDateDict.getString("matchdate");

                   Log.v("MyFix", "lastMatchDate " + lastMatchDate);

                   if(matchDate.equals(lastMatchDate)){
                       Log.v("MyFix", "2 are the same");
                   } else {
                       Log.v("MyFix", "add new matchdate to array");
                       matchDatesArray.put(matchDate);
                   }

               } else {
                   Log.v("MyFix", "add new matchdate to array (first time only)");
                   matchDatesArray.put(matchDate);
               }
            }

            Log.v("MyFix", "matchDatesArray = " + matchDatesArray);

        }catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

         DateHeader = LayoutInflater.from(getBaseContext()).inflate(R.layout.redcell,
                 null);

         adapter = new MergeAdapter();

        for(int t = 0; t < matchDatesArray.length(); t++){

          JSONObject mdheaderdict = matchDatesArray.getJSONObject(t);
           String matchheader = mdheaderdict.getString("matchdate");

               TextView matchdayheader = (TextView) DateHeader.findViewById(R.id.redheadertext);
               matchdayheader.setText(matchheader);
               adapter.addView(DateHeader);
        }
     }
       setListAdapter(adapter);

}

heres an example of  the json feed
fixturesdata{"code":200,"error":null,"data":{"fixtures":[{"kickoff":"15:00:00","matchdate":"2012-07-14","homescore":null,"awayscore":null,"attendance":null,"homepens":null,"awaypens":null,"division_id":"5059","division":"Testing 1","comp":"LGE","location":null,"fixture_note":null,"hometeam_id":"64930","hometeam":"Team 1","awayteam_id":"64933","awayteam":"Team 4"},{"kickoff":"15:00:00","matchdate":"2012-07-14","homescore":null,"awayscore":null,"attendance":null,"homepens":null,"awaypens":null,"division_id":"5059","division":"Testing 1","comp":"LGE","location":null,"fixture_note":null,"hometeam_id":"64935","hometeam":"Team 6","awayteam_id":"64937","awayteam":"Team 8"},{"kickoff":"15:00:00","matchdate":"2012-07-28","homescore":null,"awayscore":null,"attendance":null,"homepens":null,"awaypens":null,"division_id":"5059","division":"Testing 1","comp":"LGE","location":null,"fixture_note":null,"hometeam_id":"64930","hometeam":"Team 1","awayteam_id":"64931","awayteam":"Team 2"},{"kickoff":"15:00:00","matchdate":"2012-07-28","homescore":null,"awayscore":null,"attendance":null,"homepens":null,"awaypens":null,"division_id":"5059","division":"Testing 1","comp":"LGE","location":null,"fixture_note":null,"hometeam_id":"64930","hometeam":"Team 1","awayteam_id":"64931","awayteam":"Team 2"}]}}

A: What you want isn't to add the views in a loop, but to make a proper ListView with Sections. I recommend that you read this tutorial which includes sample code.
Sectioning your ListView


text:
Q: Find the roots of the equation $(1+\tan^2x)\sin x-\tan^2x+1=0$ which satisfy the inequality $\tan x<0$ Find the roots of the equation $$(1+\tan^2x)\sin x-\tan^2x+1=0$$ which satisfy the inequality $$\tan x<0$$
Shold I solve the equation first and then try to find which of the roots satisfy the inequality? Should I use $\tan x$ in the solution itself and obtain only the needed roots?
I wasn't able to see how the inequality can be used beforehand, so I solved the equation. For $x\ne \dfrac{\pi}{2}(2k+1),k\in\mathbb{Z}$, the equation is $$\dfrac{\sin^2x+\cos^2x}{\cos^2x}\sin x-\left(\dfrac{\sin^2x}{\cos^2x}-\dfrac{\cos^2x}{\cos^2x}\right)=0$$ which is equivalent to $$\sin x+\cos2x=0\\\sin x+1-2\sin^2x=0\\2\sin^2x-\sin x-1=0$$ which gives for the sine $-\dfrac12$ or $1$. Then the solutions are $$\begin{cases}x=-\dfrac{\pi}{6}+2k\pi\\x=\dfrac{7\pi}{6}+2k\pi\end{cases}\cup x=\dfrac{\pi}{2}+2k\pi$$ How do I use $\tan x<0$?

A: Let $\sin x = s$; the given equation reduces to:
$$2s^2-s-1=0,~(s-1)(2s+1)=0$$
we have in the first full rotation of the radius vector
$$s=1\to x= \frac{\pi}{2},~\frac{3 \pi}{2}$$
$$s=-\frac{1}{2}\to x= \frac{7 \pi}{6},~\frac{11 \pi}{6}$$
between which only $x= \dfrac{11 \pi}{6}$ has its tangent negative.
This and its co-terminals $ x= 11 \pi/6 +2 k \pi$ satisfy the given equation.

A: It seems like you forgot a minus sign in front of $\frac{5\pi}{6}$ according to @AnneBauval, so your third solution doesn't work (it gives $\sqrt{3}$). Your second solution isn't in the domain since as you said at the beginning that $x\ne\frac{\pi}{2}(2k+1)=\pi k+\frac{\pi}{2}$ and substituting $k\mapsto2k$ tells us that the second solution isn't allowed. So the first solution is the only one that is usable.

A: $\frac\pi2+2k\pi$ should never appear because the initial equation is not defined when $\cos x=0.$
You forgot a $-$ sign in front of $\frac{5\pi}6+2k\pi.$
As for your final question: simply discard $-\frac{5\pi}6+2k\pi$ (whose $\tan$ is $>0$) and retain $-\frac\pi6+2k\pi$ (whose $\tan$ is $<0$).

A: $tanx < 0 $ essentially means $ x \in \frac{(2n-1)\pi}{2} ,n\pi $ and the by taking intersection of this and the solution that you obtained, the final answer is $x = 2n\pi -\frac{\pi}{6}$


text:
Q: Expected pair of collisions in two choice hashing In two choice hashing(with chaining), two random hash functions h1, h2 are selected to hash n keys to m positions. The process goes like this:
Insert all n keys sequentially, by evaluating for each key x, the two hash functions, and adding the key to the shorter list of those indexed by h1(x), h2(x). Let Y be the number of pairs (x, x') such that they end up in the same linked list. What would the expectation of Y(E[Y]) be like?
Assume h1, h2 hash keys uniformly and independently

A: I doubt that there is a clean analytic solution to this problem.
But it is very tractable to produce numerical approximations for the case of a large number of buckets.  Let x be the ratio between the number of keys stored and the number of buckets.  Let fn(x) be the expected portion of buckets with n keys and Fn(x) be the expected portion of buckets with at most n keys.
Then trivially Fn(x) = f0(x) + f1(x) + ... + fn(x).  And also fn'(x) is the probability that with a key add a bucket of size n-1 will be added to, minus the probability that with a key add, a bucket of size n will be to.
The probability that a bucket of size n will be added to next is the probability that the first hash function chooses a bucket of size n and the second chooses one of size at least n, plus the probability that the first hash function chooses a bucket of size greater than n and the second chooses one of size n.  The probability of choosing a bucket of size greater than n is simply 1 - Fn(x).  So this probability is fn(x)(1 - Fn-1(x)) + (1 - Fn(x))fn(x).
That makes fn'(x) = fn-1(x)(1 - Fn-2(x)) + (1 - Fn-1(x))fn-1(x) -  fn(x)(1 - Fn-1(x)) - (1 - Fn(x))fn(x).  Which is a horribly non-linear system of equations and there is no need to expect any nice solution to it.  But it is also amenable to http://en.wikipedia.org/wiki/Runge%E2%80%93Kutta_methods and you shouldn't need too many terms to get accurate estimates since the portion heavily filled buckets falls off faster than exponentially.  (To see why, convince yourself that if n is significantly larger than x, then fn+1'(x) is approximately fn2(x).  The repeated squaring of small terms means that there is a very sharp falloff from fn(x) < 0.01 to fn(x) < 0.00000001.)

A: It depends on m. For m being O(n^(3/2)), E[Y] = O(1).


text:
Q: Supercapacitors as EV batteries How can we make a supercapacitor bank of 48 V, 8000 F disharge slower when operating an EV motor having following specification:

*

*Voltage: 48

*Power: 15 kw

*Type: BLDC/3 ph AC induction

*Efficiency: upto 93%

I wish to use this motor to run an electric car for 120 - 200 km per charge. Please note that my EV will be designed for a max speed of 120 kmph.

A: Capacitors are quite efficient at storing then releasing energy.  A particular capacitor can only hold some maximum energy.  To drain it longer, you have to drain it at lower power, meaning less energy per unit time.
If you have a 100 gallon tank of water, and remove water at the rate of 1 gallon per minute, then the tank will be empty in 100 minutes.  The same basic logic works with capacitors, or anything else that stores something.
You claim to have a 8000 F capacitor that can be charged to 48 V.  The total energy it can store is:
    E = ½ C V2
    ½ (8000 F)(48 V)2 = 9.22 MJ
If you drain your tank of 9.22 MJ at 15 kJ per second, it will run out in 614 seconds, or about 10 minutes.  Since the circuit needs some minimum voltage to function, all the energy in the cap can't be used, so the actual run time will be less than indicated by the total energy in the cap.  Put another way, when the cap gets low, you can no longer take out energy.  Some energy will remain in the cap.
So to answer your question of how to make 9.22 MJ last longer when drawing from it at a rate of 15 kW, the answer is you can't.  To make it last longer, you either have to increase the amount of stored energy, or draw it at a lower rate.
The obvious solution is to use batteries instead of capacitors.  With current technology, they have a much larger energy density in terms of weight, size, and cost.

A: You need to study the subject first, BEFORE you commit yourself to ANY performance standards. In this case, you've gotten yourself into all sorts of trouble.
The very first thing you should have done was researched the energy efficiency of automobiles. Try here, for instance. If you read it and pay attention, you'll see that a reasonable number for an electric car (small and light) is on the order of 5 mi/kwH, or about 8 km/kWh. Note that this is almost certainly not at speeds of 120 km/hr.
Since a kWh is 1 kw x 3600 sec, that's an energy efficiency of about .45 MJ/km. Add in a factor of 1/0.93 for motor efficiency, and in round numbers you need .5 MJ/km.
To look at it another way, you motor is spec'ed for 15 kW. In one hour it will require 15 kWh total energy. For the efficiency stated, that will be 8 km/kWh x 15 kW, for a maximum speed of 120 km/hr. So the motor is actually properly sized for a vehicle such as an EV-1. Except that the EV-1 performance given in the link may well have happened at a lower average speed. If so, you won't get even 120.
Now. How big is your battery/supercap? Since $$E = \frac{CV^2}{2}$$ let's assume that, in order to run at full speed the battery/supercap needs a voltage of no less than 90% of maximum, and the total energy available is $$E=\frac{8000*48^2(1^2-.9^2)}{2}$$ or 1.75 MJ.
Do you see a problem? I do hope so.
Your supercap will provide enough energy to drive about 3 km or so.
Of course, if you're using a very small, very light vehicle you'll do much better than this, but I'd be astonished if you got a factor of 10 better. You don't talk about how you're going to make this vehicle, and perhaps it's going to be super-optimized for low drag and 1 driver only. If so, you may stand a chance, but it won't remotely be a practical vehicle.
As for your original question, it's been answered - you can't. Or rather, if you hope to put out the rated power, well, power is power. If you can make a really low-drag vehicle which uses less than the maximum motor power to achieve the speeds you want, then you'll draw less power than specified.
Lots of luck. You're going to need it.


text:
Q: PHP - I can't save any files It's a little bit difficult explain my problem.. Well, I'm creating a Upload File which the user can save just files .txt, .pdf or .doc, but there's a some files as a photo that return a array( $_FILES) empty and a other photo whose size is equal to the previous photo, return two error message the way correct..
Please, Is it my logic is wrong?
 <?php

    if(isset($_FILES['file']['name'])){

        $valid_file = true;
        //Errors Messages
        $messageError = array();

        //Types
        $allowTypes = array('text/plain','application/msword','application/pdf');

        $folder = 'C:\wamp\www\uploadtest\files/';
        $path = $folder.basename($_FILES['file']['name']);

        if(!$_FILES['file']['error'])
        {
            //Check Types
            if(!in_array($_FILES['file']['type'], $allowTypes)){
                $valid_file = false;
                $messageError[] = 'File type not allowed';
            }

            //Check Size
            if($_FILES['file']['size'] > (1024000))
            {
                $valid_file = false;
                $messageError[] = "Oops!  can't be larger than 1 MB";
            }

            //Upload Process
            if($valid_file){
                if(move_uploaded_file($_FILES['file']['tmp_name'],$path)){
                    echo "Sent!";
                }else{
                    echo "Error to send!";
                }
            }
        }else{
            echo 'Ooops! '.$_FILES['file']['error'];
        }

    }else{
        $messageError[] = "Please, Select a File!";
    }

        if(isset($messageError) or !empty($messageError)){
            foreach ($messageError as $me) {
                echo $me.'<br>';
            }
        }
    ?>


text:
Q: combine strings into an array in php I have a web service to identify people and their functions from an external database that returns me a set of data if the login is successful. The data (that interests me right now) is separated in different strings as follow:
$groups="group1, group2, group3"
$functions="member, member, admin"

The first element of the string $groups corresponds to the first element of the $functions string.
We can have empty spots in the strings:
$groups="group1,, group3";
$functions="member,, admin";

What is the best way to combine them to obtain:
$usertype(
    group1=>member,
    group2=>member,
    group3=>admin,
);

Then I plan to use array_search() to get the name of the group that corresponds to a function.

A: This is very trick especially when the first element is empty but here is a comprehensive solution
What you need is :
// Your Varriables
$groups = "group1,, group3";
$functions = "member,, admin";

// Break Into Array
$groups = explode(",", $groups);
$functions = explode(",", $functions);

// Combine both new Arrays and Output Result
$new = array_combine($groups, $functions);
print_r($new);

If you need to fix null values  then :
Example :
// Your Varriables
$groups = "group1,, group3";
$functions = "member,, admin";

// Break Into Array
$groups = explode(",", $groups);
$functions = explode(",", $functions);

// Fix Null Values
$groups = fixNull($groups, true);
$functions = fixNull($functions);

// Combine both new Arrays and Output Result
$new = array_combine($groups, $functions);
print_r($new);

Output
Array
(
    [group1] => member
    [group2] => member
    [group3] => admin
)

See Live DEMO
More Complex:
// Your Varriables
$groups = ",,, group3";
$functions = ",member,, admin";

// Fix Null Values
$groups = fixNull(explode(",", $groups), true);
$functions = fixNull(explode(",", $functions));

// Combine both new Arrays and Output Result
$new = array_combine($groups, $functions);
print_r($new);

Output
Array
(
    [group4] => member
    [group5] => member
    [group6] => member
    [group3] => admin
)

Live DEMO
Function Used
function fixNull($array, $inc = false) {
    $ci = new CachingIterator(new ArrayIterator($array), CachingIterator::FULL_CACHE);
    if ($inc) {
        $next = array_filter($array);
        $next = current($next);
        $next ++;
    } else {
        $next = array_filter($array);
        sort($next);
        $next = end($next);
    }

    $next || $next = null;
    $modified = array();

    foreach($ci as $item) {
        $modified[] = empty($item) ? trim($next) : trim($item);
        if (! $ci->getInnerIterator()->current()) {
            $item || $item = $next;
            $next = $inc ? ++ $item : $item;
        }
    }
    return $modified;
}

A: $groups = explode(",", $groups);
$functions = explode(",", $functions);

//then use the elements of the $groups array as key and the elements of the $functions array as the value
$merged = array_combine($groups, $functions);

A: Something along the lines of this should help:
$usertype = array_combine(explode(',', $groups), explode(',', $functions));

A: Use explode() to make arrays of your strings, and array_combine() to use one array as keys, the other one as values.
$groups = "group1, group2, group3";
$functions = "member, member, admin";

$usertype = array_combine(explode(", ", $groups), explode(", ", $functions));

A: Have you tried a explode($delimiter , $string) and then filter the array? I think that would be a good way of doing it:
$groups="group1,, group3";
$functions="member,, admin";

$groups_array = array_map('trim',explode(',', $groups));
$functions_array = array_map('trim',explode(',', $functions));

$final = array();
for ($i = 0; $i <= count($groups_array); $i++) {
    $final[$groups_array[$i]] = $functions_array[$i];
}

$merged = array_combine($groups_array, $functions_array);

Demo

A: explode and array_combine.
Note that you have a problem with whitespaces. Therefore use the following:
<?php
$groups="group1, group2, group3";
$functions="member, member, admin";

$groupArray = array_map(function($element){return trim($element);},
explode(',',$groups)); // split into array and remove leading and ending whitespaces
$functionArray = array_map(function($element){return trim($element);},
explode(',',$functions));  // split into array and remove leading and ending whitespaces

print_r(array_combine($groupArray,$functionArray));
?>

This will output:
Array
(
    [group1] => member
    [group2] => member
    [group3] => admin
)

EDIT: removed trim for the possibility that the first element is empty.

A: $groups="group1, group2, group3"
$functions="member, member, admin"

preg_match_all('/\w+/', $groups, $groups);
preg_match_all('/\d+/', $functions, $functions);

$final = array();
foreach ($groups[0] AS $key => $letter)
    $final[] = $letter . '=>' . $functions[0][$key];

echo join(', ', $final);


text:
Q: Next Js context parameter from getStaticProps returns "{ locales: undefined, locale: undefined, defaultLocale: undefined }" I am simply trying to use the context parameter from Next Js's getStaticProps function, but when I console log it, I get "{ locales: undefined, locale: undefined, defaultLocale: undefined }".
I use getStaticProps inside the pages folder as I am supposed to but I still get that weird object on all pages.
I would really appreciate any help as I was not able to find any information.

A: It's totally normal, it's part of Next.js i18n routing

*

*locale contains the active locale (if enabled).

*locales contains all supported locales (if enabled).

*defaultLocale contains the configured default locale (if enabled).

Don't worry about it if you are not using internationalisation.


text:
Q: Исключение: ссылка на объект не указывает на экземпляр объекта В программе на С++/CLI нужно по нажатию кнопки из одной формы открыть другую. Однако во время выполнения кода выскакивает ошибка "Ссылка на объект не указывает на экземпляр объекта". Что с этим можно сделать?
Вот код обработчика события:
private: System::Void cmd_Activate_Click(System::Object^ sender, System::EventArgs^ e)
{
    this->Hide();
    Application::OpenForms["frm_Activate1"]->Show();

}


text:
Q: Golang a map of functions with a receiver Is there anyway to make a map of function pointers, but functions that take recievers? I know how to do it with regular functions:
package main

func someFunc(x int) int {
    return x
}

func main() {
    m := make(map[string]func(int)int, 0)
    m["1"] = someFunc
    print(m["1"](56))
}

But can you do that with functions that take recievers? Something like this (though I've tried this and it doesn't work):
package main

type someStruct struct {
    x int
}

func (s someStruct) someFunc() int {
    return s.x
}

func main() {
    m := make(map[string](someStruct)func()int, 0)
    s := someStruct{56}
    m["1"] = someFunc
    print(s.m["1"]())
}

An obvious work around is to just pass the struct as a parameter, but that's a little dirtier than I would have liked

A: You can do that using Method Expressions:
https://golang.org/ref/spec#Method_expressions
The call is a bit different, since the method expression takes the receiver as the first argument.
Here's your example modified:
package main

type someStruct struct {
    x int
}

func (s someStruct) someFunc() int {
    return s.x
}

func main() {
    m := make(map[string]func(someStruct)int, 0)
    s := someStruct{56}
    m["1"] = (someStruct).someFunc
    print(m["1"](s))
}

And here's a Go playground for you to test it:
https://play.golang.org/p/PLi5A9of-U


text:
Q: Is it really that hard to securely store a secret key in mobile platforms? I have little experience with Android app development, and close to none with iOS. I'm writing an app that has to store a certain "key", and I would like this key to be stored in a secure way. As secure as possible, with reasonable development effort. The key has to be stored: the whole point is that the user should not need to be online to fetch it from a server.
I'm not sure which is the best solution for each of the two platforms. I've read a bit about Keystore in Android and Keychain in iOS, but I can't quite get how secure they are. Many say none of them is really secure, as an attacker could reverse engineer the app, find a file, get access to... but in the end people have been storing passwords and keys somewhere on PCs for decades, no method is 100% safe, so I fail to understand whether it's just paranoia* when it comes to mobile apps (well, more paranoia than usual) or if mobile platforms are really that much insecure.
Is it reasonably safe to assume that Keystore and Keychain would give me as much security as I would need to protect the key from a not-too-advanced (or expensive) attack?
PS Don't get me wrong, I appreciate security as much as anyone, and I always strive for it. But reading that an app would be "not secure" "because the phone might get stolen" prompts me to question whether we should write software at all :)

A: First of all, Keystore is used to sign application before send it to the store, for example if you send your application to a paly/apple store, using keystore/keychain protect your application to stay safe from malware, because some one can download it, put a malware and send it again to store !
Also, if you update the version of your old application, your clients can't update the old app, they will install the 2 versions in the same time, because your app is not linked using the keyStore/Keychain, hope I'm clear.
What are you looking at : is a storage with a encrypted information, in this case I use Realm  because The Realm file can be stored encrypted on disk by passing a 512-bit encryption key (64 bytes).


text:
Q: C: Terminating the program by pressing a key In C, I normally use the getch() function to wait for a key to be pressed and then end the program, but recently I read that since it's not a standard function, it's bad programming practice to use it.
So instead of the following:
int main() {
    dosomething();
    getch(); //wait for the user to see the results and press a key to end
    return 0;
}

What should I do to replace the getch ?

A: getc(stdin);
is portable in this sense

A: Using a non-standard I/O function isn't bad practice per se; it becomes an issue if you intend to port this code to a different platform that doesn't support getch().
The problem is, there are no standard library functions that detect individual keystrokes (getchar() and fgetc() are buffered and require you to hit Enter before they return); you're going to have to use something non-standard to do that.  If you only intend for this code to run on this specific platform, use getch() if that's what you need and just remember that this solution won't necessarily apply to other platforms.  If you intend to port this code to platforms that don't support getch(), isolate the system-specific call behind a wrapper function so that when you port the code, only the code inside the wrapper function needs to change.
int getKeystroke(void)
{
  /**
   * Put platform-specific call here
   */
  return getch();
}

int main(void)
{
  ... // do stuff here
  getKeystroke();
  return 0;
}

A: You could fix the terminal window to not go away.

A: getchar() is standard but due to line buffering you will still need to press Enter before getchar returns.

A: I prefer running program from command line.

A: I think using getch() is the most common by far is keeping a console window from closing , but in C++ most experienced programmers will recommend that you use cin.get
 std::cin.get();

instead of:
getch();

A: Are you using Turbo C compiler? getch() is widely used there.
OTOH if you want the program to wait, run the binary inside the shell/terminal/prompt. Navigate to that directory and invoke
Windows:
C:> executable.exe

Linux:
~$ ./exec

You can use getchar(), the only problem being that it is buffered. getch() isnt buffered. You can make getchar() also to be non-buffered, but the code for that is not worth it. I tried it once, but due to it's sheer complexity never bothered to try it again.

A: In addition to other answers, you can also use this in windows, especially if your intention is to wait for key press to finish the program:
system("pause");

A: Just trying to answer something different, you can use
while(1)
    sleep(10);
at the end of main function (before return 0;) and then you can press ctrl-c to terminate the program. I think you should not face portability issue and I hope this is not bad programming practice either :)


text:
Q: Python code execution bottleneck due to SSL - How to optimimze? I would like to improve the performance of a Python script and have been using cProfile to generate a performance report:
ncalls  tottime  percall  cumtime  percall filename:lineno(function)
   75   23.514    0.314   23.514    0.314 {method 'read' of '_ssl._SSLSocket' objects}
   75    8.452    0.113    8.452    0.113 {method 'do_handshake' of '_ssl._SSLSocket' objects}
   75    2.113    0.028    2.113    0.028 {method 'load_verify_locations' of '_ssl._SSLContext' objects}
   75    1.479    0.020    1.479    0.020 {method 'connect' of '_socket.socket' objects}

Example code:
import requests
import json
from collections import defaultdict

#Added for multiprocessing
from urllib.request import urlopen
from multiprocessing.dummy import Pool as ThreadPool

results = defaultdict(list)

# Make the Pool of workers
pool = ThreadPool(4)

# Open the urls in their own threads
# and return the results
results = pool.map(urlopen, requests.post())

  #close the pool and wait for the work to finish
pool.close()
pool.join()

for store, data in results.items():
    print('Store: {}'.format(store), end=', ')
    if data:
        for inventory in data:
            print(inventory)

A: You are effectively measuring the response time of remote websites, which is probably not what you want. In order to maximize the throughput (the number of HTTP requests sent or data received per second) you should send many simultaneous requests asynchronously. You can use an async HTTP library like aiohttp or just the native Python asyncio/asyncore.


text:
Q: Counter not working I am trying to do some grouping with the usage of counters, such that it will increment accordingly.. I apologize if my title gives the wrong impression but...
Anyway, when I have 2 or more selections and as I execute my code, instead of seeing groups with naming such as - TEST_1_GRP, TEST_2_GRP, TEST_3_GRP etc., I am getting TEST_1_GRP, TEST_1_GRP1, TEST_1_GRP2 as my results...
I tried placing some of the line for the counter portion around (like within/ before the for sentence), I am getting nowhere..
Below is my code:
def fix_shapes():
    all_geos = cmds.ls(sl = True)
    for geo in all_geos:
        shapes = cmds.listRelatives(geo, fullPath=True, shapes=True)

        if len(shapes) == 1:
            continue

        new_listing = []
        listing.append(shapes[:1])
        # pop out the first shape, since we don't have to fix it
        multi_shapes = shapes[1:]
        for multi_shape in multi_shapes:
            new_transform = cmds.duplicate(multi_shape, parentOnly=True)
            new_geos = cmds.parent(multi_shape, new_transform, addObject=True, shape=True)
            listing.append(new_geos)

            # remove the shape from its original transform
            cmds.parent(multi_shape, removeObject=True, shape=True)

        # counter to 'version' up new_geos group naming
        counter = 0
        new_group_name = cmds.group(em=True, name = 'TEST_' + str(counter + 1) + '_GRP')

        for item in new_listing:
            counter = counter + 1
            new_geos_parent_name = cmds.listRelatives(item, parent = True)
            cmds.parent(new_geos_parent_name, new_group_name)

A: Move your counter as follows, you aren't using the counter in your last loop so remove it from that. Check this does what you want?
def fix_shapes():
    all_geos = cmds.ls(sl = True)
    counter = 0
    for geo in all_geos:
        shapes = cmds.listRelatives(geo, fullPath=True, shapes=True)

        if len(shapes) == 1:
            continue

        new_listing = []
        listing.append(shapes[:1])
    # pop out the first shape, since we don't have to fix it
        multi_shapes = shapes[1:]
        for multi_shape in multi_shapes:
            new_transform = cmds.duplicate(multi_shape, parentOnly=True)
            new_geos = cmds.parent(multi_shape, new_transform, addObject=True, shape=True)
            listing.append(new_geos)

        # remove the shape from its original transform
            cmds.parent(multi_shape, removeObject=True, shape=True)

    # counter to 'version' up new_geos group naming

        new_group_name = cmds.group(em=True, name = 'TEST_' + str(counter + 1) + '_GRP')

        for item in new_listing:
            new_geos_parent_name = cmds.listRelatives(item, parent = True)
            cmds.parent(new_geos_parent_name, new_group_name)

A: I believe this may solve your problem. Keep in mind that the first time you execute your code, it will work as expected and produce groups named TEST_1_GRP TEST_2_GRP etc. However, the second time it will be named TEST_1_GRP1 TEST_2_GRP1 etc. because you're not saving or checking if the name exists. To work around this you can either store a global variable, check during names during execution, or store the counted value in the scene file or someplace else. I'll leave this to you.
def fix_shapes():
    all_geos = cmds.ls(sl = True)
    counter = 0 ### moved counter outside loop
    for geo in all_geos:
        shapes = cmds.listRelatives(geo, fullPath=True, shapes=True)

        if len(shapes) == 1:
            continue

        listing = [] ### fixed naming, was new_listing, not coherent
        listing.append(shapes[:1])
        # pop out the first shape, since we don't have to fix it
        multi_shapes = shapes[1:]
        for multi_shape in multi_shapes:
            new_transform = cmds.duplicate(multi_shape, parentOnly=True)
            new_geos = cmds.parent(multi_shape, new_transform, addObject=True, shape=True)
            listing.append(new_geos)

            # remove the shape from its original transform
            cmds.parent(multi_shape, removeObject=True, shape=True)

        # counter to 'version' up new_geos group naming
        new_group_name = cmds.group(em=True, name = 'TEST_' + str(counter + 1) + '_GRP')

        counter += 1 ### simpler way to increment instead of "counter = counter + 1"

        for item in listing: ### fixed new_listing name here as well
            new_geos_parent_name = cmds.listRelatives(item, parent = True)
            cmds.parent(new_geos_parent_name, new_group_name)

I've marked the changes with ### with some comments.

A: def fix_shapes():
    all_geos = cmds.ls(sl = True)
    counter = 0
    for geo in all_geos:
        shapes = cmds.listRelatives(geo, fullPath=True, shapes=True)

        if len(shapes) == 1:
            continue

        new_listing = []
        new_listing.append(shapes[:1])
    # pop out the first shape, since we don't have to fix it
        multi_shapes = shapes[1:]
        for multi_shape in multi_shapes:
            new_transform = cmds.duplicate(multi_shape, parentOnly=True)
            new_geos = cmds.parent(multi_shape, new_transform, addObject=True, shape=True)
            new_listing.append(new_geos)

        # remove the shape from its original transform
            cmds.parent(multi_shape, removeObject=True, shape=True)

    # counter to 'version' up new_geos group naming
        new_grp_id = "TEST_{0}_GRP".format(counter)
        if not cmds.objExists(new_grp_id):
           new_group_name = cmds.group(em=True, name = new_grp_id)
           counter += 1
        else:
           for o in reversed(xrange(100)):
               if cmds.objExists("TEST_{0}_GRP".format(o)):
                  counter = o + 1
                  break
           new_group_name = cmds.group(em=True, name = "TEST_{0}_GRP".format(counter))
           counter += 1

        for item in new_listing:
            new_geos_parent_name = cmds.listRelatives(item, parent = True)
            cmds.parent(new_geos_parent_name, new_group_name)

for the second iteration you need something like max range counter,
so we have build some checks .... so now it will do create grps and add items to it, by next iterations it will find the max value of "TEST_n_GRP" and increase that, think that it will find the biggest int, not the between integers, eg: in scene: grp_1 and grp_3, the next biggest number is the grp_4, but it will not find grp_2! you can remove the reversed operator, for that.
with the reversed operator you will find really fast the biggest/last integers but not the between ints


text:
Q: JQuery input checkbox set class only if class is missing I want to set class to Checkbox only if preexising class is missing for the checkbox. Also note it it may contain empty class then also overwrite it with new class.
I'm using following but how should I add the condition to the find?
$(this).find("input[type='radio'],input[type='checkbox']").addClass('IE8Border');

I'm trying in this direction:
$(this).find("input[type='radio'],input[type='checkbox']").each(function() {
    $(this)[("[class='']")].addClass('IE8Border');
    $(this)[(":not([class])")].addClass('IE8Border');
});

A: You can use hasClass to check if a class was already added.
Try this:
$(this).find("input[type='radio'],input[type='checkbox']").filter(function(){
    return !$(this).hasClass('IE8Border');
}).addClass('IE8Border');

You can also avoid using filter with the following version:
$(this).find("input[type='radio']:not(.IE8Border),input[type='checkbox']:not(.IE8Border)").addClass('IE8Border');

EDIT:
If your check is just for existence of a class then try this:
$(this).find("input[type='radio'],input[type='checkbox']").filter(function(){
  var thisClass = $(this).attr("class");
    return !(thisClass && thisClass.length > 0);
}).addClass('IE8Border');

A: I'm a little unclear on what you're asking, so I have two answers for you:
If you are trying to avoid adding duplicate classes (i.e. adding IE8Border twice), you don't need to filter anything. .addClass() will only add the class if it doesn't already exist on the element.
If you want to add a class to only those elements that don't already have a class, try this:
$(this).find("input[type='radio'],input[type='checkbox']").filter(function() {
   return this.className === '';
}).addClass('IE8Border');

Have a look at this demo to see this working ->

A: I fully agree on Cybernate's answer. But do you just want to add a class or do you want to overwrite? For the latter one try:
$("input[type='radio'],input[type='checkbox']",this).filter(function(){
    var thisClass = $(this).attr("class");
    return !(thisClass && thisClass.length > 0);
}).removeAttr('class').addClass('IE8Border');

and to extend of Cybernate's answer, instead of filter(), you can also use the not() function.
$("input[type='radio'],input[type='checkbox']").not('.IE8Border').addClass('IE8Border');


text:
Q: Unix for loop and grep combined ksh hp-ux What if you have 5 or 6 files, specific files .biz in a directory, and you want to store them one at the time in a variable $file, and apply a set of command  until no more .biz file are found in the directory.
I tried to use
for f in graham/quant
do
  if grep  "max" $file;
  then
    maximum.sh $file
  elif grep  "milan" $file;
  then
    milan.sh $file
  elif grep  "min" $file;
  then
    minimum.sh $file
  .
  .
  .
  else
     echo " keep working you are close "
  fi
done

but the program executes all the files with the first valid condition.
If you have 5 files with .biz extension, all of them will be executed with first valid condition 5 times.
the output will be :
  Milan
  Milan
  Milan
  Milan
  Milan

instead of
  Milan
  Minimum
  Maximum
  .
  .

Any ideas?

A: grep -lZ max   graham/quant/*.biz | xargs -0r maximum.sh
grep -lZ milan graham/quant/*.biz | xargs -0r milan.sh
grep -lZ min   graham/quant/*.biz | xargs -0r minimum.sh

Note: requires GNU grep for the -Z option to output NUL-separated filenames.
These lines use grep's -l option to output a list of files containing the wanted pattern (max, milan, or min), and the -Z option to use NULs to separate the filenames (so that it is safe to use with filenames with any valid characters).
This is piped into xargs to run the appropriate script for each matching file.
It is assumed that these scripts can correctly handle multiple filename arguments on the command line.  If not, add -n 1 to the xargs options.
e.g. grep -lZ max   graham/quant/*.biz | xargs -0r -n 1 maximum.sh
From man grep:

-l, --files-with-matches
Suppress normal output; instead print the  name  of  each  input file  from  which  output would normally have been printed.  The scanning will stop on the first match.

and:

-Z, --null
Output a zero byte (the ASCII  NUL  character)  instead  of  the character  that normally follows a file name.  For example, grep -lZ outputs a zero byte after each  file  name  instead  of  the usual  newline.
This option makes the output unambiguous, even in the presence of file names containing unusual characters like newlines.
This  option  can  be  used  with commands like find -print0, perl -0, sort -z, and  xargs -0  to  process  arbitrary file names, even those that contain newline characters.

A: As the users says it is using an ancient unix shell, lets try another version of the script:
#!/bin/sh
#test version for ancient shell.
cd graham/quant
for file in *.biz
do
  grep -q "max" "$file"
  if [ "$?" = "0"  ]; then
       maximum.sh "$file"
  fi

  grep -q "milan" "$file"
  if [ "$?" = "0"  ]; then
       milan.sh "$file"
  fi

  grep -q "min" "$file"
  if [ "$?" = "0"  ]; then
       minimum.sh "$file"
  fi

done
cd $OLDPWD


text:
Q: GNU screen auto re-size with screen -x Is there a way to auto re-size screen windows, along with screen -x option? I know we can do this by using the screen fit command, once the shared screen session is open, but is there a way to do this automatically? (just like with screen -r -d, the window is re-sized automatically). I am trying to open a shared screen session automatically, when a new ssh session is opened (by using the screen -x command in .bash_profile), this works; but the window is not re sized. Any suggestions would help.

A: From http://www.gnu.org/software/screen/manual/screen.html

C-a F
  (fit)
  Resize the window to the current region size. See Window Size.

Note this is a capital F, so for me, it's ctrl+a shift+f

A: I haven't tried it myself, but looking at http://www.gnu.org/software/screen/manual/screen.html I'd suggest starting screen with the option -A.


text:
Q: Custom plugin for Elasticsearch to change the default relevancy I am currently using Elasticsearch and there are few things I have noticed about the ranks of the search results, which led me to think about whether there is a way to create plugins/script for ES, which can be used to modify the current scoring algorithm?

A: You can either write a custom Java plugin for that, use function score queries, or scripted similarity (which just came out this week).
If you can I would use the two later methods; writing a custom plugin should only be required very rarely.

A: You can refer to the blog A Gentle Intro to Function Scoring which describes ranking of videos on a website using a combination of textual relevance and the videos popularity on a site.
To modify the scoring algorithm the Elasticsearch provides script_score, function_score and Decay Function.


text:
Q: Symfony 2 / Php : json_encode I've been looking to a solution to my problem for a while without success so I'm asking here.
How can we return a json-encoded result on an array of objects (or just an object) containing private properties ?
Indeed, when you use json_encode($myObject), it won't display the private or protected properties, which are present everywhere in the model when using Symfony...
I'm surprised I couldn't find any method like json_encode that would call getters instead of properties themselves.
Any idea ?
EDIT
In that case I would rather do a unique function that looks like :
public function toArray() {
    $vars = get_object_vars($this);
    $result = array();
    foreach ($vars as $key => $value) {
        if (is_object($value)) {
            $result[$key] = toArray($value);
        } else {
            $result[$key] = $value;
        }
    }
    return $result;
}

in order to avoid rewriting every property name everytime...
But anyway I think I'll just create an array containing the vars I need, so that I won't touch the model (which is generated code).

A: Have you try GetSetMethodNormalizer ?
http://api.symfony.com/2.0/Symfony/Component/Serializer/Normalizer/GetSetMethodNormalizer.html
Ex. https://stackoverflow.com/a/6709828/520114

A: Right now there is no way for this. Only php serialize/unserialize handles the true serialisation of objects.
You'll have to implement them yourselve, or rather let objects return their json values themselves.
You will have to implement your own method toArray() where you expose all your private values in an array:
public function toArray()
{
  return array(
      'property1' => $this->myproperty1,
      'property2' => $this->myproperty2
  );
}

And call it like this:
json_encode(MyObject->toArray());

[Edit: this question is not about doctrine, but since you mention both symfony2 and the model, you can consider using Array Hydration for your model: http://www.doctrine-project.org/docs/orm/2.0/en/reference/dql-doctrine-query-language.html#array-hydration ]


text:
Q: Phantom-DSL cassandra with frozen type I'm trying to map a column which is a Map with frozen type
My column family has a field
batsmen_data map<text, frozen<bat_card>>
bat_card has two fields
 bat_id int,
 bat_name text,

Map the column field
object batsmenData extends MapColumn[ScoreCardData, ScoreCard, String ,Batting](this) {
    override lazy val name="batsmen_data"
}

This is not an ideal way to do it. Because MapColumn Supports only primitive types. Can any one help me out on how to create a UDT Columns

A: I've figured out a way to map the UDT using phantom. But not sure this is right way.
I have a column
batsmen_data map<text, frozen<bat_card>>

To map this, we write the below code
object batsmenData extends  MapColumn[ScoreCardData, ScoreCard, String, Batting](this) with CustomPrimitives {
        override lazy val name="batsmen_data"
}

When you compile, error will be shown No Primitive found for class Batting
This is because Phantom has defined Primitives for native types like String, Int etc. To avoid you have to define primitive for class Batting as shown below(You have to extend CustomPrimitives trait in the class, else you will get the same error).
trait CustomPrimitives extends Config {
    implicit object BattingPrimitive extends Primitive[Batting]{

        override type PrimitiveType = Batting

        override def clz: Class[Batting] = classOf[Batting]

        override def cassandraType: String = {
            Connector.session.getCluster.getMetadata.getKeyspace(cassandraKeyspace).getUserType("bat_card").toString()
        }
         override def fromRow(column: String, row: dsl.Row): Try[Batting] = ???
        override def fromString(value: String): Batting = ???
        override def asCql(value: Batting): String = ???
    }

After this one more error will be shown saying Codec not found for requested operation: [frozen <-> Batting]. This is because cassandra expects a codec for the custom UDT type to serialize and deserialze the data. To Avoid this you have to write a CodecClass which will help to deserialize(as i need only deserializing) the UDT value into custom object.
public class BattingCodec extends TypeCodec<Batting>{
    protected BattingCodec(TypeCodec<UDTValue> innerCodec, Class<Batting> javaType)  {
        super(innerCodec.getCqlType(), javaType);
    }

    @Override
    public ByteBuffer serialize(Batting value, ProtocolVersion protocolVersion) throws InvalidTypeException {
        return null;
    }

    @Override
    public Batting deserialize(ByteBuffer bytes, ProtocolVersion protocolVersion) throws InvalidTypeException {
         return null;
    }

    @Override
    public Batting parse(String value) throws InvalidTypeException {
        return null;
    }

    @Override
    public String format(Batting value) throws InvalidTypeException {
        return null;
    }
}

Once the codec is defined last step is to register this codec into codec registry.
val codecRegistry = CodecRegistry.DEFAULT_INSTANCE
val bat_card = Connector.session.getCluster.getMetadata.getKeyspace(cassandraKeyspace).getUserType("bat_card")
            val batCodec = new BattingCodec(TypeCodec.userType(bat_card), classOf[Batting])
            codecRegistry.register(batCodec)

Now using deserialize function in BattingCodec, we can map the bytes to required object.
This method is working fine. But i'm not sure this is the ideal way to achieve the UDT functionality using Phantom


text:
Q: What version of IOS to use when upload app to appstore? I am just about to upload my first app to appstore :-)
I have tested the app on an iPhone 3G (IOS 4.2) and my iPhone 4. What version of code should i upload and:

*

*If i upload 4.2 to support iPhone 3G, will that cause any problems with newer phones?

*If i upload the latest version of the code i guess iPhone 3G's will not be able to run it?

*Is it worth while to still support iPhone 3G?
Can someone please recommend me what to do?

A: If you upload a version that the 3G does not support, then all 3G users will not be able to download the app.
If you upload a version that is supported by 3G, then only if the users have updated their firmware will be able to use the app.
In other words, the role of thumb is: upload the one that is tested on the latest firmware, but can be launched from as many firmware version as possible.
That might mean to just upload the one that is tested on the least firmware possible, but be careful because newer firmware versions might stop supporting certain APIs that you might have used, and then all newer (potential) customers will be locked out of your app.

A: If i upload 4.2 to support iPhone 3G, will that cause any problems with newer phones?
No.
If i upload the latest version of the code i guess iPhone 3G's will not be able to run it?
You need to compile for arm6 in addition to arm7 architecture.
Is it worth while to still support iPhone 3G?
That's a matter of opinion. This there any requirement for you specific app that requires a iPhone 3GS?

A: Choosing the latest ios as the deployment version is bad idea. iOS 4.3 isn't supported by Verizon devices, which means that you will lose a big portion of US users.
I believe most of apple's apps are using "iOS 3.1" as the deployment version, and i would recommend choosing the this as the lowest supported version.
iOS 3.1 is the last version supported by the original iphone, which guarantees that all users can use your app. Note it's not enougth to just pick 3.1 as the deployment version. you will have to test it with a REAL 3.1 firmware. There are a few guides on downgrading your iphone to 3.1, which is helpful for testing (such as http://lifehacker.com/5572003/how-to-downgrade-your-iphone-3g%5Bs%5D-from-ios-4-to-ios-313)


text:
Q: Android GraphView library - Series added with GraphView.getSecondScale().addSeries(series) cannot be removed I have three series in my graph. Series 1 and 2 use the left side scale, series 3 use the second scale by adding with
CurrentPlot.getSecondScale().addSeries(sensor3Series);

The user has the option to see all three series or only some of them.
Series 1 and 2 can be removed with
currentPlot.removeSeries(sensor1Series);
currentPlot.removeSeries(sensor2Series);

but series 3 cannot be removed.
I tried
currentPlot.removeAllSeries();
currentPlot.removeSeries(sensor3Series);

Both do not remove the series using the second scale.
Please advice how to remove
Code extract:
Initialization (simplified):
private void initChart(boolean isContinuous) {

        // find the temperature levels plot in the layout
        currentPlot = (GraphView) findViewById(R.id.graph);
        // setup and format sensor 1 data series
        sensor1Series = new LineGraphSeries<>();
        // setup and format sensor 2 data series
        sensor2Series = new LineGraphSeries<>();
        // setup and format sensor 3 data series
        sensor3Series = new LineGraphSeries<>();

        currentPlot.getGridLabelRenderer().setNumVerticalLabels(10);
        currentPlot.getGridLabelRenderer().setNumHorizontalLabels(5);

        sensor1Series.setColor(Color.YELLOW);
        sensor2Series.setColor(Color.RED);
        sensor3Series.setColor(Color.GREEN);
        currentPlot.getGridLabelRenderer().setVerticalAxisTitle("Watt");

        // SKIPPED code to add data to the 3 series with appendData()

        currentPlot.setTitle(dayToShow);

        minMaxVal = getMinMax();

        // SKIPPED set min and max bounds of both scales to manual and set the values

        // SKIPPED add setOnDataPointTapListeners to all three series with setOnDataPointTapListener()

        currentPlot.addSeries(sensor2Series);
        currentPlot.getSecondScale().addSeries(sensor3Series);
        currentPlot.addSeries(sensor1Series);
    }

Code to remove selected series (via CheckBox) in onClick:
    case R.id.cb_solar:
        CheckBox cbSolar = (CheckBox)findViewById(R.id.cb_solar);
        if (cbSolar.isChecked()) {
            currentPlot.addSeries(sensor1Series);
            showSeries1 = true;
        } else {
            currentPlot.removeSeries(sensor1Series);
            showSeries1 = false;
        }
        break;
    case R.id.cb_cons:
        CheckBox cbCons = (CheckBox)findViewById(R.id.cb_cons);
        if (cbCons.isChecked()) {
            currentPlot.addSeries(sensor2Series);
            showSeries2 = true;
        } else {
            currentPlot.removeSeries(sensor2Series);
            showSeries2 = false;
        }
        break;
    case R.id.cb_light:
        CheckBox cbLight = (CheckBox)findViewById(R.id.cb_light);
        if (cbLight.isChecked()) {
            currentPlot.getSecondScale().addSeries(sensor3Series);
            showSeries3 = true;
        } else {
            currentPlot.removeAllSeries();
                    //removeSeries(sensor3Series);
            showSeries3 = false;
        }
        break;

EDIT:
Workaround the problem - set the color of the series to Color.TRANSPARENT
case R.id.cb_light:
                CheckBox cbLight = (CheckBox)findViewById(R.id.cb_light);
                if (cbLight.isChecked()) {
                    currentPlot.getSecondScale().addSeries(sensor3Series);
                    sensor3Series.setColor(Color.GREEN);
                    showSeries3 = true;
                } else {
                    currentPlot.removeSeries(sensor3Series);
                    sensor3Series.setColor(Color.TRANSPARENT);
                    showSeries3 = false;
                }
                break;

This makes the third series invisible, but the second scale on the right side is still visible.

A: try:
graph.getSecondScale().getSeries().clear();


text:
Q: Replace the label on a frequency plots I plotted a frequency table of a variable gender which is coded like this : female :2, male: 3.
In the plot, I see 2 and 3, but I'd like to put "Female" and "Male, without changing the value in the data.frame, because it would take more place.
How can I do that?
plot(table4, main="Frequency table",xlab= "Gender", ylab="Country" )

A: First, made some sample data and calculated frequency table with function table().
 df<-data.frame(Sex=sample(c(2,3),10,replace=TRUE),Country=sample(c(4,5),10,replace=TRUE))
 table4<-table(df)
 table4
   Country
Sex 4 5
  2 4 1
  3 2 3

With function str() you can see structure of table4. Sex levels 2 and 3 are stored as dimension names. So you can replace them using function attr() and selecting $Sex.
 str(table4)
 'table' int [1:2, 1:2] 4 2 1 3
 - attr(*, "dimnames")=List of 2
  ..$ Sex    : chr [1:2] "2" "3"
  ..$ Country: chr [1:2] "4" "5"
 attr(table4,"dimnames")$Sex<-c("Female","Male")

Now plot changed table4 object.
plot(table4,main="Frequency table",xlab= "Gender", ylab="Country" )


text:
Q: How to turn a one-to-one relationship to one-to-many relationship The relationship between my fact table and dimension table is one-to-one. What can I do to turn the relationship to one-to-many.
https://i.stack.imgur.com/w1zDi.jpg
[1]:

A: The documentation here explains how to edit a relationship


text:
Q: Removing or hiding component on specific route path In my app when you click on the /favouritetabs route path, the Search bar is still rendered and ideally I'd like that to be not visible when on the favourites page.  Here's my code:

       <SearchTab search={this.handleSubmit} value={this.handleChange}/>

<Switch className="wrapper2 songContainer">
    <Route exact path="/home" render={props => <SongInfo {...props} artist={this.state.artistName} title={this.state.songTitle} link={this.state.tabId} />} />
    <Route exact path="/favouritetabs" component={FavouriteTabs} />} />
</Switch>

What would be the best way to go about doing this?

A: Given the information, you seem to want to display the SearchTab always except for the route of /favouritetabs.
The simplest way of doing that here would be another Switch that checks for /favouritetabs in the first Route and the second would match on anything (or whatever you would like it to match on)
const searchTab = () => (
    <SearchTab
        search={this.handleSubmit}
        value={this.handleChange} />
);

// ...

       <Switch>
           <Route exact path={`/favouritetabs`} component={null} />
           <Route component={searchTab} />
       </Switch>


text:
Q: Android studio hangs with no reason I have worked on a project for weeks now on android studio but few hours ago android studio just hangs with no abvious reason. I restart it, I restart the PC, I did "Invalidate Caches / Restart". I search for solutions on google but no luck specially that I don't know what's the reason.
when I open Android studio it open the project but after a few seconds it hangs even if I don't do anything at all.

A: @user4847410
this is idea.log
2015-06-29 17:48:54,801 [      0]   INFO -        #com.intellij.idea.Main - ------------------------------------------------------ IDE STARTED ------------------------------------------------------
2015-06-29 17:48:54,856 [     55]   INFO -        #com.intellij.idea.Main - IDE: Android Studio (build #AI-141.1980579, 03 Jun 2015 00:00)
2015-06-29 17:48:54,856 [     55]   INFO -        #com.intellij.idea.Main - OS: Windows 7 (6.1, amd64)
2015-06-29 17:48:54,856 [     55]   INFO -        #com.intellij.idea.Main - JRE: 1.8.0_45-b15 (Oracle Corporation)
2015-06-29 17:48:54,856 [     55]   INFO -        #com.intellij.idea.Main - JVM: 25.45-b02 (Java HotSpot(TM) 64-Bit Server VM)
2015-06-29 17:48:54,858 [     57]   INFO -        #com.intellij.idea.Main - JVM Args: -Xms128m -Xmx750m -XX:MaxPermSize=350m -XX:ReservedCodeCacheSize=225m -XX:+UseConcMarkSweepGC -XX:SoftRefLRUPolicyMSPerMB=50 -ea -Djna.nosys=true -Djna.boot.library.path= -Djna.debug_load=true -Djna.debug_load.jna=true -Dsun.io.useCanonCaches=false -Djava.net.preferIPv4Stack=true -Didea.paths.selector=AndroidStudio1.2 -Didea.platform.prefix=AndroidStudio -Djb.vmOptions=C:\Program Files\Android\Android Studio\bin\studio64.exe.vmoptions -Xbootclasspath/a:C:\Program Files\Android\Android Studio\lib\boot.jar -Didea.jre.check=false
2015-06-29 17:48:55,221 [    420]   INFO -        #com.intellij.idea.Main - JNA library loaded (64-bit) in 363 ms
2015-06-29 17:48:55,223 [    422]   INFO - penapi.util.io.win32.IdeaWin32 - Native filesystem for Windows is operational
2015-06-29 17:48:55,223 [    422]   INFO -        #com.intellij.idea.Main - Using "FocusKiller" library to prevent focus stealing.
2015-06-29 17:48:56,355 [   1554]   INFO - llij.ide.plugins.PluginManager - 25 plugins initialized in 476 ms
2015-06-29 17:48:56,358 [   1557]   INFO - llij.ide.plugins.PluginManager - Loaded bundled plugins: Android Support (10.1.2.2), CVS Integration (11), Copyright (8.1), Coverage, EditorConfig (1.0), Git Integration (8.1), GitHub, Google Cloud Testing (1.0), Google Cloud Tools For Android Studio (0.2.8), Google Login (1.0), Gradle, Groovy (9.0), I18n for Java, IDEA CORE, IntelliLang (8.0), JUnit (1.0), Java Bytecode Decompiler (0.1), JavaFX (1.0), Maven Integration, Properties Support, Subversion Integration (1.1), Task Management (1.0), Terminal (0.1), TestNG-J (8.0), hg4idea (10.0)
2015-06-29 17:48:56,866 [   2065]   INFO - ellij.util.io.PagedFileStorage - lower=100; upper=200; buffer=10; max=739246080
2015-06-29 17:48:56,904 [   2103]   INFO - api.vfs.impl.local.FileWatcher - Starting file watcher: C:\Program Files\Android\Android Studio\bin\fsnotifier.exe
2015-06-29 17:48:56,912 [   2111]   INFO - api.vfs.impl.local.FileWatcher - Native file watcher is operational.
2015-06-29 17:48:57,287 [   2486]   INFO - lij.diagnostic.DebugLogManager - Set DEBUG for the following categories: []
2015-06-29 17:48:57,487 [   2686]   INFO - org.jetbrains.io.BuiltInServer - We cannot bind to our default range, so, try to bind to any free port
2015-06-29 17:48:57,781 [   2980]   INFO - rains.ide.BuiltInServerManager - built-in server started, port 58491
2015-06-29 17:48:57,986 [   3185]   INFO -                  TestNG Runner - Create TestNG Template Configuration
2015-06-29 17:48:58,029 [   3228]   INFO - ellij.project.impl.ProjectImpl - 20 project components initialized in 345 ms
2015-06-29 17:48:58,030 [   3229]   INFO - le.impl.ModuleManagerComponent - 0 module(s) loaded in 0 ms
2015-06-29 17:48:58,487 [   3686]   INFO - pl.stores.ApplicationStoreImpl - 83 application components initialized in 2111 ms
2015-06-29 17:48:58,509 [   3708]   INFO - .intellij.idea.IdeaApplication - App initialization took 4215 ms
2015-06-29 17:48:59,346 [   4545]   INFO -                  TestNG Runner - Create TestNG Template Configuration
2015-06-29 17:48:59,558 [   4757]   INFO - ellij.project.impl.ProjectImpl - 136 project components initialized in 602 ms
2015-06-29 17:48:59,698 [   4897]   INFO - le.impl.ModuleManagerComponent - 2 module(s) loaded in 139 ms
2015-06-29 17:49:02,318 [   7517]   INFO - indexing.UnindexedFilesUpdater - Indexable files iterated in 2051 ms
2015-06-29 17:49:03,847 [   9046]   INFO - tartup.impl.StartupManagerImpl - E:\android_studio_workspace\IraqiExc.idea\misc.xml case-sensitivity: false
2015-06-29 17:49:04,083 [   9282]   INFO - indexing.UnindexedFilesUpdater - Indexable files iterated in 41 ms
2015-06-29 17:49:04,263 [   9462]   INFO - lij.tasks.impl.TaskManagerImpl - Updating issues cache (every 20 min)
2015-06-29 17:49:04,563 [   9762]   INFO - CompilerWorkspaceConfiguration - Available processors: 8
2015-06-29 17:49:05,113 [  10312]   INFO - nject.config.XPathSupportProxy - XPath Support is not available
2015-06-29 17:49:05,164 [  10363]   INFO - attrs.AttributeDefinitionsImpl - Found tag with unknown parent: AndroidManifest.AndroidManifestSupportsInput
2015-06-29 17:49:05,164 [  10363]   INFO - attrs.AttributeDefinitionsImpl - Found tag with unknown parent: AndroidManifest.AndroidManifestCompatibleScreens
2015-06-29 17:49:05,411 [  10610]   INFO - tor.impl.FileEditorManagerImpl - Project opening took 6491 ms


text:
Q: Maximize the function $f(x, y) = 2xy + 3x$ under the constraint $x + 2y = 83$. $$\begin{array}{ll} \text{maximize} & f(x, y) := 2xy + 3x\\ \text{subject to} & x + 2y = 83\end{array}$$
I can apply, for example, the Lagrange theorem since its assumptions are satisfied and computing the Lagrange system I get the critical point is $x=43$, $y=20$. However, the Lagrange theorem gives only the necessary condition. How can I show that the function has a min/max at $x=43, y=20$?It looks like I cannot use Weirstrass theorem since the set $x + 2y = 83$ is closed but not bounded..

A: As suggested by @dmtri's comment, solving the constraint for $y$ yields $y= \frac12(83-x)$. Substituting this into the objective function yields $$f(x) = 2x\cdot\frac12(83-x) +3x = x(83-x) + 3x = x(86-x) = -x^2 + 86x.$$
Now, the graph $\{(x,f(x)): x\in\mathbb R\}$ is a descending parabola. We can write the quadratic $-x^2+86x$ in vertex form: $-x^2+86x = a(x-h)^2+k$ where the coordinates of the vertex are $(h,k)$. Expanding the vertex form, we have $ax^2 - 2ahx + ah^2+k$. Since $f(0)=0$, we immediately see that $ah^2+k=0$. Moreover, $a$ must match the coefficient of $x^2$, so $a=-1$. This yields $-x^2 +2hx = -x^2+86x$, and hence $h=43$. It follows then that $k= -ah^2 = 43^2 = 1849$. Since $f$ is concave, the maximum value that $f$ obtains is thus $1849$.
To solve this using calculus, we first note that $f$ is continuously differentiable and that $\lim_{x\to-\infty}f(x)=\lim_{x\to\infty} f(x)=-\infty$, so the maximum must occur at a point where $f'(x)=0$. Differentiating, we have $f'(x) = -2x +86$. Solving $f'(x)=0$ yields $x=43$. Now, $f'(x)>0$ for $x<43$ so $f$ is increasing on $(-\infty,43)$ and $f'(x)<0$ for $x>43$ so $f$ is decreasing on $(43,\infty)$, so $x=43$ is a local (and because $f$ is concave, global) maximum for $f$. We evaluate $f(43) = 43(86-43) = 43^2 = 1849$.
Although the above method is simpler, we can still use Lagrange multipliers to solve this problem. To solve
\begin{align}
\max&\quad f(x,y)\\
\mathrm{s.t.}&\quad g(x,y)=0
\end{align}
we form the system of equations
\begin{align}
\nabla f(x,y) &= \lambda\nabla g(x,y)\\
g(x,y) &= 0,
\end{align}
where $\nabla$ denotes the gradient operator. We compute
$$
\nabla f(x,y) = \left(\frac{\partial f}{\partial x}, \frac{\partial f}{\partial y} \right) = (2y+3, 2x)
$$
and
$$
\lambda\nabla g(x,y) = \lambda \left(\frac{\partial g}{\partial x}, \frac{\partial g}{\partial y} \right) = (\lambda, 2\lambda),
$$
which yields the system of equations:
\begin{align}
2y + 3 &= \lambda\\
2x &= 2\lambda\\
x + y - 83 &= 0.
\end{align}
By inspection, $x=\lambda$, whence $y = \frac12(x-3)$. Substituting into the third equation, we find that $$x = x + \frac12(x-3) - 83 = 0 \implies x=43.$$
Therefore $y = \frac12(43-3) = 20$, and the maximum of $f$ is obtained at $(43,20)$, with $f(43,20) = 1849$. To prove that $(43,20)$ is indeed a maximum, we consider the Lagrangian function $L(x,y) = f(x,y)-\lambda g(x,y) = 2xy+3x - \lambda(x+2y-83)$ and the bordered Hessian matrix
$$
\mathcal HL(x,y) = \begin{pmatrix}
\frac{\partial^2L}{\partial x^2}&\frac{\partial^2L}{\partial x\partial y}&\frac{\partial^2L}{\partial x\partial \lambda}\\
\frac{\partial^2L}{\partial y\partial x}&\frac{\partial^2L}{\partial y^2}&\frac{\partial^2L}{\partial y\partial\lambda}\\\frac{\partial^2L}{\partial \lambda\partial x}&\frac{\partial^2L}{\partial\lambda \partial y}&\frac{\partial^2L}{\partial\lambda^2}
\end{pmatrix} = \begin{pmatrix}0&2&-1\\2&0&-2\\-1&-2&0\end{pmatrix}.
$$
Since $\det(\mathcal HL(43, 20))=-8<0$, we conclude that $(43,20)$ is indeed a maximum.


text:
Q: jQuery replaceWith() with an external php generated footer essentially i have this function that simply takes a variable that i want to then replace a specific  with that variable.
JQUERY
function updateCart(new_total)
    {
        var total = new_total;
        var content = $("#replaceme");
        content.replaceWith("
hello
");

        alert(content.html());
    }

PHP
echo "
" . $_COOKIE[$cookie_name1] . " Item | $" . $total . "
";

i am not sure why this is not working, like i mentioned before the php is included as footer.php and the html is generated by use of an echo statement but i do not see how this should make any difference to the jQuery function as the page does load and also when i test to see if the correct div is being selected by alert(content.html()); i successfully get the content of #replaceme
any help would be greatly appreciated! thanks!
to show that i know how to use this function, this following code test i work wrote, just not in the my other use case
$(document).ready(function(){
        var content = $("#checkout-summary");
        content.replaceWith("
hello
");
        //$("#checkout-summary").after("
hello
").remove();
        console.log(content.html());
    });

A: It works on pc. If you have issue with mobile use this alternative:
$("#replaceme").after("
hello
").remove();

A: I am not sure why but i had to essentially change
$("#replaceme").replaceWith("
hello
")

with
$("div#replaceme").replaceWith("
hello
")

i guess moral is be as specific as possible.


text:
Q: How to specify width of custom view? I'm having trouble trying to set a specific size for the width of my custom view. I know I can just hard-code a value in the layout_width field in the XML file but I'm trying not to result to hard-coding values. I need my View to be half the size of the screen. So, within the class I find half the screen size:
    WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    Display display = wm.getDefaultDisplay();
    try{
        Point size = new Point();
        display.getSize(size);
        screenWidth = size.x;
    }catch(NoSuchMethodError e){
        screenWidth = display.getWidth();
    }

Then, I call:
 measure(width|MeasureSpec.EXACTLY, LayoutParams.WRAP_CONTENT|MeasureSpec.EXACTLY);
 //Where width is equal to half the screen width

but this does not seem to be working for my case. So, to sum it all up, how do you properly specify a particular size for a custom View? Any help will be useful and appreciated! Thanks!

A: I believe that you might not be able to accurately get the width of the screen at this point because you need to wait till the entire hierarchy (up until the most root view) is laid out. You may need to do something like:
ViewTreeObserver.OnGlobalLayoutListener layoutListener = new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {

            int width = getWidth();
            int height = getHeight();
            //set layoutparams with those values.
            }
        };

getViewTreeObserver().addOnGlobalLayoutListener(layoutListener);

You can confirm the correctness of this by seeing if the values you're getting when you try getting the display width inside of onMeasure differ from the values you get when the onGlobalLayout callback is invoked.

A: Override the onMeasure() method in your Custom View:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int width = getResources().getDisplayMetrics().widthPixels >> 1;
    widthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}

Basically, override the width MeasureSpec to be exactly half the width of the screen, then pass that through to the superclass.


text:
Q: How GET/REQUEST all values from a field in a database (phpMyAdmin) using SQL and PHP? I am currently doing work with a database online. The is entries from different countries and I need to do a drop down list for these countries. Rather than typing the countries into the HTML is there any way of using GET/REQUEST or anything to get the data from the database to create a drop down?
Obviously, there are a few duplicate countries such as I think USA occurs 3 or 4 times but I would like that to appear on the list only once.
Update: coming to think of it GET/REQUEST can't be used so is there an alternative possibly using an SQL statement?

A: Basic structure of an HTML dropdown is:
<select>
   <option>Option1</option>
   <option>Option2</option>
   <option>Option3</option>
</select>

Knowing that, simple make a query from your database, and loop through the values. Assuming you already know how to do that.
<select>

<?php
while(<loop through each value in database>){
    echo "<option>{$data}</option>";       //Assuming $data has current iteration's value
}
?>

</select>

A: the equivalent sql statement for GET is SELECT.


text:
Q: Can an HTTP request to an HTTPS server be forced to encrypt? I have an Unbuntu server running NodeJS, where I want to upload some files. Some of the files contain some data that I would prefer would not to be leaked, but it wouldn't be a massive issue if someone got a hold of the files. My NodeJS server is currently a plain HTTP server, but from what I understand from this article, it should be possible to force HTTP file uploads to be encrypted. Does that mean I can upload a file using an HTTP POST request, and it's encrypted? How does the file upload know to encrypt the file?
The HTTP request is sent from Microsoft Flow.

A: HTTP protocol works on top of TCP protocol. HTTPS works on top of TLS. so underlying connections are different. In order to submit your form with HTTPS encryption you would need to upgrade your HTTP connection to HTTPS using "Upgrade" HTTP header. https://en.wikipedia.org/wiki/HTTP/1.1_Upgrade_header
HTTP was not designed to encrypt data.
Regarding your nodejs question, lets look at the code snippet here
var https = require('https');
https.createServer(options, app).listen(443);

Module https will create a server that is listening on 443 port, which is used for your HTTPS traffic. next snippet creates your HTTP server which listens for traffic on port 80
var http = require('http');
http.createServer(app).listen(80);

So now, you have two servers listening on two different ports. To conclude my answer, HTTP and HTTPS are used on different connections. you cannot mutate your HTTP session in to HTTPS on the fly I am afraid.

A: I think the easiest solution could be to set the action to the https url.
<form action="https://<YOUR_Server/post-handler" method="post" ...>


text:
Q: robocopy options to ignore OSX invisible files, or, dot_clean first? I'm trying to copy ~8GB of files from a USB stick to a win7 system. The files on the USB stick appear to be coming from an OSX system (.DS_Store files and corresponding ._filenames for each file). For what it is worth, the USB stick is formatted FAT32.
The main directory contains seven subdirectories with a total of 250+ subdirs and there is a total of some 2500+ files. When I drag and drop copy I get a "Destination Path Too Long" error msg:

When I use the cp command, I get similar PathTooLongException error messages (notably, more of them...?)
Using the robocopy command and the /e option, I am able to successfully copy all the files without error:
robocopy G:\SOURCE_FOLDER C:\Users\user\Desktop\DESTINATION_FOLDER /e
Is there a way to copy all the files with robocopy but to exclude the ._ "meta" files and .DS_Store files? Or is it better to simply recursively delete them? After doing some more research, would it be a better idea to dot_clean the files before copying them to a windows system? Thanks!

A: You can use Robocopy with the /XA:SH and the /XD *. flags to exclude hidden folder and files which should keep the dot files from being copied over.


text:
Q: Why Reap and Sow is not working here Here in the first example my code works:
Reap[
  For[x = 1, x <= 10, x++,
    f[x];
    Sow[{x, f[x]}]]][[2, 1]]`

and I can plot $x$ vs $f(x)$.
However, for a 3D plot this code doesn't work:
f[x_, y_] := x + 1 + y^2
Reap[
  For[x = 1, x <= 10, x++,
    For[y = 1, y <= 10, y++,
      f[x, y];
      Sow[{x, y, f[x, y]}]]]][[2, 1]]

A: Perhaps your question is really about Reap and Sow. Or perhaps it is about how to produce your list of points. If the latter, use Array:
Catenate@Array[{#1, #2, f[#1, #2]} &, {10, 10}]

Edit:
As Bob Hanlon suggested, one may also use Table.
xs = Range[10]
ys = Range[10]
Catenate@Table[{x, y, f[x, y]}, {x, xs}, {y, ys}]

Your xs and ys can be arbitrary lists, which adds some flexibility. This same functionality may be achieved with Outer:
Catenate@Outer[{#1, #2, f[#1, #2]} &, xs, ys]

In short, it is unlikely that use of For, Sow, and Reap are the best way towards your goal. Ordinarily, use Sow and Reap only when you don't know how many results you want to keep.


text:
Q: Binomial identity $\sum_{i=0}^{n-1-j}\binom{n}{i+j}\binom{i+j}{j}(-1)^i=\binom{n}{j}(-1)^{n+j+1}$ Let $n$ be a positive integer and fix a non-negative integer $j\le n-1$. Is it true that
$$
\sum_{i=j}^{n-1}\binom{n}{i}\binom{i}{j}(-1)^i=\binom{n}{j}(-1)^{n-1}
$$
or, equivalently,
$$
\sum_{i=0}^{n-1-j}\binom{n}{i+j}\binom{i+j}{j}(-1)^i=\binom{n}{j}(-1)^{n+j+1}\,\,\,?
$$
[This is only a conjecture]

A: First note that your conjecture is equivalent to
$$\sum_{i=j}^n\binom{n}i\binom{i}j(-1)^i=0\;.\tag{1}$$
Now
$$\binom{n}i\binom{i}j=\binom{n}j\binom{n-j}{i-j}\;,$$
so $(1)$ can be rewritten as
$$0=\sum_{i=j}^n\binom{n}j\binom{n-j}{i-j}(-1)^i=\binom{n}j\sum_{i=j}^n\binom{n-j}{i-j}(-1)^i\;,$$
which is equivalent to
$$\sum_{i=j}^n\binom{n-j}{i-j}(-1)^i=0\;.\tag{2}$$
Letting $k=i-j$, we can rewrite $(2)$ as
$$\sum_{k=0}^{n-j}\binom{n-j}k(-1)^{k+j}=0\;,$$
which, after multiplication by $(-1)^j$, becomes
$$\sum_{k=0}^{n-j}\binom{n-j}k(-1)^k=0\;.$$
This is just a special case of the binomial theorem, specifically, for $(-1+1)^{n-j}$, which we know is $0$ unless $n=j$, in which case it's $1$. Thus, your conjecture is true provided that $n>j$.


text:
Q: Xamarin Pinning Certificate ServicePointManager Callback does not fire Xamarin android and iOS I have been looking at xamarin pinning certificate and I have tried the code below but  Service callback never gets called.
I just added a button that makes an http call and I was expecting for the callback to be invoked
**using xamarin.forms.4.6.0.800  and .net standard 2.0 **
AppXaml
    protected override async void OnInitialized()
    {
        InitializeComponent();
        CertificateValidator.Initialize();

        await NavigationService.NavigateAsync("NavigationPage/MainPage");
    }

ViewModel
public class MainPageViewModel : ViewModelBase
{
    private readonly HttpClient httpClient;
    public MainPageViewModel(INavigationService navigationService)
        : base(navigationService)
    {
        this.httpClient = new HttpClient(new HttpClientHandler());
    }

    private DelegateCommand makeCallCommand;
    public DelegateCommand MakeCallCommand =>
        makeCallCommand ?? (makeCallCommand = new DelegateCommand(async () => await MakeCall()));

    async Task MakeCall()
    {
       var result= await httpClient.GetStringAsync("https://www.xamarin.com");
    }
}

CertificateValidator
public static class CertificateValidator
{

    private const string PublicKey = "whatever";

    public static void Initialize()
    {
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        ServicePointManager.ServerCertificateValidationCallback = ValidateCertificate;
    }

    public static bool ValidateCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        Debugger.Break();
        return PublicKey == certificate?.GetPublicKeyString();
    }
}

In Android I have tried all below and none trigger a callback .
Happy to use native handlers but not sure where to start. Is there a nuget?


text:
Q: Error in installation and loading of the "scales" packages in R studio server version 1.0.153 I am using R Studio Server version 1.0.153. I just got the "scales" package installed version 0.5.0 . But when loading the package library(scales), I get the following error:
Error in [[3L]](cond):
Package 'scales' version 0.4.1 cannot be unloaded:
Error in unloadNamespace(package) : namespace 'scales' is imported by
'ggplot2' so cannot be unloaded.

Please help me with a possible solution.Thanks a lot.

A: Also install the ggplot2 library in the R studio
Any don't forget to import library in the console before using it


text:
Q: Execute a random SQL query and get the result into datagridview I am using C# and MySQL
So far I've tried to execute SELECT, INSERT, DELETE commands and display result in datagridview using DataSet and MySqlDataAdapter successfully.
But now I want to 1.execute a random query (whatever user type into a Textbox and press Execute button) and also 2.display result in a datagridview**.
What are these steps needed to archive that task?
(I tried to search but only return me those results in what people are using specific command like SELECT, my case is different, the query is randomly typed by user)

A: Here is a sample code snippet of binding a query result into a gridview:
DataSet objDataSet = new DataSet();
SqlConnection objConn = new SqlConnection();

SqlCommand objComm = new SqlCommand("SELECT COUNT(*) FROM table", objConn);

SqlDataAdapter objDataAdapter = new SqlDataAdapter(objComm);

if (objConn.State == ConnectionState.Closed)
{
    objConn.Open();
}

objDataAdapter.Fill(objDataSet, strTable);

dataGridView1.DataSource = objDataSet;