问:
Set Orientation to Picture with AVFoundation in Swift 3
I'm new to Swift and I don't have a lot programming exercise so maybe this problem is simple to solve for you O:-)...

I only need a simple Camera with AVFoundation to capture pictures, no live mode or video recording is needed.
I have a problem with the video orientation and wasn't able to find the answer in the forum by now. I know that many people have this problem, but all I tried did not work and I am not able to solve this problem in my code. I don't really understand how capturing pictures with AVFoundation works and where exactly the picture is taken...

Can you tell me how to set the device image orientation to the picture so that it will be shown with the device orientation when I use the picture in an image view?

Here is my code:

```<code>import UIKit
import AVFoundation
import Photos

class ViewController: UIViewController {

@IBOutlet weak var cameraView: UIView!

@IBOutlet weak var imageProcessedView: UIImageView!
var imageProcessed: UIImage?
let captureSession = AVCaptureSession()
var captureDevice: AVCaptureDevice?
var previewLayer: AVCaptureVideoPreviewLayer?
var stillImageOutput: AVCaptureStillImageOutput = AVCaptureStillImageOutput()

override func viewDidLoad() {
    super.viewDidLoad()
    UIDevice.current.beginGeneratingDeviceOrientationNotifications()

    imageProcessedView.alpha = 1.0
    captureSession.sessionPreset = AVCaptureSessionPresetPhoto
    backCamera()
}

func backCamera()
{
    let devices = AVCaptureDevice.devices()

    for device in devices! {
        if ((device as AnyObject).hasMediaType(AVMediaTypeVideo)){
            captureDevice = device as? AVCaptureDevice
            do {
                try captureSession.addInput(AVCaptureDeviceInput(device: captureDevice))
            } catch {
                print("error")
            }
            break
        }
    }
 }

//Session starts and preview appears:
@IBAction func takePhoto(_ sender: Any) {
    if captureDevice != nil
    {
        imageProcessedView.alpha = 0.0
        previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
        self.cameraView.layer.addSublayer(previewLayer!)
        previewLayer?.frame = self.cameraView.layer.bounds
        previewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
        captureSession.startRunning()
        stillImageOutput.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]

        if captureSession.canAddOutput(stillImageOutput){
            captureSession.addOutput(stillImageOutput)
        }
        }else{
            print("No captureDevice")
        }

}

@IBAction func capturePicture(_ sender: Any) {
    if let videoConnection = stillImageOutput.connection(withMediaType: AVMediaTypeVideo){

        var currentDevice: UIDevice
        currentDevice = .current

        var deviceOrientation: UIDeviceOrientation
        deviceOrientation = currentDevice.orientation

        //variables to set the orientation as parameter like "portrait" and as rawValue like the integer 0 for portrait mode
        var avCaptureOrientation: AVCaptureVideoOrientation
        avCaptureOrientation = .portrait

        var orientationValue: Int
        orientationValue = 0

        if deviceOrientation == .portrait {
            avCaptureOrientation = .portrait
            orientationValue = 0
            print("Device: Portrait")
        }else if (deviceOrientation == .landscapeLeft){
            avCaptureOrientation = .landscapeLeft
            orientationValue = 3
            print("Device: LandscapeLeft")
        }else if (deviceOrientation == .landscapeRight){
            avCaptureOrientation = .landscapeRight
            orientationValue = 2
            print("Device LandscapeRight")
        }else if (deviceOrientation == .portraitUpsideDown){
            avCaptureOrientation = .portraitUpsideDown
            orientationValue = 1
            print("Device PortraitUpsideDown")
        }else{
            print("Unknown Device Orientation")
        }

        stillImageOutput.captureStillImageAsynchronously(from: videoConnection, completionHandler: {(imageDataSampleBuffer, error) in
        let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer)

            let image = UIImage(data: imageData!)
            self.imageProcessed = image!
            //In this print command always "3" appears
            print("Metadata Orientation: \(image!.imageOrientation.rawValue)")
            //in this view the orientation is correct but later when I use the picture to display it in an imageView it is wrong
            self.cameraView.backgroundColor = UIColor(patternImage: image!)

            self.captureSession.stopRunning()
        })
    }
}
</code>```

Thanks a lot!!!

Marina

Ok now I changed my code a little. I can see the correct DeviceOrientation and also the imageOrientation seems to be correct, as it is shown in the print command.

But I still have the problem, that putting the picture is orientated wrong when I put it into the imageView (it is also scaled a way too big).

The function where I want to set the picture into the image view is:

```<code>@IBAction func showCirclesInPic(_ sender: Any) {
    if imageProcessed != nil {
        previewLayer!.removeFromSuperlayer()
        cameraView.addSubview(imageProcessedView)

        if (imageProcessed!.imageOrientation != .up){
            UIGraphicsBeginImageContextWithOptions(imageProcessed!.size, false, imageProcessed!.scale)
            imageProcessed!.draw(in: CGRect(x:0, y:0, width: imageProcessed!.size.width, height: imageProcessed!.size.height))
            imageProcessed = UIGraphicsGetImageFromCurrentImageContext()!
            UIGraphicsEndImageContext()
        }
        imageProcessedView.contentMode = .scaleAspectFit
        imageProcessedView.image = imageProcessed
        //print("ImageProcessed: \(ImageProcessingCV.showCircles(imageProcessed)!)")
    }
}
</code>```

Here is the rest of my changed Code:

```<code>import UIKit
import AVFoundation
import Photos

class ViewController: UIViewController {

@IBOutlet weak var cameraView: UIView!

@IBOutlet weak var imageProcessedView: UIImageView!
var imageProcessed: UIImage?
let captureSession = AVCaptureSession()
var captureDevice: AVCaptureDevice?
var previewLayer: AVCaptureVideoPreviewLayer?
var stillImageOutput: AVCaptureStillImageOutput = AVCaptureStillImageOutput()

override func viewDidLoad() {
    super.viewDidLoad()

    imageProcessedView.alpha = 1.0
    captureSession.sessionPreset = AVCaptureSessionPresetPhoto
    backCamera()
}

func backCamera()
{
    let devices = AVCaptureDevice.devices()

    for device in devices! {
        if ((device as AnyObject).hasMediaType(AVMediaTypeVideo)){
            captureDevice = device as? AVCaptureDevice
            do {
                try captureSession.addInput(AVCaptureDeviceInput(device: captureDevice))
            } catch {
                print("error")
            }
            break
        }
    }
 }

@IBAction func takePhoto(_ sender: Any) {
    if captureDevice != nil
    {
        imageProcessedView.alpha = 0.0
        previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
        self.cameraView.layer.addSublayer(previewLayer!)
        previewLayer?.frame = self.cameraView.layer.bounds
        previewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
        captureSession.startRunning()
        stillImageOutput.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]

        if captureSession.canAddOutput(stillImageOutput){
            captureSession.addOutput(stillImageOutput)
        }
        }else{
            print("No captureDevice")
        }

}

@IBAction func capturePicture(_ sender: Any) {
    if let videoConnection = stillImageOutput.connection(withMediaType: AVMediaTypeVideo){

        var currentDevice: UIDevice
        currentDevice = .current
        UIDevice.current.beginGeneratingDeviceOrientationNotifications()
        var deviceOrientation: UIDeviceOrientation
        deviceOrientation = currentDevice.orientation

        var imageOrientation: UIImageOrientation?

        if deviceOrientation == .portrait {
            imageOrientation = .up
            print("Device: Portrait")
        }else if (deviceOrientation == .landscapeLeft){
            imageOrientation = .left
            print("Device: LandscapeLeft")
        }else if (deviceOrientation == .landscapeRight){
            imageOrientation = .right
            print("Device LandscapeRight")
        }else if (deviceOrientation == .portraitUpsideDown){
            imageOrientation = .down
            print("Device PortraitUpsideDown")
        }else{
            print("Unknown Device Orientation")
        }
        stillImageOutput.captureStillImageAsynchronously(from: videoConnection, completionHandler: {(imageDataSampleBuffer, error) in
            let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer)
            let dataProvider  = CGDataProvider(data: imageData! as CFData)
            let cgImageRef = CGImage(jpegDataProviderSource: dataProvider!, decode: nil, shouldInterpolate: true, intent: CGColorRenderingIntent.defaultIntent )
            self.imageProcessed = UIImage(cgImage: cgImageRef!, scale: 1.0, orientation: imageOrientation!)
            //print("Image Orientation: \(self.imageProcessed?.imageOrientation.rawValue)")
            print("ImageO: \(imageOrientation!.rawValue)")

            self.cameraView.backgroundColor = UIColor(patternImage: self.imageProcessed!)

            self.captureSession.stopRunning()
        })
    }
}

@IBAction func focusAndExposeTap(_ gestureRecognizer: UITapGestureRecognizer) {
    let devicePoint = self.previewLayer?.captureDevicePointOfInterest(for: gestureRecognizer.location(in: gestureRecognizer.view))
    focus(with: .autoFocus, exposureMode: .autoExpose, at: devicePoint!, monitorSubjectAreaChange: true)
}

private func focus(with focusMode: AVCaptureFocusMode, exposureMode: AVCaptureExposureMode, at devicePoint: CGPoint, monitorSubjectAreaChange: Bool)
{
    if let device = captureDevice
    {
        do{
            try device.lockForConfiguration()
            if device.isFocusPointOfInterestSupported && device.isFocusModeSupported(focusMode)
            {
                device.focusPointOfInterest = devicePoint
                device.focusMode = focusMode
            }
            if device.isExposurePointOfInterestSupported && device.isExposureModeSupported(exposureMode)
            {
                device.exposurePointOfInterest = devicePoint
                device.exposureMode = exposureMode
            }
            device.isSubjectAreaChangeMonitoringEnabled = monitorSubjectAreaChange
            device.unlockForConfiguration()
        }catch{
            print("Could not lock device for configuration: \(error)")
        }
    }
}

@IBAction func showCirclesInPic(_ sender: Any) {
    if imageProcessed != nil {
        previewLayer!.removeFromSuperlayer()
        cameraView.addSubview(imageProcessedView)

        if (imageProcessed!.imageOrientation != .up){
            UIGraphicsBeginImageContextWithOptions(imageProcessed!.size, false, imageProcessed!.scale)
            imageProcessed!.draw(in: CGRect(x:0, y:0, width: imageProcessed!.size.width, height: imageProcessed!.size.height))
            imageProcessed = UIGraphicsGetImageFromCurrentImageContext()!
            UIGraphicsEndImageContext()
        }
        imageProcessedView.contentMode = .scaleAspectFit
        imageProcessedView.image = imageProcessed
        //print("ImageProcessed: \(ImageProcessingCV.showCircles(imageProcessed)!)")
    }
}

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

答:
In order to change the orientation of the camera output while taking picture you should add a listener on the orientation changes using NotificationCenter. I will be attaching a sample code for a camera using AVFoundation that you may use.
Please note that the capture and flip camera are added programmatically. Even more, you can set an image for the flip cam(there is a comment to tell you where to set it).

Code Fixed

```<code>//
//  CameraViewController.swift
//  MatchFriend
//
//  Created by Tarek Ezzat Abdallah on 10/1/16.
//  Copyright © 2016 Tarek. All rights reserved.
//

import UIKit
import AVFoundation

class CameraViewController: UIViewController{

    var captureSession: AVCaptureSession?
    var previewLayer : AVCaptureVideoPreviewLayer?
    var stillImageOutput: AVCaptureStillImageOutput?
    var imageToSend: UIImage!
    // If we find a device we'll store it here for later use
    var captureDevice : AVCaptureDevice?

