问:
SQL trouble with multiple left joins and OR
I am trying to join an uploaded CSV (to MySQL0 to multiple other SQL tables and create output, but I am getting an issue where I see my data from the first table (the uploaded CSV) but it does not match up with the other tables (existing MySQL tables). I checked to make sure that the formats of the columns upon which I LEFT JOIN are the same. Is the problem that I am using an OR statement in the final JOIN, or could it be with that statement being rudimentary fuzzy logic. </p>

```<code>$sql= "SELECT x.*, y.*, z.* FROM tbl_invoice as x LEFT JOIN conversion as y ON
y.doc_sku = x.doc_sku LEFT JOIN tbl_catalog as z ON z.distributor_sku = COALESCE(y.dist_sku, x.doc_sku) OR x.item_name like '%z.item_description%' WHERE x.timestamp IN (SELECT MAX(timestamp) FROM tbl_invoice)";
    //echo $sql;die;
    $result = $conn->query($sql);
    $res = array();
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            $res[] = $row;
        }
    }
    $html = "<table><tr><th>manufacturer</th><th>item_name</th><th>item_quantity</th><th>purchase_price</th><th>purchase_quantity</th><th>dist_sku</th><th>Total</th><th>item_description</th></tr>";
    foreach($res as $key=>$val)
    {
        $html .="<tr><td>".$val['manufacturer']."</td><td>".$val['item_name']."</td><td>".$val['item_quantity']."</td><td>".$val['purchase_price']."</td><td>".$val['purchase_quantity']."</td><td>".$val['dist_sku']."</td><td>".($val['purchase_price']-$val['price'])*$val['purchase_quantity']."</td><td>".$val['item_description']."</td></tr>";
    }
    $html .="</table>";
    echo $html;
    unlink($inputFileName);
    echo "```";print_r($res);die;
} else {
    echo "Sorry, there was an error uploading your file.";
}}?>
</code>```

答:
Your join like statement isn't working as you expect it to. It's looking for a literal copy of the string z.item_description. Your query should be

```<code>SELECT
  x.*
  , y.*
  , z.*
FROM
  tbl_invoice as x
  LEFT JOIN conversion as y
    ON y.doc_sku = x.doc_sku
  LEFT JOIN tbl_catalog as z
    ON z.distributor_sku    = COALESCE(y.dist_sku, x.doc_sku)
    OR x.item_name       like concat('%', z.item_description, '%')
WHERE
  x.timestamp IN (
    SELECT
      MAX(timestamp)
    FROM
      tbl_invoice
  )
</code>```

Body:
I am trying to join an uploaded CSV (to MySQL0 to multiple other SQL tables and create output, but I am getting an issue where I see my data from the first table (the uploaded CSV) but it does not match up with the other tables (existing MySQL tables). I checked to make sure that the formats of the columns upon which I LEFT JOIN are the same. Is the problem that I am using an OR statement in the final JOIN, or could it be with that statement being rudimentary fuzzy logic.

$sql= "SELECT x.*, y.*, z.* FROM tbl_invoice as x LEFT JOIN conversion as y ON
y.doc_sku = x.doc_sku LEFT JOIN tbl_catalog as z ON z.distributor_sku = COALESCE(y.dist_sku, x.doc_sku) OR x.item_name like '%z.item_description%' WHERE x.timestamp IN (SELECT MAX(timestamp) FROM tbl_invoice)";
    //echo $sql;die;
    $result = $conn->query($sql);
    $res = array();
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            $res[] = $row;
        }
    }
    $html = "

manufacturer	item_name	item_quantity	purchase_price	purchase_quantity	dist_sku	Total	item_description
";
    foreach($res as $key=>$val)
    {
        $html .="
".$val['manufacturer']."	".$val['item_name']."	".$val['item_quantity']."	".$val['purchase_price']."	".$val['purchase_quantity']."	".$val['dist_sku']."	".($val['purchase_price']-$val['price'])*$val['purchase_quantity']."	".$val['item_description']."
";
    }
    $html .="
";
    echo $html;
    unlink($inputFileName);
    echo "
";print_r($res);die;
} else {
    echo "Sorry, there was an error uploading your file.";
}}?>

Body:
Your join like statement isn't working as you expect it to. It's looking for a literal copy of the string z.item_description. Your query should be

SELECT
  x.*
  , y.*
  , z.*
FROM
  tbl_invoice as x
  LEFT JOIN conversion as y
    ON y.doc_sku = x.doc_sku
  LEFT JOIN tbl_catalog as z
    ON z.distributor_sku    = COALESCE(y.dist_sku, x.doc_sku)
    OR x.item_name       like concat('%', z.item_description, '%')
WHERE
  x.timestamp IN (
    SELECT
      MAX(timestamp)
    FROM
      tbl_invoice
  )


来源: stackexchange

问:
Service: No provider for Renderer2
Angular 4.2 with Typescript 2.3

I am refactoring a service that is responsible for creating a new script tag and adding it to the document.

Here is the old code:

```<code>loadScript(src:string){
    const script = document.createElement('script');
    document.body.appendChild(script);
    script.src = src;
}
</code>```

Now, I'd like to use the Renderer2 to avoid doing direct DOM manipulation. So I've injected what I need in my service and updated the code:

```<code>constructor(private renderer:Renderer2, @Inject(DOCUMENT) private document){}

loadScript(src:string){
    const script = this.renderer.createElement('script');
    this.renderer.appendChild(this.document.body,script);
    script.src = src;
}
</code>```

However, I run into this error:

Error: no provider for Renderer2!

The service belongs to a CoreModule whose only import is CommonModule from @angular/common

This plunkr demonstrates the problem

答:
You can initialize service with an instance of Renderer2 in root component

```<code>@Injectable()
class MyService {
  renderer : Renderer2;
}
...
class App {
  name:string;
  constructor(service: MyService, renderer: Renderer2) {
      service.renderer = renderer;
  }
}
</code>```

See also

Using Renderer in Angular 4

ContentLicense: CC BY-SA 4.0

Title: Service: No provider for Renderer2

Body:
Angular 4.2 with Typescript 2.3

I am refactoring a service that is responsible for creating a new script tag and adding it to the document.

Here is the old code:

loadScript(src:string){
    const script = document.createElement('script');
    document.body.appendChild(script);
    script.src = src;
}

Now, I'd like to use the Renderer2 to avoid doing direct DOM manipulation. So I've injected what I need in my service and updated the code:

constructor(private renderer:Renderer2, @Inject(DOCUMENT) private document){}

loadScript(src:string){
    const script = this.renderer.createElement('script');
    this.renderer.appendChild(this.document.body,script);
    script.src = src;
}

However, I run into this error:

Error: no provider for Renderer2!

The service belongs to a CoreModule whose only import is CommonModule from @angular/common

This plunkr demonstrates the problem

Body:
You can initialize service with an instance of Renderer2 in root component

@Injectable()
class MyService {
  renderer : Renderer2;
}
...
class App {
  name:string;
  constructor(service: MyService, renderer: Renderer2) {
      service.renderer = renderer;
  }
}

See also

Using Renderer in Angular 4

ContentLicense: CC BY-SA 3.0


问:
Simple Java multi-threaded socket application
I have this simple multi-threaded java socket application. Using classes Client.java

```<code>public class Client {

private static Socket socket;
private static boolean waitForServer = false;
public static void main(String[] args) throws IOException {
    while(true){
        socket = new Socket("localhost", ServerPortInfo.getPort());
        PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
        BufferedReader bufferedReader = new java.io.BufferedReader(new InputStreamReader(System.in));

        while(true){
            PrintWriter.println(name + " Hello");
                waitForServer = true;

            if (waitForServer){
                BufferedReader inputBufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String inputString = null;
                while((inputString = inputBufferedReader.readLine()) != null){
                    System.out.println(inputString);
                    break;
                }

            }

        }

    }
  }
}
</code>```

And Server.java

```<code>public class Server {

public static ArrayList<ServerThread> connections = new ArrayList<ServerThread>();

public static void main(String[] args) throws IOException, SQLException, ClassNotFoundException {
    // Init server functionality
    new Server().runServer();

}

// Implementing server functionality
public void runServer() throws IOException{

    ServerSocket serverSocket = new ServerSocket(ServerPortInfo.getPort());
    System.out.println("Server is running... Waiting for connections");
    while (true){
        Socket socket = serverSocket.accept();
        // After connection handle clients in threads
        ServerThread newThread = new ServerThread(socket);
        connections.add(newThread);
        newThread.start();
    }

}
}
</code>```

And then a Thread that handles that connection...

```<code>public class ServerThread extends Thread {

private static Socket socket;
public static boolean alive = true;

ServerThread(Socket socket){
    this.socket = socket;
}

public void run(){
    if (alive) {
        //DO STUFF NOW
}

}
</code>```

And now when I have multiple connections. It creates a different Thread for every connection.
What should i do when a user wants to disconnect from this server?

Should i kill the thread, socket?

I tried just saying to the thread
alive = false; so the run would just stop running. But this breaks other connections as well.

EDIT

ServerThread ->

```<code>private Socket socket;
</code>```

And a function ->

```<code>void closeConnection() throws IOException{
    this.socket.close();
}
</code>```

works like a charm.

答:
public static variables are a recipe for disaster (as I'm sure you've
      just found out the hard way). But as @cktang said, close the socket,
      then kill that thread (not the others). -@JoeC

Changed private static Socket socket; to private Socket socket;.
Closed the socket and then Thread.

Body:
I have this simple multi-threaded java socket application. Using classes Client.java

public class Client {

private static Socket socket;
private static boolean waitForServer = false;
public static void main(String[] args) throws IOException {
    while(true){
        socket = new Socket("localhost", ServerPortInfo.getPort());
        PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
        BufferedReader bufferedReader = new java.io.BufferedReader(new InputStreamReader(System.in));

        while(true){
            PrintWriter.println(name + " Hello");
                waitForServer = true;

            if (waitForServer){
                BufferedReader inputBufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String inputString = null;
                while((inputString = inputBufferedReader.readLine()) != null){
                    System.out.println(inputString);
                    break;
                }

            }

        }

    }
  }
}

And Server.java

public class Server {

public static ArrayList<ServerThread> connections = new ArrayList<ServerThread>();

public static void main(String[] args) throws IOException, SQLException, ClassNotFoundException {
    // Init server functionality
    new Server().runServer();

}

// Implementing server functionality
public void runServer() throws IOException{

    ServerSocket serverSocket = new ServerSocket(ServerPortInfo.getPort());
    System.out.println("Server is running... Waiting for connections");
    while (true){
        Socket socket = serverSocket.accept();
        // After connection handle clients in threads
        ServerThread newThread = new ServerThread(socket);
        connections.add(newThread);
        newThread.start();
    }

}
}

And then a Thread that handles that connection...

public class ServerThread extends Thread {

private static Socket socket;
public static boolean alive = true;

ServerThread(Socket socket){
    this.socket = socket;
}

public void run(){
    if (alive) {
        //DO STUFF NOW
}

}

And now when I have multiple connections. It creates a different Thread for every connection.
What should i do when a user wants to disconnect from this server?

Should i kill the thread, socket?

I tried just saying to the thread
alive = false; so the run would just stop running. But this breaks other connections as well.

EDIT

ServerThread ->

private Socket socket;

And a function ->

void closeConnection() throws IOException{
    this.socket.close();
}

works like a charm.


问:
Why am I getting a seg fault in this line of code when I try to segue from storyboard?
So, I am trying to segue a button in storyboard to another ViewController. However, every time I tap the button, the app just crashes. This is the line of code that gets highlighted when the app crashes.

```<code>    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    let barcodeViewController: BarcodeReaderViewController = segue.destination as! BarcodeReaderViewController
    barcodeViewController.delegate = self

}
</code>```

This is my BarCodeVC

```<code>import UIKit
import AVFoundation

