text:
Q: How to open Google Maps to show route using Swift I read around the Internet but couldn't find a legit answer. I need to open Google Maps when the user clicks a button to show directions. Start and destination must be automatically filled.
How can I achieve this in Swift?
If anyone has a solution, please provide me with a sample code. The start is always going to be the user's current location.

A: Here is the Swift 3 Update
First, you need to two items to LSApplicationQueriesSchemes in the info.plist.

Then you can use this function to load address on Google maps.
 let primaryContactFullAddress = "No 28/A, Kadalana, Moratuwa, Sri Lanka"

 @IBAction func showLocaionOnMaps(_ sender: Any) {
        let testURL: NSURL = NSURL(string: "comgooglemaps-x-callback://")!
        if UIApplication.shared.canOpenURL(testURL as URL) {
            if let address = primaryContactFullAddress.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) {
                let directionsRequest: String = "comgooglemaps-x-callback://" + "?daddr=\(address)" + "&x-success=sourceapp://?resume=true&x-source=AirApp"
                let directionsURL: NSURL = NSURL(string: directionsRequest)!
                let application:UIApplication = UIApplication.shared
                if (application.canOpenURL(directionsURL as URL)) {
                    application.open(directionsURL as URL, options: [:], completionHandler: nil)
                }
            }
        } else {
            NSLog("Can't use comgooglemaps-x-callback:// on this device.")
        }
}

A: Swift 4 Working Code
if let url = URL(string: "comgooglemaps://?saddr=&daddr=\(location.coordinate.latitude),\(location.coordinate.longitude)&directionsmode=driving") {
        UIApplication.shared.open(url, options: [:])
    }

this code works for me. And ı didn't insert
* LSApplicationQueriesSchemes

If you use emulator can't see the results. Don't forget work your project on the Phone.

A: OK I found the answer myself.
If you want to show directions from the user's current location, leave the field saddr blank and in the field daddr you can enter the destination coordinates.
This is how I did it
if (UIApplication.sharedApplication().canOpenURL(NSURL(string:"comgooglemaps://")!)) {
            UIApplication.sharedApplication().openURL(NSURL(string:
                "comgooglemaps://?saddr=&daddr=\(place.latitude),\(place.longitude)&directionsmode=driving")!)

        } else {
            NSLog("Can't use comgooglemaps://");
        }
    }

for any further queries you can refer to this link Google Map URL Scheme

A: I want the possibility that the user can open Google Maps via browser (only works when user hasn't the Google Maps App)
Google gives a documentation for that here.
Since iOS 9 you have to set a scheme. This you will find here.
For me the google solution doesn't work. Maybe you are smarter and find a solution (please post!).
Anyway I made a simple web call:
let lat = 37.7
let lon = -122.4
if (UIApplication.sharedApplication().canOpenURL(NSURL(string:"https://maps.google.com")!))
{
     UIApplication.sharedApplication().openURL(NSURL(string:
     "https://maps.google.com/?q=@\(lat),\(lon)")!)
}

This could be use as a kind of fallback from sumeshs answer.

A: 1) Method: You can pass the only destination address current address will be automatically fetched by google map application.
let strLat : String = "23.035007"
let strLong : String = "72.529324"

override func viewDidLoad() {
        super.viewDidLoad()
        if (UIApplication.shared.canOpenURL(URL(string:"comgooglemaps://")!)) {
            UIApplication.shared.openURL(URL(string:"comgooglemaps://?saddr=&daddr=\(strLat),\(strLong)&directionsmode=driving")!)
        }
        else {
            print("Can't use comgooglemaps://");
        }
    }

2) You can pass both start and destination address
let strLat : String = "23.035007"
let strLong : String = "72.529324"

let strLat1 : String = "23.033331"
let strLong2 : String = "72.524510"

override func viewDidLoad() {
        super.viewDidLoad()
        if (UIApplication.shared.canOpenURL(URL(string:"comgooglemaps://")!)) {
            UIApplication.shared.openURL(URL(string:"comgooglemaps://?saddr=\(strLat),\(strLong)&daddr=\(strLat1),\(strLong2)&directionsmode=driving&zoom=14&views=traffic")!)
        }
        else {
            print("Can't use comgooglemaps://");
        }
    }

A:   let lat = self.upcomingListArr[indexPath.item].latitude!
            let long = self.upcomingListArr[indexPath.item].longitude!
            if (UIApplication.shared.canOpenURL(NSURL(string:"comgooglemaps://")! as URL)) {
                UIApplication.shared.openURL(NSURL(string:
                    "comgooglemaps://?saddr=&daddr=\(String(describing: lat)),\(String(describing: long))")! as URL)

            } else {
                UIApplication.shared.openURL(NSURL(string:
                    "https://www.google.co.in/maps/dir/?saddr=&daddr=\(String(describing: lat)),\(String(describing: long))")! as URL)
            }

A: Swift 5 - Code
func openGoogleMap() {
     guard let lat = booking?.booking?.pickup_lat, let latDouble =  Double(lat) else {Toast.show(message: StringMessages.CurrentLocNotRight);return }
     guard let long = booking?.booking?.pickup_long, let longDouble =  Double(long) else {Toast.show(message: StringMessages.CurrentLocNotRight);return }
      if (UIApplication.shared.canOpenURL(URL(string:"comgooglemaps://")!)) {  //if phone has an app

          if let url = URL(string: "comgooglemaps-x-callback://?saddr=&daddr=\(latDouble),\(longDouble)&directionsmode=driving") {
                    UIApplication.shared.open(url, options: [:])
           }}
      else {
             //Open in browser
            if let urlDestination = URL.init(string: "https://www.google.co.in/maps/dir/?saddr=&daddr=\(latDouble),\(longDouble)&directionsmode=driving") {
                               UIApplication.shared.open(urlDestination)
                           }
                }

        }

Don't forget to write this in info.plist
<key>LSApplicationQueriesSchemes</key>
    <array>
    <string>comgooglemaps</string>
    <string>comgooglemaps-x-callback</string>
    </array>

A: The Answer is already there but in older versions of Swift
In Swift 3
//Working in Swift new versions.
if (UIApplication.shared.canOpenURL(URL(string:"comgooglemaps://")!))
{
    UIApplication.shared.openURL(NSURL(string:
    "comgooglemaps://?saddr=&daddr=\(Float(latitude!)),\(Float(longitude!))&directionsmode=driving")! as URL)
} else
{
    NSLog("Can't use com.google.maps://");
}

A: You can create small builder for URL, that will redirect you to GoogleMaps
/*

 add to InfoPlist:

       <key>LSApplicationQueriesSchemes</key>
        <array>
          <string>comgooglemaps</string>
          <string>comgooglemaps-x-callback</string>
        </array>
 */
final public class GoogleMapsURIConstructor {

  public enum NavigationType: String {

    case driving
    case transit
    case walking
  }

  public class func prepareURIFor(latitude lat: Double,
                                  longitude long: Double,
                                  fromLatitude fromLat: Double? = nil,
                                  fromLongitude fromLong: Double? = nil,
                                  navigation navigateBy: NavigationType) -> URL? {
    if let googleMapsRedirect = URL(string: "comgooglemaps://"),
      UIApplication.shared.canOpenURL(googleMapsRedirect) {

      if let fromLat = fromLat,
        let fromLong = fromLong {

        let urlDestination = URL(string: "comgooglemaps-x-callback://?saddr=\(fromLat),\(fromLong)?saddr=&daddr=\(lat),\(long)&directionsmode=\(navigateBy.rawValue)")
        return urlDestination

      } else {

        let urlDestination = URL(string: "comgooglemaps-x-callback://?daddr=\(lat),\(long)&directionsmode=\(navigateBy.rawValue)")
        return urlDestination
      }
    } else {
      if let fromLat = fromLat,
        let fromLong = fromLong {

        let urlDestination = URL(string: "https://www.google.co.in/maps/dir/?saddr=\(fromLat),\(fromLong)&daddr=\(lat),\(long)&directionsmode=\(navigateBy.rawValue)")
        return urlDestination

      } else {

        let urlDestination = URL(string: "https://www.google.co.in/maps/dir/?saddr=&daddr=\(lat),\(long)&directionsmode=\(navigateBy.rawValue)")
        return urlDestination
      }
    }
  }
}

usage:
  let uri = GoogleMapsURIConstructor.prepareURIFor(latitude: lat,
                                                   longitude: long,
                                                   fromLatitude: userLatitude,
                                                   fromLongitude: userLongitude,
                                                   navigation: .driving)
   UIApplication.shared.open(uri, options: [: ], completionHandler: nil)

result:

A: For those that the solution for the accepted answer didn't work for them, remember to add comgooglemaps to LSApplicationQueriesSchemes in the info.plist.

A: First off all, thank you guys for your answers beyond. But when I'm working around, I didn't find the working answer for me. And as result I've made working code with two cases: when user has the google maps app and if not.
Here is my version of code. Xcode 10, Swift 4.2. Hope it will help.
Step 1: Find your info.plist and Open As -> Source Code

Step 2: Add these lines between <dict> and </dict>

Step 3: In your action add this code. Don't forget to set your latitude and longitude.
        let latitude = 44.987781
        let longitude = 88.987781
        let appDomen: String = "comgooglemaps://"
        let browserDomen: String = "https://www.google.co.in/maps/dir/"
        let directionBody: String = "?saddr=&daddr=\(latitude),\(longitude)&directionsmode=driving"

        // Make route with google maps application
        if let appUrl = URL(string: appDomen), UIApplication.shared.canOpenURL(appUrl) {
            guard let appFullPathUrl = URL(string: appDomen + directionBody) else { return }
            UIApplication.shared.openURL(appFullPathUrl)

        // If user don't have an application make route in browser
        } else if let browserUrl = URL(string: browserDomen), UIApplication.shared.canOpenURL(browserUrl) {
            guard let browserFullPathUrl = URL(string: browserDomen + directionBody) else { return }
            UIApplication.shared.openURL(browserFullPathUrl)
        }

A: If google map app not installed, open with apple map version.
import Foundation
import CoreLocation
import UIKit
import MapKit

struct GoogleMapApp {
    func openWithDirection(cordinate: CLLocationCoordinate2D, locationName: String) {
        let hasGoogleMapApp = UIApplication.shared.canOpenURL(URL(string: "comgooglemaps://")!)

        if hasGoogleMapApp {
            let urlString = "comgooglemaps-x-callback://?saddr=&daddr=\(cordinate.latitude),\(cordinate.longitude)&directionsmode=driving"
            if let url = URL(string: urlString) {
                UIApplication.shared.open(url, options: [:])
            }
        } else {
            // If google map not installed, open with Apple Map App
            let mapItem = MKMapItem(placemark: MKPlacemark(coordinate: cordinate, addressDictionary: nil))
            mapItem.name = locationName
            mapItem.openInMaps(launchOptions: [MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDriving])
        }
    }
}