    @IBOutlet weak var cameraView: UIView!
    var captureButton: UIButton!
    var flipCam:UIButton!
    var camPos:String = "back"
    func capture(_ sender: AnyObject)
    {
        if let videoConnection = stillImageOutput?.connection(withMediaType: AVMediaTypeVideo)
        {
            stillImageOutput?.captureStillImageAsynchronously(from: videoConnection)
            {
                (imageDataSampleBuffer, error) -> Void in
                let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer)
                let dataProvider  = CGDataProvider(data: imageData as! CFData)
                let cgImageRef = CGImage(jpegDataProviderSource: dataProvider!, decode: nil, shouldInterpolate: true, intent: CGColorRenderingIntent.defaultIntent )
                let image = UIImage(cgImage: cgImageRef!, scale: 1.0, orientation: UIImageOrientation.right)

            }
        }

    }
    override func viewDidLoad()
    {
        super.viewDidLoad()
        cameraView.backgroundColor = .clear
        self.view.backgroundColor = .clear

        captureButton = UIButton(frame: CGRect(x: 160, y: 580, width: 80, height: 80))
        captureButton.addTarget(self, action: #selector(CameraViewController.capture(_:)), for: UIControlEvents.touchUpInside)
        flipCam = UIButton(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
        flipCam.addTarget(self, action: #selector(CameraViewController.flip), for: UIControlEvents.touchUpInside)
        self.view.addSubview(captureButton)
        self.view.addSubview(flipCam)
        captureButton.backgroundColor = UIColor.red
        NotificationCenter.default.addObserver(self, selector: #selector(CameraViewController.rotated), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)

        //        let backCamera = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
        camStart(camPos)
        setViews()

    }
    func camStart(_ position: String)
    {
        captureSession = AVCaptureSession()
        captureSession?.sessionPreset = AVCaptureSessionPresetHigh

        let videoDevices = AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo)
        var capDevice:AVCaptureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)

        if(position == "back")
        {
            for device in videoDevices!
            {
                let device = device as! AVCaptureDevice
                if device.position == AVCaptureDevicePosition.back
                {
                    capDevice = device
                    break
                }
            }
        }
        else{

            for device in videoDevices!
            {
                let device = device as! AVCaptureDevice
                if device.position == AVCaptureDevicePosition.front
                {
                    capDevice = device
                    break
                }
            }
        }

        //        var error : NSError?
        let input = try? AVCaptureDeviceInput(device: capDevice)

        if (captureSession?.canAddInput(input) != nil){

            captureSession?.addInput(input)

            stillImageOutput = AVCaptureStillImageOutput()
            stillImageOutput?.outputSettings = [AVVideoCodecKey : AVVideoCodecJPEG]

            if (captureSession?.canAddOutput(stillImageOutput) != nil){
                captureSession?.addOutput(stillImageOutput)
                previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
                previewLayer?.videoGravity = AVLayerVideoGravityResizeAspect
                previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.portrait
                previewLayer!.frame = self.view.layer.frame
                previewLayer!.videoGravity = AVLayerVideoGravityResizeAspectFill
                cameraView.layer.addSublayer(previewLayer!)

                captureSession?.startRunning()
            }
        }

    }
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        captureButton.frame = CGRect(x: self.view.frame.width/2 - 40, y: self.view.frame.height - 70 - 40, width: 80, height: 80)
        flipCam.frame = CGRect(x: self.view.frame.width/6 - 40, y: self.view.frame.height - 60 - 40, width: 80, height: 80)
        //add the image to flip camera
        //flipCam.setImage(UIImage(named: "switchCam"), for: UIControlState.normal)
        flipCam.setTitle("flip", for: .normal)

        if previewLayer != nil{
            previewLayer!.frame = self.view.frame
        }

    }
    override func viewWillAppear(_ animated: Bool)
    {
        super.viewWillAppear(true)
        setViews()
    }

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

    func setViews()
    {
        captureButton.layer.cornerRadius = captureButton.layer.bounds.width/2
        captureButton.layer.borderWidth = 1

    }

    func configureDevice()
    {
        let error: NSErrorPointer? = nil
        if let device = captureDevice {
            do {
                try captureDevice!.lockForConfiguration()

            } catch let error1 as NSError
            {
                error??.pointee = error1
            }

            device.focusMode = .locked
            device.unlockForConfiguration()
        }

    }
    func flip()
    {
        captureSession?.stopRunning()
        if camPos == "back"
        {
            camPos = "front"
        }
        else{
            camPos = "back"

        }
        camStart(camPos)

    }
    func rotated() {
        if UIDeviceOrientationIsLandscape(UIDevice.current.orientation) {
            if UIDevice.current.orientation == UIDeviceOrientation.landscapeLeft{
                previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.landscapeRight
            }
            else
            {
                previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.landscapeLeft

            }
        }

        if UIDeviceOrientationIsPortrait(UIDevice.current.orientation) {
            if UIDevice.current.orientation == UIDeviceOrientation.portrait{

                previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.portrait
            }
            else
            {
                previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.portraitUpsideDown

            }
        }

    }
}
</code>```

Body:
I'm new to Swift and I don't have a lot programming exercise so maybe this problem is simple to solve for you O:-)...

I only need a simple Camera with AVFoundation to capture pictures, no live mode or video recording is needed.
I have a problem with the video orientation and wasn't able to find the answer in the forum by now. I know that many people have this problem, but all I tried did not work and I am not able to solve this problem in my code. I don't really understand how capturing pictures with AVFoundation works and where exactly the picture is taken...

Can you tell me how to set the device image orientation to the picture so that it will be shown with the device orientation when I use the picture in an image view?

Here is my code:

import UIKit
import AVFoundation
import Photos

class ViewController: UIViewController {

@IBOutlet weak var cameraView: UIView!

@IBOutlet weak var imageProcessedView: UIImageView!
var imageProcessed: UIImage?
let captureSession = AVCaptureSession()
var captureDevice: AVCaptureDevice?
var previewLayer: AVCaptureVideoPreviewLayer?
var stillImageOutput: AVCaptureStillImageOutput = AVCaptureStillImageOutput()

override func viewDidLoad() {
    super.viewDidLoad()
    UIDevice.current.beginGeneratingDeviceOrientationNotifications()

    imageProcessedView.alpha = 1.0
    captureSession.sessionPreset = AVCaptureSessionPresetPhoto
    backCamera()
}

func backCamera()
{
    let devices = AVCaptureDevice.devices()

    for device in devices! {
        if ((device as AnyObject).hasMediaType(AVMediaTypeVideo)){
            captureDevice = device as? AVCaptureDevice
            do {
                try captureSession.addInput(AVCaptureDeviceInput(device: captureDevice))
            } catch {
                print("error")
            }
            break
        }
    }
 }

//Session starts and preview appears:
@IBAction func takePhoto(_ sender: Any) {
    if captureDevice != nil
    {
        imageProcessedView.alpha = 0.0
        previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
        self.cameraView.layer.addSublayer(previewLayer!)
        previewLayer?.frame = self.cameraView.layer.bounds
        previewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
        captureSession.startRunning()
        stillImageOutput.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]

        if captureSession.canAddOutput(stillImageOutput){
            captureSession.addOutput(stillImageOutput)
        }
        }else{
            print("No captureDevice")
        }

}

@IBAction func capturePicture(_ sender: Any) {
    if let videoConnection = stillImageOutput.connection(withMediaType: AVMediaTypeVideo){

        var currentDevice: UIDevice
        currentDevice = .current

        var deviceOrientation: UIDeviceOrientation
        deviceOrientation = currentDevice.orientation

        //variables to set the orientation as parameter like "portrait" and as rawValue like the integer 0 for portrait mode
        var avCaptureOrientation: AVCaptureVideoOrientation
        avCaptureOrientation = .portrait

        var orientationValue: Int
        orientationValue = 0

        if deviceOrientation == .portrait {
            avCaptureOrientation = .portrait
            orientationValue = 0
            print("Device: Portrait")
        }else if (deviceOrientation == .landscapeLeft){
            avCaptureOrientation = .landscapeLeft
            orientationValue = 3
            print("Device: LandscapeLeft")
        }else if (deviceOrientation == .landscapeRight){
            avCaptureOrientation = .landscapeRight
            orientationValue = 2
            print("Device LandscapeRight")
        }else if (deviceOrientation == .portraitUpsideDown){
            avCaptureOrientation = .portraitUpsideDown
            orientationValue = 1
            print("Device PortraitUpsideDown")
        }else{
            print("Unknown Device Orientation")
        }

        stillImageOutput.captureStillImageAsynchronously(from: videoConnection, completionHandler: {(imageDataSampleBuffer, error) in
        let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer)

            let image = UIImage(data: imageData!)
            self.imageProcessed = image!
            //In this print command always "3" appears
            print("Metadata Orientation: \(image!.imageOrientation.rawValue)")
            //in this view the orientation is correct but later when I use the picture to display it in an imageView it is wrong
            self.cameraView.backgroundColor = UIColor(patternImage: image!)

            self.captureSession.stopRunning()
        })
    }
}

Thanks a lot!!!

Marina

Ok now I changed my code a little. I can see the correct DeviceOrientation and also the imageOrientation seems to be correct, as it is shown in the print command.

But I still have the problem, that putting the picture is orientated wrong when I put it into the imageView (it is also scaled a way too big).

The function where I want to set the picture into the image view is:

@IBAction func showCirclesInPic(_ sender: Any) {
    if imageProcessed != nil {
        previewLayer!.removeFromSuperlayer()
        cameraView.addSubview(imageProcessedView)

        if (imageProcessed!.imageOrientation != .up){
            UIGraphicsBeginImageContextWithOptions(imageProcessed!.size, false, imageProcessed!.scale)
            imageProcessed!.draw(in: CGRect(x:0, y:0, width: imageProcessed!.size.width, height: imageProcessed!.size.height))
            imageProcessed = UIGraphicsGetImageFromCurrentImageContext()!
            UIGraphicsEndImageContext()
        }
        imageProcessedView.contentMode = .scaleAspectFit
        imageProcessedView.image = imageProcessed
        //print("ImageProcessed: \(ImageProcessingCV.showCircles(imageProcessed)!)")
    }
}

Here is the rest of my changed Code:

import UIKit
import AVFoundation
import Photos

class ViewController: UIViewController {

@IBOutlet weak var cameraView: UIView!

@IBOutlet weak var imageProcessedView: UIImageView!
var imageProcessed: UIImage?
let captureSession = AVCaptureSession()
var captureDevice: AVCaptureDevice?
var previewLayer: AVCaptureVideoPreviewLayer?
var stillImageOutput: AVCaptureStillImageOutput = AVCaptureStillImageOutput()

override func viewDidLoad() {
    super.viewDidLoad()

    imageProcessedView.alpha = 1.0
    captureSession.sessionPreset = AVCaptureSessionPresetPhoto
    backCamera()
}

func backCamera()
{
    let devices = AVCaptureDevice.devices()

    for device in devices! {
        if ((device as AnyObject).hasMediaType(AVMediaTypeVideo)){
            captureDevice = device as? AVCaptureDevice
            do {
                try captureSession.addInput(AVCaptureDeviceInput(device: captureDevice))
            } catch {
                print("error")
            }
            break
        }
    }
 }

@IBAction func takePhoto(_ sender: Any) {
    if captureDevice != nil
    {
        imageProcessedView.alpha = 0.0
        previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
        self.cameraView.layer.addSublayer(previewLayer!)
        previewLayer?.frame = self.cameraView.layer.bounds
        previewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
        captureSession.startRunning()
        stillImageOutput.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]

        if captureSession.canAddOutput(stillImageOutput){
            captureSession.addOutput(stillImageOutput)
        }
        }else{
            print("No captureDevice")
        }

}

@IBAction func capturePicture(_ sender: Any) {
    if let videoConnection = stillImageOutput.connection(withMediaType: AVMediaTypeVideo){

        var currentDevice: UIDevice
        currentDevice = .current
        UIDevice.current.beginGeneratingDeviceOrientationNotifications()
        var deviceOrientation: UIDeviceOrientation
        deviceOrientation = currentDevice.orientation

        var imageOrientation: UIImageOrientation?

        if deviceOrientation == .portrait {
            imageOrientation = .up
            print("Device: Portrait")
        }else if (deviceOrientation == .landscapeLeft){
            imageOrientation = .left
            print("Device: LandscapeLeft")
        }else if (deviceOrientation == .landscapeRight){
            imageOrientation = .right
            print("Device LandscapeRight")
        }else if (deviceOrientation == .portraitUpsideDown){
            imageOrientation = .down
            print("Device PortraitUpsideDown")
        }else{
            print("Unknown Device Orientation")
        }
        stillImageOutput.captureStillImageAsynchronously(from: videoConnection, completionHandler: {(imageDataSampleBuffer, error) in
            let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer)
            let dataProvider  = CGDataProvider(data: imageData! as CFData)
            let cgImageRef = CGImage(jpegDataProviderSource: dataProvider!, decode: nil, shouldInterpolate: true, intent: CGColorRenderingIntent.defaultIntent )
            self.imageProcessed = UIImage(cgImage: cgImageRef!, scale: 1.0, orientation: imageOrientation!)
            //print("Image Orientation: \(self.imageProcessed?.imageOrientation.rawValue)")
            print("ImageO: \(imageOrientation!.rawValue)")

            self.cameraView.backgroundColor = UIColor(patternImage: self.imageProcessed!)

            self.captureSession.stopRunning()
        })
    }
}

@IBAction func focusAndExposeTap(_ gestureRecognizer: UITapGestureRecognizer) {
    let devicePoint = self.previewLayer?.captureDevicePointOfInterest(for: gestureRecognizer.location(in: gestureRecognizer.view))
    focus(with: .autoFocus, exposureMode: .autoExpose, at: devicePoint!, monitorSubjectAreaChange: true)
}

private func focus(with focusMode: AVCaptureFocusMode, exposureMode: AVCaptureExposureMode, at devicePoint: CGPoint, monitorSubjectAreaChange: Bool)
{
    if let device = captureDevice
    {
        do{
            try device.lockForConfiguration()
            if device.isFocusPointOfInterestSupported && device.isFocusModeSupported(focusMode)
            {
                device.focusPointOfInterest = devicePoint
                device.focusMode = focusMode
            }
            if device.isExposurePointOfInterestSupported && device.isExposureModeSupported(exposureMode)
            {
                device.exposurePointOfInterest = devicePoint
                device.exposureMode = exposureMode
            }
            device.isSubjectAreaChangeMonitoringEnabled = monitorSubjectAreaChange
            device.unlockForConfiguration()
        }catch{
            print("Could not lock device for configuration: \(error)")
        }
    }
}

@IBAction func showCirclesInPic(_ sender: Any) {
    if imageProcessed != nil {
        previewLayer!.removeFromSuperlayer()
        cameraView.addSubview(imageProcessedView)

        if (imageProcessed!.imageOrientation != .up){
            UIGraphicsBeginImageContextWithOptions(imageProcessed!.size, false, imageProcessed!.scale)
            imageProcessed!.draw(in: CGRect(x:0, y:0, width: imageProcessed!.size.width, height: imageProcessed!.size.height))
            imageProcessed = UIGraphicsGetImageFromCurrentImageContext()!
            UIGraphicsEndImageContext()
        }
        imageProcessedView.contentMode = .scaleAspectFit
        imageProcessedView.image = imageProcessed
        //print("ImageProcessed: \(ImageProcessingCV.showCircles(imageProcessed)!)")
    }
}

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

Body:
In order to change the orientation of the camera output while taking picture you should add a listener on the orientation changes using NotificationCenter. I will be attaching a sample code for a camera using AVFoundation that you may use.
Please note that the capture and flip camera are added programmatically. Even more, you can set an image for the flip cam(there is a comment to tell you where to set it).

Code Fixed

//
//  CameraViewController.swift
//  MatchFriend
//
//  Created by Tarek Ezzat Abdallah on 10/1/16.
//  Copyright © 2016 Tarek. All rights reserved.
//

import UIKit
import AVFoundation

class CameraViewController: UIViewController{

    var captureSession: AVCaptureSession?
    var previewLayer : AVCaptureVideoPreviewLayer?
    var stillImageOutput: AVCaptureStillImageOutput?
    var imageToSend: UIImage!
    // If we find a device we'll store it here for later use
    var captureDevice : AVCaptureDevice?

    @IBOutlet weak var cameraView: UIView!
    var captureButton: UIButton!
    var flipCam:UIButton!
    var camPos:String = "back"
    func capture(_ sender: AnyObject)
    {
        if let videoConnection = stillImageOutput?.connection(withMediaType: AVMediaTypeVideo)
        {
            stillImageOutput?.captureStillImageAsynchronously(from: videoConnection)
            {
                (imageDataSampleBuffer, error) -> Void in
                let imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(imageDataSampleBuffer)
                let dataProvider  = CGDataProvider(data: imageData as! CFData)
                let cgImageRef = CGImage(jpegDataProviderSource: dataProvider!, decode: nil, shouldInterpolate: true, intent: CGColorRenderingIntent.defaultIntent )
                let image = UIImage(cgImage: cgImageRef!, scale: 1.0, orientation: UIImageOrientation.right)

            }
        }

    }
    override func viewDidLoad()
    {
        super.viewDidLoad()
        cameraView.backgroundColor = .clear
        self.view.backgroundColor = .clear

        captureButton = UIButton(frame: CGRect(x: 160, y: 580, width: 80, height: 80))
        captureButton.addTarget(self, action: #selector(CameraViewController.capture(_:)), for: UIControlEvents.touchUpInside)
        flipCam = UIButton(frame: CGRect(x: 0, y: 0, width: 40, height: 40))
        flipCam.addTarget(self, action: #selector(CameraViewController.flip), for: UIControlEvents.touchUpInside)
        self.view.addSubview(captureButton)
        self.view.addSubview(flipCam)
        captureButton.backgroundColor = UIColor.red
        NotificationCenter.default.addObserver(self, selector: #selector(CameraViewController.rotated), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)

        //        let backCamera = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
        camStart(camPos)
        setViews()

    }
    func camStart(_ position: String)
    {
        captureSession = AVCaptureSession()
        captureSession?.sessionPreset = AVCaptureSessionPresetHigh

        let videoDevices = AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo)
        var capDevice:AVCaptureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)

        if(position == "back")
        {
            for device in videoDevices!
            {
                let device = device as! AVCaptureDevice
                if device.position == AVCaptureDevicePosition.back
                {
                    capDevice = device
                    break
                }
            }
        }
        else{

            for device in videoDevices!
            {
                let device = device as! AVCaptureDevice
                if device.position == AVCaptureDevicePosition.front
                {
                    capDevice = device
                    break
                }
            }
        }

        //        var error : NSError?
        let input = try? AVCaptureDeviceInput(device: capDevice)

        if (captureSession?.canAddInput(input) != nil){

            captureSession?.addInput(input)

            stillImageOutput = AVCaptureStillImageOutput()
            stillImageOutput?.outputSettings = [AVVideoCodecKey : AVVideoCodecJPEG]

            if (captureSession?.canAddOutput(stillImageOutput) != nil){
                captureSession?.addOutput(stillImageOutput)
                previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
                previewLayer?.videoGravity = AVLayerVideoGravityResizeAspect
                previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.portrait
                previewLayer!.frame = self.view.layer.frame
                previewLayer!.videoGravity = AVLayerVideoGravityResizeAspectFill
                cameraView.layer.addSublayer(previewLayer!)

                captureSession?.startRunning()
            }
        }

    }
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        captureButton.frame = CGRect(x: self.view.frame.width/2 - 40, y: self.view.frame.height - 70 - 40, width: 80, height: 80)
        flipCam.frame = CGRect(x: self.view.frame.width/6 - 40, y: self.view.frame.height - 60 - 40, width: 80, height: 80)
        //add the image to flip camera
        //flipCam.setImage(UIImage(named: "switchCam"), for: UIControlState.normal)
        flipCam.setTitle("flip", for: .normal)

        if previewLayer != nil{
            previewLayer!.frame = self.view.frame
        }

    }
    override func viewWillAppear(_ animated: Bool)
    {
        super.viewWillAppear(true)
        setViews()
    }

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

    func setViews()
    {
        captureButton.layer.cornerRadius = captureButton.layer.bounds.width/2
        captureButton.layer.borderWidth = 1

    }

    func configureDevice()
    {
        let error: NSErrorPointer? = nil
        if let device = captureDevice {
            do {
                try captureDevice!.lockForConfiguration()

            } catch let error1 as NSError
            {
                error??.pointee = error1
            }

            device.focusMode = .locked
            device.unlockForConfiguration()
        }

    }
    func flip()
    {
        captureSession?.stopRunning()
        if camPos == "back"
        {
            camPos = "front"
        }
        else{
            camPos = "back"

        }
        camStart(camPos)

    }
    func rotated() {
        if UIDeviceOrientationIsLandscape(UIDevice.current.orientation) {
            if UIDevice.current.orientation == UIDeviceOrientation.landscapeLeft{
                previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.landscapeRight
            }
            else
            {
                previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.landscapeLeft

            }
        }

        if UIDeviceOrientationIsPortrait(UIDevice.current.orientation) {
            if UIDevice.current.orientation == UIDeviceOrientation.portrait{

                previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.portrait
            }
            else
            {
                previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.portraitUpsideDown

            }
        }

    }
}


来源: stackexchange

问:
Swift 3 trying to do conditional with string
I have the following code that was working great in swift 2.3

```<code>"code": self.searchByCode == true ? description : NSNull(),
</code>```

In Swift 3 Im getting this error.

Any clue?

答:
Your problem is that this expression self.searchByCode == true ? description : NSNull() can result in either a String or NSNull, so the compiler can't infer it's type.

You can store it in a Any variable before adding it to the dict or you could try this (I think this could work but I haven't tried it):

(self.searchByCode == true ? description : NSNull()) as Any

ContentLicense: CC BY-SA 3.0

Body:
I have the following code that was working great in swift 2.3

"code": self.searchByCode == true ? description : NSNull(),

In Swift 3 Im getting this error.

Any clue?


问:
Create path from javascript object property
Let's say I've got the following javascript object

```<code>var obj = {
            a:{
                b:"value",
                c:{
                    d:"value2"
                }
            }
        }