protocol BarcodeDelegate {
  func barcodeReaded(barcode: String)
}

class BarcodeViewController: UIViewController,
                             AVCaptureMetadataOutputObjectsDelegate {

var delegate: BarcodeDelegate?

var videoCaptureDevice: AVCaptureDevice =
 AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
var device = AVCaptureDevice.defaultDevice(withMediaType:
  AVMediaTypeVideo)
var output = AVCaptureMetadataOutput()
var previewLayer: AVCaptureVideoPreviewLayer?

var captureSession = AVCaptureSession()
var code: String?

override func viewDidLoad() {
  super.viewDidLoad()

  self.view.backgroundColor = UIColor.clear
  self.setupCamera()
}

private func setupCamera() {

  let input = try? AVCaptureDeviceInput(device: videoCaptureDevice)

  if self.captureSession.canAddInput(input) {
      self.captureSession.addInput(input)
  }

  self.previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)

  if let videoPreviewLayer = self.previewLayer {
      videoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
      videoPreviewLayer.frame = self.view.bounds
      view.layer.addSublayer(videoPreviewLayer)
  }

  let metadataOutput = AVCaptureMetadataOutput()
  if self.captureSession.canAddOutput(metadataOutput) {
      self.captureSession.addOutput(metadataOutput)

      metadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
      metadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode, AVMetadataObjectTypeEAN13Code]
  } else {
      print("Could not add metadata output")
  }
}

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

   if (captureSession.isRunning == false) {
      captureSession.startRunning();
   }
}

override func viewWillDisappear(_ animated: Bool) {
  super.viewWillDisappear(animated)

  if (captureSession.isRunning == true) {
     captureSession.stopRunning();
  }
}

func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
   // This is the delegate'smethod that is called when a code is readed
   for metadata in metadataObjects {
       let readableObject = metadata as! AVMetadataMachineReadableCodeObject
       let code = readableObject.stringValue

       self.dismiss(animated: true, completion: nil)
       self.delegate?.barcodeReaded(barcode: code!)
       print(code!)
   }
 }
}
</code>```

My segue is just a simple drag to show, not programmatically. So I am a bit confused as to why it's crashing.

Here's the error:

Could not cast value of type 'BarCodeProj.ViewController'
        (0x1000361b0) to 'BarCodeProj.BarcodeViewController'
        (0x100035a78).

答:
This is a case where the console error tells you everything you need to know. segue.destination is not a BarcodeReaderViewController so your attempt to cast it to one (with as!) is causing a catastrophic failure.

First, check in your storyboard and make sure you set the type of the view controller properly (the one that you are transitioning to.)

Do this by selecting the appropriate view controller in the storyboard and checking here:

Body:
So, I am trying to segue a button in storyboard to another ViewController. However, every time I tap the button, the app just crashes. This is the line of code that gets highlighted when the app crashes.

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    let barcodeViewController: BarcodeReaderViewController = segue.destination as! BarcodeReaderViewController
    barcodeViewController.delegate = self

}

This is my BarCodeVC

import UIKit
import AVFoundation

protocol BarcodeDelegate {
  func barcodeReaded(barcode: String)
}

class BarcodeViewController: UIViewController,
                             AVCaptureMetadataOutputObjectsDelegate {

var delegate: BarcodeDelegate?

var videoCaptureDevice: AVCaptureDevice =
 AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
var device = AVCaptureDevice.defaultDevice(withMediaType:
  AVMediaTypeVideo)
var output = AVCaptureMetadataOutput()
var previewLayer: AVCaptureVideoPreviewLayer?

var captureSession = AVCaptureSession()
var code: String?

override func viewDidLoad() {
  super.viewDidLoad()

  self.view.backgroundColor = UIColor.clear
  self.setupCamera()
}

private func setupCamera() {

  let input = try? AVCaptureDeviceInput(device: videoCaptureDevice)

  if self.captureSession.canAddInput(input) {
      self.captureSession.addInput(input)
  }

  self.previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)

  if let videoPreviewLayer = self.previewLayer {
      videoPreviewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
      videoPreviewLayer.frame = self.view.bounds
      view.layer.addSublayer(videoPreviewLayer)
  }

  let metadataOutput = AVCaptureMetadataOutput()
  if self.captureSession.canAddOutput(metadataOutput) {
      self.captureSession.addOutput(metadataOutput)

      metadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
      metadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode, AVMetadataObjectTypeEAN13Code]
  } else {
      print("Could not add metadata output")
  }
}

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

   if (captureSession.isRunning == false) {
      captureSession.startRunning();
   }
}

override func viewWillDisappear(_ animated: Bool) {
  super.viewWillDisappear(animated)

  if (captureSession.isRunning == true) {
     captureSession.stopRunning();
  }
}

func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
   // This is the delegate'smethod that is called when a code is readed
   for metadata in metadataObjects {
       let readableObject = metadata as! AVMetadataMachineReadableCodeObject
       let code = readableObject.stringValue

       self.dismiss(animated: true, completion: nil)
       self.delegate?.barcodeReaded(barcode: code!)
       print(code!)
   }
 }
}

My segue is just a simple drag to show, not programmatically. So I am a bit confused as to why it's crashing.

Here's the error:

Could not cast value of type 'BarCodeProj.ViewController'
        (0x1000361b0) to 'BarCodeProj.BarcodeViewController'
        (0x100035a78).


问:
cannot resolve symbol 'REQUEST_CODE_READ_CONTACTS
I'm trying to request permission to access the ringer using this:

```<code>     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
            && ActivityCompat.checkSelfPermission(MainActivity.this,
            Manifest.permission.READ_CONTACTS)
            == PackageManager.PERMISSION_DENIED) {

        ActivityCompat.requestPermissions(MainActivity.this,
                new String[]{ Manifest.permission.READ_CONTACTS },
                REQUEST_CODE_READ_CONTACTS);
    }
</code>```

What I don't understand is that the code REQUEST_CODE_READ_CONTACTSis showing up with the error "cannot resolve symbol 'REQUEST_CODE_READ_CONTACTS'.

答:
The value is a request code that you have to define yourself.

```<code>private static final int REQUEST_CODE_READ_CONTACTS = 99; // Can be any value >= 0
</code>```

You can use it to determine which permission request the user has responded to in the onRequestPermissionsResult() callback by checking for the matching value.

```<code>public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case REQUEST_CODE_READ_CONTACTS:
            // Do your thing
            break;
        case ...
    }
}
</code>```

Body:
I'm trying to request permission to access the ringer using this:

     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
            && ActivityCompat.checkSelfPermission(MainActivity.this,
            Manifest.permission.READ_CONTACTS)
            == PackageManager.PERMISSION_DENIED) {

        ActivityCompat.requestPermissions(MainActivity.this,
                new String[]{ Manifest.permission.READ_CONTACTS },
                REQUEST_CODE_READ_CONTACTS);
    }

What I don't understand is that the code REQUEST_CODE_READ_CONTACTSis showing up with the error "cannot resolve symbol 'REQUEST_CODE_READ_CONTACTS'.

Body:
The value is a request code that you have to define yourself.

private static final int REQUEST_CODE_READ_CONTACTS = 99; // Can be any value >= 0

You can use it to determine which permission request the user has responded to in the onRequestPermissionsResult() callback by checking for the matching value.

public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case REQUEST_CODE_READ_CONTACTS:
            // Do your thing
            break;
        case ...
    }
}


问:
Three JS render array of objects
I want to render an array of objects in a three.js scene

My issue is that when I try to render the object three.js returns me this error

```<code>three.module.js:8589 Uncaught TypeError: Cannot read property 'center' of undefined
at Sphere.copy (three.module.js:8589)
at Frustum.intersectsObject (three.module.js:9344)
at projectObject (three.module.js:21975)
at projectObject (three.module.js:22020)
at WebGLRenderer.render (three.module.js:21776)
at render (eval at ./app/components/View/scene.js (1.chunk.js:23),
</code>```

This is the object i'm trying to render

```<code>const models = {
 cube: [
{
  type: 'cube',
  name: 'cube_1',
  wire: true,
  material: {
    color: 'tomato',
  },
  soma: {
    position: {
      x: 0,
      y: 0,
      z: 0
    },
    rotation: {
      x: 45,
      y: 45,
      z: 45
    },
    scale: {
      x: 1,
      y: 1,
      z: 1
    },
    size: {
      width: 40,
      height: 40,
      depth: 40
    }
  }
 }
]
</code>```

}

And this is what I do to render it

```<code>  const { soma, name, type, material, wire } = models.cube[0]
  const widthC = soma.size.width
  const heightC = soma.size.height
  const depthC = soma.size.depth
  window[`wire_${name}`] = new THREE.EdgesGeometry(new THREE.BoxGeometry( widthC, heightC, depthC ));
  window[`wire_mat_${name}`] = new THREE.LineBasicMaterial( { ...material } );
  window[`model_${name}`] = new THREE.LineSegments( `wire_${name}`,`wire_mat_${name}` )
  scene.add( `model_${name}` );
</code>```

答:
I believe you are posting a PHP/javascript mixed code snipet. It is a little confusing at first for non PHP users, but it looks like you are passing strings instead of objects in the 2 last lines of the code:

```<code>window['model_${name}'] = new THREE.LineSegments( 'wire_${name}','wire_mat_${name}' );
scene.add( 'model_${name}' );
</code>```

which should be instead:

```<code>window['model_${name}'] = new THREE.LineSegments( window['wire_${name}'],window['wire_mat_${name}'] );

scene.add( window['model_${name}'] );
</code>```

Hope it will help you move forward...

Title: Three JS render array of objects

Body:
I want to render an array of objects in a three.js scene

My issue is that when I try to render the object three.js returns me this error

three.module.js:8589 Uncaught TypeError: Cannot read property 'center' of undefined
at Sphere.copy (three.module.js:8589)
at Frustum.intersectsObject (three.module.js:9344)
at projectObject (three.module.js:21975)
at projectObject (three.module.js:22020)
at WebGLRenderer.render (three.module.js:21776)
at render (eval at ./app/components/View/scene.js (1.chunk.js:23),

This is the object i'm trying to render

const models = {
 cube: [
{
  type: 'cube',
  name: 'cube_1',
  wire: true,
  material: {
    color: 'tomato',
  },
  soma: {
    position: {
      x: 0,
      y: 0,
      z: 0
    },
    rotation: {
      x: 45,
      y: 45,
      z: 45
    },
    scale: {
      x: 1,
      y: 1,
      z: 1
    },
    size: {
      width: 40,
      height: 40,
      depth: 40
    }
  }
 }
]

}

And this is what I do to render it

  const { soma, name, type, material, wire } = models.cube[0]
  const widthC = soma.size.width
  const heightC = soma.size.height
  const depthC = soma.size.depth
  window[`wire_${name}`] = new THREE.EdgesGeometry(new THREE.BoxGeometry( widthC, heightC, depthC ));
  window[`wire_mat_${name}`] = new THREE.LineBasicMaterial( { ...material } );
  window[`model_${name}`] = new THREE.LineSegments( `wire_${name}`,`wire_mat_${name}` )
  scene.add( `model_${name}` );

Body:
I believe you are posting a PHP/javascript mixed code snipet. It is a little confusing at first for non PHP users, but it looks like you are passing strings instead of objects in the 2 last lines of the code:

window['model_${name}'] = new THREE.LineSegments( 'wire_${name}','wire_mat_${name}' );
scene.add( 'model_${name}' );

which should be instead:

window['model_${name}'] = new THREE.LineSegments( window['wire_${name}'],window['wire_mat_${name}'] );

scene.add( window['model_${name}'] );

Hope it will help you move forward...


问:
Is there anything else to do Audio in 92khz to 192khz?
I spend lot of time researching/finding a best developer friendly framework or libraries for cross platform to deal with solid/accurate/lipsync sort of audio solution. Still could not find one which can be used for cross platform.

I tried GStreamer (was the best one) but it is best for linux as it covers CELT/Vorbis/Speex (encoder/decoder), GStreamer does the great job for Linux. But porting Gstreamer to Windows and Mac platform is not friendly, and lot of restrictions, and facing lot of problems, where i found myself its not the best way to build better application, the way i know about audio.

Is there any audio libraries or framework which can handle lowest latency for any cross platform ? No matter what language it is C/ADA/LUA/Python/Java..., to study from that libraries. To build my own freedom of audio quality over internet for musicians/conversation peer 2 peer in RTP method to have maximum range of 192 khz.

Expecting experts, advise.

```<code>My project is:
1. Peer 1 - playing electrical guiter from UK (london)
2. Peer 2 - playing drums from USA (new york)
3. Peer 3 - playing bass guiter from UK (luton)
</code>```

And Peer 4 is listening, and doing recording in Holland (amsterdam)

Thanks in advance.

答: It's C++ and i don't know if it fully fits your bill, but RtAudio provides a nice and easy to use cross-platform wrapper for realtime audio output & input.</p>

ContentLicense: CC BY-SA 2.5

Body:
I spend lot of time researching/finding a best developer friendly framework or libraries for cross platform to deal with solid/accurate/lipsync sort of audio solution. Still could not find one which can be used for cross platform.

I tried GStreamer (was the best one) but it is best for linux as it covers CELT/Vorbis/Speex (encoder/decoder), GStreamer does the great job for Linux. But porting Gstreamer to Windows and Mac platform is not friendly, and lot of restrictions, and facing lot of problems, where i found myself its not the best way to build better application, the way i know about audio.

Is there any audio libraries or framework which can handle lowest latency for any cross platform ? No matter what language it is C/ADA/LUA/Python/Java..., to study from that libraries. To build my own freedom of audio quality over internet for musicians/conversation peer 2 peer in RTP method to have maximum range of 192 khz.

Expecting experts, advise.

My project is:
1. Peer 1 - playing electrical guiter from UK (london)
2. Peer 2 - playing drums from USA (new york)
3. Peer 3 - playing bass guiter from UK (luton)

And Peer 4 is listening, and doing recording in Holland (amsterdam)

Thanks in advance.


问:
display the UpdateView form on the same page as CreateView form in django
I want to display the UpdateView form on the same page as CreateView form so whenever "Edit" button is clicked the UpdateView form is displayed on the same page

```<code><button type="button" class="edit_btn" data-url="{% url 'parts:stock_update_view' stock.id %}">Edit</button>
</code>```

ajax for edit button:

```<code>         $.ajax({
             url: $(this).data('url'),
             data: {
             },
             dataType: 'json',
             success: function (data) {
             alert(data.name);
             }
         });
     }
  });