A: @IBAction func NavigationTrackerPressedPressed(_ sender: UIButton){

    if let UrlNavigation = URL.init(string: "comgooglemaps://") {
        if UIApplication.shared.canOpenURL(UrlNavigation){
            if self.destinationLocation?.longitude != nil && self.destinationLocation?.latitude != nil {

                let lat =      (self.destinationLocation?.latitude)!
                let longi = (self.destinationLocation?.longitude)!

                if let urlDestination = URL.init(string: "comgooglemaps://?saddr=&daddr=\(lat),\(longi)&directionsmode=driving") {
                    UIApplication.shared.openURL(urlDestination)
                }
            }
        }
        else {
            NSLog("Can't use comgooglemaps://");
            self.openTrackerInBrowser()

        }
    }
    else
    {
        NSLog("Can't use comgooglemaps://");
       self.openTrackerInBrowser()
    }

}
func openTrackerInBrowser(){
    if self.destinationLocation?.longitude != nil && self.destinationLocation?.latitude != nil {

        let lat = (self.destinationLocation?.latitude)!
        let longi = (self.destinationLocation?.longitude)!

        if let urlDestination = URL.init(string: "https://www.google.co.in/maps/dir/?saddr=&daddr=\(lat),\(longi)&directionsmode=driving") {
            UIApplication.shared.openURL(urlDestination)
        }
    }
}

A: // I hope it will work perfactly.
let googleURL = NSURL(string: "comgooglemaps://?q=")

if(UIApplication.shared.canOpenURL(googleURL! as URL)) {
     UIApplication.shared.open(URL(string:"comgooglemaps://?saddr=\(DEVICE_LAT),\(DEVICE_LONG)&daddr=\(addressLat),\(addressLng)&directionsmode=driving")!, options: [:], completionHandler: nil)
}

//Also set permission from info.plist according to attached image.
enter image description here