</code>```

What function would, when input with the "d" object (for example, function getPath(obj, d)), output the "a.c.d" string? I've tried various things including object-path, but it doesn't seem to be designed for that

答:
I had a fair amount of fun making this one up, it generates a list of every possible path that can be made from the object and returns the longest one ending with the correct key, it returns an empty string of not found:

function getPath(obj, key) {
    paths = []

    function getPaths(obj, path) {
        if (obj instanceof Object && !(obj instanceof Array)) {
            for (var k in obj){
                paths.push(path + "." + k)
                getPaths(obj[k], path + "." + k)
            }
        }
    }

    getPaths(obj, "")
    return paths.map(function(p) {
        return p.slice(p.lastIndexOf(".") + 1) == key ? p.slice(1) : ''
    }).sort(function(a, b) {return b.split(".").length - a.split(".").length;})[0];
}

var obj = { a:{ b:"value", c:{ d:"value2"}}};
console.log(getPath(obj, "b"))
console.log(getPath(obj, "c"))
console.log(getPath(obj, "d"))

var obj = { d:{ d:"value", d:{ d:"value2"}}};
console.log(getPath(obj, "d"))```

Body:
Let's say I've got the following javascript object

var obj = {
            a:{
                b:"value",
                c:{
                    d:"value2"
                }
            }
        }