class stock_update_view(UpdateView):
    model = part_stock
    fields = ['part_id','entry_date','supplier','amount','remaining']
    success_url = reverse_lazy('parts:part_list')
    template_name = 'part_detail.html'

    def get_context_data(self, **kwargs):
        context = super(stock_update_view, self).get_context_data(**kwargs)
        context['update_form'] = context.get('form')
        return context

    def get(self, request, *args, **kwargs):
        username = request.GET.get('username', None)
        data = {

        }
        return JsonResponse(data)
</code>```

I want to get back the UpdateView form as jsonResponse so that I can render it in my template.after returning context['update_form'] = context.get('form') will I be able to render the pre-filled form in my template if yes then how can I  return it?

答:
You can define get_initial() function like this:

```<code>def get_initial(self):
    initial = {
                'part_id' : self.request.user.part_id
                'entry_date: self.....
              }
    return initial
</code>```

This function will pre-populate the form which you are passing in the context.

Body:
I want to display the UpdateView form on the same page as CreateView form so whenever "Edit" button is clicked the UpdateView form is displayed on the same page

<button type="button" class="edit_btn" data-url="{% url 'parts:stock_update_view' stock.id %}">Edit</button>

ajax for edit button:

         $.ajax({
             url: $(this).data('url'),
             data: {
             },
             dataType: 'json',
             success: function (data) {
             alert(data.name);
             }
         });
     }
  });
class stock_update_view(UpdateView):
    model = part_stock
    fields = ['part_id','entry_date','supplier','amount','remaining']
    success_url = reverse_lazy('parts:part_list')
    template_name = 'part_detail.html'

    def get_context_data(self, **kwargs):
        context = super(stock_update_view, self).get_context_data(**kwargs)
        context['update_form'] = context.get('form')
        return context

    def get(self, request, *args, **kwargs):
        username = request.GET.get('username', None)
        data = {

        }
        return JsonResponse(data)

I want to get back the UpdateView form as jsonResponse so that I can render it in my template.after returning context['update_form'] = context.get('form') will I be able to render the pre-filled form in my template if yes then how can I  return it?

Body:
You can define get_initial() function like this:

def get_initial(self):
    initial = {
                'part_id' : self.request.user.part_id
                'entry_date: self.....
              }
    return initial

This function will pre-populate the form which you are passing in the context.


问:
Do I need to duplicate code on every EC2 instance running behind an ELB?
Hi this is a very noob question, but I am trying to deply my Node JS API server on AWS.
Everything is working fine with one m1.large instance that my Front End running on S3 connects to.
Now I want to Scale and put my EC2 instance and possibly many more behing and ELB and an Auto Scaling Group.
Do I need to duplicate my server code on every EC2 instance?
If so , I assume I'll have to create a seperate DB server which all of the EC2 instances will connect to.
Am I right,anyone experienced in Amazon AWS can answer this, I tried googling but most of the links point to detailed tutorials which however don't answer my question.
Any help would be much appreciated. Thanks </p>

答:
One other option is to use Elastic Beanstalk to Deploy NodeJs applications. Here is the guide specific to NodeJs. This will take care of most of the stuff which you would need to do otherwise if you only use EC2 For example: ELB, Autoscaling Cloudwatch etc.

For Database, you may want to use the Master Slave with Read Replicas. Another option is to evaluate NoSql Databases like DynamoDB if it fits your use case. The scalability of DynamoDB tables is managed by AWS so you dont need to worry about it.


问:
How can I view the contents of a prepared statement?
I'm working on learning to use prepared statements with mysqli in PHP and usually, if I'm having a problem with a query I just echo it to the screen to see what it looks like as a first step.

How can I do that with a prepared statement?

I'd like to see the SQL statement after the variables are substituted.

答: You can use tool like Lottip. The idea is act like MySQL proxy. It parses MySQL packets, extracts query and it's params so you can see prepared statements with it's content.</p>


问:
Google Play - Fully Shadowed apk
I have an existing app on the PlayStore. I am releasing new version of the app as staged rollout. However, I am not able to publish the app due to "Fully Shadowed APK" error.

So far, I haven't found any documentation as to how to resolve this error. Anyone else faced this?

答:
I had exactly the same issue and resolved it by using the following versionCode entry in config.xml:

```<code><widget id="io.cordova.hellocordova"
  version="3.1.1"
  android-versionCode="3001001"
</code>```

Here android-versionCode is critical. It must be an integer greater than the number associated with last APK that you have uploaded. Due to some reason my previous version had an additional zero in between creating a higher number which went unnoticed. Since I can't change that because its published I added a zero in the new versionCode and made it 3001001 instead of 300101.

Worked perfectly.

Hope that helps.

Title: Google Play - Fully Shadowed apk

Body:
I had exactly the same issue and resolved it by using the following versionCode entry in config.xml:

<widget id="io.cordova.hellocordova"
  version="3.1.1"
  android-versionCode="3001001"

Here android-versionCode is critical. It must be an integer greater than the number associated with last APK that you have uploaded. Due to some reason my previous version had an additional zero in between creating a higher number which went unnoticed. Since I can't change that because its published I added a zero in the new versionCode and made it 3001001 instead of 300101.

Worked perfectly.

Hope that helps.


答:
The problem is with

```<code>public static boolean alive = true;
private static Socket socket;
</code>```

As it is static, it influences all your ServerThread's, but each ServerThread (aka connected client) should have its own socket and flag indicating if it's alive or not.

Remove the static modifier from both attributes and
make the flag
private volatile boolean alive = true;

At first close the socket a then stop the thread (and remove it from the list).

Title: Simple Java multi-threaded socket application

Body:
The problem is with

public static boolean alive = true;
private static Socket socket;

As it is static, it influences all your ServerThread's, but each ServerThread (aka connected client) should have its own socket and flag indicating if it's alive or not.

Remove the static modifier from both attributes and
make the flag
private volatile boolean alive = true;

At first close the socket a then stop the thread (and remove it from the list).


问:
Data labels in linechart Qt Charts
I am trying to add data labels in LineChart using Qt Charts
like this Image.

I am not able to figure out how I can do that. Any help will be appreciated.

I am using this example https://doc.qt.io/qt-5/qtcharts-linechart-example.html

```<code>int main(int argc, char *argv[])
{
QApplication a(argc, argv);

QLineSeries *series = new QLineSeries();

series->append(0, 6);
series->append(2, 4);
series->append(3, 8);
series->append(7, 4);
series->append(10, 5);

QChart *chart = new QChart();
chart->legend()->hide();
chart->addSeries(series);
chart->createDefaultAxes();
chart->setTitle("Simple line chart example");

QChartView *chartView = new QChartView(chart);
chartView->setRenderHint(QPainter::Antialiasing);

QMainWindow window;
window.setCentralWidget(chartView);
window.resize(400, 300);
window.show();

return a.exec();
}
</code>```

I get following output

I want something like this

答:
Have you tried to set the labels to visible?<br>   </p>

```<code>QLineSeries *series = new QLineSeries();
series->setPointLabelsVisible(true);    // is false by default
series->setPointLabelsColor(Qt::black);
series->setPointLabelsFormat("@yPoint");
</code>```

Title: Data labels in linechart Qt Charts

Body:
I am trying to add data labels in LineChart using Qt Charts
like this Image.

I am not able to figure out how I can do that. Any help will be appreciated.

I am using this example https://doc.qt.io/qt-5/qtcharts-linechart-example.html

int main(int argc, char *argv[])
{
QApplication a(argc, argv);

QLineSeries *series = new QLineSeries();

series->append(0, 6);
series->append(2, 4);
series->append(3, 8);
series->append(7, 4);
series->append(10, 5);

QChart *chart = new QChart();
chart->legend()->hide();
chart->addSeries(series);
chart->createDefaultAxes();
chart->setTitle("Simple line chart example");

QChartView *chartView = new QChartView(chart);
chartView->setRenderHint(QPainter::Antialiasing);

QMainWindow window;
window.setCentralWidget(chartView);
window.resize(400, 300);
window.show();

return a.exec();
}

I get following output

I want something like this

Body:
Have you tried to set the labels to visible?

QLineSeries *series = new QLineSeries();
series->setPointLabelsVisible(true);    // is false by default
series->setPointLabelsColor(Qt::black);
series->setPointLabelsFormat("@yPoint");


问:
Why is __debug__ not in the keywords list when it's a keyword?
__debug__ is a built-in constant, which, according to the docs on constants, doesn't seem like an implementation detail.

When trying to assign to it (which isn't supported as the docs state) the following error message is displayed:

```<code>>>> __debug__ = False
  File "<stdin>", line 1