A: We can use this method to open google maps. If google maps is not installed it will redirect to browser.
    func redirectToGoogleMap(coordinates : String) {

       if let url = URL(string: "comgooglemaps://?saddr=&daddr=\(coordinates)&directionsmode=driving"),
           UIApplication.shared.canOpenURL(url) {
           print("comgoogle maps worked")
           if #available(iOS 10, *) {
               UIApplication.shared.open(url, options: [:], completionHandler:nil)
           } else {
               UIApplication.shared.openURL(url)
           }
       } else{
        if let url = URL(string: "https://www.google.co.in/maps/dir/?saddr=&daddr=\(coordinates)&directionsmode=driving"),
            UIApplication.shared.canOpenURL(url) {
             print("google com maps worked")
            if #available(iOS 10, *) {
                UIApplication.shared.open(url, options: [:], completionHandler:nil)
            } else {
                UIApplication.shared.openURL(url)
            }
        }else{

           kSweetAlert.showAlert(CommonMethods.setLangText("oops"), subTitle: "Oops! Could not open google maps", style: AlertStyle.error)
        }
       }
   }`

A: SWIFT 5.1 (WORKED FOR ME)
// Destination Address (Lat/Long)
let place = business?.businessAddresse
// Google URL
let stringURL = "comgooglemaps://"
// Checking Nil
if !(place?.latitude == nil) || !(place?.longitude == nil) {
  if UIApplication.shared.canOpenURL(URL(string: stringURL)!) {
    // If have Google Map App Installed
    if let url = URL(string: "comgooglemaps://?saddr=&daddr=\(place?.latitude ?? 0.0),\(place?.longitude ?? 0.0)&directionsmode=driving") {
      UIApplication.shared.open(url, options: [:], completionHandler: nil)
    }
  } else {
    // If have no Google Map App (Run Browser Instead)
    if let destinationURL = URL(string: "https://www.google.co.in/maps/dir/?saddr=&daddr=\(place?.latitude ?? 0.0),\(place?.longitude ?? 0.0)&directionsmode=driving") {
      UIApplication.shared.open(destinationURL, options: [:], completionHandler: nil)
    }
  }
} else {
  // Show Alert When No Location Found
  self.delegate?.noDirectionError(title: "Error", message: "There's no direction available for this restaurant")
}

Note: This code only work on iOS Version 11 or Later, I hope this helps you guys too, cheer.

A: Here is the simple solution to choose navigation application between apple and google map(if installed, Otherwise system will navigate to default apple map).
Add this OpenMaps class in your project.
class OpenMaps {

        // Presenting Action Sheet with Map Options Like Google And Apple Maps.
        /// - Parameter coordinate: coordinate of destination
        static func presentActionSheetwithMapOption(coordinate: CLLocationCoordinate2D) {
            let latitude = coordinate.latitude
            let longitude = coordinate.longitude

            // Google MAP URL
            let googleURL = "comgooglemaps://?daddr=\(latitude),\(longitude)&directionsmode=driving"
            let googleItem = ("Google Maps", URL(string:googleURL)!)

            // Apple MAP URL
            let appleURL = "maps://?daddr=\(latitude),\(longitude)"

            var installedNavigationApps = [("Apple Maps", URL(string:appleURL)!)]

            if UIApplication.shared.canOpenURL(googleItem.1) {
                installedNavigationApps.append(googleItem)
            }

            if installedNavigationApps.count == 1 {
                if let app = installedNavigationApps.first {
                    self.openMap(app: app)
                }
                return
            }

            // If there are google map install in the device then System will ask choose map application between apple and google map.
            let alert = UIAlertController(title: nil,
                                          message: "Choose application",
                                          preferredStyle: .actionSheet)

            for app in installedNavigationApps {
                let button = UIAlertAction(title: app.0,
                                           style: .default, handler: { _ in
                    self.openMap(app: app)
                })
                alert.addAction(button)
            }

            let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
            alert.addAction(cancel)

            guard let vc = AlertViewManager.shared.getTopViewController() else {
                debugPrint("Unable To open the action sheet for maps. Function: \(#function), Line: \(#line)")
                return
            }
            vc.present(alert, animated: true)
        }

        // Open Selected Map
        /// - Parameter app: Selected Map Application Details
        private static func openMap(app: (String, URL)) {
            guard UIApplication.shared.canOpenURL(app.1) else {
                debugPrint("Unable to open the map.")
                return
            }
            UIApplication.shared.open(app.1, options: [:], completionHandler: nil)
        }
    }

Usage:
    let coordinate = CLLocationCoordinate2D(latitude: 30.7333,
                                          longitude: 76.7794)
    OpenMaps.presentActionSheetwithMapOption(coordinate: coordinate)

A: Using Swift 5 and XCode 13, I was able to use Google's Universal cross-platform syntax to open Google Maps app in directions mode.
The link will open the google maps app if it is installed on the phone. If maps is not installed it will open the url in the browser.
let url = "https://www.google.com/maps/dir/?api=1&destination=\(coords.latitude)%2C\(coords.longitude)"
guard let googleUrl = URL.init(string: url) else {
    // handle error
    return
}
UIApplication.shared.open(googleUrl)

A: In Swift 4:
 if (UIApplication.shared.canOpenURL(NSURL(string:"comgooglemaps://")! as URL)) {
       UIApplication.shared.open((NSURL(string:
            "comgooglemaps://?saddr=&daddr=\(trashDictionarySorted[indexPath.section][0])&directionsmode=driving")! as URL), options: [:], completionHandler: nil)

        } else {
            NSLog("Can't use comgooglemaps://");
        }
    }

A: The Answer is already there but in older versions of Swift, And this code can open Google Map in browser if your iPhone did't install Google Map Application.
In Swift 4
import MapKit

func openGoogleDirectionMap(_ destinationLat: String, _ destinationLng: String) {

    let LocationManager = CLLocationManager()

    if let myLat = LocationManager.location?.coordinate.latitude, let myLng = LocationManager.location?.coordinate.longitude {

        if let tempURL = URL(string: "comgooglemaps://?saddr=&daddr=\(destinationLat),\(destinationLng)&directionsmode=driving") {

            UIApplication.shared.open(tempURL, options: [:], completionHandler: { (isSuccess) in

                if !isSuccess {

                    if UIApplication.shared.canOpenURL(URL(string: "https://www.google.co.th/maps/dir///")!) {

                        UIApplication.shared.open(URL(string: "https://www.google.co.th/maps/dir/\(myLat),\(myLng)/\(destinationLat),\(destinationLng)/")!, options: [:], completionHandler: nil)

                    } else {

                         print("Can't open URL.")

                    }

                }

            })

        } else {

            print("Can't open GoogleMap Application.")

        }

    } else {

        print("Prease allow permission.")

    }

}

A: func openTrackerInBrowser(lat: String, long: String, dlat: String, dlong: String){

    if let urlDestination = URL.init(string: "https://www.google.co.in/maps/dir/?saddr=\(lat),\(long)&daddr=\(dlat),\(dlong)&directionsmode=driving") {
        UIApplication.shared.open(urlDestination, options: [:], completionHandler: nil)

    }
}


text: Q: Configuring two different IP segments on the server causes the Docker container to fail to run There are two network cards on the server. Each network card is configured with different IP segments, which causes the docker container on the service to fail to run.How to solve this problem?  thanks

redpajama_set_name: RedPajamaStackExchange


text:
Q: In dust.js, can you pass a parameter from a sub-template through to a base? In my dust template library, have a 3 levels of templates:
base: {#myparam}{.}{/myparam}
parent: {>base}
child: {>parent myparam="value"}
How might I pass myparam from 'child' to the 'base' ?

A: Try this:
{! base template !}
{myparam}

then
{! parent template !}
{>base myparam=childparam/}

then
{! child template !}
{>parent childparam="value"/}

Try this jsFiddle: http://jsfiddle.net/smfoote/gZM3H/1/


text:
Q: How would you go about building a command that runs an entire directory? I'm in the process of building a series of scripts that will efficiently run all of my water contamination samples(which are my input files) through a genetic sequencer and compare those input files against another directory of reference files. That will be spit out into an matching and nonmatching output directory. Any help would be appreciated.
I have no clue on how to go about this script. I'm relatively new to python.
Although, I already have 2 pieces of this 3 piece puzzle; the 1st, in theory will have the set default bbduk values for the command in this script. Or if you would like to run a different value , you will have the freedom to call that bbduk value another time around (and/or) just change it. The 2nd script will provide more structure for the command, acting as the backbone of it all in a way.
from water_contamination.lib.bbduk import build_command

def main(*args, **kwargs):

    #import pdb; pdb.set_trace()
    import argparse

    parser=argparse.ArgumentParser()
    parser.add_argument("-input", type=list, help="fastq1, fastq2 (Coma seperated)")
    parser.add_argument("-nonmatching_output", type=list, help="out1 and out2")
    parser.add_argument("-matching_output", type=list, help="outm1 and outm2")
    parser.add_argument("-references", type=list, help="references, reference (Coma seperated)")
    parser.add_argument("-stats", type=list, help="stats")
    parser.add_argument("-minavgquality", type=int, default=5, help="choose a minavgquality value or stay with the default of 5")
    parser.add_argument("-trimpolya", type=int, default=7, help="choose a trimpolya value or stay with the default of 7")
    parser.add_argument("-minilength", type=int, default=51, help="choose a minilength value or stay with the default of 51")
    parser.add_argument("-maxns", type=int, default=1, help="choose a maxns value or stay with the default of 1")
    parser.add_argument("-k", type=int, default=25, help="choose a k value or stay with the default of 25")
    parser.add_argument("-t", type=int, default=2, help="choose a t value or stay with the default of 2")
    parser.add_argument("-zl", type=int, default=6, help="choose zl value or stay with the default of 6")
    parser.add_argument("-entropy", type=float, default=0.5, help="choose an entropy value or stay with the default of 0.5")
    parser.add_argument("-ow", type=str, default="t", help="choose an ow value or stay with the default of t")
    args=parser.parse_args()

    bbduk_command=build_command(args)
    if args.minavgquality:
        print("minavgquality={}".format(args.minavgquality))
    if args.trimpolya:
        print("trimpolya={}".format(args.trimpolya))
    if args.minilength:
        print("minilength={}".format(args.minilength))
    if args.maxns:
        print("maxns={}".format(args.maxns))
        print(type(args.maxns))
    if args.k:
        print("k={}".format(args.k))
    if args.t:
        print("t={}".format(args.t))
    if args.zl:
        print("zl={}".format(args.zl))
    if args.entropy:
        print("entropy={}".format(args.entropy))
    if args.ow:
        print("ow={}".format(args.ow))

def build_input(fastq1, fastq2):
    return "in1=" + fastq1 + " in2=" + fastq2

def build_nonmatching_output(fastq1, fastq2):
    return "out1=" + fastq1 + " out2=" + fastq2

def build_matching_output(fastq1, fastq2):
    return "outm1=" + fastq1 + " outm2=" + fastq2

def build_reference(references):
    return "ref=" + ",".join(references)

def build_stats(stats):
    return "stats=" + stats

def bulid_minavgquality(minavgquality=5):
    return "minavgquality={}".format(minavgquality)

def build_trimpolya(trimpolya=7):
    return "trimpolya={}".format(trimpolya)

def build_minilength(minilength=51):
    return "minilength={}".format(minilength)

def build_maxns(maxns=1):
    return "maxns={}".format(maxns)

def build_k(k=25):
    return "k={}".format(k)

def build_t(t=2):
    return "t={}".format(t)

def build_zl(zl=6):
    return "zl={}".format(zl)

def build_entropy(entropy=0.5):
   return "entropy={}".format(entropy)

def build_ow(ow="T"):
    return "ow={}".format(ow)

def build_command(args):

    string_list=[input, output, reference, stats, minavgquality, trimpolya, minilength, maxns, k, t, zl, entropy, ow]
    string_list.append("echo '{}'".format(igm//apps/bbmap/bbmap/bbduk.sh))

    input=build_input(args.input)
    string_list.append(input)

    matching_output=build_matching_output(args.matching_output)
    string_list.append(matching_output)

    nonmatching_output=build_nonmatching_output(args.nonmatching_output)
    string_list.appending(nonmatching_output)

    stats=build_stats(args.stats)
    string_list.appending(stats)

    references=build_references(args.references)
    string_list.append(references)

    trimpolya=build_trimpolya(args.trimpolya)
    string_list.append(trimpolya)

    minlength=build_minlength(args.minlength)
    string_list.append(minlength)

    maxns=build_mans(args.maxns)
    string_list.append(maxns)

    minavgquality=build_minavgquality(args.minavgquality)
    string_list.append(minavgquality)

    k=build_k(args.k)
    string_list.append(k)

    t=build_t(args.t)
    string_list.append(t)

    zl=build_zl(args.zl)
    string_list.append(zl)

    ow=build_ow(args.ow)
    string_list.append(ow)

    entropy=build_entropy(args.entropy)
    string_list.append(entropy)

The expected result of all of this is to create this package to allow you to attach the according directories; input, references, stats, matching_output and nonmatching_output and let the command do the rest. Which would be to construct a command with the resources provided and to also run said command after construction and to spit out the results into the matching_output and nonmatching_output. Please reach out if you would like me to expand any deeper on anything or reiterate on anything. thank you.


text:
Q: How to check if select tags option exists with data attribute using jQuery So I want to be able to check if the select tag option exists. But I want to be able to use the data attribute. I have tried everything I could find with no luck. Here is my code:
if ($("#first-select option[data-id='G']").length > 0) {

//set the option to "selected"

}

Also when this is done, i want to be able to set that option tag to selected. What am I missing here? I did try attr('data-id') and also .data("id"). No luck.
For testing, I used console log to post a true if the above statement is true but it always gives me false.
Edit: What I really want to do is execute the code when an ajax successfully executes. So here is the code with the ajax I currently have:
success: function(data) {

                $("#name").val(data.title);

                var sEl = $("#first-select option[data-id='G']");
                if (sEl.length > 0) {
                    sEl.attr("selected", true);
                }
                else {
                    console.log('doesnt exist!');
                }
            }

HTML:
 <select name="rating" id="first-select">
                        <option value="2" data-id="PG3">PG3</option>
                        <option value="3" data-id="PG-13">PG-13</option>
                        <option value="4" data-id="R">R</option>
                        <option value="1" data-id="G">G</option>
                        <option value="5" data-id="NC-17">NC-17</option>
 </select>

The thing is that I will be using data.rated to get the rated value (which maybe PG, PG-13, R and so on) and if the rated value exists in the select I already have, then give it selected attribute.
This still does not seem to work. It worked once and now does not seem to work.

A: Seems like you are just trying to select the option where data-id matches the rating returned in your dataset. Seems like all you need is something like this (the data variable is just there as a placeholder for the data returned from your ajax request).

const data = {title: 'A movie', rated: 'G'}

$('#first-select [data-id="' + data.rated + '"]').prop('selected', true);
<select name="rating" id="first-select">
  <option value="2" data-id="PG3">PG3</option>
  <option value="3" data-id="PG-13">PG-13</option>
  <option value="4" data-id="R">R</option>
  <option value="1" data-id="G">G</option>
  <option value="5" data-id="NC-17">NC-17</option>
</select>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

An example of how to handle multiselect:

const data = {title: 'A movie', rated: 'G,PG3,PG-13'}
const ratings = data.rated.split(',');

$.each(ratings, (index, rating) => {
  $('#first-select [data-id="' + rating + '"]').prop('selected', true);
});
<select name="rating" id="first-select" multiple>
  <option value="2" data-id="PG3">PG3</option>
  <option value="3" data-id="PG-13">PG-13</option>
  <option value="4" data-id="R">R</option>
  <option value="1" data-id="G">G</option>
  <option value="5" data-id="NC-17">NC-17</option>
</select>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


text:
Q: OpenSFM setup.py file returning error after building via Docker I am having an issue building OpenSFM. I am getting an error from running the setup.py file.
First, I am running Ubuntu 16.04 on VirtualBox. I installed Docker and ran
docker pull freakthemighty/opensfm

This image was successfully built.
Additionally, I cloned the OpenSFM repository from here into my home folder.
Next, I am supposed to build by running this in the main folder:
python setup.py build

This is the resulting error
walter@VirtualUbuntu:~$ python setup.py build
Configuring...
Traceback (most recent call last):
  File "setup.py", line 21, in <module>
    subprocess.Popen(['cmake','../opensfm/src'], cwd='cmake_build').wait()
  File "/usr/lib/python2.7/subprocess.py", line 711, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1343, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

Here is the setup.py file in question.

A: The official response I got:
Hi @walter,
there are two ways of running opensfm, with or without docker.
If you want to use docker, then there is no need to run python setup.py build. Instead build the docker image using
cd path/to/OpenSfM
docker build -t mapillary/opensfm .

then run using
docker run -ti mapillary/opensfm /bin/sh -c "bin/run_all data/berlin"

Note that this will create the reconstruction inside the docker container. You will need some docker knowledge to map a local folder to a folder inside the docker image so that we can access the results outside.
The other option is not to use docker. In this case, you will need to install the dependencies on your ubuntu machine see https://github.com/mapillary/OpenSfM#installing-dependencies-on-ubuntu . After doing that you will be able to run python setup.py build
hope this helps,
pau

A: I ended up building the Dockerfile myself. I added a last few steps to get it to work and have OpenSfM build automatically.
I clone the repository first, then add a couple missing packages, followed by building the setup.py file automatically.
FROM ubuntu:16.04

# Install apt-getable dependencies
RUN apt-get update \
    && apt-get install -y \
        build-essential \
        cmake \
        git \
        libatlas-base-dev \
        libboost-python-dev \
        libeigen3-dev \
        libgoogle-glog-dev \
        libopencv-dev \
        libsuitesparse-dev \
        python-dev \
        python-numpy \
        python-opencv \
        python-pip \
        python-pyexiv2 \
        python-pyproj \
        python-scipy \
        python-yaml \
        wget \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

# Install Ceres from source
RUN \
    mkdir -p /source && cd /source && \
    wget http://ceres-solver.org/ceres-solver-1.10.0.tar.gz && \
    tar xvzf ceres-solver-1.10.0.tar.gz && \
    cd /source/ceres-solver-1.10.0 && \
    mkdir -p build && cd build && \
    cmake .. -DCMAKE_C_FLAGS=-fPIC -DCMAKE_CXX_FLAGS=-fPIC -DBUILD_EXAMPLES=OFF -DBUILD_TESTING=OFF && \
    make install && \
    cd / && \
    rm -rf /source/ceres-solver-1.10.0 && \
    rm -f /source/ceres-solver-1.10.0.tar.gz

# Install opengv from source
RUN \
    mkdir -p /source && cd /source && \
    git clone https://github.com/paulinus/opengv.git && \
    cd /source/opengv && \
    mkdir -p build && cd build && \
    cmake .. -DBUILD_TESTS=OFF -DBUILD_PYTHON=ON && \
    make install && \
    cd / && \
    rm -rf /source/opengv

#Clone the OpenSfM Repository
RUN git clone https://github.com/mapillary/OpenSfM.git

#Add additional functions that for some reason didn't come with the docker file
Run apt-get update \
    && apt-get install python-networkx \
    python-exif \
    python-xmltodict

#Automatically build OpenSfM so that its prebuilt in the docker
Run cd OpenSfM && python setup.py build

A: I was getting same error on docker for windows with python 3.
To solve this problem;

*

*I have built https://raw.githubusercontent.com/paulinus/opensfm-docker-base/master/Dockerfile.python3 as  "paulinus/opensfm-docker-base:latest" image.

*I created Dockerfile as below;

FROM paulinus/opensfm-docker-base:latest
  RUN pip3 install joblib
  RUN git clone https://github.com/mapillary/OpenSfM.git && cd OpenSfM  && git submodule update --init --recursive && python3 setup.py build

For some reason joblib was missing from required python module which creates error when you want to run commands such as "bin/opensfm_run_all data/berlin"
cmake error caused by "pybind11_add_module" was solved with "git submodule update --init --recursive" command.  (Check issue on https://github.com/patrikhuber/eos/issues/127)

*Then I built it

docker build -t opensfm-python3 .

Now opensfm works on a docker container in windows.

docker run -it opensfm-python3 bash

or you can run the command outside of the docker container as below;
docker run -it opensfm-python3 bash -c "cd OpenSfM && bin/opensfm_run_all data/berlin"


text:
Q: Zend DB - where And Or Query Could someone please tell me the correct syntax for a Zend DB query to represent the last line (the and (xxx or xxx)
...
where
    id = 1241487470
and (contract=0 or is_work IS NOT NULL)
...

I'm stuck at this:
->where('id = ?', 1241487470)
->where(...)

A: This seemed logical and worked. So Yay.
->where('id = ?', 1241487470)
->where('contract= ? or is_work IS NOT NULL)

A: This seems works too and preserve zend db escapement
->where('id = ?', 1241487470);
->where('(contract = ?', 0);
->orWhere('is_work IS NOT NULL)');


text:
Q: Meteor template elements lose style during (re)render I have a template that has a some text updated reactively once every second.
I also have a button, that when clicked, gets it's style changed to display a disabled button - this works fine but as soon as the template re-renders due to the condition above then the button reverts back to it's original style. It is almost as if the entire template is rendering from scratch (template.render is fired every second).
Is this normal? do I need to control the style via a reactive {{btnstyle}} type mechanism?

A: Yes, the typical way to do this is to set the style via a class that is set by a template helper function. For disabling button/input elements, you can just use the disabled attribute instead of class:
<button type="button" {{#if buttonDisabled}}disabled{{/if}}>Button Text</button>

or
<input type="button" value="Button Text" {{#if buttonDisabled}}disabled{{/if}} />

and then do:
Template.yourFormTemplate.buttonDisabled = function() {
  // return true or false depending on if the button should be disabled
};

The problem is that when Meteor re-renders your template, the element which you set the style of is actually getting replaced with a new one. Note that the Meteor team is currently working on a new templating engine that works on a more fine-grained level, so that elements don't necessarily get replaced like that. You can try your current code with the preview release of the new templating engine with this command:
meteor --release shark-1-29-2014-e

or
mrt --release shark-1-29-2014-e

However, it is still generally recommended to style elements via the class attribute, set with a template helper. This is a more declarative, template-driven approach that just fits better with the "Meteor way" to do things, rather than the imperative approach of setting the style directly from your JavaScript. It also helps with separating concerns, by allowing your CSS to control the actual style.


text:
Q: How to change parameters of the particular tab in Kotlin android Im trying to set width and title to the particular tab in tablayout. In Java it is easy. But how to do that in kotlin. Here is my code and it is not working
val tabsTitles = tabLayout.getChildAt(0) as ViewGroup
        tabsTitles.getChildAt(1).visibility = GONE
        tabsTitles.getChildAt(1).title = "Some title here"
        tabsTitles.getChildAt(1).width = MATCH_PARENT

        val onlineTab = tabLayout.getChildAt(0)
        onlineTab.title = "Title"
        onlineTab.width = MATCH_PARENT

A:         val sectionsPagerAdapter = SectionsPagerAdapter(this, supportFragmentManager)
        val viewPager: ViewPager = findViewById(R.id.view_pager)
        viewPager.adapter = sectionsPagerAdapter
        val tabs: TabLayout = findViewById(R.id.tabs)
        tabs.setupWithViewPager(viewPager)

        tabs.getTabAt(0)?.text = "My Title"

        val layout = (tabs.getChildAt(0) as LinearLayout).getChildAt(0) as LinearLayout
        val layoutParams = layout.layoutParams as LinearLayout.LayoutParams
        layoutParams.weight = // Desired weight
        layout.layoutParams = layoutParams


text:
Q: When do we use Retrieve and Retrieve Multiple Messages in Plugin Registration tool? In plugin i used services but when should i go for Messages like Retrieve and Retrieve Multiple

A: When we want to intercept and alter the responses back to the use for a query.
For example you could remove certain fields or make your own "calculated" field in a plugin.


text:
Q: echo as a list, loop within a loop I have a data set which looks similar to:
---------------------------------------------------------------------
id | category | sub_category | category_href | sub_category_href    |
01 | cat_1    | sub_cat 1    | cat/cat1.php  | cat/cat1/sub_cat1.php|
02 | cat_1    | sub_cat 2    | cat/cat1.php  | cat/cat1/sub_cat2.php|
03 | cat_2    | sub_cat 1    | cat/cat2.php  | cat/cat2/sub_cat1.php|
04 | cat_2    | sub_cat 2    | cat/cat2.php  | cat/cat2/sub_cat2.php|
---------------------------------------------------------------------

What I want to do with the data is have a layout like this:

Cat1

sub_cat_1

sub_cat_2

Cat2

sub_cat_1

sub_cat_2

So my question is how would I do this with php so that I can change the categories and sub categories from my db. The following is what I have below but I need a second loop for the sub categories or it will only have one sub category per category. Could someone point me in the right direction for the sub_cat loop. Thank you
EDIT:
So my question is now that I have distinct categories how I can echo the appropriate sub categories?
Thanks
<?php
include('connect.php');
$result = mysql_query("SELECT DISTINCT category FROM categories")
    or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
    echo "
";
    echo "
" . $row['category'] . "
";
    echo "
";
    echo "
";
    $result1 = mysql_query("SELECT * FROM categories ")
        or die (mysql_error());
    while ($row = mysql_fetch_array($result1)) {
        echo "
" . $row['sub_category'] . "
";
    }
    echo "
";
    echo "
";
    echo "
";
}
?>

A: That code could be looked like this:
<?php
include('connect.php');
$result = mysql_query("SELECT DISTINCT category FROM categories")
    or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
    echo "
";
    echo "
" . $row['category'] . "
";
    echo "
";
    echo "
";
    $result1 = mysql_query("SELECT * FROM categories WHERE category = {$row['category']}")
            or die (mysql_error());
    while ($row1 = mysql_fetch_array($result1)) {
        echo "
" . $row1['sub_category'] . "
";
    }
    echo "
";
    echo "
";
    echo "
";
}
?>

But I suggest you to optimize in this manner:
<?php
include('connect.php');
$result = mysql_query("SELECT * FROM categories")
    or die(mysql_error());
$cats = array();
while ($row = mysql_fetch_array($result)) {
    $category = $row['category'];
    $sub_category = $row['sub_category'];
    $sub_category_href = $row['sub_category_href'];
    $cat_hrefs[$category][$sub_category] = $sub_category_href;
}
foreach ($cat_hrefs as $category => $sub_category_hrefs) {
    echo "
";
    echo "
" . $category . "
";
    echo "
";
    echo "
";
    foreach ($sub_category_hrefs as $sub_category => $sub_category_href) {
        echo "
" . $sub_category . "
";
    }
    echo "
";
    echo "
";
    echo "
";
}
?>

You do not need to make three queries, because you can do it in one query, which is more optimal.

A: There is no need for four columns in database only sub_category & sub_category are required the other 2 category_href,sub_category_hrefare redundant as the can be generated from the first 2.
This version uses PDO which is recommended for new applications.

// connect to database
<?php
$host= "xxx";
$username="xxx";
$password="xxx";
$database="xxx";

// Opens a connection to a MySQL server
$connection=mysql_connect("localhost", $username, $password);
try {

// DBH means "D Handle"
// MySQL with PDO_MYSQL
 $DBH = new PDO("mysql:host=$host;dbname=$database", $username, $password);

}
catch(PDOException $e) {
  echo $e->getMessage();
}

// creating the statement
$STH = $DBH->query('SELECT * FROM  category  LIMIT 0 , 30');
// setting the fetch mode
$STH->setFetchMode(PDO::FETCH_ASSOC);
 //Set up flag
 $test = 0;
while($row = $STH->fetch()) {

 if($test == 0){
   echo "
".str_replace('_','',ucfirst($row['category']))."
";
   $test = 1;
 }
 else{
   $test = 0;
 }
  echo "
".$row['sub_category']."
";

}
// close the connection
$DBH = null;
?>


text:
Q: Remove dynamically generated textviews on dynamic button click event I need to remove each Table Rows on an individual button click event.
The Buttons are dynamically generated.
How will i achieve this?
Below is my code:
   public class S2 extends Modify implements OnClickListener {
   Button b;
   String arry1[], category_main,str = null, catarray[];
   int i,key = 0;
   private static String url = "http://ashapurasoftech.com/train/test.json";
   private static final String TAG_a = "menu",TAG_Name = "Name",TAG_Cat = "Category";
   JSONArray items = null;
   ArrayList<HashMap<String, String>> itemList;

@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.modify);
    category_main = "";

    new Getitems().execute(category_main);

    b =(Button) findViewById(R.id.Order);
    b.setOnClickListener(this);

    itemList = new ArrayList<HashMap<String, String>>();
}

@Override
public void onClick(View arg0) {

    switch(arg0.getId()){

    case R.id.Order:try{ onbuttonclick();} catch(JSONException e){}

                    break;

    }
}

    private void onbuttonclick() throws JSONException {

    TableRow[] tr = new TableRow[arry1.length];
    final TextView[] tx = new TextView[arry1.length];
    GridLayout gl = new GridLayout(S2.this);
    gl.setRowCount(arry1.length);
    gl.setColumnCount(1);
    final TableLayout tl = (TableLayout) findViewById(R.id.tb1);
    TableRow row = null;

    for (i = 0; i < arry1.length; i++) {

        final String cat = arry1[i].toString();

        tx[i] = new TextView(S2.this);
        tx[i].setLayoutParams(new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
        tx[i].setAllCaps(true);
        tx[i].setTextSize(15);
        tx[i].setText(cat);

        tr[i] = new TableRow(S2.this);
        tr[i].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
        tr[i].addView(tx[i],new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));

        tl.addView(tr[i],new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

        int buttonsInRow = 0;
        int numRows = tl.getChildCount();

        if( numRows > 0 ){
            row = (TableRow) tl.getChildAt( numRows - 1 );
            buttonsInRow = row.getChildCount();
        }

        if( numRows == 0 || buttonsInRow == 3 ){
            row = new TableRow( this );
            tl.addView( row );
            buttonsInRow = 0;
        }
        if( buttonsInRow < 3 ){
            Button b = new Button( this );
            b.setText("Cancel");
            b.setId(i);
            row.addView( b, 100, 50 );

        }
        b.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                b = (Button) findViewById(i);
                tl.removeView(tx[i]);
            }
        });

    }
}

this is my screen where i want to clear each items when i click on the button aside it.

A: you can probably achieve what you need in
 onClick(View arg0)

by getting the arg0 parent. check it is
 instanceof

Table row or has a tag you set up and then set its visibility to GONE

A: You can use removeView method in the similar fashion you are using addView:
tr[i].removeView(<YourTextView>;


text:
Q: How to get email from internal contacts in android? I am developing an app where i need to get contacts & emails from internal phone book..
After some search in google i found the following code for getting phonenum & name.
Main.java
Cursor numcur = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,null, null);
    if (numcur != null) {
        while (numcur.moveToNext()) {
            name = numcur.getString(numcur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            number = numcur.getString(numcur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            phonenumarray.add(number);
            displaynamearray.add(name);

        }
    }

But here to get email id's they are using seperate cursor like as below..
Cursor emailcur = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, null,null, null);
    if (emailcur != null) {
        while (emailcur.moveToNext()) {
            email = emailcur.getString(emailcur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA1));
                emailarray.add(email);

        }
    }

As here we are getting values seperately when adding values to listview for contact2 it is displayng contact7 mail id and for contact3 it is showing contat5 mail id as show in below figure.

So, can anyone help me how to get phone num, mail id for same contact..

A: try like this
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
    while (phones.moveToNext()) {
    String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
    String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

    ContactBean objContact = new ContactBean();
    objContact.setName(name);
    objContact.setPhoneNo(phoneNumber);
    list.add(objContact);

see this one How to get the Android device's primary e-mail address

A: The approach is to use the LOOKUP_KEY as explained in the http://developer.android.com/guide/topics/providers/contacts-provider.html
An example can be found here
http://android-er.blogspot.in/2012/12/access-contactscontractcommondatakindsp.html
You can also bring in the CursorJoiner concept for better performance
http://asyncindicator.blogspot.in/2012/12/cursorjoiner-and-matrixcursor.html


text:
Q: Put full page width image at bottom of page in Overleaf I have an Invoice template I want to fill. As part of an Invoice where I live we put a payment slip in the footer of the last page of that Invoice. I have generated a paymentslip in png format. It is about the size of an a4 paper and I want to put it at the bottom of it's own page. The Invoice having a footnote and all details in the First page.
I based myself on this template in Overleaf. https://github.com/eroux/latex-yait
So after all the template is customized, I insert the payment slip with
\newpage

\begin{figure}[b!]
    \makebox[\textwidth]{\includegraphics{images/paymentslip.png}}
\end{figure}

The \makebox is needed so the payment slip png has no indentation. However this snippet renders the payment slip at about center of the page. Playing around with all the different options from google did not result what I wanted.
It might be the Image width that is the problem. Has anybody any idea how I can define a box at the bottom of the page and align the payment slip at the bottom of that in latex?

A: With tikz, it is very easy to place elements with respect to the paper:
\documentclass{article}

\usepackage{tikz}

\begin{document}

your document

\clearpage

\begin{tikzpicture}[remember picture, overlay, inner sep=0pt]
\node[anchor=south west] at (current page.south west) {\includegraphics[width=\paperwidth]{example-image-duck}};
\end{tikzpicture}

\end{document}


text:
Q: An unhandled exception of type 'System.StackOverflowException' occurred in System.Web.dll

         @{Html.RenderAction("Top_Head", "My_PartialView");}

                    @RenderBody()

                 @{Html.RenderAction("Search_Price", "My_PartialView");}

2.created My_Partialview
using System;

namespace shopclothes.Controllers
{
    public class My_PartialviewController : Controller
    {
        shoponline1Entities db = new shoponline1Entities();
        // GET: /MyPartialView/

        #region[head]
         [ChildActionOnly]
        public ActionResult Top_Head()
        {

            return PartialView();
        }
        #endregion
     }
}

I follow the correct syntax? why it has been such a problem?

A: The @RenderBody should be use on Layout views, try removing that

A: error for:
  @{Html.RenderAction("Top_Head", "My_PartialView");}
 and
 @{Html.RenderAction("Search_Price", "My_PartialView");}

A: It seems there is a bug in using some @html.RenderAction or @html.Action together in layout .I recommend you try the equivalent of renderaction command in other ways.for more help you can take a look at this


text:
Q: Bootstrap 4 nested responsive table I am using Bootstrap 4. I have a table within a table that I would like to be responsive.
In reality all of it is one table, but I only want the second column and on to be scrollable. The only way I could think to get this to work was to make a nested table with everything from the second column onwards being in its own table-response div. However this is not working and the responsiveness only happens if I make the entire table response.
I'll show you what I have and maybe we can work to figure out how to make my mess responsive, but if it's possible to make a table where only the second column onwards scrolls on the x axis that would be awesome. I'm really stumped here. I would like the table with id wannabe-responsive to be scrollable, but the first table with id not-responsive to stay put.

.item {
  min-height: 350px;
  border: 1px solid #000;
  margin-bottom: 20px;
  background: #f2f2f2
}

Inventory

Time Chart

                  Potatoes

                  Apples

                  Corn

                  Lettuce

                  1:20
                  1:52
                  2:30
                  3:17
                  3:35
                  4:22
                  4:45
                  5:15
                  6:15
                  6:30
                  7:25
                  7:37
                  7:50
                  8:02
                  8:15
                  8:27
                  8:40
                  8:52

                    1
                    1
                    1
                    0
                    1
                    0
                    1
                    1
                    0
                    1
                    1
                    1
                    0
                    0
                    0
                    1
                    0
                    1

                    1
                    1
                    1
                    0
                    1
                    0
                    1
                    1
                    0
                    1
                    1
                    1
                    0
                    0
                    0
                    1
                    0
                    1

                    1
                    1
                    1
                    0
                    1
                    0
                    1
                    1
                    0
                    1
                    1
                    1
                    0
                    0
                    0
                    1
                    0
                    1

                    1
                    1
                    1
                    0
                    1
                    0
                    1
                    1
                    0
                    1
                    1
                    1
                    0
                    0
                    0
                    1
                    0
                    1

Edit: I found that adding the container class to the  container the response table does make it responsive but I'm still having issues with the data overflowing outside the rop level container. I'll update as I make progress
Edit 2: Please check out my JS Fiddle to see my progress. I almost have it working exactly how I want, but I'm still having an issue with the content getting cut short. If you run the fiddle you will see that it scrolls how I want, but it cuts off the time slots at the end, and the end of the scroll bar as well, depending on how small the screen is. My ultimate solution would for it to show the entire scroll bar at the bottom at all times, and for all of the time slots to be viewable when scrolling.
Right now it looks like this

See how both the end time slots and scroll bar are cut off? I'm so close! Any help is super super appreciated!

A: I think it's not a good idea to nest so many tables because it's dificult to handle the responsive design. I replaced the left table with flex and I removed the outer table. Here is the fix:

<!DOCTYPE html>

 <title></title>
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">

Inventory

Time Chart

Potatoes

Apples

Corn

Lettuce

       1:20
       1:52
       2:30
       3:17
       3:35
       4:22
       4:45
       5:15
       6:15
       6:30
       7:25
       7:37
       7:50
       8:02
       8:15
       8:27
       8:40
       8:52

        1
        1
        1
        0
        1
        0
        1
        1
        0
        1
        1
        1
        0
        0
        0
        1
        0
        1

        1
        1
        1
        0
        1
        0
        1
        1
        0
        1
        1
        1
        0
        0
        0
        1
        0
        1

        1
        1
        1
        0
        1
        0
        1
        1
        0
        1
        1
        1
        0
        0
        0
        1
        0
        1

        1
        1
        1
        0
        1
        0
        1
        1
        0
        1
        1
        1
        0
        0
        0
        1
        0
        1


text:
Q: Posts destroyed as spam should trigger a retroactive audit failure for previous "No Action Needed" votes As a moderator on Stack Overflow, I regularly look through the review history of obvious spam that has lasted more than an hour or so on the site. I often find one or two reviewers who voted "No Action Needed" in the First Posts or Late Answers review queue, allowing that spam to pass through review. I then have to look into the review history for each user and apply manual review bans as needed.
Almost always, the reviewers that have done this have failed multiple audits and have been banned from review on several occasions. It's a time-consuming and frustrating process to go and manually evaluate and ban each of these reviewers for approving obvious spam that I or the community later found.
Therefore, I'm proposing that when a post is destroyed by the community as spam (6 spam flags or one hard moderator spam flag), any reviewer who previously voted "No Action Needed" on that spam is immediately hit with a review audit failure as if they had reviewed that post incorrectly at the time it was destroyed. For those who had failed other audits, this would automatically trigger a review ban of the appropriate duration.
This would automate the process we already follow when dealing with those who approve spam. It would only apply to cases of spam so clear that the community or a moderator had to step in and destroy (not just delete) the post, yet someone voted "No Action Needed" on. Such posts automatically become audit candidates anyway, and currently register as an audit failure if someone votes this way after they are destroyed.
I can see placing a statute of limitations on this, such as only applying to reviews in the last 30 days or so. I don't ban reviewers I find who approved spam months ago (usually because they've been banned at least once in the interim).
I believe a system like this would help to identify and limit the damage of those who are letting spam slip through review without hitting attentive reviewers.


text:
Q: Password auth failed for user "postgres" I am trying to run my postgres server and nestjs project with docker script and it does fire up the server and database. While firing up it does run migrations too but when I open pgAdmin I see no database there and if i try to create new server i get fatal pasword incorrect error. Also my server crashes too with error saying Password authentication failed for user "postgres". It was running fine yesterday but today its not running at all. I tried pruning everything and made fresh build and then compose up but nothing. Here is docker script
version: "3.5"
services:
    dev-api:
        container_name: xxxxxxxx-api
        build:
          context: .
          dockerfile: Dockerfile
        depends_on:
          - dev-db
        environment:
          DATABASE_URL: postgresql://postgres:postgres@dev-db:5432/xxxxxxx_api
          APP_ENV: development
          PORT: 3030
          WAIT_HOSTS: dev-db:5432
        ports:
          - "3030:3030"
          - "9229:9229"
        volumes:
          - .:/usr/api/
    dev-db:
      container_name: xxxxxxxx-postgres
      image: postgres:13.5-alpine
      restart: always
      ports:
        - "5432:5432"
      volumes:
        - ./pg-data:/var/lib/postgresql/data
        - ./src/db/docker/init.sql:/docker-entrypoint-initdb.d/dbinit.sql
      environment:
        - POSTGRES_USER=postgres
        - POSTGRES_PASSWORD=postgres
        - POSTGRES_DB=xxxxxxx_api
      expose:
        - "5432"
    pgadmin:
      container_name: xxxxxxx-pgadmin
      image: dpage/pgadmin4:6.2
      ports:
        - 8080:80
      volumes:
        - pgadmin-data:/var/lib/pgadmin
      environment:
        - PGADMIN_DEFAULT_EMAIL=user@postgres.com
        - PGADMIN_DEFAULT_PASSWORD=postgres
        - PGADMIN_LISTEN_PORT=80
      depends_on:
        - dev-db
volumes:
  pgadmin-data:


text:
Q: show ProgressDialog onActivityResult I have two activities the first one load url(simple webview) and the second one get the id for url from listview then call back the first activity to load the url.
I'm use onActivityResult() method in the first activity to get the extra data(url id).
My problem is when I want to show the ProgressDialog in the first Activity in method onActivityResult() after choose item from ListView in second activity I got a ProgressDialog but it just shows for seconds (very quickly) then disappear before complete the load for url(WebView)
This is the code for the tow activities I hope help me.
public class LibActivity extends Activity {

private ImageButton btnCategoriesList;

public static final int BOOK_CATEGORY_REQUEST_CODE = 1;

private WebView webView;

public ProgressDialog dialog;
private Handler handler;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.lib);

    handler = new Handler();
    dialog = ProgressDialog.show(this, "Loading", "Please wait", true, false);

    DisplayMetrics displaymetrics = new DisplayMetrics();

    webView = (WebView) findViewById(R.id.categoryWebView);
    webView.setWebViewClient(new CategoryItemWebViewClient());
    webView.getSettings().setJavaScriptEnabled(true);
    webView.loadUrl("http://maktabati.mobi/V3/store.php?catid=" + "91");

    btnCategoriesList = (ImageButton) findViewById(R.id.btn_category_list);

    btnCategoriesList.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            showBooksCategories();
        }
    });
}

/**
 *
 */
protected void showBooksCategories() {
    Intent intent = new Intent(getApplicationContext(), BooksCategoriesActivity.class);
    startActivityForResult(intent, BOOK_CATEGORY_REQUEST_CODE);
}

/**
 *
 * @author Jamil
 *
 */
private class CategoryItemWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url.contains("book")) {
            String bookId = url.substring(12);
            Intent intent = new Intent(getApplicationContext(), BookDetailActivity.class);
            intent.putExtra("BOOK_ID", bookId);
            startActivity(intent);
            view.stopLoading();
        }
        return super.shouldOverrideUrlLoading(view, url);
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        dialog.dismiss();
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
    if (requestCode == BOOK_CATEGORY_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            dialog = ProgressDialog.show(this, "Loading", "Please wait", true);
            new Thread() {
                public void run() {
                    webView.loadUrl("http://maktabati.mobi/V3/store.php?catid=" + data.getStringExtra("CATEGORY_ID"));
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            dialog.dismiss();
                        }
                    });
                }
            }.start();

        }
    }
    super.onActivityResult(requestCode, resultCode, data);
}

the second activity
public class BooksCategoriesActivity extends Activity {

ItemsCategoriesAdapter adapter;
ArrayList<Category> lstCategory;
Handler handlerProgressDialog;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.books_categories_list);
    handlerProgressDialog = new Handler();
    CategoryHandler handler = new CategoryHandler();
    ParserCreater parserCreater = new ParserCreater(handler);
    parserCreater.parse("http://maktabati.mobi/V3/getCategories.php");
    lstCategory = handler.getLstCategory();
    final ListView listView = (ListView) findViewById(R.id.categories_list);
    adapter = new ItemsCategoriesAdapter(lstCategory);
    listView.setAdapter(adapter);
    listView.setTextFilterEnabled(true);

    listView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, final int position, long arg3) {
            Intent intent = new Intent(getApplicationContext(), LibActivity.class);
            intent.putExtra("CATEGORY_ID", lstCategory.get(position).getId());
            BooksCategoriesActivity.this.setResult(RESULT_OK, intent);
            finish();
        }
    });
}

Thanks

A: Please try what happens if you remove the following code from the onActivityResult function:
handler.post(new Runnable() {
                        @Override
                        public void run() {
                            dialog.dismiss();
                        }
                    });

The onPageFinished() function should be called after webView.loadUrl().

A: The method loadUrl() is not a blocking call, so you don't need to call it from a background thread.  If you want to capture the point at which the page is finished loading, you can set a WebviewClient object on your WebView to handle a series of callbacks in this regard.
Also, since that call does not block, it returns immediately and your dismiss() method is called almost as soon as show(), which is why you see it display only briefly.
HTH


text:
Q: R - remove everything after @ from the column
I would like to remove everything in the first column after the @. I tried all kinds of gsub functions but nothing seems to work. I have been able to get it to work for 1 string but there are 1.7k more.

A: A tidyverse solution based on a look around can be implemented as follows.
library(dplyr)
library(stringr)

data <- tibble(STATESC = c('Illinois@Cook County', 'New York@Kings County'),
               TOT_FEMALE = c(261508, 253696))

data %>%
  mutate(STATESC = str_remove(STATESC, '(?<=@).*'))

#   STATESC   TOT_FEMALE
#   <chr>          <dbl>
# 1 Illinois@     261508
# 2 New York@     253696


text:
Q: Django Model with math Hey i have a problem with my django model.
i have one class like this:
class Test(model.Models):
    EV_Nr = models.IntegerField(unique=True)
    Factor = models.DecimalField(max_digits=5, decimal_places=2, blank=False)

class Polter(models.Model):
    EV = models.ForeignKey(Test)
    RM = models.DecimalField(max_digits=10, decimal_places=2, default=0)
    FM = models.DecimalField(max_digits=10, decimal_places=2, default=0)

My Problem:

*

*RM or FM has to be 0, if both >0, it's an error and can not be saved.

*but for example: RM = 10 and FM = 0. It's ok.
-> and the model has to check for the Factor in my Test Model and to do the
 following: FM = RM / Faktor(from Test Model) and save it in my databese.
How can i do this. After two days of searching I have no idea.
Thanks for your help


text:
Q: Lazy computed properties in Immutable.js Records? Is there a standard way to define lazy computed properties on Records? When I access the computed property, it should run a function to compute the value, then cache the value. For example, something like:
const UserRecord = Record({
  firstName: '',
  lastName: '',
  get fullName() {
    console.log('Ran computation');
    return `${this.firstName} ${this.lastName}`;
  },
});

const user = new UserRecord({ firstName: 'Mark', lastName: 'Zuck' });
console.log(user.fullName); // Ran computation\nMark Zuck
console.log(user.fullName); // Mark Zuck

The closest I can get is defining a getFullName() method, then manually memoizing the computed value. I.e.:
getFullName() {
  if (!this._fullName) {
    this._fullName = `${this.firstName} ${this.lastName}`;
  }
  return this._fullName;
}

A: As long as you don't need it to ever "re-compute" this should do it I think.
const UserRecord = Record({
  firstName: '',
  lastName: '',
  get fullName() {
    console.log('Ran computation');

    var value = `${this.firstName} ${this.lastName}`;

    delete this.fullName;

    Object.defineProperty(this, 'fullName', {
        value: value
    });

    return value;
  },
});

const user = new UserRecord({ firstName: 'Mark', lastName: 'Zuck' });
console.log(user.fullName); // Ran computation\nMark Zuck
console.log(user.fullName); // Mark Zuck


text:
Q: Access Split DB: Does each user need a separate FE file to run, or can they share a FE file on the network? I have read in a few places that each user needs to have their own front-end file when using an access split DB.  Is this true?  If I place a single copy of the front end on the network, and allow each user to open a local instance of that file, will it create conflicts?  Do I really need to put 10 copies of the same file on the network and let each user open his/her own copy?  I am having trouble believing that, though I have seen it mentioned a few times on the web (unless I misinterpreted). Thanks guys!

A: Running the FE over a network connection will add more bandwidth clutter, too.  You really must deploy the FE to each workstation for the best user experience.
The way we handle it with our current project is to have a copy of the FE on the server that each user downloads.  There's a 'local' version number baked in to the FE app, and a 'latest' version on the BE.  If there's a mismatch detected due to a new version of the FE being deployed, a VB script will download the latest version and replace the one currently on the User's PC (using a batch file).  It's set to do this version check when it first starts up and then periodically while the app is running (with an ability to opt-out if the User's in the middle of some work).


text:
Q: Unable to stop / restart iptables Im really struggling with this issue of iptables refusing to stop / restart.
When i try to stop it it will output this message:
xgsv01:/# service iptables stop
iptables v1.4.8: Couldn't load match `-tcp':/lib/xtables/libipt_-tcp.so: cannot open shared object file: No such file or directory