What function would, when input with the "d" object (for example, function getPath(obj, d)), output the "a.c.d" string? I've tried various things including object-path, but it doesn't seem to be designed for that


问:
Intellij Ant - javac does not compile files, no error or message
I've been trying to compile a project using Ant in Intellij, when the javac task runs, there is no output, but no error. If I run ant manually with the same build file, everything compiles correctly and I have output from javac.

This is the task in build.xml:

<javac classpathref="libClassPath" srcdir="${sourceFolderPath}" destdir="${classFilePath}" verbose="true" debug="true"/>

This is the output from intellij's ant:

```<code>build.xml
property
taskdef
fileset
path
property
taskdef
taskdef
compileClasses
echo
===== Compiling src files C:\Users\user\project\Build/../src
echo
Class file Path: C:\Users\user\project\Build/dist/classes
mkdir
Created dir: C:\Users\user\project\Build\dist\classes
javac
</code>```

Show all output is turned on. Not sure what I'm missing. I've reinstalled intellij as well, to no avail.

答:
So this was an issue with one of the jars in the ant/lib directory. One of them had been zipped incorrectly, or been corrupted. Once I replaced this jar, everything started working.

The only way I was able to find this issue was by using the javac2 task from IDEA. For some reason, this error was hidden by intellij when using the normal javac task.

Thanks, @Ishnark for your help.

Body:
I've been trying to compile a project using Ant in Intellij, when the javac task runs, there is no output, but no error. If I run ant manually with the same build file, everything compiles correctly and I have output from javac.

This is the task in build.xml:

<javac classpathref="libClassPath" srcdir="${sourceFolderPath}" destdir="${classFilePath}" verbose="true" debug="true"/>

This is the output from intellij's ant:

build.xml
property
taskdef
fileset
path
property
taskdef
taskdef
compileClasses
echo
===== Compiling src files C:\Users\user\project\Build/../src
echo
Class file Path: C:\Users\user\project\Build/dist/classes
mkdir
Created dir: C:\Users\user\project\Build\dist\classes
javac

Show all output is turned on. Not sure what I'm missing. I've reinstalled intellij as well, to no avail.


问:
Using okular in a Python app : hiding the side pannel
I am developing a program (TeXamator) in Python to deal with exercises databases in LaTeX. Following this answer I have been able to successfully embed okular into my Qt app.

The problem is that I can't find how to access the sidebar and hide it. If I open okular, press F7 to hide/show the side bar and then go back to my app, then the side bar will be hidden/shown depending on its status when closing okular.

I've tried looking at the code of "okularpart" but I can't find anything useful.

Could someone please point me in the right direction ?

Thanks in advance.

Edit : after going through okular's source code, I understand that I should set the visibility of "m_toolbar" to False, but I don't know in which namespace it is (and if it is even accessible).
I've tried hiding each child of okupart.widget() (one by one), it hid a few things but not the sidebar.