SyntaxError: assignment to keyword
</code>```

Apparently, according to the message, it's a keyword, but:

```<code>>>> from keyword import kwlist
>>> '__debug__' in kwlist
False
</code>```

Which seems odd. None, True and False, also listed as constants, are contained in the kwlist.

Why isn't __debug__ in the keyword list?

答: It's technically not a keyword in the sense of the Python grammar. There's a specific check in the compiler that prevents assignment to __debug__, but as far as the grammar is concerned, __debug__ isn't a keyword, and keyword.kwlist is generated from the grammar.

Body:
__debug__ is a built-in constant, which, according to the docs on constants, doesn't seem like an implementation detail.

When trying to assign to it (which isn't supported as the docs state) the following error message is displayed:

>>> __debug__ = False
  File "<stdin>", line 1
SyntaxError: assignment to keyword

Apparently, according to the message, it's a keyword, but:

>>> from keyword import kwlist
>>> '__debug__' in kwlist
False

Which seems odd. None, True and False, also listed as constants, are contained in the kwlist.

Why isn't __debug__ in the keyword list?


问:
Delete postman cache
I use Postman extension to check out my RESTful APIs

I am trying to make a request to my "localhost", but it seems to have cached one of the query parameters.

I tried clearing cache of my chrome browser but this does not seem to work. I went to the extent of even changing the API resource name.

Has anyone come across such an issue?

答:
Cache-Control request header can be used but one thing to clarify

no-cache does not mean do not cache. In fact, it means on every HTTP request it "revalidate with server" before using any cached response. If the server says that the resource is still valid then the cache will still use the cached version.

while no-store is effectively asking to not cache at all and is intended not to to store anything in the cache.

Title: Delete postman cache


问:
Can we write independent of machine(i.e. independent of OS) code in asp.net?
As i have read MSIL manages the code to make it independent of machine;but i have also read that DOT NET just provide windows independence not Plateform.
Please Explain if </p>

答:
You can use Mono on Linux and Macintosh

For Mono compatibility, look here: http://www.mono-project.com/Compatibility


问:
C# How to get multiple elements in textfile with in basics for
Here is file data that I want to use and I´m more familiar with python and I can´t find solution what I need here. Thanks for helping.

prices:

Some sold "something 1", price is 20 £

Some sold "something 2", price is 40 £

Some sold "something 3", price is 60 £

Some sold "something 4", price is 80 £

Some sold "something 5", price is 100 £

```<code>using System;
using System.IO;

namespace CalcPrices
{
    internal class Program
    {
        private static void Main()
        {
            string[] lines = File.ReadAllLines(
                @"C:\Users\Eggii\Desktop\code\c# katse\GoodsPrices\GoodsPrices\bin\Debug\PriceOfSoldGoods.txt");

            for (int i = 0; i < lines.Length; i++)
            {
                string[] line = lines[i].Split();

                for (int j = 0; j < line.Length; j++)
                {
                    Console.WriteLine(line[6]);

                    // Output should be something like:
                    // 20
                    // 40
                    // 60
                    // 80
                    // 100
                    // because I want every 7th element in line
                }
            }
        }
    }
}
</code>```

答:
Change this :

```<code>string[] line = lines[i].Split();
</code>```

for this :

```<code>string[] line = lines[i].Split(' ');
</code>```

Doing so will split the string with the white space delimiter.

Body:
Here is file data that I want to use and I´m more familiar with python and I can´t find solution what I need here. Thanks for helping.

prices:

Some sold "something 1", price is 20 £

Some sold "something 2", price is 40 £

Some sold "something 3", price is 60 £

Some sold "something 4", price is 80 £

Some sold "something 5", price is 100 £

using System;
using System.IO;

namespace CalcPrices
{
    internal class Program
    {
        private static void Main()
        {
            string[] lines = File.ReadAllLines(
                @"C:\Users\Eggii\Desktop\code\c# katse\GoodsPrices\GoodsPrices\bin\Debug\PriceOfSoldGoods.txt");

            for (int i = 0; i < lines.Length; i++)
            {
                string[] line = lines[i].Split();

                for (int j = 0; j < line.Length; j++)
                {
                    Console.WriteLine(line[6]);

                    // Output should be something like:
                    // 20
                    // 40
                    // 60
                    // 80
                    // 100
                    // because I want every 7th element in line
                }
            }
        }
    }
}

Body:
Change this :

string[] line = lines[i].Split();

for this :

string[] line = lines[i].Split(' ');

Doing so will split the string with the white space delimiter.


问:
why is strcmp not working in c?
I've just started to learn c and i wanted to try the strcmp function, but it somehow always gives me the result "1", if I run it. Doesn't matter what strings I type in. Since the first string is shorter than the second, i expected "-1" as a result.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
char array1[]="na";
char array2[]="kskkjnkjnknjd";
int i;

i= strcmp(array1,array2);

printf(" %d", i);

    return 0;
}
</code>```

I also already tried to get rid of the i variable and just write "printf(" %d", strcmp(array1, array2)); and replacing the %d by a %u, but also not working. I've already searched the web and tried figuring it out for myself, probably just a simple mistake, would be glad if anyone could help. :)

答:
Look at this little program, which is structured kind of like your own program.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
  char array1[]="a";
  char array2[]="b";
  int i;

  i = strcmp(array1,array2);

  printf(" %d\n", i);

  return 0;
}
</code>```

Compile and run that, and it returns a negative integer. (It returns -1 on my gcc box.)

That's because "the strcmp function returns a negative, zero, or positive integer depending on whether the object pointed to by s1 is less than, equal to, or greater than the object pointed to by s2."

Title: why is strcmp not working in c?

Body:
I've just started to learn c and i wanted to try the strcmp function, but it somehow always gives me the result "1", if I run it. Doesn't matter what strings I type in. Since the first string is shorter than the second, i expected "-1" as a result.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
char array1[]="na";
char array2[]="kskkjnkjnknjd";
int i;

i= strcmp(array1,array2);

printf(" %d", i);

    return 0;
}

I also already tried to get rid of the i variable and just write "printf(" %d", strcmp(array1, array2)); and replacing the %d by a %u, but also not working. I've already searched the web and tried figuring it out for myself, probably just a simple mistake, would be glad if anyone could help. :)

Body:
Look at this little program, which is structured kind of like your own program.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void)
{
  char array1[]="a";
  char array2[]="b";
  int i;

  i = strcmp(array1,array2);

  printf(" %d\n", i);

  return 0;
}

Compile and run that, and it returns a negative integer. (It returns -1 on my gcc box.)

That's because "the strcmp function returns a negative, zero, or positive integer depending on whether the object pointed to by s1 is less than, equal to, or greater than the object pointed to by s2."


问:
http client vertx in unix
I'm getting an issue when running vertx on a Unix server. When full message is received the end handler does not work.

```<code>HttpClientRequest request = client.post (8580, "localhost", "/", response ->
{

  if (response.statusCode () == 200) {
    response.handler (t -> {

        LOG.info ("RECEIVE DATA: " + t.toString ());

    });
    response.endHandler (t -> {
        LOG.info ("endHandler: DONE"); //DO NOT PRINT ON LOG FILE
    });

  } else {
    LOG.info  ("Sent error:"+response.statusMessage ());
  }
});
</code>```

My source demo: https://github.com/blueskyvn/vertx_client.

答:
You should close your HTTP client after request is completed. So, move client.close(); line to the response handler.

Move your entire code for working with HTTP client to the verticle. You can just move it to your HttpVerticle class and call it after server is started. Use listen method with callback.

Title: http client vertx in unix

Body:
I'm getting an issue when running vertx on a Unix server. When full message is received the end handler does not work.

HttpClientRequest request = client.post (8580, "localhost", "/", response ->
{

  if (response.statusCode () == 200) {
    response.handler (t -> {

        LOG.info ("RECEIVE DATA: " + t.toString ());

    });
    response.endHandler (t -> {
        LOG.info ("endHandler: DONE"); //DO NOT PRINT ON LOG FILE
    });

  } else {
    LOG.info  ("Sent error:"+response.statusMessage ());
  }
});

My source demo: https://github.com/blueskyvn/vertx_client.


答:
You need to split line by whitespace and remove inner loop:

```<code>using System;
using System.IO;

namespace CalcPrices
{
    internal class Program
    {
        private static void Main()
        {
            string[] lines = File.ReadAllLines(
                @"C:\Users\Eggii\Desktop\code\c# katse\GoodsPrices\GoodsPrices\bin\Debug\PriceOfSoldGoods.txt");

            for (int i = 0; i < lines.Length; i++)
            {
                string[] line = lines[i].Split(' ');
                Console.WriteLine(line[6]);
            }
        }
    }
}
</code>```

If you want to read all data into one line so you need to change code for this:

```<code>    ...
    internal class Program
    {
        private static void Main()
        {
            string line = File.ReadAllText(
                @"C:\Users\Eggii\Desktop\code\c# katse\GoodsPrices\GoodsPrices\bin\Debug\PriceOfSoldGoods.txt");

            string[] splitLines = line.Split(' ');
            for (int j = 6; j < line.Length; j += 8)
            {
                Console.WriteLine(line[j]);
            }
        }
    }