Try `iptables -h' or 'iptables --help' for more information.
iptables v1.4.8: Couldn't load match `-tcp':/lib/xtables/libipt_-tcp.so: cannot open shared object file: No such file or directory

Try `iptables -h' or 'iptables --help' for more information.
Iptables firewall is up 'date'.
xgsv01:/#

I have researched many other users had a similar problems and they were related to once of the rulesin the chains having incorrectly specified tcp parameter but this seems to be not the case.
These are my rules:
xgsv01:/# iptables -t filter -S
-P INPUT DROP
-P FORWARD DROP
-P OUTPUT ACCEPT
-N LOGGING
-N fail2ban-ssh
-A INPUT -i lo -j ACCEPT
-A INPUT -i eth0 -p tcp -m tcp --dport 23700 -j ACCEPT
-A INPUT -i eth0 -p tcp -m tcp --dport 23600 -j ACCEPT
-A INPUT -i eth0 -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -i eth0 -p tcp -m tcp --dport 23500 -j ACCEPT
-A INPUT -i eth0 -p tcp -m tcp --dport 3784 -j ACCEPT
-A INPUT -i eth0 -p udp -m udp --dport 3784 -j ACCEPT
-A INPUT -m state --state RELATED,ESTABLISHED -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A INPUT -i eth1 -p tcp -m tcp --dport 23600 -j ACCEPT
-A INPUT -i eth0 -p tcp -m tcp --dport 110 -j ACCEPT
-A INPUT -i eth0 -p tcp -m tcp --dport 143 -j ACCEPT
-A INPUT -i tun+ -j ACCEPT
-A INPUT -i tap+ -j ACCEPT
xgsv01:/#

I was searching if i have somewhere specified '-tcp' but without luck. The other thing is i guess iptables should reference /lib/xtables/libipt_tcp.so and i am missing this shared library as well...
xgsv01:/lib/xtables# find libipt_tcp.so
find: `libipt_tcp.so': No such file or directory
xgsv01:/lib/xtables#