答:
I would expect to find it in the configuration list (since it's reachable by Settings->Navigation panel), so it won't be a widget. An alternative solution would be also to make it as small as possible.

Try to use something like

```<code>okupart.sidebar().setSidebarVisibility(false)
</code>```

Check Sidebar::setSidebarVisibility and this corresponding call.

Body:
I would expect to find it in the configuration list (since it's reachable by Settings->Navigation panel), so it won't be a widget. An alternative solution would be also to make it as small as possible.

Try to use something like

okupart.sidebar().setSidebarVisibility(false)

Check Sidebar::setSidebarVisibility and this corresponding call.


问:
How to use CholmodSupport in Eigen3 under Ubuntu
I made such a tiny example:

solver.h

```<code>#pragma once

#include <Eigen/Dense>
#include <Eigen/Sparse>
#include <Eigen/CholmodSupport>

typedef Eigen::SparseMatrix<double> SpMat;

class UseCholmodSolver
{
    public:
        UseCholmodSolver() {}
        ~UseCholmodSolver() {}
    private:
        Eigen::CholmodSupernodalLLT<SpMat> cholmod;
};
</code>```

solver.cpp

```<code>#include "solver.h"
</code>```

main.cpp

```<code>#include "solver.h"

int main()
{
    return 0;
}
</code>```

Makefile

```<code>CXXFLAGS=-g -O2 -Wall -DNDEBUG -I./ext/eigen -I/usr/include/suitesparse
CXX=g++

all: t1
clean:
    rm -f *.o main

main.o: main.cpp solver.h
solver.o: solver.cpp solver.h

t1: main.o
    $(CXX) main.o -o main -lcholmod
t2: main.o solver.o
    $(CXX) main.o solver.o -o main -lcholmod
</code>```

When I execute "make t1", everything is fine.
However, when I type "make t2", there are redefinition errors:

```<code>g++ main.o solver.o -o main -lcholmod
solver.o: In function `int Eigen::internal::cm_start<long>(cholmod_common_struct&)':
/home/xiang/Code/testEigen/./ext/eigen/Eigen/src/CholmodSupport/CholmodSupport.h:177: multiple definition of `int Eigen::internal::cm_start<long>(cholmod_common_struct&)'
main.o:/home/xiang/Code/testEigen/./ext/eigen/Eigen/src/CholmodSupport/CholmodSupport.h:177: first defined here
solver.o: In function `int Eigen::internal::cm_finish<long>(cholmod_common_struct&)':
/home/xiang/Code/testEigen/./ext/eigen/Eigen/src/CholmodSupport/CholmodSupport.h:178: multiple definition of `int Eigen::internal::cm_finish<long>(cholmod_common_struct&)'
main.o:/home/xiang/Code/testEigen/./ext/eigen/Eigen/src/CholmodSupport/CholmodSupport.h:178: first defined here
solver.o: In function `int Eigen::internal::cm_free_factor<long>(cholmod_factor_struct*&, cholmod_common_struct&)':
/home/xiang/Code/testEigen/./ext/eigen/Eigen/src/CholmodSupport/CholmodSupport.h:180: multiple definition of `int Eigen::internal::cm_free_factor<long>(cholmod_factor_struct*&, cholmod_common_struct&)'
main.o:/home/xiang/Code/testEigen/./ext/eigen/Eigen/src/CholmodSupport/CholmodSupport.h:180: first defined here
solver.o: In function `int Eigen::internal::cm_free_dense<long>(cholmod_dense_struct*&, cholmod_common_struct&)':
/home/xiang/Code/testEigen/./ext/eigen/Eigen/src/CholmodSupport/CholmodSupport.h:181: multiple definition of `int Eigen::internal::cm_free_dense<long>(cholmod_dense_struct*&, cholmod_common_struct&)'
main.o:/home/xiang/Code/testEigen/./ext/eigen/Eigen/src/CholmodSupport/CholmodSupport.h:181: first defined here
solver.o: In function `int Eigen::internal::cm_free_sparse<long>(cholmod_sparse_struct*&, cholmod_common_struct&)':
/home/xiang/Code/testEigen/./ext/eigen/Eigen/src/CholmodSupport/CholmodSupport.h:182: multiple definition of `int Eigen::internal::cm_free_sparse<long>(cholmod_sparse_struct*&, cholmod_common_struct&)'
main.o:/home/xiang/Code/testEigen/./ext/eigen/Eigen/src/CholmodSupport/CholmodSupport.h:182: first defined here
solver.o: In function `cholmod_factor_struct* Eigen::internal::cm_analyze<long>(cholmod_sparse_struct&, cholmod_common_struct&)':
/home/xiang/Code/testEigen/./ext/eigen/Eigen/src/CholmodSupport/CholmodSupport.h:184: multiple definition of `cholmod_factor_struct* Eigen::internal::cm_analyze<long>(cholmod_sparse_struct&, cholmod_common_struct&)'
main.o:/home/xiang/Code/testEigen/./ext/eigen/Eigen/src/CholmodSupport/CholmodSupport.h:184: first defined here
solver.o: In function `cholmod_dense_struct* Eigen::internal::cm_solve<long>(int, cholmod_factor_struct&, cholmod_dense_struct&, cholmod_common_struct&)':
/home/xiang/Code/testEigen/./ext/eigen/Eigen/src/CholmodSupport/CholmodSupport.h:187: multiple definition of `cholmod_dense_struct* Eigen::internal::cm_solve<long>(int, cholmod_factor_struct&, cholmod_dense_struct&, cholmod_common_struct&)'
main.o:/home/xiang/Code/testEigen/./ext/eigen/Eigen/src/CholmodSupport/CholmodSupport.h:187: first defined here
solver.o: In function `cholmod_sparse_struct* Eigen::internal::cm_spsolve<long>(int, cholmod_factor_struct&, cholmod_sparse_struct&, cholmod_common_struct&)':
/home/xiang/Code/testEigen/./ext/eigen/Eigen/src/CholmodSupport/CholmodSupport.h:190: multiple definition of `cholmod_sparse_struct* Eigen::internal::cm_spsolve<long>(int, cholmod_factor_struct&, cholmod_sparse_struct&, cholmod_common_struct&)'
main.o:/home/xiang/Code/testEigen/./ext/eigen/Eigen/src/CholmodSupport/CholmodSupport.h:190: first defined here
solver.o: In function `int Eigen::internal::cm_factorize_p<long>(cholmod_sparse_struct*, double*, long*, unsigned long, cholmod_factor_struct*, cholmod_common_struct&)':
/home/xiang/Code/testEigen/./ext/eigen/Eigen/src/CholmodSupport/CholmodSupport.h:195: multiple definition of `int Eigen::internal::cm_factorize_p<long>(cholmod_sparse_struct*, double*, long*, unsigned long, cholmod_factor_struct*, cholmod_common_struct&)'
main.o:/home/xiang/Code/testEigen/./ext/eigen/Eigen/src/CholmodSupport/CholmodSupport.h:195: first defined here
collect2: error: ld returned 1 exit status
Makefile:14: recipe for target 't2' failed
make: *** [t2] Error 1
</code>```

It seems the reason is the "long" type specialized template functions in "CholmodSupport.h". Any idea to fix this problem?

答:
There was a problem with CholmodSupport in the devel-branch of Eigen, which I just fixed here:
https://bitbucket.org/eigen/eigen/commits/5ecddbf9fae7f5a4d4e587b8809d9287306885d3

The problem was that some helper functions (used to delegate to appropriate internal cholmod-functions) were not marked inline and thus had multiple definitions, when compiled in different compilation units.

For Eigen 3.3 and Eigen 3.2 your minimal example should work fine.

Body:
I made such a tiny example:

solver.h

#pragma once

#include <Eigen/Dense>
#include <Eigen/Sparse>
#include <Eigen/CholmodSupport>

typedef Eigen::SparseMatrix<double> SpMat;

class UseCholmodSolver
{
    public:
        UseCholmodSolver() {}
        ~UseCholmodSolver() {}
    private:
        Eigen::CholmodSupernodalLLT<SpMat> cholmod;
};

solver.cpp

#include "solver.h"

main.cpp

#include "solver.h"

int main()
{
    return 0;
}

Makefile

CXXFLAGS=-g -O2 -Wall -DNDEBUG -I./ext/eigen -I/usr/include/suitesparse
CXX=g++

all: t1
clean:
    rm -f *.o main

main.o: main.cpp solver.h
solver.o: solver.cpp solver.h

t1: main.o
    $(CXX) main.o -o main -lcholmod
t2: main.o solver.o
    $(CXX) main.o solver.o -o main -lcholmod

When I execute "make t1", everything is fine.
However, when I type "make t2", there are redefinition errors:

g++ main.o solver.o -o main -lcholmod
solver.o: In function `int Eigen::internal::cm_start<long>(cholmod_common_struct&)':
/home/xiang/Code/testEigen/./ext/eigen/Eigen/src/CholmodSupport/CholmodSupport.h:177: multiple definition of `int Eigen::internal::cm_start<long>(cholmod_common_struct&)'
main.o:/home/xiang/Code/testEigen/./ext/eigen/Eigen/src/CholmodSupport/CholmodSupport.h:177: first defined here
solver.o: In function `int Eigen::internal::cm_finish<long>(cholmod_common_struct&)':
/home/xiang/Code/testEigen/./ext/eigen/Eigen/src/CholmodSupport/CholmodSupport.h:178: multiple definition of `int Eigen::internal::cm_finish<long>(cholmod_common_struct&)'
main.o:/home/xiang/Code/testEigen/./ext/eigen/Eigen/src/CholmodSupport/CholmodSupport.h:178: first defined here
solver.o: In function `int Eigen::internal::cm_free_factor<long>(cholmod_factor_struct*&, cholmod_common_struct&)':
/home/xiang/Code/testEigen/./ext/eigen/Eigen/src/CholmodSupport/CholmodSupport.h:180: multiple definition of `int Eigen::internal::cm_free_factor<long>(cholmod_factor_struct*&, cholmod_common_struct&)'
main.o:/home/xiang/Code/testEigen/./ext/eigen/Eigen/src/CholmodSupport/CholmodSupport.h:180: first defined here
solver.o: In function `int Eigen::internal::cm_free_dense<long>(cholmod_dense_struct*&, cholmod_common_struct&)':
/home/xiang/Code/testEigen/./ext/eigen/Eigen/src/CholmodSupport/CholmodSupport.h:181: multiple definition of `int Eigen::internal::cm_free_dense<long>(cholmod_dense_struct*&, cholmod_common_struct&)'
main.o:/home/xiang/Code/testEigen/./ext/eigen/Eigen/src/CholmodSupport/CholmodSupport.h:181: first defined here
solver.o: In function `int Eigen::internal::cm_free_sparse<long>(cholmod_sparse_struct*&, cholmod_common_struct&)':
/home/xiang/Code/testEigen/./ext/eigen/Eigen/src/CholmodSupport/CholmodSupport.h:182: multiple definition of `int Eigen::internal::cm_free_sparse<long>(cholmod_sparse_struct*&, cholmod_common_struct&)'
main.o:/home/xiang/Code/testEigen/./ext/eigen/Eigen/src/CholmodSupport/CholmodSupport.h:182: first defined here
solver.o: In function `cholmod_factor_struct* Eigen::internal::cm_analyze<long>(cholmod_sparse_struct&, cholmod_common_struct&)':
/home/xiang/Code/testEigen/./ext/eigen/Eigen/src/CholmodSupport/CholmodSupport.h:184: multiple definition of `cholmod_factor_struct* Eigen::internal::cm_analyze<long>(cholmod_sparse_struct&, cholmod_common_struct&)'
main.o:/home/xiang/Code/testEigen/./ext/eigen/Eigen/src/CholmodSupport/CholmodSupport.h:184: first defined here
solver.o: In function `cholmod_dense_struct* Eigen::internal::cm_solve<long>(int, cholmod_factor_struct&, cholmod_dense_struct&, cholmod_common_struct&)':
/home/xiang/Code/testEigen/./ext/eigen/Eigen/src/CholmodSupport/CholmodSupport.h:187: multiple definition of `cholmod_dense_struct* Eigen::internal::cm_solve<long>(int, cholmod_factor_struct&, cholmod_dense_struct&, cholmod_common_struct&)'
main.o:/home/xiang/Code/testEigen/./ext/eigen/Eigen/src/CholmodSupport/CholmodSupport.h:187: first defined here
solver.o: In function `cholmod_sparse_struct* Eigen::internal::cm_spsolve<long>(int, cholmod_factor_struct&, cholmod_sparse_struct&, cholmod_common_struct&)':
/home/xiang/Code/testEigen/./ext/eigen/Eigen/src/CholmodSupport/CholmodSupport.h:190: multiple definition of `cholmod_sparse_struct* Eigen::internal::cm_spsolve<long>(int, cholmod_factor_struct&, cholmod_sparse_struct&, cholmod_common_struct&)'
main.o:/home/xiang/Code/testEigen/./ext/eigen/Eigen/src/CholmodSupport/CholmodSupport.h:190: first defined here
solver.o: In function `int Eigen::internal::cm_factorize_p<long>(cholmod_sparse_struct*, double*, long*, unsigned long, cholmod_factor_struct*, cholmod_common_struct&)':
/home/xiang/Code/testEigen/./ext/eigen/Eigen/src/CholmodSupport/CholmodSupport.h:195: multiple definition of `int Eigen::internal::cm_factorize_p<long>(cholmod_sparse_struct*, double*, long*, unsigned long, cholmod_factor_struct*, cholmod_common_struct&)'
main.o:/home/xiang/Code/testEigen/./ext/eigen/Eigen/src/CholmodSupport/CholmodSupport.h:195: first defined here
collect2: error: ld returned 1 exit status
Makefile:14: recipe for target 't2' failed
make: *** [t2] Error 1

It seems the reason is the "long" type specialized template functions in "CholmodSupport.h". Any idea to fix this problem?


问:
What is the count code in Entity Framework?
I'm new to Entity Framework, I know count code in SQL but what is that in EF?

```<code>select COUNT(*)
from Factor f
left join FactorItems FI on f.FactorID=FI.FactorRef
</code>```

and this is my entity code:

```<code>var CountOfitem = (from FI in context.FactorItems
                   join P in context.tblparts on FI.PartRef equals P.PartsID
                   where (FI.FactorRef == FactorID)
                   select new
                            {
                                gridcount = FI.Rowno
                            }
</code>```

How can I get count in my select new ?

答:
You could do:

```<code>var CountOfitem= (from FI in context.FactorItems
                  join P in context.tblparts on FI.PartRef equals P.PartsID
                  where (FI.FactorRef == FactorID)
                  select new
                      {
                          gridcount=FI.Rowno
                       }).Count();
</code>```

to get the number of items.

Body:
I'm new to Entity Framework, I know count code in SQL but what is that in EF?

select COUNT(*)
from Factor f
left join FactorItems FI on f.FactorID=FI.FactorRef

and this is my entity code:

var CountOfitem = (from FI in context.FactorItems
                   join P in context.tblparts on FI.PartRef equals P.PartsID
                   where (FI.FactorRef == FactorID)
                   select new
                            {
                                gridcount = FI.Rowno
                            }

How can I get count in my select new ?

Body:
You could do:

var CountOfitem= (from FI in context.FactorItems
                  join P in context.tblparts on FI.PartRef equals P.PartsID
                  where (FI.FactorRef == FactorID)
                  select new
                      {
                          gridcount=FI.Rowno
                       }).Count();

to get the number of items.


问:
How to handle new fields with jquery that have array
I have for example 3 fields that user can input a number a,b,c

So field C will check if number entered in field C is  b.

In the form i have a button that create an additional line with
another a,b,c; so i don't know how to control same operation like before...

FIDDLE

```<code>$(".c").change(function() {

  if ($('.c').val() > $('.a').val() || $('.c').val() < $('.b').val()) {
    $('.c').css("backgroundColor", "#ff0000");
  } else {
    $('.c').css("backgroundColor", "#00FF00");
  }
});

$('.add').click(function() {

  var tr = '<tr>' + '<td>Cota1</td>' +
    '<td><input type="text" name="tol_cota1[]" class="form-control a"></td>' +
    '<td><input type="text" name="tolb_cota1[]" class="form-control b"></td>' +
    '<td><input type="text" name="medido_cota1[]" class="form-control c"></td>' +
    '<td><input type="button"  class="btn btn-danger remove" value="Remove Line"></td>' + '</tr>';

  $('.details').append(tr);

});

// delete row
$('.details').delegate('.remove', 'click', function() {
  var con = confirm("Are you sure you want to remove the line?");
  if (con) {
    $(this).parent().parent().remove();
  }
});
</code>```

答:
The change event doesn't bubble, which means you will need an event listener for every input in your form.

jQuery will take care of that automatically when using using the .on() method with a selector (its second parameter), which is equivalent to the old deprecated .delegate() method. From its description in the official docs, it will:

Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.

So, if you do something like this:

```<code>$('.details').on('change', 'input', (event) => { ... });
</code>```

This will listen for change events on any <input> element inside all elements matching the .details selector, regardless if they already existed when the method was called or if they were created afterwards as it is your case.

Now, once a change event occurs, you should use the .parent(), .eq and .find() methods to select the row in which the <input> that triggered the event is located, from there you get all 3 inputs based on their position or selector, their value, and do your logic to update that specific row.

Anyway, if instead of listening for change events you use input, which does bubble, you can benefit from event delegation. This means that a single event listener will be created for the whole
 in this case, instead of one per <input>. Using event.target you will be able to distinguish which one triggered the event, which you need to use anyway to get the other inputs in the same row.

All together, it will look something like this:

// Better to keep the reference instead of getting it each time:

const details = $('#details');

details.on('input', 'input', (event) => {
    const children = $(event.target).parents().eq(1).children();
    const avgInput = children.eq(3).find('input');
    const max = parseInt(children.eq(1).find('input').val());
    const min = parseInt(children.eq(2).find('input').val());
    const avg = parseInt(avgInput.val());

    if (isNaN(max) ||isNaN(min)|| isNaN(avg)) {
      // Don't do anything if any of them is blank.

      return;
    }

    avgInput.css('backgroundColor', avg > max || avg < min ? '#ff0000' : '#00FF00');
});

details.on('click', '.remove', (event) => {
  if (confirm('Are you sure you want to remove the line?')) {
    $(event.target).parents().eq(1).remove();
  }
});

$('#add').click(() => {
  details.append(`

     Cota1
     <input type="text">
     <input type="text">
     <input type="text">
     <button class="remove">DELETE</button>

  `);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  font-family: sans-serif;
  font-size: .75rem;
}

table {
  border-collapse: collapse;
  table-layout: fixed;
  position: relative;
}

table th,
table td {
  width: 20%;
  padding: 0;
  border-bottom: 1px solid #EEE;
  height: 1.75rem;
}

input {
  width: 100%;
  box-sizing: border-box;
  padding: .5rem;
  border: none;
  outline: none;
  text-align: center;
}

input:hover {
  background: #FAFAFA;
}

input:focus {
  background: #FFA;
}

.remove {
  width: 100%;
  box-sizing: border-box;
  padding: .5rem;
  border: none;
  outline: none;
  background: #FFF;
  cursor: pointer;
}

.remove:hover {
  background: #F44;
}

#add {
  width: 100%;
  border: none;
  background: #FFF;
  padding: .5rem;
  border-radius: 2px;
  color: #000;
  text-transform: uppercase;
  font-size: .75rem;
  margin: 1rem 0 0;
  box-shadow: 0 0 1rem rgba(0, 0, 0, .25);
  transition: box-shadow ease-in .125s;
}

#add:hover {
  box-shadow: 0 0 .5rem rgba(0, 0, 0, .25);
}</code>```

      TOL +
      TOL -
      AVG

     Cota1
     <input type="text">
     <input type="text">
     <input type="text">

<button id="add">ADD</button>

```

Body:
I have for example 3 fields that user can input a number a,b,c

So field C will check if number entered in field C is  b.

In the form i have a button that create an additional line with
another a,b,c; so i don't know how to control same operation like before...

FIDDLE

$(".c").change(function() {

  if ($('.c').val() > $('.a').val() || $('.c').val() < $('.b').val()) {
    $('.c').css("backgroundColor", "#ff0000");
  } else {
    $('.c').css("backgroundColor", "#00FF00");
  }
});

$('.add').click(function() {

  var tr = '
' + 'Cota1	' +
    '<input type="text" name="tol_cota1[]" class="form-control a">	' +
    '<input type="text" name="tolb_cota1[]" class="form-control b">	' +
    '<input type="text" name="medido_cota1[]" class="form-control c">	' +
    '<input type="button"  class="btn btn-danger remove" value="Remove Line">	' + '
';

  $('.details').append(tr);

});

// delete row
$('.details').delegate('.remove', 'click', function() {
  var con = confirm("Are you sure you want to remove the line?");
  if (con) {
    $(this).parent().parent().remove();
  }
});

Body:
The change event doesn't bubble, which means you will need an event listener for every input in your form.

jQuery will take care of that automatically when using using the .on() method with a selector (its second parameter), which is equivalent to the old deprecated .delegate() method. From its description in the official docs, it will:

Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.

So, if you do something like this:

$('.details').on('change', 'input', (event) => { ... });

This will listen for change events on any <input> element inside all elements matching the .details selector, regardless if they already existed when the method was called or if they were created afterwards as it is your case.

Now, once a change event occurs, you should use the .parent(), .eq and .find() methods to select the row in which the <input> that triggered the event is located, from there you get all 3 inputs based on their position or selector, their value, and do your logic to update that specific row.

Anyway, if instead of listening for change events you use input, which does bubble, you can benefit from event delegation. This means that a single event listener will be created for the whole <tbody> in this case, instead of one per <input>. Using event.target you will be able to distinguish which one triggered the event, which you need to use anyway to get the other inputs in the same row.

All together, it will look something like this:

// Better to keep the reference instead of getting it each time:

const details = $('#details');

details.on('input', 'input', (event) => {
    const children = $(event.target).parents().eq(1).children();
    const avgInput = children.eq(3).find('input');
    const max = parseInt(children.eq(1).find('input').val());
    const min = parseInt(children.eq(2).find('input').val());
    const avg = parseInt(avgInput.val());

    if (isNaN(max) ||isNaN(min)|| isNaN(avg)) {
      // Don't do anything if any of them is blank.

      return;
    }

    avgInput.css('backgroundColor', avg > max || avg < min ? '#ff0000' : '#00FF00');
});

details.on('click', '.remove', (event) => {
  if (confirm('Are you sure you want to remove the line?')) {
    $(event.target).parents().eq(1).remove();
  }
});

$('#add').click(() => {
  details.append(`
    <tr>
     <td>Cota1</td>
     <td><input type="text"></td>
     <td><input type="text"></td>
     <td><input type="text"></td>
     <td><button class="remove">DELETE</button></td>
    </tr>
  `);
});

body {
  font-family: sans-serif;
  font-size: .75rem;
}

table {
  border-collapse: collapse;
  table-layout: fixed;
  position: relative;
}

table th,
table td {
  width: 20%;
  padding: 0;
  border-bottom: 1px solid #EEE;
  height: 1.75rem;
}

input {
  width: 100%;
  box-sizing: border-box;
  padding: .5rem;
  border: none;
  outline: none;
  text-align: center;
}

input:hover {
  background: #FAFAFA;
}

input:focus {
  background: #FFA;
}

.remove {
  width: 100%;
  box-sizing: border-box;
  padding: .5rem;
  border: none;
  outline: none;
  background: #FFF;
  cursor: pointer;
}

.remove:hover {
  background: #F44;
}

#add {
  width: 100%;
  border: none;
  background: #FFF;
  padding: .5rem;
  border-radius: 2px;
  color: #000;
  text-transform: uppercase;
  font-size: .75rem;
  margin: 1rem 0 0;
  box-shadow: 0 0 1rem rgba(0, 0, 0, .25);
  transition: box-shadow ease-in .125s;
}

#add:hover {
  box-shadow: 0 0 .5rem rgba(0, 0, 0, .25);
}