</code>```

Title: C# How to get multiple elements in textfile with in basics for

Body:
You need to split line by whitespace and remove inner loop:

using System;
using System.IO;

namespace CalcPrices
{
    internal class Program
    {
        private static void Main()
        {
            string[] lines = File.ReadAllLines(
                @"C:\Users\Eggii\Desktop\code\c# katse\GoodsPrices\GoodsPrices\bin\Debug\PriceOfSoldGoods.txt");

            for (int i = 0; i < lines.Length; i++)
            {
                string[] line = lines[i].Split(' ');
                Console.WriteLine(line[6]);
            }
        }
    }
}

If you want to read all data into one line so you need to change code for this:

    ...
    internal class Program
    {
        private static void Main()
        {
            string line = File.ReadAllText(
                @"C:\Users\Eggii\Desktop\code\c# katse\GoodsPrices\GoodsPrices\bin\Debug\PriceOfSoldGoods.txt");

            string[] splitLines = line.Split(' ');
            for (int j = 6; j < line.Length; j += 8)
            {
                Console.WriteLine(line[j]);
            }
        }
    }


问:
Photorec missing library libjpeg.so.62
I am trying to undelete a file from my NAS with PhotoRec tool on USB. However when I try to run it, i get the following error:

```<code>./photorec: error while loading shared libraries: libjpeg.so.62: cannot open shared object file: No such file or directory
</code>```

I am aware that it's saying I have to install libjpeg package, however I can not do so because it's a WD machine running their proprietary OS.

Is there another way of running Photorec and bypass this error?
From what I can see on it's official page, the specified library is optional as stated here.

Jpeg library - Optional, used by PhotoRec to improved JPEG recovery rate

Since the file is not a JPEG image I don't need this improvement.

Also I can run TestDisk just fine, however it can't find the deleted file and from what I've read, PhotoRec is better in performing such tasks.

Any help is appreciated (suggestions for another tool as well).

答:
I have found an answer to the problem on the cgsecurity forums.

Here is a link to the forum post where you can download a compiled version of the libjpeg library and run Photorec.

Instructions can be found in the post itself and are very simple:

Download the compressed file.

Uncompress it in the /ur/lib/ directory.

Check if library is in fact added with the following command ldconfig -v | grep libjpeg.

Run Photorec.

Title: Photorec missing library libjpeg.so.62

Body:
I am trying to undelete a file from my NAS with PhotoRec tool on USB. However when I try to run it, i get the following error:

./photorec: error while loading shared libraries: libjpeg.so.62: cannot open shared object file: No such file or directory

I am aware that it's saying I have to install libjpeg package, however I can not do so because it's a WD machine running their proprietary OS.

Is there another way of running Photorec and bypass this error?
From what I can see on it's official page, the specified library is optional as stated here.

Jpeg library - Optional, used by PhotoRec to improved JPEG recovery rate

Since the file is not a JPEG image I don't need this improvement.

Also I can run TestDisk just fine, however it can't find the deleted file and from what I've read, PhotoRec is better in performing such tasks.

Any help is appreciated (suggestions for another tool as well).


答:
If you copied the code above from answer in this topic
then just initialize it with 1 and add this method in your code

```<code>public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults){

    switch (requestCode){
        case REQUEST_CODE_READ_CONTACTS:
            if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                READ_CONTACTS_GRANTED = true;
            }
    }
    if(READ_CONTACTS_GRANTED){
        loadContacts();
    }
    else{
        Toast.makeText(this, "Allow permission in settings", Toast.LENGTH_LONG).show();
    }
}
</code>```

Body:
I'm trying to request permission to access the ringer using this:

     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
            && ActivityCompat.checkSelfPermission(MainActivity.this,
            Manifest.permission.READ_CONTACTS)
            == PackageManager.PERMISSION_DENIED) {

        ActivityCompat.requestPermissions(MainActivity.this,
                new String[]{ Manifest.permission.READ_CONTACTS },
                REQUEST_CODE_READ_CONTACTS);
    }

What I don't understand is that the code REQUEST_CODE_READ_CONTACTSis showing up with the error "cannot resolve symbol 'REQUEST_CODE_READ_CONTACTS'.

Body:
If you copied the code above from answer in this topic
then just initialize it with 1 and add this method in your code

public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults){

    switch (requestCode){
        case REQUEST_CODE_READ_CONTACTS:
            if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                READ_CONTACTS_GRANTED = true;
            }
    }
    if(READ_CONTACTS_GRANTED){
        loadContacts();
    }
    else{
        Toast.makeText(this, "Allow permission in settings", Toast.LENGTH_LONG).show();
    }
}


答: Theoretically and technically .NET provides platform independence. Practically there are no implementations from Microsoft of .NET outside Windows for obvious reasons. There is Mono for other platforms that is mostly compatible but you need to check if the part of the framework you are using is supported on Mono. Most of ASP.NET is supported.</p>

Title: Can we write independent of machine(i.e. independent of OS) code in asp.net?

Body:
As i have read MSIL manages the code to make it independent of machine;but i have also read that DOT NET just provide windows independence not Plateform.
Please Explain if


问:
why Multiple file selection not working with multiple attribute?
I want to upload multiple files,and i create a input field with attribute multiple,But i couldnt select multiple files.

app.html

<input type="file"   (change)="onChange($event)" required class="form-control " multiple>
component.ts

```<code>    onChange(event: any) {
    let fileList: FileList = event.target.files;
    console.log(event.target.files)
    if(fileList.length > 0) {
    let file: File = fileList[0];
    let formData:FormData = new FormData();
    formData.append('degree_attachment', file, file.name);
    let headers = new Headers();
    headers.append('Accept', 'application/json');
    let options = new RequestOptions({ headers: headers });
    this.http.post('http://localhost:8080/EventManager/UploadFile',
    formData,options)
    .map(res => res.json())
    .catch(error => Observable.throw(error))
    .subscribe(
        data => console.log('success'),
        error => console.log(error)
    )
  }}
</code>```

答:
It should be able to select multiple files.

Live demo: Plunker

Code:

```<code>@Component({
  selector: 'my-app',
  template: `
    <form enctype='multipart/form-data'>
      <input
        (change)="onChange($event)"
        type='file'
        name='files[]'
        multiple
      />

      <button type='submit'>Submit</button>
    </form>
  `,
})
export class App {
  onChange(event: any) {
    let fileList: FileList = event.target.files;
    console.log(event.target.files)
  }}
}
</code>```

Body:
I want to upload multiple files,and i create a input field with attribute multiple,But i couldnt select multiple files.

app.html

<input type="file"   (change)="onChange($event)" required class="form-control " multiple>
component.ts

    onChange(event: any) {
    let fileList: FileList = event.target.files;
    console.log(event.target.files)
    if(fileList.length > 0) {
    let file: File = fileList[0];
    let formData:FormData = new FormData();
    formData.append('degree_attachment', file, file.name);
    let headers = new Headers();
    headers.append('Accept', 'application/json');
    let options = new RequestOptions({ headers: headers });
    this.http.post('http://localhost:8080/EventManager/UploadFile',
    formData,options)
    .map(res => res.json())
    .catch(error => Observable.throw(error))
    .subscribe(
        data => console.log('success'),
        error => console.log(error)
    )
  }}

Body:
It should be able to select multiple files.

Live demo: Plunker

Code:

@Component({
  selector: 'my-app',
  template: `
    <form enctype='multipart/form-data'>
      <input
        (change)="onChange($event)"
        type='file'
        name='files[]'
        multiple
      />

      <button type='submit'>Submit</button>
    </form>
  `,
})
export class App {
  onChange(event: any) {
    let fileList: FileList = event.target.files;
    console.log(event.target.files)
  }}
}


问:
Cron isn't running when I start my docker container
To preface, I have been referencing these two articles for help:

Run a cron job with Docker - Julien Boulay

Running cron jobs inside a Docker container - Chris S.

My goal is to have a cron job automatically start when I start my docker container. Currently, it doesn't automatically start, but I can manually go into my container and run service cron start, which starts the job, and it works correctly.

So the problem is: How do I get my cron job to start automatically when my container starts up?

Dockerfile

```<code>FROM microsoft/dotnet:latest
RUN apt-get update && apt-get install -y cron

COPY . /app

WORKDIR /app

ADD crontab /etc/cron.d/crontab
RUN chmod 0600 /etc/cron.d/crontab
RUN crontab -u root /etc/cron.d/crontab
RUN touch /var/log/cron.log

RUN ["dotnet", "restore"]

RUN ["dotnet", "build"]

EXPOSE 5000/tcp

CMD cron && tail -f /var/log/cron.log
CMD service cron start
</code>```

crontab

```<code>* * * * * echo "Hello world" >> /var/log/cron.log 2>&1
# Empty space
</code>```

Though I wasn't able to get cron working in that particular container, I was able to create a standalone docker container specifically for cron, and was successful in getting it to run automatically.

As far as setup for the cron container, I followed the linked article, Run a cron job with Docker - Julien Boulay, and was able to get it working.

答:
There is a bug in Debian based distributions which will cause cronjobs to fail because docker uses layered filesystem and cron doesn't start and says NUMBER OF HARD LINKS > 1 (/etc/crontab).

The fix is simple, add touch /etc/crontab /etc/cron.*/* to the entrypoint of your container.

I have made a blog post explaining how to setup cron in a Docker container here : https://esc.sh/blog/cron-jobs-in-docker/

Body:
To preface, I have been referencing these two articles for help:

Run a cron job with Docker - Julien Boulay

Running cron jobs inside a Docker container - Chris S.

My goal is to have a cron job automatically start when I start my docker container. Currently, it doesn't automatically start, but I can manually go into my container and run service cron start, which starts the job, and it works correctly.

So the problem is: How do I get my cron job to start automatically when my container starts up?

Dockerfile

FROM microsoft/dotnet:latest
RUN apt-get update && apt-get install -y cron

COPY . /app

WORKDIR /app

ADD crontab /etc/cron.d/crontab
RUN chmod 0600 /etc/cron.d/crontab
RUN crontab -u root /etc/cron.d/crontab
RUN touch /var/log/cron.log

RUN ["dotnet", "restore"]

RUN ["dotnet", "build"]

EXPOSE 5000/tcp

CMD cron && tail -f /var/log/cron.log
CMD service cron start

crontab

* * * * * echo "Hello world" >> /var/log/cron.log 2>&1
# Empty space

Though I wasn't able to get cron working in that particular container, I was able to create a standalone docker container specifically for cron, and was successful in getting it to run automatically.

As far as setup for the cron container, I followed the linked article, Run a cron job with Docker - Julien Boulay, and was able to get it working.


问:
ffmpeg is reading SDP from RTSP stream but unable to save a screenshot. is it network or utility issue?
My task is to get a screenshot from IP camera rtsp stream via ffmpeg.
I got following error when I'm trying to do that on DigitalOcean droplet:

```<code>root@docker-512mb-fra1-01:~# ffmpeg -hide_banner -loglevel debug -i rtsp://10.132.193.9//ch0.h264 -f image2 latest.jpg
Splitting the commandline.
Reading option '-hide_banner' ... matched as option 'hide_banner' (do not show program banner) with argument '1'.
Reading option '-loglevel' ... matched as option 'loglevel' (set logging level) with argument 'debug'.
Reading option '-i' ... matched as input url with argument 'rtsp://10.132.193.9//ch0.h264'.
Reading option '-f' ... matched as option 'f' (force format) with argument 'image2'.
Reading option 'latest.jpg' ... matched as output url.
Finished splitting the commandline.
Parsing a group of options: global .
Applying option hide_banner (do not show program banner) with argument 1.
Applying option loglevel (set logging level) with argument debug.
Successfully parsed a group of options.
Parsing a group of options: input url rtsp://10.132.193.9//ch0.h264.
Successfully parsed a group of options.
Opening an input file: rtsp://10.132.193.9//ch0.h264.
[rtsp @ 0x1298440] SDP:
v=0
o=- 1499314217993040 1 IN IP4 192.168.1.128
s=H.264 Program Stream, streamed by the LIVE555 Media Server
i=ch0.h264
t=0 0
a=DevVer:pusher2
a=GroupName:IPCAM
a=NickName:CIF
a=CfgSection:PROG_CHN0
a=tool:LIVE555 Streaming Media v2011.08.13
a=type:broadcast
a=control:*
a=range:npt=0-
a=x-qt-text-nam:H.264 Program Stream, streamed by the LIVE555 Media Server
a=x-qt-text-inf:ch0.h264
m=video 0 RTP/AVP 96
c=IN IP4 0.0.0.0
b=AS:4000
a=rtpmap:96 H264/90000
a=control:trackID=1
a=fmtp:96 packetization-mode=1;profile-level-id=64001F;sprop-parameter-sets=Z2QAH6wrUCgC3IA=,aO48MA==
a=framesize:96 1280-720
a=cliprect:0,0,1280,720
m=audio 0 RTP/AVP 97
a=rtpmap:97 mpeg4-generic/8000/2
a=fmtp:97 streamtype=5;profile-level-id=1;cpresent=0;mode=AAC-hbr;sizelength=13;indexlength=3;indexdeltalength=3;config=1590
a=control:trackID=2