Could you please somebody give me an advice or any other help? Im not an experienced Linux user - just some basics.
iptables version 1.4.8
    Linux version 2.6.32-5-686 (Debian 2.6.32-46) (dannf@debian.org) (gcc version 4.3.5 (Debian 4.3.5-4) ) #1 SMP Sun Sep 23 09:49:36 UTC 2012
Other rules:
xgsv01:/# iptables -t nat -S
-P PREROUTING ACCEPT
-P POSTROUTING ACCEPT
-P OUTPUT ACCEPT
-A PREROUTING -s 147.175.0.0/16 -p tcp -m tcp --dport 22 -j DNAT --to-destination 92.240.237.87:23600
xgsv01:/# man iptables
xgsv01:/# iptables -t mangle -S
-P PREROUTING ACCEPT
-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-P POSTROUTING ACCEPT
xgsv01:/# iptables -t raw -S
-P PREROUTING ACCEPT
-P OUTPUT ACCEPT

A: Can you try to remove all your iptables config and apply the default ones?
Will you be able to restart iptables service gracefully then?
Take a look here for few iptables how-to's, it may help too.


text:
Q: How to use form authentication without aspnetdb? I am developing a small website which will be part of a big website. It won't have its own authentication and database but I want to use form authentication with it. I put in few lines in web.config
<authentication mode="Forms">
  <forms loginUrl="Login.aspx" timeout="2880" defaultUrl="Default.aspx" />