<table>
  <thead>
    <tr>
      <th> </th>
      <th>TOL +</th>
      <th>TOL -</th>
      <th>AVG</th>
      <th></th>
    </tr>
  </thead>

  <tbody id="details">
    <tr>
     <td>Cota1</td>
     <td><input type="text"></td>
     <td><input type="text"></td>
     <td><input type="text"></td>
     <td> </td>
    </tr>
  </tbody>
</table>

<button id="add">ADD</button>

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


问:
Composite key in SQL is one to many and not many to one right?
If I create a table with a composite key(One to many relationships). How do I ensure that the one-to-many relationship is one sided? What I mean is A and B are composite keys; A can have multiple B's, But B cannot have Multiple A's

Edit: Changed the data type from numeric to int

Eg:

```<code>CREATE TABLE voting (
TaskOrder int,
MemberID int,
PRIMARY KEY (TaskOrder , MemberID)
);
</code>```

Functional requirement - One Member can have multiple task orders. But one task order cannot be assigned to multiple Members.

How do I make sure? At first, I thought of using a composite key. Is there any other alternative? or using a composite key is ok?

答:
Since B can not have multiple A, that makes B unique. B would be your primary key.

```<code>create table voting (
    TaskOrder int
  , MemberID int
  , primary key (TaskOrder)
 );
</code>```

Unless you have some reason to use an unspecified numeric, just use int.

Body:
If I create a table with a composite key(One to many relationships). How do I ensure that the one-to-many relationship is one sided? What I mean is A and B are composite keys; A can have multiple B's, But B cannot have Multiple A's

Edit: Changed the data type from numeric to int

Eg:

CREATE TABLE voting (
TaskOrder int,
MemberID int,
PRIMARY KEY (TaskOrder , MemberID)
);

Functional requirement - One Member can have multiple task orders. But one task order cannot be assigned to multiple Members.

How do I make sure? At first, I thought of using a composite key. Is there any other alternative? or using a composite key is ok?

Body:
Since B can not have multiple A, that makes B unique. B would be your primary key.

create table voting (
    TaskOrder int
  , MemberID int
  , primary key (TaskOrder)
 );

Unless you have some reason to use an unspecified numeric, just use int.


问:
WinForms Charting: X Axis Labels - where are they?
Ok.... I have a WinForms Chart that is successfully plotting my series.  HOWEVER, the X Axis numeric labels (not the Title, the "number line") do NOT display at all.  I have not altered or touched anything!  I have the EXACT same setup in another VSExpress project, same plot setup, and those Axis numeric labels display just fine.  What the hell is going on???

** The Y Axis numbers show up just fine, with no issue. It's only the X Axis that is being like this.

* The Y axis values are Pressures  values
* The X Axis values are Volumes  values

I have tried:

Forcing the "Interval" = 1

Forcing the Axis "Max" / "Min" to specific values

Setting the "IntervalType"

Setting the "LabelStyle"

Nothing has changed.  Zero effect.  There is still NO indication to the user what the values of the X Axis are displaying.  There is only ONE plot, ONE chart, ONE chartArea and a single series with 3 data points.  WHERE. ARE. THE. AXIS. NUMBERS!??