Failed to parse interval end specification ''
[rtsp @ 0x1298440] video codec set to: h264
[rtsp @ 0x1298440] RTP Packetization Mode: 1
[rtsp @ 0x1298440] RTP Profile IDC: 64 Profile IOP: 0 Level: 1f
[rtsp @ 0x1298440] Extradata set to 0x1298a20 (size: 23)
[rtsp @ 0x1298440] audio codec set to: aac
[rtsp @ 0x1298440] audio samplerate set to: 8000
[rtsp @ 0x1298440] audio channels set to: 2
[udp @ 0x129e7e0] end receive buffer size reported is 131072
[udp @ 0x129e680] end receive buffer size reported is 131072
[udp @ 0x12bf380] end receive buffer size reported is 131072
[udp @ 0x12bf1c0] end receive buffer size reported is 131072
[rtsp @ 0x1298440] hello state=0
[rtsp @ 0x1298440] UDP timeout, retrying with TCP
[rtsp @ 0x1298440] hello state=0
[rtsp @ 0x1298440] Could not find codec parameters for stream 0 (Video: h264, 1 reference frame, none(left), 1280x720, 1/180000): unspecified pixel format
Consider increasing the value for the 'analyzeduration' and 'probesize' options
Input #0, rtsp, from 'rtsp://10.132.193.9//ch0.h264':
  Metadata:
    title           : H.264 Program Stream, streamed by the LIVE555 Media Server
    comment         : ch0.h264
  Duration: N/A, start: 0.000000, bitrate: N/A
    Stream #0:0, 0, 1/90000: Video: h264, 1 reference frame, none(left), 1280x720, 1/180000, 90k tbr, 90k tbn, 180k tbc
    Stream #0:1, 0, 1/8000: Audio: aac, 8000 Hz, stereo, fltp
Successfully opened the file.
Parsing a group of options: output url latest.jpg.
Applying option f (force format) with argument image2.
Successfully parsed a group of options.
Opening an output file: latest.jpg.
Successfully opened the file.
detected 1 logical cores
[graph 0 input from stream 0:0 @ 0x1298280] Setting 'video_size' to value '1280x720'
[graph 0 input from stream 0:0 @ 0x1298280] Setting 'pix_fmt' to value '-1'
[buffer @ 0x12f9680] Unable to parse option value "-1" as pixel format
[graph 0 input from stream 0:0 @ 0x1298280] Setting 'time_base' to value '1/90000'
[graph 0 input from stream 0:0 @ 0x1298280] Setting 'pixel_aspect' to value '0/1'
[graph 0 input from stream 0:0 @ 0x1298280] Setting 'sws_param' to value 'flags=2'
[graph 0 input from stream 0:0 @ 0x1298280] Setting 'frame_rate' to value '180000/2'
[buffer @ 0x12f9680] Unable to parse option value "-1" as pixel format
[buffer @ 0x12f9680] Error setting option pix_fmt to value -1.
[graph 0 input from stream 0:0 @ 0x1298280] Error applying options to the filter.
Error opening filters!
Exiting normally, received signal 2.
</code>```

As you see, ffmpeg is able to read SDP metadata, but for some reason is unable to save a screenshot

Also same command works fine on my laptop with same VPN configuration!

Just in case, IP camera doesn't have a public IP address and accessible via VPN.

What could be wrong and how to debug?

I tried to increase -analyzeduration and -probesize options from default 5s to 30s, but it doesn't work.

答: It was a problem with firewall. Did service ufw stop and now ffmpeg works fine!

Body:
My task is to get a screenshot from IP camera rtsp stream via ffmpeg.
I got following error when I'm trying to do that on DigitalOcean droplet:

root@docker-512mb-fra1-01:~# ffmpeg -hide_banner -loglevel debug -i rtsp://10.132.193.9//ch0.h264 -f image2 latest.jpg
Splitting the commandline.
Reading option '-hide_banner' ... matched as option 'hide_banner' (do not show program banner) with argument '1'.
Reading option '-loglevel' ... matched as option 'loglevel' (set logging level) with argument 'debug'.
Reading option '-i' ... matched as input url with argument 'rtsp://10.132.193.9//ch0.h264'.
Reading option '-f' ... matched as option 'f' (force format) with argument 'image2'.
Reading option 'latest.jpg' ... matched as output url.
Finished splitting the commandline.
Parsing a group of options: global .
Applying option hide_banner (do not show program banner) with argument 1.
Applying option loglevel (set logging level) with argument debug.
Successfully parsed a group of options.
Parsing a group of options: input url rtsp://10.132.193.9//ch0.h264.
Successfully parsed a group of options.
Opening an input file: rtsp://10.132.193.9//ch0.h264.
[rtsp @ 0x1298440] SDP:
v=0
o=- 1499314217993040 1 IN IP4 192.168.1.128
s=H.264 Program Stream, streamed by the LIVE555 Media Server
i=ch0.h264
t=0 0
a=DevVer:pusher2
a=GroupName:IPCAM
a=NickName:CIF
a=CfgSection:PROG_CHN0
a=tool:LIVE555 Streaming Media v2011.08.13
a=type:broadcast
a=control:*
a=range:npt=0-
a=x-qt-text-nam:H.264 Program Stream, streamed by the LIVE555 Media Server
a=x-qt-text-inf:ch0.h264
m=video 0 RTP/AVP 96
c=IN IP4 0.0.0.0
b=AS:4000
a=rtpmap:96 H264/90000
a=control:trackID=1
a=fmtp:96 packetization-mode=1;profile-level-id=64001F;sprop-parameter-sets=Z2QAH6wrUCgC3IA=,aO48MA==
a=framesize:96 1280-720
a=cliprect:0,0,1280,720
m=audio 0 RTP/AVP 97
a=rtpmap:97 mpeg4-generic/8000/2
a=fmtp:97 streamtype=5;profile-level-id=1;cpresent=0;mode=AAC-hbr;sizelength=13;indexlength=3;indexdeltalength=3;config=1590
a=control:trackID=2

Failed to parse interval end specification ''
[rtsp @ 0x1298440] video codec set to: h264
[rtsp @ 0x1298440] RTP Packetization Mode: 1
[rtsp @ 0x1298440] RTP Profile IDC: 64 Profile IOP: 0 Level: 1f
[rtsp @ 0x1298440] Extradata set to 0x1298a20 (size: 23)
[rtsp @ 0x1298440] audio codec set to: aac
[rtsp @ 0x1298440] audio samplerate set to: 8000
[rtsp @ 0x1298440] audio channels set to: 2
[udp @ 0x129e7e0] end receive buffer size reported is 131072
[udp @ 0x129e680] end receive buffer size reported is 131072
[udp @ 0x12bf380] end receive buffer size reported is 131072
[udp @ 0x12bf1c0] end receive buffer size reported is 131072
[rtsp @ 0x1298440] hello state=0
[rtsp @ 0x1298440] UDP timeout, retrying with TCP
[rtsp @ 0x1298440] hello state=0
[rtsp @ 0x1298440] Could not find codec parameters for stream 0 (Video: h264, 1 reference frame, none(left), 1280x720, 1/180000): unspecified pixel format
Consider increasing the value for the 'analyzeduration' and 'probesize' options
Input #0, rtsp, from 'rtsp://10.132.193.9//ch0.h264':
  Metadata:
    title           : H.264 Program Stream, streamed by the LIVE555 Media Server
    comment         : ch0.h264
  Duration: N/A, start: 0.000000, bitrate: N/A
    Stream #0:0, 0, 1/90000: Video: h264, 1 reference frame, none(left), 1280x720, 1/180000, 90k tbr, 90k tbn, 180k tbc
    Stream #0:1, 0, 1/8000: Audio: aac, 8000 Hz, stereo, fltp
Successfully opened the file.
Parsing a group of options: output url latest.jpg.
Applying option f (force format) with argument image2.
Successfully parsed a group of options.
Opening an output file: latest.jpg.
Successfully opened the file.
detected 1 logical cores
[graph 0 input from stream 0:0 @ 0x1298280] Setting 'video_size' to value '1280x720'
[graph 0 input from stream 0:0 @ 0x1298280] Setting 'pix_fmt' to value '-1'
[buffer @ 0x12f9680] Unable to parse option value "-1" as pixel format
[graph 0 input from stream 0:0 @ 0x1298280] Setting 'time_base' to value '1/90000'
[graph 0 input from stream 0:0 @ 0x1298280] Setting 'pixel_aspect' to value '0/1'
[graph 0 input from stream 0:0 @ 0x1298280] Setting 'sws_param' to value 'flags=2'
[graph 0 input from stream 0:0 @ 0x1298280] Setting 'frame_rate' to value '180000/2'
[buffer @ 0x12f9680] Unable to parse option value "-1" as pixel format
[buffer @ 0x12f9680] Error setting option pix_fmt to value -1.
[graph 0 input from stream 0:0 @ 0x1298280] Error applying options to the filter.
Error opening filters!
Exiting normally, received signal 2.

As you see, ffmpeg is able to read SDP metadata, but for some reason is unable to save a screenshot

Also same command works fine on my laptop with same VPN configuration!

Just in case, IP camera doesn't have a public IP address and accessible via VPN.

What could be wrong and how to debug?

I tried to increase -analyzeduration and -probesize options from default 5s to 30s, but it doesn't work.


问:
cursor.fetchall() returns empty tuple with cx_Oracle
I created a table with 4 records. The table description is like:
Employer

Now when I run the following piece of code:

```<code>import cx_Oracle
con = cx_Oracle.connect("system/******@localhost/xe")
cur = con.cursor()
cur.execute("SELECT * FROM Employer")
print(cur.fetchall())
print("\nNumber of rows fetched =",cur.rowcount)
print("\nDescription:",cur.description)`
</code>```

The fetchall() fuction returns [].
The rowcount is 0.
But the description is correct, i.e. what it should be.