</authentication>
<authorization>
    <deny users="?"/>
</authorization>

In the code, what do I need to have in that ???????? place? At the moment, it will just stay at the login page and doesn't not redirect to Default page. Btw, Login page is not really a login page it's just a page that will be called from the big website and check if the user is authorized or not.
If everything is fine Then

                ?????????????????
                FormsAuthentication.SetAuthCookie("UserName", True)
                FormsAuthentication.RedirectFromLoginPage("UserName", True)

 Else
         'show error

 End If

A: I am not sure how good my code is but it does work for now ...
Protected Sub DoLogin()

    Dim authCookie As HttpCookie = FormsAuthentication.GetAuthCookie(UserName, False)
    Dim ticket As FormsAuthenticationTicket = FormsAuthentication.Decrypt(authCookie.Value)
    Dim newTicket As New FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, "")
    authCookie.Value = FormsAuthentication.Encrypt(newTicket)
    Response.Cookies.Add(authCookie)
    Response.Redirect("Default.aspx", False)

End Sub


text:
Q: How to reset React Navigation to initial default state (the state that the app opens)? I'm trying to reset the navigation state to default state (whatever is when the app is first opened without any actions) upon user logout.
How do I achieve that?
I've seen Reset stack after navigate to login screen yet it still specifies a route and I don't know what to put there. I've tried providing undefined yet got an error.
How can I make React Navigation to just purge everything and act as if the app opened? I'm looking for something like StackActions.reset({}) (pseudocode, doesn't work) that is empty, and trigger whatever React Navigation does on app start.