I was under the impression, that unless the user has tampered with something, those axis labels should just show up automatically (and then it's up to the user to format, etc.).... am I wrong about that?

Here is a snippet from the Designer:

```<code>chartArea2.AxisX.MinorGrid.LineDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Dash;
            chartArea2.AxisX.MinorTickMark.Enabled = true;
            chartArea2.AxisX.Title = "Cum. Adjusted Inventory (Mcf)";
            chartArea2.AxisX.TitleFont = new System.Drawing.Font("Microsoft Sans Serif", 14F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            chartArea2.AxisX.LabelStyle.Interval = 1;
            chartArea2.AxisX.IntervalType = System.Windows.Forms.DataVisualization.Charting.DateTimeIntervalType.Auto;
            chartArea2.AxisY.MinorGrid.LineDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Dash;
            chartArea2.AxisY.MinorTickMark.Enabled = true;
            chartArea2.AxisY.Title = "Pressure (psia)";
            chartArea2.AxisY.TitleFont = new System.Drawing.Font("Microsoft Sans Serif", 14F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
</code>```

~Sincerely frustrated,
A

答:
I figured out the answer to my question.

I had this code written in a .cs file:

```<code> System.Windows.Forms.DataVisualization.Charting.Series newObservationSeries = new System.Windows.Forms.DataVisualization.Charting.Series()
            {
                ChartType = SeriesChartType.Line,
                MarkerStyle = MarkerStyle.Diamond,
                MarkerSize = 5,
                BorderWidth = 2,
                BorderDashStyle = ChartDashStyle.Dash,
                AxisLabel = "Pressure"
            };
</code>```

This last line "AxisLabel = "Pressure"" was screwing up the plots ability to discern the correct Axis Labels.  I simply REMOVED that line, and the labels appeared.  It was from a prior attempt to create an Axis Title, before I knew how to do so.  I simply forgot to remove it.

The correct code is:

```<code> System.Windows.Forms.DataVisualization.Charting.Series newObservationSeries = new System.Windows.Forms.DataVisualization.Charting.Series()
            {
                ChartType = SeriesChartType.Line,
                MarkerStyle = MarkerStyle.Diamond,
                MarkerSize = 5,
                BorderWidth = 2,
                BorderDashStyle = ChartDashStyle.Dash
            };
</code>```

Cheers!

Body:
Ok.... I have a WinForms Chart that is successfully plotting my series.  HOWEVER, the X Axis numeric labels (not the Title, the "number line") do NOT display at all.  I have not altered or touched anything!  I have the EXACT same setup in another VSExpress project, same plot setup, and those Axis numeric labels display just fine.  What the hell is going on???

** The Y Axis numbers show up just fine, with no issue. It's only the X Axis that is being like this.

* The Y axis values are Pressures  values
* The X Axis values are Volumes  values

I have tried:

Forcing the "Interval" = 1

Forcing the Axis "Max" / "Min" to specific values

Setting the "IntervalType"

Setting the "LabelStyle"

Nothing has changed.  Zero effect.  There is still NO indication to the user what the values of the X Axis are displaying.  There is only ONE plot, ONE chart, ONE chartArea and a single series with 3 data points.  WHERE. ARE. THE. AXIS. NUMBERS!??

I was under the impression, that unless the user has tampered with something, those axis labels should just show up automatically (and then it's up to the user to format, etc.).... am I wrong about that?

Here is a snippet from the Designer:

chartArea2.AxisX.MinorGrid.LineDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Dash;
            chartArea2.AxisX.MinorTickMark.Enabled = true;
            chartArea2.AxisX.Title = "Cum. Adjusted Inventory (Mcf)";
            chartArea2.AxisX.TitleFont = new System.Drawing.Font("Microsoft Sans Serif", 14F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            chartArea2.AxisX.LabelStyle.Interval = 1;
            chartArea2.AxisX.IntervalType = System.Windows.Forms.DataVisualization.Charting.DateTimeIntervalType.Auto;
            chartArea2.AxisY.MinorGrid.LineDashStyle = System.Windows.Forms.DataVisualization.Charting.ChartDashStyle.Dash;
            chartArea2.AxisY.MinorTickMark.Enabled = true;
            chartArea2.AxisY.Title = "Pressure (psia)";
            chartArea2.AxisY.TitleFont = new System.Drawing.Font("Microsoft Sans Serif", 14F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));

~Sincerely frustrated,
A

Body:
I figured out the answer to my question.

I had this code written in a .cs file:

 System.Windows.Forms.DataVisualization.Charting.Series newObservationSeries = new System.Windows.Forms.DataVisualization.Charting.Series()
            {
                ChartType = SeriesChartType.Line,
                MarkerStyle = MarkerStyle.Diamond,
                MarkerSize = 5,
                BorderWidth = 2,
                BorderDashStyle = ChartDashStyle.Dash,
                AxisLabel = "Pressure"
            };

This last line "AxisLabel = "Pressure"" was screwing up the plots ability to discern the correct Axis Labels.  I simply REMOVED that line, and the labels appeared.  It was from a prior attempt to create an Axis Title, before I knew how to do so.  I simply forgot to remove it.

The correct code is:

 System.Windows.Forms.DataVisualization.Charting.Series newObservationSeries = new System.Windows.Forms.DataVisualization.Charting.Series()
            {
                ChartType = SeriesChartType.Line,
                MarkerStyle = MarkerStyle.Diamond,
                MarkerSize = 5,
                BorderWidth = 2,
                BorderDashStyle = ChartDashStyle.Dash
            };

Cheers!


问:
How to get cookie from scrapy response and set the cookie to the next request?
I have disabled the Default Scrapy cookie option, so that i have to set it manually.

```<code>COOKIES_ENABLED = False
COOKIES_DEBUG = True
</code>```

Now, i need to set cookie with the value which is received as the response of the same site. I can able to get the cookie as below,

```<code>cookie = response.headers.getlist('Set-Cookie')[0].split(";")[0].split("=")
</code>```

now i am trying to set it to the form request by

```<code>FormRequest.from_response(response,
                formdata={"username": "asldkfs", "pass": "slskd"},
                cookies={cookie[0]:cookie[1]},
                meta = {'dont_redirect': True,'handle_httpstatus_list': [302]},
                callback=self.redirection)

def redirection(self,response):
    self.log("redirection")
    self.log(response.headers)
    self.log("Cookie2")
    cook1 = response.headers.getlist('Set-Cookie')[0].split(";")[0].split("=")
    self.log(cook1)
    self.log("end cookie2")
    return Request("http://something.net/some/sa/"+response.headers.getlist('Location')[0],cookies={cook1[0]:cook1[1]},
        callback=self.check_login_response)

.
.
.
</code>```

So I could not set the cookie.Do i need to set any other value also or what could be the problem?

答: I think you could not work with cookies if you disabled it.</p>

Body:
I have disabled the Default Scrapy cookie option, so that i have to set it manually.

COOKIES_ENABLED = False
COOKIES_DEBUG = True

Now, i need to set cookie with the value which is received as the response of the same site. I can able to get the cookie as below,

cookie = response.headers.getlist('Set-Cookie')[0].split(";")[0].split("=")

now i am trying to set it to the form request by

FormRequest.from_response(response,
                formdata={"username": "asldkfs", "pass": "slskd"},
                cookies={cookie[0]:cookie[1]},
                meta = {'dont_redirect': True,'handle_httpstatus_list': [302]},
                callback=self.redirection)

def redirection(self,response):
    self.log("redirection")
    self.log(response.headers)
    self.log("Cookie2")
    cook1 = response.headers.getlist('Set-Cookie')[0].split(";")[0].split("=")
    self.log(cook1)
    self.log("end cookie2")
    return Request("http://something.net/some/sa/"+response.headers.getlist('Location')[0],cookies={cook1[0]:cook1[1]},
        callback=self.check_login_response)

.
.
.

So I could not set the cookie.Do i need to set any other value also or what could be the problem?


问:
How to change timezone of postgreSQL 9.5 on docker?
Default timezone is UTC.
But I want to change it to GMT+2.
I tried as below.

```<code>alter database governance set timezone = 'GMT+2';
</code>```

But it does't work.

How can I manage it?

postgresql version is 9.5.
And it run on Docker.

Thanks!

答:
To change timezone of you image try this:

```<code>docker run -it -e "TZ=GMT+2" postgres:alpine
</code>```

docker-compose.yml

```<code>postgres:
  image: postgres:alpine
  environment:
    - TZ=GMT+2
</code>```

Body:
Default timezone is UTC.
But I want to change it to GMT+2.
I tried as below.

alter database governance set timezone = 'GMT+2';

But it does't work.

How can I manage it?

postgresql version is 9.5.
And it run on Docker.

Thanks!

Body:
To change timezone of you image try this:

docker run -it -e "TZ=GMT+2" postgres:alpine

docker-compose.yml

postgres:
  image: postgres:alpine
  environment:
    - TZ=GMT+2


问:
Create Active Directory User using Zend Framework
I have managed to query my Active Directory Domain Controller for user info using Zend_Ldap. But is it possible to, and in that case how do I, add a new user to the Active Directory using Zend Frameworks Zend_Ldap (or other php class that has this functionality)</p>

答: The section "Adding data to the LDAP" in the docs is a good starter. ;-)</p>

ContentLicense: CC BY-SA 2.5


答:
If you want to get the number of FactorItems, simply write:

```<code>var count = context.FactorItems.Count()
</code>```

or

```<code>var count = context.FactorItems.Where(...).Select(...).Count()
</code>```

Title: What is the count code in Entity Framework?

Body:
If you want to get the number of FactorItems, simply write:

var count = context.FactorItems.Count()

or

var count = context.FactorItems.Where(...).Select(...).Count()


问:
Generate one file for a list of parsed files using source_gen in dart
I have a list of models that I need to create a mini reflective system.

I analyzed the Serializable package and understood how to create one generated file per file, however, I couldn't find how can I create one file for a bulk of files.

So, how to dynamically generate one file, using source_gen, for a list of files?

Example:

Files

user.dart

category.dart

Generated:

info.dart (containg information from user.dart and category.dart)

答:
Found out how to do it with the help of people in Gitter.

You must have one file, even if empty, to call the generator. In my example, it is lib/batch.dart.

source_gen: ^0.5.8

Here is the working code:

The tool/build.dart

```<code>import 'package:build_runner/build_runner.dart';
import 'package:raoni_global/phase.dart';

main() async {
  PhaseGroup pg = new PhaseGroup()
    ..addPhase(batchModelablePhase(const ['lib/batch.dart']));

  await build(pg,
      deleteFilesByDefault: true);
}
</code>```

The phase:

```<code>batchModelablePhase([Iterable<String> globs =
const ['bin/**.dart', 'web/**.dart', 'lib/**.dart']]) {
  return new Phase()
    ..addAction(
        new GeneratorBuilder(const
        [const BatchGenerator()], isStandalone: true
        ),
        new InputSet(new PackageGraph.forThisPackage().root.name, globs));
}
</code>```

The generator:

```<code>import 'dart:async';

import 'package:analyzer/dart/element/element.dart';
import 'package:build/build.dart';
import 'package:source_gen/source_gen.dart';
import 'package:glob/glob.dart';
import 'package:build_runner/build_runner.dart';

class BatchGenerator extends Generator {
  final String path;

  const BatchGenerator({this.path: 'lib/models/*.dart'});

  @override
  Future<String> generate(Element element, BuildStep buildStep) async {
    // this makes sure we parse one time only
    if (element is! LibraryElement)
      return null;

    String libraryName = 'raoni_global', filePath = 'lib/src/model.dart';
    String className = 'Modelable';

    // find the files at the path designed
    var l = buildStep.findAssets(new Glob(path));

    // get the type of annotation that we will use to search classes
    var resolver = await buildStep.resolver;
    var assetWithAnnotationClass = new AssetId(libraryName, filePath);
    var annotationLibrary = resolver.getLibrary(assetWithAnnotationClass);
    var exposed = annotationLibrary.getType(className).type;

    // the caller library' name
    String libName = new PackageGraph.forThisPackage().root.name;

    await Future.forEach(l.toList(), (AssetId aid) async {
      LibraryElement lib;

      try {
        lib = resolver.getLibrary(aid);
      } catch (e) {}

      if (lib != null && Utils.isNotEmpty(lib.name)) {
        // all objects within the file
        lib.units.forEach((CompilationUnitElement unit) {
          // only the types, not methods
          unit.types.forEach((ClassElement el) {
            // only the ones annotated
            if (el.metadata.any((ElementAnnotation ea) =>
            ea.computeConstantValue().type == exposed)) {
              // use it
            }
          });
        });
      }
    });

    return '''
       $libName
    ''';
  }
}
</code>```

Body:
Found out how to do it with the help of people in Gitter.

You must have one file, even if empty, to call the generator. In my example, it is lib/batch.dart.

source_gen: ^0.5.8

Here is the working code:

The tool/build.dart

import 'package:build_runner/build_runner.dart';
import 'package:raoni_global/phase.dart';

main() async {
  PhaseGroup pg = new PhaseGroup()
    ..addPhase(batchModelablePhase(const ['lib/batch.dart']));

  await build(pg,
      deleteFilesByDefault: true);
}

The phase:

batchModelablePhase([Iterable<String> globs =
const ['bin/**.dart', 'web/**.dart', 'lib/**.dart']]) {
  return new Phase()
    ..addAction(
        new GeneratorBuilder(const
        [const BatchGenerator()], isStandalone: true
        ),
        new InputSet(new PackageGraph.forThisPackage().root.name, globs));
}

The generator:

import 'dart:async';

import 'package:analyzer/dart/element/element.dart';
import 'package:build/build.dart';
import 'package:source_gen/source_gen.dart';
import 'package:glob/glob.dart';
import 'package:build_runner/build_runner.dart';

class BatchGenerator extends Generator {
  final String path;

  const BatchGenerator({this.path: 'lib/models/*.dart'});

  @override
  Future<String> generate(Element element, BuildStep buildStep) async {
    // this makes sure we parse one time only
    if (element is! LibraryElement)
      return null;

    String libraryName = 'raoni_global', filePath = 'lib/src/model.dart';
    String className = 'Modelable';

    // find the files at the path designed
    var l = buildStep.findAssets(new Glob(path));

    // get the type of annotation that we will use to search classes
    var resolver = await buildStep.resolver;
    var assetWithAnnotationClass = new AssetId(libraryName, filePath);
    var annotationLibrary = resolver.getLibrary(assetWithAnnotationClass);
    var exposed = annotationLibrary.getType(className).type;

    // the caller library' name
    String libName = new PackageGraph.forThisPackage().root.name;

    await Future.forEach(l.toList(), (AssetId aid) async {
      LibraryElement lib;

      try {
        lib = resolver.getLibrary(aid);
      } catch (e) {}

      if (lib != null && Utils.isNotEmpty(lib.name)) {
        // all objects within the file
        lib.units.forEach((CompilationUnitElement unit) {
          // only the types, not methods
          unit.types.forEach((ClassElement el) {
            // only the ones annotated
            if (el.metadata.any((ElementAnnotation ea) =>
            ea.computeConstantValue().type == exposed)) {
              // use it
            }
          });
        });
      }
    });

    return '''
       $libName
    ''';
  }
}


问:
Angular 2/4 - Carousel & jQuery plugins
I've seen some similar questions on GitHub regarding owl-carousel and carousels in general. However they do not answer my questions.

I am building a basic website, and at one point of time I need a carousel which can hold multiple images, and work like owl-carousel or slick.

Those plugins are some examples of thousands of jQuery plugins which makes it easier to build the web (when not using angular 2/4).

I would like to use jQuery plugins, however I am not aware of the issues and challenges I will be getting when using them.

Here is a list of my questions regarding Angular 2/4:

Should I use jQuery plugins when there is no alternative?

What will I loose if I do use jQuery plugins?

If I use jQuery plugins in the best way, will I still be able to use Angular Universal?

What alternatives are there?

答:
You're welcome to use jQuery plugins when there are no other alternatives, but there's almost always a better alternative than most strict JS jQuery plugins.

If you use jQuery plugins you lose many key interactions that Angular uses to create quick and compact rendering that is cross-browser compatible.

The best alternative for carousels is going to be Bootstrap - Carousel. Bootstrap is often built into most Angular boilerplates and templates that you find on GitHub. Check out https://ng-bootstrap.github.io/#/getting-started and https://ng-bootstrap.github.io/#/components/carousel. It offers quick implementation for an Angular based carousel.

Title: Angular 2/4 - Carousel & jQuery plugins


问:
How can I list all databases and all tables of my databases with a final "Attach" and list total row of each table in SQL Server?
I did this. But unfortunately that return all in many table. I want to return all in one unique table. Maybe using "UNION" but I don't know the way to do.

This is my code:

```<code>EXEC sp_msforeachdb 'select ''?''AS "DataBase", s.name, t.name AS "Tables",max(si.rows) as "Rows Line"
 from [?].sys.tables t inner join [?].sys.schemas s
 on t.schema_id = s.schema_id
 inner join [?].sys.partitions si on t.object_id  = si.object_id
 where t.name like "%ATTACH" group by s.name,t.name'`
</code>```

答:
I have found finally a solution.i just used a Stored Procedures for having the result i was looking for.So decided to post the answer here maybe that will help someone else.</p>

```<code>DECLARE @banco_nome nvarchar(MAX), @tabela_nome nvarchar(MAX)

DECLARE @banco_cursor CURSOR
DECLARE @sqlstatement nvarchar(MAX)
DECLARE @count_sql nvarchar(MAX)
DECLARE @total int

DECLARE @RegistrosFotograficos TABLE
(
  DatabaseName nvarchar(max),
  TableName nvarchar(max),
  Total int
)

SET @banco_cursor = CURSOR FORWARD_ONLY FOR
    SELECT name FROM sys.databases

OPEN @banco_cursor
FETCH NEXT FROM @banco_cursor INTO @banco_nome
WHILE @@FETCH_STATUS = 0
BEGIN
    SET @sqlstatement = 'DECLARE tabela_cursor CURSOR FORWARD_ONLY FOR SELECT TABLE_NAME FROM ' + @banco_nome + '.INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = ''BASE TABLE'' AND TABLE_NAME LIKE ''%ATTACH'' ORDER BY TABLE_NAME'
    EXEC sp_executesql @sqlstatement

    OPEN tabela_cursor
    FETCH NEXT FROM tabela_cursor INTO @tabela_nome
    WHILE @@FETCH_STATUS = 0
    BEGIN
        SET @count_sql = 'USE ' + @banco_nome + '; SELECT @total=COUNT(1) FROM ' + @tabela_nome;
        EXECUTE sp_executesql @count_sql, N'@total int OUTPUT', @total=@total OUTPUT

        INSERT INTO @RegistrosFotograficos (DatabaseName, TableName, Total) VALUES (@banco_nome, @tabela_nome, @total);

        FETCH NEXT FROM tabela_cursor INTO @tabela_nome
    END
    CLOSE tabela_cursor;
    DEALLOCATE tabela_cursor;

    FETCH NEXT FROM @banco_cursor INTO @banco_nome
END
CLOSE @banco_cursor;
DEALLOCATE @banco_cursor;

SELECT * FROM @RegistrosFotograficos
</code>```

Body:
I did this. But unfortunately that return all in many table. I want to return all in one unique table. Maybe using "UNION" but I don't know the way to do.

This is my code:

EXEC sp_msforeachdb 'select ''?''AS "DataBase", s.name, t.name AS "Tables",max(si.rows) as "Rows Line"
 from [?].sys.tables t inner join [?].sys.schemas s
 on t.schema_id = s.schema_id
 inner join [?].sys.partitions si on t.object_id  = si.object_id
 where t.name like "%ATTACH" group by s.name,t.name'`

Body:
I have found finally a solution.i just used a Stored Procedures for having the result i was looking for.So decided to post the answer here maybe that will help someone else.

DECLARE @banco_nome nvarchar(MAX), @tabela_nome nvarchar(MAX)

DECLARE @banco_cursor CURSOR
DECLARE @sqlstatement nvarchar(MAX)
DECLARE @count_sql nvarchar(MAX)
DECLARE @total int

DECLARE @RegistrosFotograficos TABLE
(
  DatabaseName nvarchar(max),
  TableName nvarchar(max),
  Total int
)

SET @banco_cursor = CURSOR FORWARD_ONLY FOR
    SELECT name FROM sys.databases

OPEN @banco_cursor
FETCH NEXT FROM @banco_cursor INTO @banco_nome
WHILE @@FETCH_STATUS = 0
BEGIN
    SET @sqlstatement = 'DECLARE tabela_cursor CURSOR FORWARD_ONLY FOR SELECT TABLE_NAME FROM ' + @banco_nome + '.INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = ''BASE TABLE'' AND TABLE_NAME LIKE ''%ATTACH'' ORDER BY TABLE_NAME'
    EXEC sp_executesql @sqlstatement

    OPEN tabela_cursor
    FETCH NEXT FROM tabela_cursor INTO @tabela_nome
    WHILE @@FETCH_STATUS = 0
    BEGIN
        SET @count_sql = 'USE ' + @banco_nome + '; SELECT @total=COUNT(1) FROM ' + @tabela_nome;
        EXECUTE sp_executesql @count_sql, N'@total int OUTPUT', @total=@total OUTPUT

        INSERT INTO @RegistrosFotograficos (DatabaseName, TableName, Total) VALUES (@banco_nome, @tabela_nome, @total);

        FETCH NEXT FROM tabela_cursor INTO @tabela_nome
    END
    CLOSE tabela_cursor;
    DEALLOCATE tabela_cursor;

    FETCH NEXT FROM @banco_cursor INTO @banco_nome
END
CLOSE @banco_cursor;
DEALLOCATE @banco_cursor;

SELECT * FROM @RegistrosFotograficos


问:
Ternary operator with String literals in Android Data Binding Library
I have an EditText and I want to set its inputType depending on if the Parameter is numeric or not:

```<code>interface Parameter {
    boolean isNumeric();
}
</code>```

I have this:

```<code>   <EditText
       ...
       android:inputType="@{parameter.isNumeric()? number : text}"/>
</code>```

But there is an error when parsing XML. I have tried by wrapping number and text values in single and double (escaped) quotation marks.

How can I solve this?

答:
The number and text values would be considered variables in Java context. You have to make sure to set the appropriate Java value. First you have to import InputType in your <data> block. Then use the relating integer values.

```<code><EditText
    android:inputType="@{parameter.isNumeric() ? InputType.TYPE_CLASS_NUMBER : InputType.TYPE_CLASS_TEXT}" />
</code>```

Body:
I have an EditText and I want to set its inputType depending on if the Parameter is numeric or not:

interface Parameter {
    boolean isNumeric();
}

I have this:

   <EditText
       ...
       android:inputType="@{parameter.isNumeric()? number : text}"/>

But there is an error when parsing XML. I have tried by wrapping number and text values in single and double (escaped) quotation marks.

How can I solve this?

Body:
The number and text values would be considered variables in Java context. You have to make sure to set the appropriate Java value. First you have to import InputType in your <data> block. Then use the relating integer values.

<EditText
    android:inputType="@{parameter.isNumeric() ? InputType.TYPE_CLASS_NUMBER : InputType.TYPE_CLASS_TEXT}" />


问:
Get all specific product types
I need to get specific product types from the database.

I know how to get all products but I need to filter by just a specific product type.

What I get to till now:

```<code>global $wpdb;
$sql = "SELECT * FROM {$wpdb->posts} WHERE post_type = 'product' AND post_status = 'publish'
</code>```

But where is the product type field?

答:
```<code>    $args = array(
       'post_type' => 'product',
       'tax_query' => array(
            array(
                'taxonomy' => 'product_type',
                'field'    => 'slug',
                'terms'    => 'simple',
            ),
        ),
     );
$products = new WP_Query($args);
var_dump($products);
</code>```

Try this

Title: Get all specific product types

Body:
I need to get specific product types from the database.

I know how to get all products but I need to filter by just a specific product type.

What I get to till now:

global $wpdb;
$sql = "SELECT * FROM {$wpdb->posts} WHERE post_type = 'product' AND post_status = 'publish'

But where is the product type field?

Body:
    $args = array(
       'post_type' => 'product',
       'tax_query' => array(
            array(
                'taxonomy' => 'product_type',
                'field'    => 'slug',
                'terms'    => 'simple',
            ),
        ),
     );
$products = new WP_Query($args);
var_dump($products);

Try this


问:
How to change returned ContentType in ASP.NET MVC controller (ActionResult)
I have ASP.NET MVC controller named dictionary with method ControlsLangJsFile.
Method returns view of users control (ASCX) which contain JavaScript variables.

When i call the method it returns variables with parsed strings, but Content Type is html/text. It should be: application/x-javascript

```<code>public ActionResult ControlsLangJsFile()
    {
        return View("~/Views/Dictionary/ControlsLangJsFile.ascx",);
    }
</code>```

How do i achieve this?

答:
Users control doesn't accept ContentType="text/xml"

Solution:

```<code>public ActionResult ControlsLangJsFile()
    {
        Response.ContentType = "text/javascript";
        return View("~/Views/Dictionary/ControlsLangJsFile.ascx");
    }
</code>```

Body:
I have ASP.NET MVC controller named dictionary with method ControlsLangJsFile.
Method returns view of users control (ASCX) which contain JavaScript variables.

When i call the method it returns variables with parsed strings, but Content Type is html/text. It should be: application/x-javascript

public ActionResult ControlsLangJsFile()
    {
        return View("~/Views/Dictionary/ControlsLangJsFile.ascx",);
    }

How do i achieve this?

Body:
Users control doesn't accept ContentType="text/xml"

Solution:

public ActionResult ControlsLangJsFile()
    {
        Response.ContentType = "text/javascript";
        return View("~/Views/Dictionary/ControlsLangJsFile.ascx");
    }


问:
ag-grid checkboxSelection default value
I have an ag-grid with a simple checkboxSelection and would like to have some rows "checked" when loading the grid/data.

```<code>{
                headerName: ' ',
                colId: 'select',
                checkboxSelection: true,
                headerCheckboxSelection: false,
                width: 22,
                maxWidth: 22,
                suppressToolPanel: true,
                suppressMenu: true,
                suppressSorting: true,
                suppressSizeToFit: true,
                suppressMovable: true,
                suppressFilter: true,
                suppressResize: true,
                pinned: 'left'
},
</code>```

Is there a callback I can use to set the selection state of a row?

答:
I needed to loop the rendered rows and select them manually after load:</p>

```<code>this.gridApi.forEachLeafNode( (node) => {
   if (node.data.id === roleId) {
       node.setSelected(true);
   }
});
</code>```

Title: ag-grid checkboxSelection default value

Body:
I have an ag-grid with a simple checkboxSelection and would like to have some rows "checked" when loading the grid/data.

{
                headerName: ' ',
                colId: 'select',
                checkboxSelection: true,
                headerCheckboxSelection: false,
                width: 22,
                maxWidth: 22,
                suppressToolPanel: true,
                suppressMenu: true,
                suppressSorting: true,
                suppressSizeToFit: true,
                suppressMovable: true,
                suppressFilter: true,
                suppressResize: true,
                pinned: 'left'
},

Is there a callback I can use to set the selection state of a row?

Body:
I needed to loop the rendered rows and select them manually after load:

this.gridApi.forEachLeafNode( (node) => {
   if (node.data.id === roleId) {
       node.setSelected(true);
   }
});