Description: [('COMPANYID', , 5, 5, 0, 0, 0), ('COMPANYNAME', , 50, 50, 0, 0, 0), ('EMAILID', , 30, 30, 0, 0, 1), ('MOBILE', , 11, 22, 10, 0, 1), ('CITY', , 15, 15, 0, 0, 1), ('INDUSTRYTYPE', , 20, 20, 0, 0, 1), ('FUNCTIONALAREA', , 20, 20, 0, 0, 1), ('MEMBERSHIPPLAN', , 20, 20, 0, 0, 1), ('DATEOFSIGNUP', , 23, 7, 0, 0, 1), ('DATEOFRENEWAL', , 23, 7, 0, 0, 1), ('RENEWALSTATUS', , 10, 10, 0, 0, 1)]

When I'm running the same query on the DB it runs fine. But here the fetchall() returns an empty tuple and the rowcount is 0. Please help. Thank you.

答: Believe it or not, you are not connected to the correct database and/or the table is truly empty. The description you get is inferred by the database and does not require the query to have any results.</p>

Body:
I created a table with 4 records. The table description is like:
Employer

Now when I run the following piece of code:

import cx_Oracle
con = cx_Oracle.connect("system/******@localhost/xe")
cur = con.cursor()
cur.execute("SELECT * FROM Employer")
print(cur.fetchall())
print("\nNumber of rows fetched =",cur.rowcount)
print("\nDescription:",cur.description)`

The fetchall() fuction returns [].
The rowcount is 0.
But the description is correct, i.e. what it should be.

Description: [('COMPANYID', , 5, 5, 0, 0, 0), ('COMPANYNAME', , 50, 50, 0, 0, 0), ('EMAILID', , 30, 30, 0, 0, 1), ('MOBILE', , 11, 22, 10, 0, 1), ('CITY', , 15, 15, 0, 0, 1), ('INDUSTRYTYPE', , 20, 20, 0, 0, 1), ('FUNCTIONALAREA', , 20, 20, 0, 0, 1), ('MEMBERSHIPPLAN', , 20, 20, 0, 0, 1), ('DATEOFSIGNUP', , 23, 7, 0, 0, 1), ('DATEOFRENEWAL', , 23, 7, 0, 0, 1), ('RENEWALSTATUS', , 10, 10, 0, 0, 1)]

When I'm running the same query on the DB it runs fine. But here the fetchall() returns an empty tuple and the rowcount is 0. Please help. Thank you.


问:
Is there a relation between Sleep() and synchronization?
Consider the following program demonstrating channels:

```<code>package main

import (
    "fmt"
)

func pinger(c chan string) {
    for i := 0; ; i++ {
        c <- "ping"
    }
}

func ponger(c chan string) {
    for i := 0; ; i++ {
        c <- "pong"
    }
}

func printer(c chan string) {
    for {
        msg := <-c
        fmt.Println(msg)
        //time.Sleep(time.Second * 1)
    }
}

func main() {
    var c = make(chan string)

    go pinger(c)
    go ponger(c)
    go printer(c)

    var input string
    fmt.Scanln(&input)
}
</code>```

If I uncomment the time.Sleep call, the output is "ping" and "pong" taking turns in a nice, predictable manner. However, adding the comment makes the order unpredictable. I'm a Go novice and wondering what enabled this synchronization. Why does adding a wait time make the rest of the channel feeder tow the line?

答:
Is there a relation between Sleep() and synchronization?

NO

Synchronization happens between value sent to channel and retrieve from channel.

```<code>var c = make(chan string)
</code>```

Channel c can hold one value of type string at a time. Until the value is retrieve from channel <- c; function pinger, ponger cannot send value to channel c (i.e. pinger and ponger is waiting to send value to channel till the time you read from printer function).

So in your example, you introduced the time delay via Sleep func to read the value from channel c on printer function.

That's why you get nice and slow read with the help of Sleep func :)

Body:
Consider the following program demonstrating channels:

package main

import (
    "fmt"
)

func pinger(c chan string) {
    for i := 0; ; i++ {
        c <- "ping"
    }
}

func ponger(c chan string) {
    for i := 0; ; i++ {
        c <- "pong"
    }
}

func printer(c chan string) {
    for {
        msg := <-c
        fmt.Println(msg)
        //time.Sleep(time.Second * 1)
    }
}

func main() {
    var c = make(chan string)

    go pinger(c)
    go ponger(c)
    go printer(c)

    var input string
    fmt.Scanln(&input)
}

If I uncomment the time.Sleep call, the output is "ping" and "pong" taking turns in a nice, predictable manner. However, adding the comment makes the order unpredictable. I'm a Go novice and wondering what enabled this synchronization. Why does adding a wait time make the rest of the channel feeder tow the line?

Body:
Is there a relation between Sleep() and synchronization?

NO

Synchronization happens between value sent to channel and retrieve from channel.

var c = make(chan string)

Channel c can hold one value of type string at a time. Until the value is retrieve from channel <- c; function pinger, ponger cannot send value to channel c (i.e. pinger and ponger is waiting to send value to channel till the time you read from printer function).

So in your example, you introduced the time delay via Sleep func to read the value from channel c on printer function.

That's why you get nice and slow read with the help of Sleep func :)


问:
linux/g++ Multiple definition on linking
All related questions I was able to find do not detail my exact scenario, so I hope this is not considered a duplicate question.

I have class A(using A.h to declare and A.cpp to define) that includes and uses functions from a Math.h.

When I try to build my main.cpp to use object A that #includes the header for class A, I get a multiple definition error for every single math function defined in Math.h(Math.h does not have a .cpp, all functions/variables are defined in the header).

A.h

```<code>#ifndef A_H
#define A_H

#include "Math.h"

//Other #includes

namespace MY_NAMESPACE
{
    class A
    {
        public:

            A();
            //Variable/Function declarations

        private:

            //Variable/Function declarations
    };
}

#endif
</code>```

A.cpp

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

void MY_NAMESPACE::A::Func1()
{
    //define
}

ect...
</code>```

main.cpp

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

int main()
{
    MY_NAMESPACE::A* a = new MY_NAMESPACE::A();

    delete a;

    return 0;
}
</code>```

Math.h(Declared and defined only in header)

```<code>#ifndef MATH_H
#define MATH_H

float DotProduct(Vector3 v1, Vector3 v2)
{
    return (v1.x * v2.x) + (v1.y * v2.y) + (v1.z * v2.z);
}

#endif

etc...
</code>```

I am new to linux/g++. This has never caused any issue in the past when programming in Visual Studio on a Windows platform.

This is pretty basic stuff, so I am rather baffled.

makefile

CC=g++
      FLAGS=-std=c++11 -g

```<code>build: clean A.o main