A: You can use conditional routes, as suggested in the documents for authentication flow
like below
isSignedIn ? (
  <>
    <Stack.Screen name="Home" component={HomeScreen} />
    <Stack.Screen name="Profile" component={ProfileScreen} />
    <Stack.Screen name="Settings" component={SettingsScreen} />
  </>
) : (
  <>
    <Stack.Screen name="SignIn" component={SignInScreen} />
    <Stack.Screen name="SignUp" component={SignUpScreen} />
  </>
);

And the isSignedIn can be handled by Context Api or redux


text:
Q: C# why null after casting Hi everyone pleas help me i so confused why my code has a null after casting
this is the xaml code i have
<Window.Resources>
    <Style x:Key="Menu" TargetType="{x:Type Border}">
        <Setter Property="BorderThickness" Value="0" />
        <Setter Property="Background" Value="Transparent" />
        <Setter Property="Width" Value="25" />
        <EventSetter Event="MouseLeftButtonUp" Handler="Menu_MouseLeftButtonUp" />
    </Style>
</Window.Resources>

<Grid>
    <Border Name="BorderCloseWindow" CornerRadius="0,8,0,0"
            Style="{StaticResource Menu}">
        <Image Source="pack://application:,,,/images/icons/CloseSTD.png" />
    </Border>
</Grid>

and this the C# that handle the border
private void Menu_MouseLeftButtonUp(object sender, RoutedEventArgs e)
{
    Border b = e.Source as Border;
    if (b.Name == "BorderCloseWindow")
    {
        this.Close();
    }
}

and if i mouse button down in the border that will give error like this
Object reference not set to an instance of an object.
that happen in
if(b.Name == "BorderCloseWindow")

please help me why that give null? and how to repair my program so can run.

A: Probably sender will be Border, try to cast sender as Border first:
  Border b = sender as Border;

If it will not help, just set breakpoint within handler, than open watch window and you will see actual types of sender and e.Source.

A: First, that's how as behaves when the cast doesn't succeed. It is made this way so that you can easily check whether it did or not. If you wrote
Border b = (Border)e.Source;

it would throw InvalidCastException.
Second, e.Source contains the object that you actually clicked on, in this case, the Image. If you want to access the objects that is handling the event, use the sender parameter.
So your code should look like this:
private void Menu_MouseLeftButtonUp(object sender, RoutedEventArgs e)
{
    Border b = (Border)sender;
    if (b.Name == "BorderCloseWindow")
    {
        this.Close();
    }
}

Or even better, just
private void Menu_MouseLeftButtonUp(object sender, RoutedEventArgs e)
{
    this.Close();
}