clean:
  rm -f -v bin/*.*

A.o:
  $(CC) -c $(FLAGS) A.cpp

main:
  $(CC) $(FLAGS) main.cpp A.o
</code>```

Any advice?

EDIT Actual error snippit

In function WF_RPI::MATH::Normalize(WF_RPI::MATH::Vector3)':
  /home/pi/projects/WFRPI/TPx2SController/../WFStandard/WFSMath.h:574:
  multiple definition of
  WF_RPI::MATH::Normalize(WF_RPI::MATH::Vector3)'
  Arcus.o:/home/pi/projects/WFRPI/Arcus/../TPx2SController/../WFStandard/WFSMath.h:574:
  first defined here bin//libtpx2s.a(tpx2s.o): In function
  WF_RPI::MATH::Normalize(WF_RPI::MATH::Vector2)':
  /home/pi/projects/WFRPI/TPx2SController/../WFStandard/WFSMath.h:590:
  multiple definition of
  WF_RPI::MATH::Normalize(WF_RPI::MATH::Vector2)'
  Arcus.o:/home/pi/projects/WFRPI/Arcus/../TPx2SController/../WFStandard/WFSMath.h:590:
  first defined here bin//libtpx2s.a(tpx2s.o): In function
  `WF_RPI::MATH::Magnitude(WF_RPI::MATH::Vector2)':

答:
Functions in Math.h need to be inlined ...

```<code>inline float DotProduct(Vector3 v1, Vector3 v2)
{
    return (v1.x * v2.x) + (v1.y * v2.y) + (v1.z * v2.z);
}
</code>```

C/C++ currently uses a textual insertion for an include file.  That means that for each .cpp file, it is made up of all of the text in all of its includes, and its own code.

When a compiler sees

```<code> int funName( int param ) {
         // something...
 }
</code>```

It declares an external function.  When it links the C++ files together, it spots there are multiple definitions causing the issue.

The fix (as mentioned right at the top), is to mark the functions as inline.  Which allows multiple definitions to be linked.

The error describes a more complex issue, than you have described.  It mentions an archive (.a) file which has the duplicate definition with the header file WFSMath.h.

The archive will need to be re-built, as it may have embedded non-inline implementations, and some make systems are less than perfect at spotting a library requires re-building if a header file changes.

Body:
All related questions I was able to find do not detail my exact scenario, so I hope this is not considered a duplicate question.

I have class A(using A.h to declare and A.cpp to define) that includes and uses functions from a Math.h.

When I try to build my main.cpp to use object A that #includes the header for class A, I get a multiple definition error for every single math function defined in Math.h(Math.h does not have a .cpp, all functions/variables are defined in the header).

A.h

#ifndef A_H
#define A_H

#include "Math.h"

//Other #includes

namespace MY_NAMESPACE
{
    class A
    {
        public:

            A();
            //Variable/Function declarations

        private:

            //Variable/Function declarations
    };
}

#endif

A.cpp

#include "A.h"

void MY_NAMESPACE::A::Func1()
{
    //define
}

ect...

main.cpp

#include "A.h"

int main()
{
    MY_NAMESPACE::A* a = new MY_NAMESPACE::A();

    delete a;

    return 0;
}

Math.h(Declared and defined only in header)

#ifndef MATH_H
#define MATH_H

float DotProduct(Vector3 v1, Vector3 v2)
{
    return (v1.x * v2.x) + (v1.y * v2.y) + (v1.z * v2.z);
}

#endif

etc...

I am new to linux/g++. This has never caused any issue in the past when programming in Visual Studio on a Windows platform.

This is pretty basic stuff, so I am rather baffled.

makefile

CC=g++
      FLAGS=-std=c++11 -g

build: clean A.o main

clean:
  rm -f -v bin/*.*

A.o:
  $(CC) -c $(FLAGS) A.cpp

main:
  $(CC) $(FLAGS) main.cpp A.o

Any advice?

EDIT Actual error snippit

In function WF_RPI::MATH::Normalize(WF_RPI::MATH::Vector3)':
  /home/pi/projects/WFRPI/TPx2SController/../WFStandard/WFSMath.h:574:
  multiple definition of
  WF_RPI::MATH::Normalize(WF_RPI::MATH::Vector3)'
  Arcus.o:/home/pi/projects/WFRPI/Arcus/../TPx2SController/../WFStandard/WFSMath.h:574:
  first defined here bin//libtpx2s.a(tpx2s.o): In function
  WF_RPI::MATH::Normalize(WF_RPI::MATH::Vector2)':
  /home/pi/projects/WFRPI/TPx2SController/../WFStandard/WFSMath.h:590:
  multiple definition of
  WF_RPI::MATH::Normalize(WF_RPI::MATH::Vector2)'
  Arcus.o:/home/pi/projects/WFRPI/Arcus/../TPx2SController/../WFStandard/WFSMath.h:590:
  first defined here bin//libtpx2s.a(tpx2s.o): In function
  `WF_RPI::MATH::Magnitude(WF_RPI::MATH::Vector2)':

Body:
Functions in Math.h need to be inlined ...

inline float DotProduct(Vector3 v1, Vector3 v2)
{
    return (v1.x * v2.x) + (v1.y * v2.y) + (v1.z * v2.z);
}

C/C++ currently uses a textual insertion for an include file.  That means that for each .cpp file, it is made up of all of the text in all of its includes, and its own code.

When a compiler sees

 int funName( int param ) {
         // something...
 }

It declares an external function.  When it links the C++ files together, it spots there are multiple definitions causing the issue.

The fix (as mentioned right at the top), is to mark the functions as inline.  Which allows multiple definitions to be linked.

The error describes a more complex issue, than you have described.  It mentions an archive (.a) file which has the duplicate definition with the header file WFSMath.h.

The archive will need to be re-built, as it may have embedded non-inline implementations, and some make systems are less than perfect at spotting a library requires re-building if a header file changes.


问:
How to play video using Servlet or JSP?
How to play video using Servlet or JSP?</p>

答:
In JSP, it's not different from as you would do in normal HTML. Just use the <embed> and/or the <object> element which points to an URL where the video file is located. You need to consult the documentation of the video format vendor for details how to use it. Since you didn't mention what format the video file is in, we can't help you further in detail. So here's just one example: in case of Quicktime .mov files, you can consult it at Apple.

A servlet is only useful if you haven't stored the video file in public webcontent. But still then, it's nothing special which needs to be done by the servlet. Just read InputStream from the file source (somewhere else on fixed disk, or in a database, etc) and write to OutputStream of the response along a correct set of response headers.

Title: How to play video using Servlet or JSP?

Body: How to play video using Servlet or JSP?


问:
React minified error #31: "Objects are not valid as a React child" in IE 11
I'm having a react error when browsing my application on IE 11. The specific problem is React minified error #31:

Objects are not valid as a React child (found: object with keys
  {$$typeof, type, key, ref, props, _owner}).

It might be related to babel not transpiling our indexjs correctly on IE 11.

答:
Probably you are missing 'babel-polyfill'.
Require it in the very beginning itself.
You might want to  check  these link
https://babeljs.io/docs/usage/polyfill/

https://github.com/storybooks/storybook/issues/213


问:
Using c++ typedef/using type alias
I am reading C++ primer book and completely don't understand one line:

```<code> using int_array = int[4];
 typedef int int_array[4]; // This line
 for (int_array *p = ia; p != ia + 3; ++p) {
      for (int *q = *p; q != *p + 4; ++q)
          cout << *q << ' '; cout << endl;
 }
</code>```

Ok typedef is same as using. Does it mean int[4][4] is now int and how to understand that? And what type is int_array in for loop?

Thanks

答:
This line does nothing as it is redundant

The lines

```<code>using int_array = int[4];
</code>```

and

```<code>typedef int int_array[4];
</code>```

do the same thing. See reference for using and typedef. You can leave one or the other out and the behaviour is the same. It is not an error to have two different declarations, as they are not conflicting (they do the exact same thing).

The first way of doing it (using the using keyword) was introduced with C++11 and is in my opinion easier to read, so I prefer it over the typedef version.

Title: Using c++ typedef/using type alias

Body:
I am reading C++ primer book and completely don't understand one line:

 using int_array = int[4];
 typedef int int_array[4]; // This line
 for (int_array *p = ia; p != ia + 3; ++p) {
      for (int *q = *p; q != *p + 4; ++q)
          cout << *q << ' '; cout << endl;
 }

Ok typedef is same as using. Does it mean int[4][4] is now int and how to understand that? And what type is int_array in for loop?

Thanks

Body:
This line does nothing as it is redundant

The lines

using int_array = int[4];

and

typedef int int_array[4];

do the same thing. See reference for using and typedef. You can leave one or the other out and the behaviour is the same. It is not an error to have two different declarations, as they are not conflicting (they do the exact same thing).

The first way of doing it (using the using keyword) was introduced with C++11 and is in my opinion easier to read, so I prefer it over the typedef version.


问:
Trying to hide again line with code of string in Android Studio
my question is hard to explain in text, but easy in screenshot :)
When i click on lane, which value in string.xml Android Studio show to user what is there. Something like this:

My question is: how to hide again this text in Anrdoid Studio ?

Thanks for your answers.

答: ctrl+"+" to expand and ctrl+"-" to preview


问:
Scala: Is hashCode() & equals() for case classes only generated if not already specified in a non-trivial superclass?
I tried to define an abstract class "Vertex" in such a way that all instances of all its subclasses are identified (in sets/maps/distinct, etc.) by the abstract field "id", even if the subclasses are different case classes that define additional individual parameters. Thus, I want to achieve that all subclasses call hashCode() & equals() as defined in the abstract superclass. In other words, for case classes that inherit from "Vertex" I want to disable the automatic overrides that are generated by the Scala compiler for case classes.

According to the following example, it seems to hold true that the Scala compiler does not generate hashCode() & equals() for a case class if that case class already has these functions explicitly defined in a non-trivial superclass:

```<code>abstract class AbstractVertex {
  val id: String

  // identify only by id, ignoring any additional fields of case classes

  override def hashCode(): Int = id.hashCode
  override def equals(obj: scala.Any): Boolean = {
    obj match {
      case other: AbstractVertex => other.id == id
      case _ => false
    }
  }
}

case class VertexType1(id: String, data: String) extends AbstractVertex

case class VertexType2(id: String, data: String) extends AbstractVertex

case class VertexType3(id: String, data: String) { // NOT an AbstractVertex
  // manually provide our own hashCode and equals
  override def hashCode(): Int = id.hashCode
  override def equals(obj: scala.Any): Boolean = {
    obj match {
      case other: VertexType3 => other.id == id
      case _ => false
    }
  }
}

case class VertexType4(id: String, data: String) // NOT an AbstractVertex

object Playground extends App {
  // create several vertices, all of the same id
  val v1a = VertexType1("x", "some")
  val v1b = VertexType1("x", "other")
  val v2a = VertexType2("x", "some")
  val v2b = VertexType2("x", "other")
  val v3a = VertexType3("x", "some")
  val v3b = VertexType3("x", "other")
  val v4a = VertexType4("x", "some")
  val v4b = VertexType4("x", "other")
  val v4c = VertexType4("x", "some")

  println(Set(v1a, v1b, v2a, v2b).size) // gives 1
  println(Set(v1a, v1b).size) // gives 1
  println(Set(v2a, v2b).size) // gives 1
  println(Set(v3a, v3b).size) // gives 1
  println(Set(v4a, v4b, v4c).size) // gives 2

  println(v1a == v1b) // gives true
  println(v1a == v2a) // gives true
  println(v1a == v3a) // gives false
  println(v1a == v4a) // gives false
  println(v4a == v4b) // gives false
  println(v4a == v4c) // gives true
}
</code>```

Thus, the behavior is as intended. Even more, compiling the above code snippet via scalac -Xprint:typer Playground.scala | grep "hashCode" -C 5 shows that hashCode() is only generated for VertexType4, and taken as explicitly defined for VertexType3, while VertexType1 and VertexType2 do not generate these, so they fall back to the hashCode() as defined in AbstractVertex. Similar for equals().

So everything works fine as intended. However, since this is a quite subtle detail of how Scala's compiler deals with generating hashCode() & equals() for case classes, I wonder how "stable" this behavior is. There are often many changes between different Scala versions, so this might break in future. Can I rely on this behavior? For example, is there probably some official ticket or so, where this kind of behavior is explicitly specified?

答:
This is documented behavior. Section §5.3.2 of the Scala specification states (emphasis mine):

Every case class implicitly overrides some method definitions of class scala.AnyRef unless a definition of the same method is already given in the case class itself or a concrete definition of the same method is given in some base class of the case class different from AnyRef. In particular:

Method equals: (Any)Boolean is structural equality, where two instances are equal if they both belong to the case class in question and they have equal (with respect to equals) constructor arguments (restricted to the class's elements, i.e., the first parameter section).

Method hashCode: Int computes a hash-code. If the hashCode methods of the data structure members map equal (with respect to equals) values to equal hash-codes, then the case class hashCode method does too.

Method toString: String returns a string representation which contains the name of the class and its elements.

Body:
I tried to define an abstract class "Vertex" in such a way that all instances of all its subclasses are identified (in sets/maps/distinct, etc.) by the abstract field "id", even if the subclasses are different case classes that define additional individual parameters. Thus, I want to achieve that all subclasses call hashCode() & equals() as defined in the abstract superclass. In other words, for case classes that inherit from "Vertex" I want to disable the automatic overrides that are generated by the Scala compiler for case classes.

According to the following example, it seems to hold true that the Scala compiler does not generate hashCode() & equals() for a case class if that case class already has these functions explicitly defined in a non-trivial superclass:

abstract class AbstractVertex {
  val id: String

  // identify only by id, ignoring any additional fields of case classes

  override def hashCode(): Int = id.hashCode
  override def equals(obj: scala.Any): Boolean = {
    obj match {
      case other: AbstractVertex => other.id == id
      case _ => false
    }
  }
}

case class VertexType1(id: String, data: String) extends AbstractVertex

case class VertexType2(id: String, data: String) extends AbstractVertex

case class VertexType3(id: String, data: String) { // NOT an AbstractVertex
  // manually provide our own hashCode and equals
  override def hashCode(): Int = id.hashCode
  override def equals(obj: scala.Any): Boolean = {
    obj match {
      case other: VertexType3 => other.id == id
      case _ => false
    }
  }
}

case class VertexType4(id: String, data: String) // NOT an AbstractVertex

object Playground extends App {
  // create several vertices, all of the same id
  val v1a = VertexType1("x", "some")
  val v1b = VertexType1("x", "other")
  val v2a = VertexType2("x", "some")
  val v2b = VertexType2("x", "other")
  val v3a = VertexType3("x", "some")
  val v3b = VertexType3("x", "other")
  val v4a = VertexType4("x", "some")
  val v4b = VertexType4("x", "other")
  val v4c = VertexType4("x", "some")

  println(Set(v1a, v1b, v2a, v2b).size) // gives 1
  println(Set(v1a, v1b).size) // gives 1
  println(Set(v2a, v2b).size) // gives 1
  println(Set(v3a, v3b).size) // gives 1
  println(Set(v4a, v4b, v4c).size) // gives 2

  println(v1a == v1b) // gives true
  println(v1a == v2a) // gives true
  println(v1a == v3a) // gives false
  println(v1a == v4a) // gives false
  println(v4a == v4b) // gives false
  println(v4a == v4c) // gives true
}

Thus, the behavior is as intended. Even more, compiling the above code snippet via scalac -Xprint:typer Playground.scala | grep "hashCode" -C 5 shows that hashCode() is only generated for VertexType4, and taken as explicitly defined for VertexType3, while VertexType1 and VertexType2 do not generate these, so they fall back to the hashCode() as defined in AbstractVertex. Similar for equals().

So everything works fine as intended. However, since this is a quite subtle detail of how Scala's compiler deals with generating hashCode() & equals() for case classes, I wonder how "stable" this behavior is. There are often many changes between different Scala versions, so this might break in future. Can I rely on this behavior? For example, is there probably some official ticket or so, where this kind of behavior is explicitly specified?