This would work if set different handler method for each Control you want to handle some event for. It is much less fragile: it will still work if you change the name of the Border (you don't even need to have it named) and if you accidentally change the name of the method either in XAML or C#, you most likely get a compile-time error.

A: It appears e.Source is not a Border so e.Source as Border is null.
Source may be another object inside the border, with the event routed to the border.
you can try to test the type of e.Source with
if (e.Source is Border)
{
}

or you could get your border object by casting sender instead of e.Source.

A: Apparently, e.Source is not of type Border.
The first thing you should fix is your cast. You are using
Border b = e.Source as Border;

which returns null if e.Source is not a Border, leading to a subsequent NullReferenceException. Since you are not checking for null afterwards, you should use a normal cast:
Border b = (Border)e.Source;

This won't fix your underlying problem, but it will make sure that

*

*you get the correct exception for the underlying problem (an InvalidCastException rather than a NullReferenceException) and

*the error is thrown in the line that is really the cause of the problem (rather than the following if, which is entirely innocent).

Now the second thing, the source of your problem: RoutedEventsArgs.Source is not the border that you attached your event handler to (i.e., it's not the control handling the event). It's the control that raised the event, which is probably the image inside the border. See the documentation of RoutedEventArgs.Source for details.
Thus, to fix this problem, use the sender instead of e.Source:
Border b = (Border)sender;

A: Change your code to look like this:
private void Menu_MouseLeftButtonUp(object sender, RoutedEventArgs e)
{
  System.Diagnostics.Debug.WriteLine(
    "Sender contains an object of type {0}",
    sender.GetType());
  System.Diagnostics.Debug.WriteLine(
    "e.Source contains an object of type {0}",
    e.Source.GetType());
}

When you trigger the event, the information you need will be written to the Output Window. You may need to make this visible using the View menu of Visual Studio. Then you will be able to see what is going on and sort it out yourself.

A: e.Source is an object of type image.
So you need to cast the sender as Border.
Border b = sender as Border;


text:
Q: How to see if object is behind a wall and if it's in field of view? I made this code to see if it's in FOV and it works but if I'm far and if I'm on his side the number returned is greater than 0 and that means I'm front of him when I am not.
Vector3 objectNormalized = Vector3.Normalize(transform.position);
Vector3 targetNormalized = Vector3.Normalize(target.position);
Vector3 forward = transform.TransformDirection(transform.forward);
Vector3 pos = targetNormalized - objectNormalized;

Also, how can I see if it's behind a wall or another object? I'm coding an AI so I really need this.

A: For detecting if no collider is between you and the object do a physics raycast from your camera to the objects center and check if RaycastHit.collider.gameObject is the object you raycasted to. Depending on your use case you might want to try a few raycasts to different parts of the model.
As for being in the field of view, you have procedural TestPlanesAABB or event-based OnBecameVisible and OnBecameInvisible. If you decide on using TestPlanesAABB, remember to update the plane array on camera movement, not just start as in the example.


text:
Q: Pandas DataFrame Please seniors, I have dataframes with four columns. I want to add another column, but kept getting error. I have tried to use df["] = dkdkdkddk. This doesn't work. Below is the code.
How else can I add the column please
def eval_func(chromosome):
F = chromosome.getCompiledCode()
fit = []
for version in range(len(numberOfversion)):
    spectrum = FaultVersionsDict[str(numberOfversion[version])]
    EP = spectrum[:, 0]
    EF = spectrum[:, 1]
    NP = spectrum[:, 2]
    NF = spectrum[:, 3]
    spectrum[:, 4] = (EF+NP)/(EP+EF+NP+NF) #This is generating error. please help

Sequel to the first comment, I am updating the post.
The sample of the current dataframe is like
EP EF NP NF
30 40 10 20
20 40 20 20`
.`
.
.`
.
60 10 20 10

This is a csv files and I have up to 200 csv files all together.
I just want to create another column after NF to make it the fifth column. The problem is that I have tried all the ways to add new columns, but kept getting error.
The error is always IndexError: index 4 is out of bounds for axis 1 with size 4

A: Build the sample DF:
import pandas as pd

EP = [30, 20, 60]
EF = [40, 40, 10]
NP = [10, 20, 20]
NF = [20, 20, 10]
spectrum = pd.DataFrame(EP, columns=["EP"])
spectrum['EF'] = EF
spectrum['NP'] = NP
spectrum['NF'] = NF

after that, you can simply do that (without the loop):
spectrum['Calculation'] = (spectrum.EF+spectrum.NP)/(spectrum.EP+spectrum.EF+spectrum.NP+spectrum.NF)


text:
Q: is my MYSQL injection statement vulnerable? I believe this statement is vulnerable for injection, but am unsure.
Any help in this regard?
Thanks.
function CheckUserLogin($userName,$password)
{
    $sql="SELECT user_id
         FROM users
         WHERE user_name='".addslashes($userName)."' AND password ='".addslashes($password)."'";
    $this->query($sql);
    if($this->movenext()>0)
    {
        return $this->col['user_id'];
    }
    else
    {
        return false;
    }
}

The query function is as such
function query($_query){
    list($usec, $sec) = explode(" ",microtime());
    $time_start  = ((float)$usec + (float)$sec);

    $this->query = $_query;
    $this->result = @mysql_query($_query, $this->link_id) or die("error in sql query

".$_query."
.mysql error : ".mysql_error($this->link_id)."
");

    list($usec, $sec) = explode(" ",microtime());
    $time_end  =  ((float)$usec + (float)$sec);
    $time = $time_end - $time_start;
}

A: This is what the docs on addslashes say:

Please note that use of addslashes() for database parameter escaping can be cause of security issues on most databases.

The same article has:

To escape database parameters, DBMS specific escape function (e.g. mysqli_real_escape_string() for MySQL or pg_escape_literal(), pg_escape_string() for PostgreSQL) should be used for security reasons.

However, the best way to use parameters in SQL statements is by using prepared statements. There the parameter values are never injected into the SQL statement, and so there cannot be malicious injection either. Instead the database engine uses the parameter values directly (and as literals) to execute the already compiled query.
Please read How can I prevent SQL injection in PHP: it has lots of information about this subject.

A: Here are some example given about Injection and how to make query injection free.
And Also Here


text:
Q: Editing com.apple.atrun.plist on El Capitan I am running El Capitan on several computers and would like to be able to use at to run scheduled jobs in the background.  Enabling at requires editing /System/Library/LaunchDaemon/com.apple.atrun.plist.  Any way I have tried to do this, I have run into a permissions problem: using sudo, logging in as root or trying to change the permissions from the file information panel all result on a permissions error of some sort.
I have tried:

*

*sudo vi /System/Library/LaunchDaemon/com.apple.atrun.plist and not been able to save the edited file.

*Copying to file, editing it and copying back - I am not allowed to copy back using sudo.

*Using Xcode to edited the fiel through a GUI, cannot save.

*using Property List Editor, cannot save, even logged in as root.

*Changing owner, group is not allowed, even using sudo or logged in a root.

*Changing permissions of all the subdirectories in the tree above (System, System/Library, etc.) used sudo, also tried changed disk permissions.

*Run disk utility.

There must be some way of doing this, please advise.

A: The file com.apple.atrun.plist is protected by System Integrity Protection.
So boot to the Recovery HD partition (hold down Command + R while restarting), disable SIP and modify the item:

*

*In the menubar open Utilities->Terminal

*Enter csrutil disable

*Reboot to your main volume and edit the file

*Reboot into the Recovery Partition again

*Enable SIP again csrutil enable

*Reboot to your main volume

A: Using 10.11.6 (El Capitan) I was able to get atrun to run following the instructions found in the article "Using at for command scheduling under Mac OS X".
To enable atrun, execute,
sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.atrun.plist
To disable atrun, execute,
sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.atrun.plist
The article has additional useful information about atrun and at commands.


text:
Q: Need advise for DataStructure like Tuple or keyValuePair but mutable type I need a type like a Tuple or KeyValuePair type and with option to sets its values (mutable type).
Any ideas of existing generics that would fulfill these needs?
(Dictionary seems to me to be some kind of overkill for my purpose)
I can write my own class as well, but I was hoping that there is some mutable type of KeyValuePair already implemented.

A: The problem with having a mutable is that you can very easily end up referencing the same tuple multiple times where you change the value in one place it will also change in other places where you don't expect it to. So if you do use mutable tubles you will have to be very stringent about cloning the tuple at the appropriate places, for example if you put it into a collection.
But a mutable tuple would look something like this:
public class MutableTuple<T1, T2> {
    public T1 Item1 { get; set; }
    public T2 Item2 { get; set; }

    public MutableTuple(T1 item1, T2 item2) {
        Item1 = item1;
        Item2 = item2;
    }
}

A: public class MutableKeyValuePair<TKey, TValue>
{
    public TKey Key { get; set; }
    public TValue Value { get; set; }
}

That's it.

A: No, there isn't. Unless you consider object[] to be one :-)
Note that implementing a MutableTuple<T1, ...> is quite easy.
A full implementation of a MutableTuple<T1, T2, T3>, nearly equivalent to a Tuple<T1, T2, T3> (the various interfaces are implemented publicly and not privately) (partially based on the Mono implementation of Tuple<>)
public static class MutableTuple
{
    public static MutableTuple<T1, T2, T3> Create<T1, T2, T3>(T1 item1, T2 item2, T3 item3)
    {
        return new MutableTuple<T1, T2, T3>(item1, item2, item3);
    }
}

[Serializable]
public class MutableTuple<T1, T2, T3> : IComparable, IStructuralEquatable, IStructuralComparable
{
    public T1 Item1 { get; set; }
    public T2 Item2 { get; set; }
    public T3 Item3 { get; set; }

    public MutableTuple(T1 item1, T2 item2, T3 item3)
    {
        this.Item1 = item1;
        this.Item2 = item2;
        this.Item3 = item3;
    }

    public override bool Equals(object obj)
    {
        return this.Equals(obj, EqualityComparer<object>.Default);
    }

    public override int GetHashCode()
    {
        return this.GetHashCode(EqualityComparer<object>.Default);
    }

    public override string ToString()
    {
        var sb = new StringBuilder();

        sb.Append(this.Item1);
        sb.Append(", ");
        sb.Append(this.Item2);
        sb.Append(", ");
        sb.Append(this.Item3);
        sb.Append(")");

        return sb.ToString();
    }

    public int CompareTo(object obj)
    {
        return this.CompareTo(obj, Comparer<object>.Default);
    }

    public bool Equals(object obj, IEqualityComparer comparer)
    {
        if (obj == null)
        {
            return false;
        }

        var tuple = obj as MutableTuple<T1, T2, T3>;
        return tuple != null && (comparer.Equals(this.Item1, tuple.Item1) && comparer.Equals(this.Item2, tuple.Item2)) && comparer.Equals(this.Item3, tuple.Item3);
    }

    public int GetHashCode(IEqualityComparer comparer)
    {
        unchecked
        {
            int hash = 17;

            hash = (hash * 23) + comparer.GetHashCode(this.Item1);
            hash = (hash * 23) + comparer.GetHashCode(this.Item2);
            hash = (hash * 23) + comparer.GetHashCode(this.Item3);

            return hash;
        }
    }

    public int CompareTo(object obj, IComparer comparer)
    {
        if (obj == null)
        {
            return 1;
        }

        var other = obj as MutableTuple<T1, T2, T3>;

        if (other == null)
        {
            throw new ArgumentException();
        }

        int res = comparer.Compare(this.Item1, other.Item1);

        if (res != 0)
        {
            return res;
        }

        res = comparer.Compare(this.Item2, other.Item2);

        if (res != 0)
        {
            return res;
        }

        res = comparer.Compare(this.Item3, other.Item3);

        return res;
    }
}


text:
Q: how to show elements when button was clicked in JavaScript I tried to create codes which elements are showed when button was clicked, it actually could make them shows but I want to them to show separately on each button, (I want to hide other elements when other button was clicked), where do I need to fix?

function button1() {
  'use strict';
 document.getElementById("red1"). className = "red1" ;
 document.getElementById("blue1"). className = "blue1" ;
}

function button2(){
  'use strict';
  document.getElementById("red2"). className = "red2" ;
  document.getElementById("blue2"). className = "blue2" ;
}

function button3(){
  'use strict';
  document.getElementById("red3"). className = "red3" ;
  document.getElementById("blue3"). className = "blue3" ;
}

function button4(){
  'use strict';
  document.getElementById("red4"). className = "red4" ;
  document.getElementById("blue4"). className = "blue4" ;
}

function button5(){
  'use strict';
  document.getElementById("red5"). className = "red5" ;
  document.getElementById("blue5"). className = "blue5" ;
}

function button6(){
  'use strict';
  document.getElementById("green6"). className = "green6" ;
  document.getElementById("red6"). className = "red6" ;
  document.getElementById("blue6"). className = "blue6" ;
}

function init(){
  'use strict';
  document.getElementById("btn1").addEventListener("click",button1);
  document.getElementById('btn2').addEventListener('click',button2);
  document.getElementById('btn3').addEventListener('click',button3);
  document.getElementById('btn4').addEventListener('click',button4);
  document.getElementById('btn5').addEventListener('click',button5);
  document.getElementById('btn6').addEventListener('click',button6);
}

window.onload = init;
.hidden{
  display: none;
}

.red1{
  width: 600px;
  height: 600px;
  background-color: red;
}

.blue1{
  width: 300px;
  height: 300px;
  background-color: blue;
  margin-top: -600px;
}

.red2{
  width: 600px;
  height: 600px;
  background-color: red;
}

.blue2{
  width: 300px;
  height: 300px;
  background-color: blue;
}

.red3{
  width: 600px;
  height: 600px;
  background-color: red;
}

.blue3{
  width: 300px;
  height: 300px;
  background-color: blue;
  margin-left:600px;
  margin-top: -600px;
}

.red4{
  width: 600px;
  height: 600px;
  background-color: red;
  margin-left: 300px;

}

.blue4{
  width: 300px;
  height: 300px;
  background-color: blue;
  position: absolute;
  margin-top: -400px;
}

.red5{
  width: 600px;
  height: 600px;
  background-color: red;
  position: absolute;
  z-index: 10;
}

.blue5{
  width: 300px;
  height: 300px;
  background-color: blue;
  margin-top:36px;
  margin-left: 45px;
  position: absolute;
  z-index: 40;
}

.red6{
  width: 600px;
  height: 600px;
  background-color: red;
  position: absolute;
  z-index: 20;

}

.blue6{
  width: 300px;
  height: 300px;
  background-color: blue;
  z-index: 100;
  position: absolute;

}

.green6{
  width: 900px;
  height: 700px;
  background-color: green;
  margin-top: 0;
  z-index: 10;
  position: absolute;

}
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta charset="utf-8">
    <title>2 Boxes</title>
    <link rel="stylesheet" type="text/css" href="css/stylesheet.css">

Boxes

  <form id="myForm">
    <fieldset>
      Blue box sits inside the red box
      <button type="button" id="btn1">Click</button>
    </fieldset>
    <fieldset>
      Blue box sits under the red box
      <button type="button" id="btn2">Click</button>
    </fieldset>
    <fieldset>
      Blue box sits to the right of the red box
      <button type="button" id="btn3">Click</button>
    </fieldset>
    <fieldset>
      Red box sits to the right of the blue box
      <button type="button" id="btn4">Click</button>
    </fieldset>
    <fieldset>
      Blue box sits inside the red box and move the blue box 20px down and 45 pixels to the right of the top left hand corner of the red box
      <button type="button" id="btn5">Click</button>
    </fieldset>
    <fieldset>
      Green box around both the blue and red boxes
      <button type="button" id="btn6">Click</button>
    </fieldset>
  </form>

A: I would prefer to write an additional function, which is hiding all elements and call this function at the begining of your other functions. Example:
function hideAll() {
 document.getElementById("red1").className = "hidden" ;
 document.getElementById("blue1").className = "hidden" ;
 ...
}

Call the function in other functions. Example:
function button1() {
 hideAll();
 document.getElementById("red1").className = "red1" ;
 document.getElementById("blue1").className = "blue1" ;
}

Now you also have to adapt your other CSS rules in order to remove the display: none as follows:
.red1{
  width: 600px;
  height: 600px;
  background-color: red;
  display: block;
}

.blue1{
  width: 300px;
  height: 300px;
  background-color: blue;
  margin-top: -600px;
  display: block;
}
 ...

Bare in mind, that this way of programming is very inefficient and there are many ways to refactor this code in order to be more readable and adaptable.


text:
Q: ResponseFormat returns 0 byte I want to make a REST web service with JSON return format. actually it is working for a simple string return type, but when I have a custom type as the return value I receive 0 byte.
if I change the ResponseFormat to XML, it works fine
thanks for any help!
EDIT - adding sample
interface:
[WebGet(UriTemplate="WebGetTry/{param1}/{param2}", ResponseFormat=WebMessageFormat.Json)]
WebGetType WebGetTry(string param1, string param2);

implement:
public WebGetType WebGetTry(string param1, string param2) {
  return new WebGetType();
}

after that my test is simple calling the address from IE. returning Page Cannot be displayed error

A: You need to specify the implementation of your JSON endpoint. please check your web.config and add this:
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
    <standardEndpoints>
        <webHttpEndpoint>
<standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="false" defaultOutgoingResponseFormat="Json"/>
  </webHttpEndpoint>
</standardEndpoints>


text:
Q: Redshift - Printing output of variable I am trying to fetch the count of rows from a table and have it printed it. I am doing it as below:
cursor = db.cursor()
cursor.execute("""SELECT count (*) table limit 30""")
df = cursor.fetchall()

I am trying to print the output of the above as below:
for num in df:
    print(num)

This is returning '1' though the expected output is 30. Could anyone advice as to where am I going wrong. Thanks

A: Since you want to print the value of the first (and only) column in the result set, you should be using this:
cursor = db.cursor()
cursor.execute("""SELECT COUNT(*) AS cnt FROM table LIMIT 30""")
row = cursor.fetchone()
if row is not None:
    print(df["cnt"])

If this still returns a count of 1, then there is another possible explanation.  Your table could coincidentally have just a single record in it.  LIMIT 30 does not mean 30 records always get returned, just that a maximum of 30 records gets returned.
Side note: Using LIMIT without ORDER BY is fairly meaningless.  If you limit, you should generally also sort.