问:
read operator from file and perform operation C++
In this problem I have to ask for a filename in which data will be read, and if 'def' is answered use the default file provided, and count the number of lines in the file.
Then read the data file one line at a time and calculate the value of w as follows:
-if w is 'add', calculate x+y
-if w is 'sub', calculate x-y
-if w is 'mult', calculate x*y
-if w is 'div', calculate x/y

and then print the results to the screen on line at a time.

example of data in the file:

mult  4.25  4.56

div  7.64  1.01

div  6.51  2.46

mult  8.90  6.16

mult  7.40  8.53

sub  3.05  7.15

sub  9.51  6.16

sub  5.79  1.60

add  5.30  8.87

sub  8.09  1.65

And my code: I have the first 3 parts work but the while loop for performing the operations isn't working. Where am I going wrong? Thanks!

```<code>#include <iostream>
#include <cstdlib>
#include <fstream>

using namespace std;

int main(){

    ifstream input;
    string filename;
    cout<<"Enter the file name. Enter 'def' to use default file: ";
    cin>>filename;

    if(filename == "def"){
        input.open("M2-P2-data2Read.dat");
    }
    else{
        input.open(filename.c_str());
    }

    int number_of_lines = 0;
    string line;

    while (getline(input, line))
        ++number_of_lines;
    cout << "Number of lines in file: " << number_of_lines;

    string w;
    double x, y;

    input >> w;

    while(input) {
    if(w == "add")
        double x, y;
        input >> x >> y;
        cout << "Solution: " << x+y << endl;
    if(w == "sub")
        double x, y;
        input >> x >> y;
        cout << "Solution: " << x-y << endl;
    if(w == "mult")
        double x, y;
        input >> x >> y;
        cout << "Solution: " << x*y << endl;
    if(w == "div")
        double x, y;
        input >> x >> y;
        cout << "Solution: " << x/y << endl;
    input >> w;

   }

}
</code>```

答:
I think this is what you are aiming for:</p>

```<code>#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>

int main() {
    std::ifstream input;
    std::string   filename;
    std::cout << "Enter the file name. Enter 'def' to use default file: ";
    std::cin >> filename;

    if ( filename == "def" ) {
        input.open( "Sample.dat" );
    } else {
        input.open( filename.c_str() );
    }

    int number_of_lines = 0;
    std::string line;

    while ( getline( input, line ) ) {
        ++number_of_lines;
    }
    std::cout << "\nNumber of lines in file: " << number_of_lines << "\n\n";

    input.clear();
    input.seekg( 0, input.beg );

    std::string w;
    double x = 0;
    double y = 0;

    while ( input >> w >> x >> y ) {

        if ( w == "add" ) {
            std::cout << "Solution: " << x + y << std::endl;
        }

        if ( w == "sub" ) {
            std::cout << "Solution: " << x - y << std::endl;
        }

        if ( w == "mult" ) {
            std::cout << "Solution: " << x * y << std::endl;
        }

        if ( w == "div" ) {
            // Should test for denominator = 0
            std::cout << "Solution: " << x / y << std::endl;
        }

    }

    std::cout << "\nPress any key and enter to quit." << std::endl;
    char c;
    std::cin >> c;

    return 0;
}
</code>```

Body:
In this problem I have to ask for a filename in which data will be read, and if 'def' is answered use the default file provided, and count the number of lines in the file.
Then read the data file one line at a time and calculate the value of w as follows:
-if w is 'add', calculate x+y
-if w is 'sub', calculate x-y
-if w is 'mult', calculate x*y
-if w is 'div', calculate x/y

and then print the results to the screen on line at a time.

example of data in the file:

mult  4.25  4.56

div  7.64  1.01

div  6.51  2.46

mult  8.90  6.16

mult  7.40  8.53

sub  3.05  7.15

sub  9.51  6.16

sub  5.79  1.60

add  5.30  8.87

sub  8.09  1.65

And my code: I have the first 3 parts work but the while loop for performing the operations isn't working. Where am I going wrong? Thanks!

#include <iostream>
#include <cstdlib>
#include <fstream>

using namespace std;

int main(){

    ifstream input;
    string filename;
    cout<<"Enter the file name. Enter 'def' to use default file: ";
    cin>>filename;

    if(filename == "def"){
        input.open("M2-P2-data2Read.dat");
    }
    else{
        input.open(filename.c_str());
    }

    int number_of_lines = 0;
    string line;

    while (getline(input, line))
        ++number_of_lines;
    cout << "Number of lines in file: " << number_of_lines;

    string w;
    double x, y;

    input >> w;

    while(input) {
    if(w == "add")
        double x, y;
        input >> x >> y;
        cout << "Solution: " << x+y << endl;
    if(w == "sub")
        double x, y;
        input >> x >> y;
        cout << "Solution: " << x-y << endl;
    if(w == "mult")
        double x, y;
        input >> x >> y;
        cout << "Solution: " << x*y << endl;
    if(w == "div")
        double x, y;
        input >> x >> y;
        cout << "Solution: " << x/y << endl;
    input >> w;

   }

}

Body:
I think this is what you are aiming for:

#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>

int main() {
    std::ifstream input;
    std::string   filename;
    std::cout << "Enter the file name. Enter 'def' to use default file: ";
    std::cin >> filename;

    if ( filename == "def" ) {
        input.open( "Sample.dat" );
    } else {
        input.open( filename.c_str() );
    }

    int number_of_lines = 0;
    std::string line;

    while ( getline( input, line ) ) {
        ++number_of_lines;
    }
    std::cout << "\nNumber of lines in file: " << number_of_lines << "\n\n";

    input.clear();
    input.seekg( 0, input.beg );

    std::string w;
    double x = 0;
    double y = 0;

    while ( input >> w >> x >> y ) {

        if ( w == "add" ) {
            std::cout << "Solution: " << x + y << std::endl;
        }

        if ( w == "sub" ) {
            std::cout << "Solution: " << x - y << std::endl;
        }

        if ( w == "mult" ) {
            std::cout << "Solution: " << x * y << std::endl;
        }

        if ( w == "div" ) {
            // Should test for denominator = 0
            std::cout << "Solution: " << x / y << std::endl;
        }

    }

    std::cout << "\nPress any key and enter to quit." << std::endl;
    char c;
    std::cin >> c;

    return 0;
}


来源: stackexchange

问:
How to use method to output a random string from array?
How can I fix the code so my method compiles correctly to output a random string from the array I created into the main method?</p>

```<code>class Main
{
  public static void main (String[] args)
  {
   randomWord();
   System.out.println (random);
  }

  static String[] randomWord()
  {
    String[] randomWords = {"dog", "cat", "monkey"}
    String random = randomWords[(int)(Math.random() * randomWords.length)];
    return random;
  }
}
</code>```

答:
You seem to not understand how to use methods with return values. This method:

```<code>  static String[] randomWord()
  {
    String[] randomWords = {"dog", "cat", "monkey"}
    String random = randomWords[(int)(Math.random() * randomWords.length)];
    return random;
  }
</code>```

Should really return a String instead of String[], because what you are returning, random, is a string. So change it to:

```<code>  static String randomWord()
  // ...
</code>```

To use this method, you don't just call it like this:

```<code>randomWord()
</code>```

This will discard the return value. To get the return value, you can create a variable:

```<code>String random = randomWord();
</code>```

Now you can print it:

```<code>System.out.println(random);
</code>```

You can write the two lines in one line as well:

```<code>System.out.println(randomWord());
</code>```

ContentLicense: CC BY-SA 3.0

Body:
How can I fix the code so my method compiles correctly to output a random string from the array I created into the main method?

class Main
{
  public static void main (String[] args)
  {
   randomWord();
   System.out.println (random);
  }

  static String[] randomWord()
  {
    String[] randomWords = {"dog", "cat", "monkey"}
    String random = randomWords[(int)(Math.random() * randomWords.length)];
    return random;
  }
}

Body:
You seem to not understand how to use methods with return values. This method:

  static String[] randomWord()
  {
    String[] randomWords = {"dog", "cat", "monkey"}
    String random = randomWords[(int)(Math.random() * randomWords.length)];
    return random;
  }

Should really return a String instead of String[], because what you are returning, random, is a string. So change it to:

  static String randomWord()
  // ...

To use this method, you don't just call it like this:

randomWord()

This will discard the return value. To get the return value, you can create a variable:

String random = randomWord();

Now you can print it:

System.out.println(random);

You can write the two lines in one line as well:

System.out.println(randomWord());


问:
Print statement in class getting executed even though there is no class instance/object
content of my python file

```<code>class myclass(object):
    def __init__(self):
        pass
    def myfun(self):
        pass
    print ("hello world")
</code>```

Output on executing file

```<code>hello world
</code>```

Query

```<code>since I did not create object of class . How's it still able to print "hello world"
</code>```

答:
It will get a call, as python work like that.
Your code will always return output.

hello world

```<code>class myclass(object):
    def __init__(self):
        pass

    def myfun(self):
        print("hello world")
        pass
</code>```

If you want to avoid it you have to add print statement inside the method.

Body:
content of my python file

class myclass(object):
    def __init__(self):
        pass
    def myfun(self):
        pass
    print ("hello world")

Output on executing file

hello world

Query

since I did not create object of class . How's it still able to print "hello world"

Body:
It will get a call, as python work like that.
Your code will always return output.

hello world

class myclass(object):
    def __init__(self):
        pass

    def myfun(self):
        print("hello world")
        pass

If you want to avoid it you have to add print statement inside the method.


问:
Not all selected images are in $_FILES
This is a strange one. I have an upload function that uploads all selected images from the client's computer to the server. This is working, however, when selecting a large number of images it cuts off after 19 images. I tried uploading 71 images and every time I check the number of images in $_FILES it only contains 19. Has anyone had this issue before? See my code below:

HTML

```<code><input type="file" webkitdirectory mozdirectory msdirectory odirectory directory multiple class="" id="image_folder" name="image_folder[]" value=""  style="display: none;"/>
</code>```

PHP

```<code>//Upload book images
            if (count($_FILES['image_folder']['name']) > 0) {
                for($file = 0; $file < count($_FILES['image_folder']['name']); $file++) {
                    //Get the temp file path
                    $tmpFilePath = $_FILES['image_folder']['tmp_name'][$file];

                    //Make sure we have a filepath
                    if ($tmpFilePath != "") {

                        //save the filename
                        $shortname = $_FILES['image_folder']['name'][$file];

                        $directoryName = "../Authors/AUT".sprintf("%09d", $AUT_ID)."/Content/";

                        //Check if the directory already exists.
                        if (!is_dir($directoryName)) {
                            mkdir($directoryName, 0755, true);
                        }

                        //save the url and the file
                        $filePath = "../Authors/AUTH".sprintf("%09d", $AUTH_ID)."/Content/".$shortname;

                        //Upload the file into the dir
                        if (move_uploaded_file($tmpFilePath, $filePath)) {
                            //TODO:: Save path to database.

                        }
                    }
                }
            }
</code>```

So like I said, my code works and 19 images are uploaded out of the total 71. I have checked my Server's max execution time as well and amended it. However, it still makes no difference. Besides, I don't think it has something to do with that as the total count of Images in $_FILES are is only 19 instead of 71.

答: Increase max_file_uploads limit in your php.ini file.

Title: Not all selected images are in $_FILES

Body:
This is a strange one. I have an upload function that uploads all selected images from the client's computer to the server. This is working, however, when selecting a large number of images it cuts off after 19 images. I tried uploading 71 images and every time I check the number of images in $_FILES it only contains 19. Has anyone had this issue before? See my code below:

HTML

<input type="file" webkitdirectory mozdirectory msdirectory odirectory directory multiple class="" id="image_folder" name="image_folder[]" value=""  style="display: none;"/>

PHP

//Upload book images
            if (count($_FILES['image_folder']['name']) > 0) {
                for($file = 0; $file < count($_FILES['image_folder']['name']); $file++) {
                    //Get the temp file path
                    $tmpFilePath = $_FILES['image_folder']['tmp_name'][$file];

                    //Make sure we have a filepath
                    if ($tmpFilePath != "") {

                        //save the filename
                        $shortname = $_FILES['image_folder']['name'][$file];

                        $directoryName = "../Authors/AUT".sprintf("%09d", $AUT_ID)."/Content/";

                        //Check if the directory already exists.
                        if (!is_dir($directoryName)) {
                            mkdir($directoryName, 0755, true);
                        }

                        //save the url and the file
                        $filePath = "../Authors/AUTH".sprintf("%09d", $AUTH_ID)."/Content/".$shortname;

                        //Upload the file into the dir
                        if (move_uploaded_file($tmpFilePath, $filePath)) {
                            //TODO:: Save path to database.

                        }
                    }
                }
            }

So like I said, my code works and 19 images are uploaded out of the total 71. I have checked my Server's max execution time as well and amended it. However, it still makes no difference. Besides, I don't think it has something to do with that as the total count of Images in $_FILES are is only 19 instead of 71.


问:
how to access dataTable variable outside ajax
I have this datatable that is created inside a function call. But if I want to create new rows based on event listeners like this, it gives an error that the table variable is undefined, which is understandable because it is inside a function call and not global. So how do I create a workaround for this and add event listeners under $(document).ready() section?

The structure of my JS file is very shabby, but it's intended to be in that way.

```<code>$(document).ready(function()
{
     var table=null;
     $('#button').click(function()
     {
         callfunction1();
     }
     callfunction1()
     {
         $.ajax({
              'success': function(response) //response contains the plain table
                         {
                             createDatatable(response)
                         }
         })
     }
     createDatatable(response)
     {
            $('#division').html(response); //creating the plain table
            table=$('#tableId').Datatable({}); //converting it to datatable
     }
     //I want to add event listeners here, because if I add
     //it anywhere else, it doesn't work, because basically
     //it's a function call.
}
</code>```

答:
So after all your answers(which I am very grateful for) , I have found out a different approach for it. As per documentation here, I added a $.ajax({}_.done() (this is as good as accessing the dataTable variable outside ajax call) function to host my event listener for accessing my dataTable.

Once again, I thank you all for the answers.
Edit: As requested for the correct solution.

```<code>$(document).ready(function()
{
     var table=null;
     $('#button').click(function()
     {
         callfunction1();
     }
     callfunction1()
     {
         $.ajax({
              'success': function(response) //response contains the plain table
                         {
                             createDatatable(response)
                         }
         }).done(function()
         {
                 //add event listener here,You can access the table variable here. but you can not access the variable outside, instead just pass the variable to another function.
                 console.log(table);//this will work.
         });
     }
     createDatatable(response)
     {
            $('#division').html(response); //creating the plain table
            table=$('#tableId').Datatable({}); //converting it to datatable
     }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have this datatable that is created inside a function call. But if I want to create new rows based on event listeners like this, it gives an error that the table variable is undefined, which is understandable because it is inside a function call and not global. So how do I create a workaround for this and add event listeners under $(document).ready() section?

The structure of my JS file is very shabby, but it's intended to be in that way.

$(document).ready(function()
{
     var table=null;
     $('#button').click(function()
     {
         callfunction1();
     }
     callfunction1()
     {
         $.ajax({
              'success': function(response) //response contains the plain table
                         {
                             createDatatable(response)
                         }
         })
     }
     createDatatable(response)
     {
            $('#division').html(response); //creating the plain table
            table=$('#tableId').Datatable({}); //converting it to datatable
     }
     //I want to add event listeners here, because if I add
     //it anywhere else, it doesn't work, because basically
     //it's a function call.
}

Body:
So after all your answers(which I am very grateful for) , I have found out a different approach for it. As per documentation here, I added a $.ajax({}_.done() (this is as good as accessing the dataTable variable outside ajax call) function to host my event listener for accessing my dataTable.

Once again, I thank you all for the answers.
Edit: As requested for the correct solution.

$(document).ready(function()
{
     var table=null;
     $('#button').click(function()
     {
         callfunction1();
     }
     callfunction1()
     {
         $.ajax({
              'success': function(response) //response contains the plain table
                         {
                             createDatatable(response)
                         }
         }).done(function()
         {
                 //add event listener here,You can access the table variable here. but you can not access the variable outside, instead just pass the variable to another function.
                 console.log(table);//this will work.
         });
     }
     createDatatable(response)
     {
            $('#division').html(response); //creating the plain table
            table=$('#tableId').Datatable({}); //converting it to datatable
     }
}


问:
Google Play App Signing for Ionic 2 Apps
I just wanted to upload a new Ionic 2 Android app to Google Play when Google asked me if I wanted to use Google App Signing. I liked the idea since it already had happened that I lost a certificate and was not able to update my app anymore.

But I can't find any help or tutorials on this anywhere. So my question is what steps I have to take to use Google App Signing for Ionic 2 Apps? Where do I get my Upload Certificate from?

All help I found was regarding Android Studio but I guess that does not help me with my Ionic 2 App.

In the help documents it says that the upload certificate is generated when enrolling Google App Signing but under App Signing in Google Play it does not give me the upload certificate.

Does any work have experience with this?

答: I started a project from scratch and had to sign it as you always do and upload the manually signed apk after my listing was complete. After that I noticed both the app signing and upload key were available in the app signing section. Then future apps can then be signed with Google.</p>


问:
How to get the values of few input fields in java script and write them on web?
I would like to take all values from all input fields and write them on the web.

Here is my code:

var button = document.querySelector("button");
button.addEventListener("click", function() {

  var inputs = document.querySelectorAll("input").value;
  for (i = 0; i < inputs.length; i++) {
    inputs[i];
  }

  var output = document.getElementById("output");
  output.innerHTML = "To sa: " + inputs;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
</div>

<button>Check</button>
<div id="output"></div></code>```

答:
var button = document.querySelector("button");
button.addEventListener("click", function() {

  var inputs = document.querySelectorAll("input");
  for (i = 0; i < inputs.length; i++) {
  var output = document.getElementById("output");

  output.innerHTML += inputs[i].value;
  }

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
</div>

<button>Check</button>
<div id="output"></div></code>```

Body:
I would like to take all values from all input fields and write them on the web.

Here is my code:

var button = document.querySelector("button");
button.addEventListener("click", function() {

  var inputs = document.querySelectorAll("input").value;
  for (i = 0; i < inputs.length; i++) {
    inputs[i];
  }

  var output = document.getElementById("output");
  output.innerHTML = "To sa: " + inputs;
});

  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">

<button>Check</button>

Body:
var button = document.querySelector("button");
button.addEventListener("click", function() {

  var inputs = document.querySelectorAll("input");
  for (i = 0; i < inputs.length; i++) {
  var output = document.getElementById("output");

  output.innerHTML += inputs[i].value;
  }

});

<div>
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
</div>

<button>Check</button>
<div id="output"></div>


问:
Infinite loop when using disabled attribute binding to a function
The pre rendering is not working when I bind the "disabled" directive to a function which contains a console.log().

```<code><button [disabled]="!isValid()"></button>
</code>```

My function

```<code> public isValid(){
     console.log("isvalid");
     return true;
 }
</code>```

From my visual studio output console, I got this :

```<code> Microsoft.AspNetCore.NodeServices: Information: isvalid
 Microsoft.AspNetCore.NodeServices: Information: isvalid
 Microsoft.AspNetCore.NodeServices: Information: isvalid
 ..... (the same infinite loop message) ............
</code>```

If I remove the console.log, the pre-rendering works, but I suppose the proccess keep on checking the if the button isValid or not.

My package versions

```<code>"angular2-platform-node": "2.1.0-rc.1",
"angular2-universal": "2.1.0-rc.1",
"angular2-universal-patch": "0.2.1",
"angular2-universal-polyfills": "2.1.0-rc.1",
"aspnet-prerendering": "2.0.3",

Microsoft.AspNetCore.SpaServices : 1.1.0;
Microsoft.AspNetCore.NodeServices : 1.1.0;
</code>```

答:
The issue is, that when you call a method in the template, it is called every time change detection is run, which happens often. So this is actually not an infinite loop, Angular just calls this method on each change detection.

You can solve this by handling the logic in the component, store it in a variable, and use the variable in the template.

Body:
The pre rendering is not working when I bind the "disabled" directive to a function which contains a console.log().

<button [disabled]="!isValid()"></button>

My function

 public isValid(){
     console.log("isvalid");
     return true;
 }

From my visual studio output console, I got this :

 Microsoft.AspNetCore.NodeServices: Information: isvalid
 Microsoft.AspNetCore.NodeServices: Information: isvalid
 Microsoft.AspNetCore.NodeServices: Information: isvalid
 ..... (the same infinite loop message) ............

If I remove the console.log, the pre-rendering works, but I suppose the proccess keep on checking the if the button isValid or not.

My package versions

"angular2-platform-node": "2.1.0-rc.1",
"angular2-universal": "2.1.0-rc.1",
"angular2-universal-patch": "0.2.1",
"angular2-universal-polyfills": "2.1.0-rc.1",
"aspnet-prerendering": "2.0.3",

Microsoft.AspNetCore.SpaServices : 1.1.0;
Microsoft.AspNetCore.NodeServices : 1.1.0;


问:
how can we make a column having mutiple values in it as foreign key to another table in mysql
i have two tables

```<code>intent_sample(id,sample_data,intent_id,entity_id)
entities(id,entity_name,entity_id)
</code>```

Since a sample_data can have any no of entities in it, I want to store multiple values in a single column and also want to link entity_id to entities table as it foreign key.

How can we do it.

I thought of using JSON data type in mysql for entity_id but is it possible to make a column having json data type as foreign key to another table

答:
Use a composite key

```<code>FOREIGN KEY (`id`,`entity_id`)
    REFERENCES entities(`intent_id`,`entity_id`)
</code>```

This will allow a relation between the foreign key in one table to the id's in another table.

I don't have all of the details so you can modify it to work with your tables.

Body:
i have two tables

intent_sample(id,sample_data,intent_id,entity_id)
entities(id,entity_name,entity_id)

Since a sample_data can have any no of entities in it, I want to store multiple values in a single column and also want to link entity_id to entities table as it foreign key.

How can we do it.

I thought of using JSON data type in mysql for entity_id but is it possible to make a column having json data type as foreign key to another table

Body:
Use a composite key

FOREIGN KEY (`id`,`entity_id`)
    REFERENCES entities(`intent_id`,`entity_id`)

This will allow a relation between the foreign key in one table to the id's in another table.

I don't have all of the details so you can modify it to work with your tables.


问:
Django IntegerField with Choice Options (how to create 0-10 integer options)
I want to limit the field to values 0-10 in a select widget.

```<code>field=models.IntegerField(max_length=10, choices=CHOICES)
</code>```

I could just write out all the choices tuples from (0,0),(1,1) on, but there must be an obvious way to handle this.

Help is highly appreciated.

答:
As well as @Torsten has mentioned, you could improve it by:

```<code>field = models.IntegerField(choices=list(zip(range(1, 10), range(1, 10))), unique=True)
</code>```

But remember this will gives you from 1 to 9. Put range (1,11) if you want until 10

Body:
I want to limit the field to values 0-10 in a select widget.

field=models.IntegerField(max_length=10, choices=CHOICES)

I could just write out all the choices tuples from (0,0),(1,1) on, but there must be an obvious way to handle this.

Help is highly appreciated.

Body:
As well as @Torsten has mentioned, you could improve it by:

field = models.IntegerField(choices=list(zip(range(1, 10), range(1, 10))), unique=True)

But remember this will gives you from 1 to 9. Put range (1,11) if you want until 10


问:
Where do the settings in my Git configuration come from?
I've noticed that I have two listings for core.autocrlf when I run git config -l

```<code>$ git config -l
core.symlinks=false
core.autocrlf=false
color.diff=auto
color.status=auto
color.branch=auto
color.interactive=true
pack.packsizelimit=2g
help.format=html
http.sslcainfo=/bin/curl-ca-bundle.crt
sendemail.smtpserver=/bin/msmtp.exe
diff.astextplain.textconv=astextplain
rebase.autosquash=true
user.name=name
user.email=email@example.com
core.autocrlf=true
</code>```

Those last three (from user.name down) are the only ones in my C:\users\username\.gitconfig file. Where are all of the other ones coming from?  Why is core.autocrlf listed twice?

This is with MSysGit 1.8.3, and I also have Sourcetree installed (Windows 7). In Sourcetree I have unchecked the "Allow Sourcetree to modify your global Git config files"

答:
If you want to find to find the actual file location, it'll be in your home directory.

It is hidden and preceded with a ".".

So if you're on a Mac, in your terminal you can cd ~ && open .gitconfig or open it with your favourite text editor, e.g cd ~ && atom .gitconfig.

Body:
I've noticed that I have two listings for core.autocrlf when I run git config -l

$ git config -l
core.symlinks=false
core.autocrlf=false
color.diff=auto
color.status=auto
color.branch=auto
color.interactive=true
pack.packsizelimit=2g
help.format=html
http.sslcainfo=/bin/curl-ca-bundle.crt
sendemail.smtpserver=/bin/msmtp.exe
diff.astextplain.textconv=astextplain
rebase.autosquash=true
user.name=name
user.email=email@example.com
core.autocrlf=true

Those last three (from user.name down) are the only ones in my C:\users\username\.gitconfig file. Where are all of the other ones coming from?  Why is core.autocrlf listed twice?

This is with MSysGit 1.8.3, and I also have Sourcetree installed (Windows 7). In Sourcetree I have unchecked the "Allow Sourcetree to modify your global Git config files"


问:
Video creation with the most recent ffmpeg API (2017)
I have started learning how to work with ffmpeg which has a suffering deprecation of all tutorial and available examples such as this.

I am looking for a code which creates an output video.

Unfortunately, most of good examples are focusing on reading from a file rather than creating one.

Here, I have found a deprecated example and I spent a long time to fix its errors until it became like this:

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

extern "C" {
        #include <libavcodec/avcodec.h>
        #include <libavformat/avformat.h>
        #include <libswscale/swscale.h>
        #include <libavformat/avio.h>
        #include <libavutil/opt.h>
}

#define WIDTH 800
#define HEIGHT 480
#define STREAM_NB_FRAMES  ((int)(STREAM_DURATION * FRAME_RATE))
#define FRAME_RATE 24
#define PIXEL_FORMAT AV_PIX_FMT_YUV420P
#define STREAM_DURATION 5.0 //seconds
#define BIT_RATE 400000

#define AV_CODEC_FLAG_GLOBAL_HEADER (1 << 22)
#define CODEC_FLAG_GLOBAL_HEADER AV_CODEC_FLAG_GLOBAL_HEADER
#define AVFMT_RAWPICTURE 0x0020

using namespace std;

static int sws_flags = SWS_BICUBIC;

AVFrame *picture, *tmp_picture;
uint8_t *video_outbuf;
int frame_count, video_outbuf_size;

/****** IF LINUX ******/
inline int sprintf_s(char* buffer, size_t sizeOfBuffer, const char* format, ...)
{
    va_list ap;
    va_start(ap, format);
    int result = vsnprintf(buffer, sizeOfBuffer, format, ap);
    va_end(ap);
    return result;
}

/****** IF LINUX ******/
template<size_t sizeOfBuffer>
inline int sprintf_s(char (&buffer)[sizeOfBuffer], const char* format, ...)
{
    va_list ap;
    va_start(ap, format);
    int result = vsnprintf(buffer, sizeOfBuffer, format, ap);
    va_end(ap);
    return result;
}

static void closeVideo(AVFormatContext *oc, AVStream *st)
{
    avcodec_close(st->codec);
    av_free(picture->data[0]);
    av_free(picture);
    if (tmp_picture)
    {
        av_free(tmp_picture->data[0]);
        av_free(tmp_picture);
    }
    av_free(video_outbuf);
}

static AVFrame *alloc_picture(enum AVPixelFormat pix_fmt, int width, int height)
{
    AVFrame *picture;
    uint8_t *picture_buf;
    int size;

    picture = av_frame_alloc();
    if(!picture)
        return NULL;
    size = avpicture_get_size(pix_fmt, width, height);
    picture_buf = (uint8_t*)(av_malloc(size));
    if (!picture_buf)
    {
        av_free(picture);
        return NULL;
    }
    avpicture_fill((AVPicture *) picture, picture_buf, pix_fmt, WIDTH, HEIGHT);
    return picture;
}

static void openVideo(AVFormatContext *oc, AVStream *st)
{
    AVCodec *codec;
    AVCodecContext *c;

    c = st->codec;
    if(c->idct_algo == AV_CODEC_ID_H264)
        av_opt_set(c->priv_data, "preset", "slow", 0);

    codec = avcodec_find_encoder(c->codec_id);
    if(!codec)
    {
        std::cout << "Codec not found." << std::endl;
        std::cin.get();std::cin.get();exit(1);
    }

    if(codec->id == AV_CODEC_ID_H264)
        av_opt_set(c->priv_data, "preset", "medium", 0);

    if(avcodec_open2(c, codec, NULL) < 0)
    {
        std::cout << "Could not open codec." << std::endl;
        std::cin.get();std::cin.get();exit(1);
    }
    video_outbuf = NULL;
    if(!(oc->oformat->flags & AVFMT_RAWPICTURE))
    {
        video_outbuf_size = 200000;
        video_outbuf = (uint8_t*)(av_malloc(video_outbuf_size));
    }
    picture = alloc_picture(c->pix_fmt, c->width, c->height);
    if(!picture)
    {
        std::cout << "Could not allocate picture" << std::endl;
        std::cin.get();exit(1);
    }
    tmp_picture = NULL;
    if(c->pix_fmt != AV_PIX_FMT_YUV420P)
    {
        tmp_picture = alloc_picture(AV_PIX_FMT_YUV420P, WIDTH, HEIGHT);
        if(!tmp_picture)
        {
            std::cout << " Could not allocate temporary picture" << std::endl;
            std::cin.get();exit(1);
        }
    }
}

static AVStream* addVideoStream(AVFormatContext *context, enum AVCodecID codecID)
{
    AVCodecContext *codec;
    AVStream *stream;
    stream = avformat_new_stream(context, NULL);
    if(!stream)
    {
        std::cout << "Could not alloc stream." << std::endl;
        std::cin.get();exit(1);
    }

    codec = stream->codec;
    codec->codec_id = codecID;
    codec->codec_type = AVMEDIA_TYPE_VIDEO;

    // sample rate
    codec->bit_rate = BIT_RATE;
    // resolution must be a multiple of two
    codec->width = WIDTH;
    codec->height = HEIGHT;
    codec->time_base.den = FRAME_RATE; // stream fps
    codec->time_base.num = 1;
    codec->gop_size = 12; // intra frame every twelve frames at most
    codec->pix_fmt = PIXEL_FORMAT;
    if(codec->codec_id == AV_CODEC_ID_MPEG2VIDEO)
        codec->max_b_frames = 2; // for testing, B frames

    if(codec->codec_id == AV_CODEC_ID_MPEG1VIDEO)
        codec->mb_decision = 2;

    if(context->oformat->flags & AVFMT_GLOBALHEADER)
        codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;

    return stream;
}

static void fill_yuv_image(AVFrame *pict, int frame_index, int width, int height)
{
    int x, y, i;
    i = frame_index;

    /* Y */
    for(y=0;y<height;y++) {
        for(x=0;x<width;x++) {
            pict->data[0][y * pict->linesize[0] + x] = x + y + i * 3;
        }
    }

    /* Cb and Cr */
    for(y=0;y<height/2;y++) {
        for(x=0;x<width/2;x++) {
            pict->data[1][y * pict->linesize[1] + x] = 128 + y + i * 2;
            pict->data[2][y * pict->linesize[2] + x] = 64 + x + i * 5;
        }
    }
}

static void write_video_frame(AVFormatContext *oc, AVStream *st)
{
    int out_size, ret;
    AVCodecContext *c;
    static struct SwsContext *img_convert_ctx;
    c = st->codec;

    if(frame_count >= STREAM_NB_FRAMES)
    {

    }
    else
    {
        if(c->pix_fmt != AV_PIX_FMT_YUV420P)
        {
            if(img_convert_ctx = NULL)
            {
                img_convert_ctx = sws_getContext(WIDTH, HEIGHT, AV_PIX_FMT_YUV420P, WIDTH, HEIGHT,
                                                c->pix_fmt, sws_flags, NULL, NULL, NULL);
                if(img_convert_ctx == NULL)
                {
                    std::cout << "Cannot initialize the conversion context" << std::endl;
                    std::cin.get();exit(1);
                }
            }
            fill_yuv_image(tmp_picture, frame_count, WIDTH, HEIGHT);
            sws_scale(img_convert_ctx, tmp_picture->data, tmp_picture->linesize, 0, HEIGHT,
                        picture->data, picture->linesize);
        }
        else
        {
            fill_yuv_image(picture, frame_count, WIDTH, HEIGHT);
        }
    }

    if (oc->oformat->flags & AVFMT_RAWPICTURE)
    {
        /* raw video case. The API will change slightly in the near
           futur for that */
        AVPacket pkt;
        av_init_packet(&pkt);

        pkt.flags |= AV_PKT_FLAG_KEY;
        pkt.stream_index= st->index;
        pkt.data= (uint8_t *)picture;
        pkt.size= sizeof(AVPicture);

        ret = av_interleaved_write_frame(oc, &pkt);
    }
    else
    {
        /* encode the image */
        out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, picture);
        /* if zero size, it means the image was buffered */
        if (out_size > 0)
        {
            AVPacket pkt;
            av_init_packet(&pkt);

            if (c->coded_frame->pts != AV_NOPTS_VALUE)
                pkt.pts= av_rescale_q(c->coded_frame->pts, c->time_base, st->time_base);
            if(c->coded_frame->key_frame)
                pkt.flags |= AV_PKT_FLAG_KEY;
            pkt.stream_index= st->index;
            pkt.data= video_outbuf;
            pkt.size= out_size;
            /* write the compressed frame in the media file */
            ret = av_interleaved_write_frame(oc, &pkt);
        } else {
            ret = 0;
        }
    }
    if (ret != 0) {
        std::cout << "Error while writing video frames" << std::endl;
        std::cin.get();exit(1);
    }
    frame_count++;
}

int main ( int argc, char *argv[] )
{
    const char* filename = "test.h264";
    AVOutputFormat *outputFormat;
    AVFormatContext *context;
    AVCodecContext *codec;
    AVStream *videoStream;
    double videoPTS;

    // init libavcodec, register all codecs and formats
    av_register_all();
    // auto detect the output format from the name
    outputFormat = av_guess_format(NULL, filename, NULL);
    if(!outputFormat)
    {
        std::cout << "Cannot guess output format! Using mpeg!" << std::endl;
        std::cin.get();
        outputFormat = av_guess_format(NULL, "h263" , NULL);
    }
    if(!outputFormat)
    {
        std::cout << "Could not find suitable output format." << std::endl;
        std::cin.get();exit(1);
    }

    context = avformat_alloc_context();
    if(!context)
    {
        std::cout << "Cannot allocate avformat memory." << std::endl;
        std::cin.get();exit(1);
    }
    context->oformat = outputFormat;
    sprintf_s(context->filename, sizeof(context->filename), "%s", filename);
    std::cout << "Is '" << context->filename << "' = '" << filename << "'" << std::endl;

    videoStream = NULL;
    outputFormat->audio_codec = AV_CODEC_ID_NONE;
    videoStream = addVideoStream(context, outputFormat->video_codec);

    /* still needed?
    if(av_set_parameters(context, NULL) < 0)
    {
        std::cout << "Invalid output format parameters." << std::endl;
        exit(0);
    }*/

    av_dump_format(context, 0, filename, 1);

    if(videoStream)
        openVideo(context, videoStream);

    if(!outputFormat->flags & AVFMT_NOFILE)
    {
        if(avio_open(&context->pb, filename, AVIO_FLAG_READ_WRITE) < 0)
        {
            std::cout << "Could not open " << filename << std::endl;
            std::cin.get();exit(1);
        }
    }

    avformat_write_header(context, 0);

    while(true)
    {
        if(videoStream)
            videoPTS = (double) videoStream->pts.val * videoStream->time_base.num / videoStream->time_base.den;
        else
            videoPTS = 0.;

        if((!videoStream || videoPTS >= STREAM_DURATION))
        {
            break;
        }
        write_video_frame(context, videoStream);
    }
    av_write_trailer(context);
    if(videoStream)
        closeVideo(context, videoStream);
    for(int i = 0; i < context->nb_streams; i++)
    {
        av_freep(&context->streams[i]->codec);
        av_freep(&context->streams[i]);
    }

    if(!(outputFormat->flags & AVFMT_NOFILE))
    {
        avio_close(context->pb);
    }
    av_free(context);
    std::cin.get();
    return 0;
}
</code>```

Compile:

```<code>g++ -I ./FFmpeg/ video.cpp -L fflibs -lavcodec -lavformat
</code>```

The code comes with two errors:

```<code>video.cpp:249:84: error: ‘avcodec_encode_video’ was not declared in this scope
         out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, picture);
                                                                                ^

video.cpp: In function ‘int main(int, char**)’:
video.cpp:342:46: error: ‘AVStream {aka struct AVStream}’ has no member named ‘pts’
             videoPTS = (double) videoStream->pts.val * videoStream->time_base.num / videoStream->time_base.den;
                                              ^
</code>```

and a huge number of warnings for deprecation.

```<code>video.cpp: In function ‘void closeVideo(AVFormatContext*, AVStream*)’:
video.cpp:60:23: warning: ‘AVStream::codec’ is deprecated [-Wdeprecated-declarations]
     avcodec_close(st->codec);
                       ^
In file included from video.cpp:9:0:
./FFmpeg/libavformat/avformat.h:876:21: note: declared here
     AVCodecContext *codec;
                     ^
video.cpp:60:23: warning: ‘AVStream::codec’ is deprecated [-Wdeprecated-declarations]
     avcodec_close(st->codec);
                       ^
In file included from video.cpp:9:0:
./FFmpeg/libavformat/avformat.h:876:21: note: declared here
     AVCodecContext *codec;
                     ^
video.cpp:60:23: warning: ‘AVStream::codec’ is deprecated [-Wdeprecated-declarations]
     avcodec_close(st->codec);
                       ^
In file included from video.cpp:9:0:
./FFmpeg/libavformat/avformat.h:876:21: note: declared here
     AVCodecContext *codec;
                     ^
video.cpp: In function ‘AVFrame* alloc_picture(AVPixelFormat, int, int)’:
video.cpp:80:12: warning: ‘int avpicture_get_size(AVPixelFormat, int, int)’ is deprecated [-Wdeprecated-declarations]
     size = avpicture_get_size(pix_fmt, width, height);
            ^
In file included from video.cpp:8:0:
./FFmpeg/libavcodec/avcodec.h:5228:5: note: declared here
 int avpicture_get_size(enum AVPixelFormat pix_fmt, int width, int height);
     ^
video.cpp:80:12: warning: ‘int avpicture_get_size(AVPixelFormat, int, int)’ is deprecated [-Wdeprecated-declarations]
     size = avpicture_get_size(pix_fmt, width, height);
            ^
In file included from video.cpp:8:0:
./FFmpeg/libavcodec/avcodec.h:5228:5: note: declared here
 int avpicture_get_size(enum AVPixelFormat pix_fmt, int width, int height);
     ^
video.cpp:80:53: warning: ‘int avpicture_get_size(AVPixelFormat, int, int)’ is deprecated [-Wdeprecated-declarations]
     size = avpicture_get_size(pix_fmt, width, height);
                                                     ^
In file included from video.cpp:8:0:
./FFmpeg/libavcodec/avcodec.h:5228:5: note: declared here
 int avpicture_get_size(enum AVPixelFormat pix_fmt, int width, int height);
     ^
video.cpp:87:5: warning: ‘int avpicture_fill(AVPicture*, const uint8_t*, AVPixelFormat, int, int)’ is deprecated [-Wdeprecated-declarations]
     avpicture_fill((AVPicture *) picture, picture_buf, pix_fmt, WIDTH, HEIGHT);
     ^
In file included from video.cpp:8:0:
./FFmpeg/libavcodec/avcodec.h:5213:5: note: declared here
 int avpicture_fill(AVPicture *picture, const uint8_t *ptr,
     ^
video.cpp:87:5: warning: ‘int avpicture_fill(AVPicture*, const uint8_t*, AVPixelFormat, int, int)’ is deprecated [-Wdeprecated-declarations]
     avpicture_fill((AVPicture *) picture, picture_buf, pix_fmt, WIDTH, HEIGHT);
     ^
In file included from video.cpp:8:0:
./FFmpeg/libavcodec/avcodec.h:5213:5: note: declared here
 int avpicture_fill(AVPicture *picture, const uint8_t *ptr,
     ^
video.cpp:87:78: warning: ‘int avpicture_fill(AVPicture*, const uint8_t*, AVPixelFormat, int, int)’ is deprecated [-Wdeprecated-declarations]
     avpicture_fill((AVPicture *) picture, picture_buf, pix_fmt, WIDTH, HEIGHT);
                                                                              ^
In file included from video.cpp:8:0:
./FFmpeg/libavcodec/avcodec.h:5213:5: note: declared here
 int avpicture_fill(AVPicture *picture, const uint8_t *ptr,
     ^
video.cpp: In function ‘void openVideo(AVFormatContext*, AVStream*)’:
video.cpp:96:13: warning: ‘AVStream::codec’ is deprecated [-Wdeprecated-declarations]
     c = st->codec;
             ^
In file included from video.cpp:9:0:
./FFmpeg/libavformat/avformat.h:876:21: note: declared here
     AVCodecContext *codec;
                     ^
video.cpp:96:13: warning: ‘AVStream::codec’ is deprecated [-Wdeprecated-declarations]
     c = st->codec;
             ^
In file included from video.cpp:9:0:
./FFmpeg/libavformat/avformat.h:876:21: note: declared here
     AVCodecContext *codec;
                     ^
video.cpp:96:13: warning: ‘AVStream::codec’ is deprecated [-Wdeprecated-declarations]
     c = st->codec;
             ^
In file included from video.cpp:9:0:
./FFmpeg/libavformat/avformat.h:876:21: note: declared here
     AVCodecContext *codec;
                     ^
video.cpp: In function ‘AVStream* addVideoStream(AVFormatContext*, AVCodecID)’:
video.cpp:151:21: warning: ‘AVStream::codec’ is deprecated [-Wdeprecated-declarations]
     codec = stream->codec;
                     ^
In file included from video.cpp:9:0:
./FFmpeg/libavformat/avformat.h:876:21: note: declared here
     AVCodecContext *codec;
                     ^
video.cpp:151:21: warning: ‘AVStream::codec’ is deprecated [-Wdeprecated-declarations]
     codec = stream->codec;
                     ^
In file included from video.cpp:9:0:
./FFmpeg/libavformat/avformat.h:876:21: note: declared here
     AVCodecContext *codec;
                     ^
video.cpp:151:21: warning: ‘AVStream::codec’ is deprecated [-Wdeprecated-declarations]
     codec = stream->codec;
                     ^
In file included from video.cpp:9:0:
./FFmpeg/libavformat/avformat.h:876:21: note: declared here
     AVCodecContext *codec;
                     ^
video.cpp: In function ‘void write_video_frame(AVFormatContext*, AVStream*)’:
video.cpp:202:13: warning: ‘AVStream::codec’ is deprecated [-Wdeprecated-declarations]
     c = st->codec;
             ^
In file included from video.cpp:9:0:
./FFmpeg/libavformat/avformat.h:876:21: note: declared here
     AVCodecContext *codec;
                     ^
video.cpp:202:13: warning: ‘AVStream::codec’ is deprecated [-Wdeprecated-declarations]
     c = st->codec;
             ^
In file included from video.cpp:9:0:
./FFmpeg/libavformat/avformat.h:876:21: note: declared here
     AVCodecContext *codec;
                     ^
video.cpp:202:13: warning: ‘AVStream::codec’ is deprecated [-Wdeprecated-declarations]
     c = st->codec;
             ^
In file included from video.cpp:9:0:
./FFmpeg/libavformat/avformat.h:876:21: note: declared here
     AVCodecContext *codec;
                     ^
video.cpp:256:20: warning: ‘AVCodecContext::coded_frame’ is deprecated [-Wdeprecated-declarations]
             if (c->coded_frame->pts != AV_NOPTS_VALUE)
                    ^
In file included from video.cpp:8:0:
./FFmpeg/libavcodec/avcodec.h:2723:35: note: declared here
     attribute_deprecated AVFrame *coded_frame;
                                   ^
video.cpp:256:20: warning: ‘AVCodecContext::coded_frame’ is deprecated [-Wdeprecated-declarations]
             if (c->coded_frame->pts != AV_NOPTS_VALUE)
                    ^
In file included from video.cpp:8:0:
./FFmpeg/libavcodec/avcodec.h:2723:35: note: declared here
     attribute_deprecated AVFrame *coded_frame;
                                   ^
video.cpp:256:20: warning: ‘AVCodecContext::coded_frame’ is deprecated [-Wdeprecated-declarations]
             if (c->coded_frame->pts != AV_NOPTS_VALUE)
                    ^
In file included from video.cpp:8:0:
./FFmpeg/libavcodec/avcodec.h:2723:35: note: declared here
     attribute_deprecated AVFrame *coded_frame;
                                   ^
video.cpp:257:42: warning: ‘AVCodecContext::coded_frame’ is deprecated [-Wdeprecated-declarations]
                 pkt.pts= av_rescale_q(c->coded_frame->pts, c->time_base, st->time_base);
                                          ^
In file included from video.cpp:8:0:
./FFmpeg/libavcodec/avcodec.h:2723:35: note: declared here
     attribute_deprecated AVFrame *coded_frame;
                                   ^
video.cpp:257:42: warning: ‘AVCodecContext::coded_frame’ is deprecated [-Wdeprecated-declarations]
                 pkt.pts= av_rescale_q(c->coded_frame->pts, c->time_base, st->time_base);
                                          ^
In file included from video.cpp:8:0:
./FFmpeg/libavcodec/avcodec.h:2723:35: note: declared here
     attribute_deprecated AVFrame *coded_frame;
                                   ^
video.cpp:257:42: warning: ‘AVCodecContext::coded_frame’ is deprecated [-Wdeprecated-declarations]
                 pkt.pts= av_rescale_q(c->coded_frame->pts, c->time_base, st->time_base);
                                          ^
In file included from video.cpp:8:0:
./FFmpeg/libavcodec/avcodec.h:2723:35: note: declared here
     attribute_deprecated AVFrame *coded_frame;
                                   ^
video.cpp:258:19: warning: ‘AVCodecContext::coded_frame’ is deprecated [-Wdeprecated-declarations]
             if(c->coded_frame->key_frame)
                   ^
In file included from video.cpp:8:0:
./FFmpeg/libavcodec/avcodec.h:2723:35: note: declared here
     attribute_deprecated AVFrame *coded_frame;
                                   ^
video.cpp:258:19: warning: ‘AVCodecContext::coded_frame’ is deprecated [-Wdeprecated-declarations]
             if(c->coded_frame->key_frame)
                   ^
In file included from video.cpp:8:0:
./FFmpeg/libavcodec/avcodec.h:2723:35: note: declared here
     attribute_deprecated AVFrame *coded_frame;
                                   ^
video.cpp:258:19: warning: ‘AVCodecContext::coded_frame’ is deprecated [-Wdeprecated-declarations]
             if(c->coded_frame->key_frame)
                   ^
In file included from video.cpp:8:0:
./FFmpeg/libavcodec/avcodec.h:2723:35: note: declared here
     attribute_deprecated AVFrame *coded_frame;
                                   ^
video.cpp:357:40: warning: ‘AVStream::codec’ is deprecated [-Wdeprecated-declarations]
         av_freep(&context->streams[i]->codec);
                                        ^
In file included from video.cpp:9:0:
./FFmpeg/libavformat/avformat.h:876:21: note: declared here
     AVCodecContext *codec;
                     ^
video.cpp:357:40: warning: ‘AVStream::codec’ is deprecated [-Wdeprecated-declarations]
         av_freep(&context->streams[i]->codec);
                                        ^
In file included from video.cpp:9:0:
./FFmpeg/libavformat/avformat.h:876:21: note: declared here
     AVCodecContext *codec;
                     ^
video.cpp:357:40: warning: ‘AVStream::codec’ is deprecated [-Wdeprecated-declarations]
         av_freep(&context->streams[i]->codec);
                                        ^
In file included from video.cpp:9:0:
./FFmpeg/libavformat/avformat.h:876:21: note: declared here
     AVCodecContext *codec;
                     ^
video.cpp:337:38: warning: ignoring return value of ‘int avformat_write_header(AVFormatContext*, AVDictionary**)’, declared with attribute warn_unused_result [-Wunused-result]
     avformat_write_header(context, 0);
                                      ^
</code>```

I have also defined a few macros to redefine those who have been omited. In a modern ffmpeg API, they must be replaced.

Could someone please help me solving errors and deprecation warnings to comply with recent ffmpeg API?

答:
As the comment says your API is very old one. Check newer samples from here:
https://github.com/FFmpeg/FFmpeg/tree/master/doc/examples

Some deprecation warnings may not be solved like as in ‘AVStream::codec’ is deprecated [-Wdeprecated-declarations]. Last time I check latest FFmpeg itself uses this too. Hope that helps.

Body:
I have started learning how to work with ffmpeg which has a suffering deprecation of all tutorial and available examples such as this.

I am looking for a code which creates an output video.

Unfortunately, most of good examples are focusing on reading from a file rather than creating one.

Here, I have found a deprecated example and I spent a long time to fix its errors until it became like this:

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

extern "C" {
        #include <libavcodec/avcodec.h>
        #include <libavformat/avformat.h>
        #include <libswscale/swscale.h>
        #include <libavformat/avio.h>
        #include <libavutil/opt.h>
}

#define WIDTH 800
#define HEIGHT 480
#define STREAM_NB_FRAMES  ((int)(STREAM_DURATION * FRAME_RATE))
#define FRAME_RATE 24
#define PIXEL_FORMAT AV_PIX_FMT_YUV420P
#define STREAM_DURATION 5.0 //seconds
#define BIT_RATE 400000

#define AV_CODEC_FLAG_GLOBAL_HEADER (1 << 22)
#define CODEC_FLAG_GLOBAL_HEADER AV_CODEC_FLAG_GLOBAL_HEADER
#define AVFMT_RAWPICTURE 0x0020

using namespace std;

static int sws_flags = SWS_BICUBIC;

AVFrame *picture, *tmp_picture;
uint8_t *video_outbuf;
int frame_count, video_outbuf_size;

/****** IF LINUX ******/
inline int sprintf_s(char* buffer, size_t sizeOfBuffer, const char* format, ...)
{
    va_list ap;
    va_start(ap, format);
    int result = vsnprintf(buffer, sizeOfBuffer, format, ap);
    va_end(ap);
    return result;
}

/****** IF LINUX ******/
template<size_t sizeOfBuffer>
inline int sprintf_s(char (&buffer)[sizeOfBuffer], const char* format, ...)
{
    va_list ap;
    va_start(ap, format);
    int result = vsnprintf(buffer, sizeOfBuffer, format, ap);
    va_end(ap);
    return result;
}

static void closeVideo(AVFormatContext *oc, AVStream *st)
{
    avcodec_close(st->codec);
    av_free(picture->data[0]);
    av_free(picture);
    if (tmp_picture)
    {
        av_free(tmp_picture->data[0]);
        av_free(tmp_picture);
    }
    av_free(video_outbuf);
}

static AVFrame *alloc_picture(enum AVPixelFormat pix_fmt, int width, int height)
{
    AVFrame *picture;
    uint8_t *picture_buf;
    int size;

    picture = av_frame_alloc();
    if(!picture)
        return NULL;
    size = avpicture_get_size(pix_fmt, width, height);
    picture_buf = (uint8_t*)(av_malloc(size));
    if (!picture_buf)
    {
        av_free(picture);
        return NULL;
    }
    avpicture_fill((AVPicture *) picture, picture_buf, pix_fmt, WIDTH, HEIGHT);
    return picture;
}

static void openVideo(AVFormatContext *oc, AVStream *st)
{
    AVCodec *codec;
    AVCodecContext *c;

    c = st->codec;
    if(c->idct_algo == AV_CODEC_ID_H264)
        av_opt_set(c->priv_data, "preset", "slow", 0);

    codec = avcodec_find_encoder(c->codec_id);
    if(!codec)
    {
        std::cout << "Codec not found." << std::endl;
        std::cin.get();std::cin.get();exit(1);
    }

    if(codec->id == AV_CODEC_ID_H264)
        av_opt_set(c->priv_data, "preset", "medium", 0);

    if(avcodec_open2(c, codec, NULL) < 0)
    {
        std::cout << "Could not open codec." << std::endl;
        std::cin.get();std::cin.get();exit(1);
    }
    video_outbuf = NULL;
    if(!(oc->oformat->flags & AVFMT_RAWPICTURE))
    {
        video_outbuf_size = 200000;
        video_outbuf = (uint8_t*)(av_malloc(video_outbuf_size));
    }
    picture = alloc_picture(c->pix_fmt, c->width, c->height);
    if(!picture)
    {
        std::cout << "Could not allocate picture" << std::endl;
        std::cin.get();exit(1);
    }
    tmp_picture = NULL;
    if(c->pix_fmt != AV_PIX_FMT_YUV420P)
    {
        tmp_picture = alloc_picture(AV_PIX_FMT_YUV420P, WIDTH, HEIGHT);
        if(!tmp_picture)
        {
            std::cout << " Could not allocate temporary picture" << std::endl;
            std::cin.get();exit(1);
        }
    }
}

static AVStream* addVideoStream(AVFormatContext *context, enum AVCodecID codecID)
{
    AVCodecContext *codec;
    AVStream *stream;
    stream = avformat_new_stream(context, NULL);
    if(!stream)
    {
        std::cout << "Could not alloc stream." << std::endl;
        std::cin.get();exit(1);
    }

    codec = stream->codec;
    codec->codec_id = codecID;
    codec->codec_type = AVMEDIA_TYPE_VIDEO;

    // sample rate
    codec->bit_rate = BIT_RATE;
    // resolution must be a multiple of two
    codec->width = WIDTH;
    codec->height = HEIGHT;
    codec->time_base.den = FRAME_RATE; // stream fps
    codec->time_base.num = 1;
    codec->gop_size = 12; // intra frame every twelve frames at most
    codec->pix_fmt = PIXEL_FORMAT;
    if(codec->codec_id == AV_CODEC_ID_MPEG2VIDEO)
        codec->max_b_frames = 2; // for testing, B frames

    if(codec->codec_id == AV_CODEC_ID_MPEG1VIDEO)
        codec->mb_decision = 2;

    if(context->oformat->flags & AVFMT_GLOBALHEADER)
        codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;

    return stream;
}

static void fill_yuv_image(AVFrame *pict, int frame_index, int width, int height)
{
    int x, y, i;
    i = frame_index;

    /* Y */
    for(y=0;y<height;y++) {
        for(x=0;x<width;x++) {
            pict->data[0][y * pict->linesize[0] + x] = x + y + i * 3;
        }
    }

    /* Cb and Cr */
    for(y=0;y<height/2;y++) {
        for(x=0;x<width/2;x++) {
            pict->data[1][y * pict->linesize[1] + x] = 128 + y + i * 2;
            pict->data[2][y * pict->linesize[2] + x] = 64 + x + i * 5;
        }
    }
}

static void write_video_frame(AVFormatContext *oc, AVStream *st)
{
    int out_size, ret;
    AVCodecContext *c;
    static struct SwsContext *img_convert_ctx;
    c = st->codec;

    if(frame_count >= STREAM_NB_FRAMES)
    {

    }
    else
    {
        if(c->pix_fmt != AV_PIX_FMT_YUV420P)
        {
            if(img_convert_ctx = NULL)
            {
                img_convert_ctx = sws_getContext(WIDTH, HEIGHT, AV_PIX_FMT_YUV420P, WIDTH, HEIGHT,
                                                c->pix_fmt, sws_flags, NULL, NULL, NULL);
                if(img_convert_ctx == NULL)
                {
                    std::cout << "Cannot initialize the conversion context" << std::endl;
                    std::cin.get();exit(1);
                }
            }
            fill_yuv_image(tmp_picture, frame_count, WIDTH, HEIGHT);
            sws_scale(img_convert_ctx, tmp_picture->data, tmp_picture->linesize, 0, HEIGHT,
                        picture->data, picture->linesize);
        }
        else
        {
            fill_yuv_image(picture, frame_count, WIDTH, HEIGHT);
        }
    }

    if (oc->oformat->flags & AVFMT_RAWPICTURE)
    {
        /* raw video case. The API will change slightly in the near
           futur for that */
        AVPacket pkt;
        av_init_packet(&pkt);

        pkt.flags |= AV_PKT_FLAG_KEY;
        pkt.stream_index= st->index;
        pkt.data= (uint8_t *)picture;
        pkt.size= sizeof(AVPicture);

        ret = av_interleaved_write_frame(oc, &pkt);
    }
    else
    {
        /* encode the image */
        out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, picture);
        /* if zero size, it means the image was buffered */
        if (out_size > 0)
        {
            AVPacket pkt;
            av_init_packet(&pkt);

            if (c->coded_frame->pts != AV_NOPTS_VALUE)
                pkt.pts= av_rescale_q(c->coded_frame->pts, c->time_base, st->time_base);
            if(c->coded_frame->key_frame)
                pkt.flags |= AV_PKT_FLAG_KEY;
            pkt.stream_index= st->index;
            pkt.data= video_outbuf;
            pkt.size= out_size;
            /* write the compressed frame in the media file */
            ret = av_interleaved_write_frame(oc, &pkt);
        } else {
            ret = 0;
        }
    }
    if (ret != 0) {
        std::cout << "Error while writing video frames" << std::endl;
        std::cin.get();exit(1);
    }
    frame_count++;
}

int main ( int argc, char *argv[] )
{
    const char* filename = "test.h264";
    AVOutputFormat *outputFormat;
    AVFormatContext *context;
    AVCodecContext *codec;
    AVStream *videoStream;
    double videoPTS;

    // init libavcodec, register all codecs and formats
    av_register_all();
    // auto detect the output format from the name
    outputFormat = av_guess_format(NULL, filename, NULL);
    if(!outputFormat)
    {
        std::cout << "Cannot guess output format! Using mpeg!" << std::endl;
        std::cin.get();
        outputFormat = av_guess_format(NULL, "h263" , NULL);
    }
    if(!outputFormat)
    {
        std::cout << "Could not find suitable output format." << std::endl;
        std::cin.get();exit(1);
    }

    context = avformat_alloc_context();
    if(!context)
    {
        std::cout << "Cannot allocate avformat memory." << std::endl;
        std::cin.get();exit(1);
    }
    context->oformat = outputFormat;
    sprintf_s(context->filename, sizeof(context->filename), "%s", filename);
    std::cout << "Is '" << context->filename << "' = '" << filename << "'" << std::endl;

    videoStream = NULL;
    outputFormat->audio_codec = AV_CODEC_ID_NONE;
    videoStream = addVideoStream(context, outputFormat->video_codec);

    /* still needed?
    if(av_set_parameters(context, NULL) < 0)
    {
        std::cout << "Invalid output format parameters." << std::endl;
        exit(0);
    }*/

    av_dump_format(context, 0, filename, 1);

    if(videoStream)
        openVideo(context, videoStream);

    if(!outputFormat->flags & AVFMT_NOFILE)
    {
        if(avio_open(&context->pb, filename, AVIO_FLAG_READ_WRITE) < 0)
        {
            std::cout << "Could not open " << filename << std::endl;
            std::cin.get();exit(1);
        }
    }

    avformat_write_header(context, 0);

    while(true)
    {
        if(videoStream)
            videoPTS = (double) videoStream->pts.val * videoStream->time_base.num / videoStream->time_base.den;
        else
            videoPTS = 0.;

        if((!videoStream || videoPTS >= STREAM_DURATION))
        {
            break;
        }
        write_video_frame(context, videoStream);
    }
    av_write_trailer(context);
    if(videoStream)
        closeVideo(context, videoStream);
    for(int i = 0; i < context->nb_streams; i++)
    {
        av_freep(&context->streams[i]->codec);
        av_freep(&context->streams[i]);
    }

    if(!(outputFormat->flags & AVFMT_NOFILE))
    {
        avio_close(context->pb);
    }
    av_free(context);
    std::cin.get();
    return 0;
}

Compile:

g++ -I ./FFmpeg/ video.cpp -L fflibs -lavcodec -lavformat

The code comes with two errors:

video.cpp:249:84: error: ‘avcodec_encode_video’ was not declared in this scope
         out_size = avcodec_encode_video(c, video_outbuf, video_outbuf_size, picture);
                                                                                ^

video.cpp: In function ‘int main(int, char**)’:
video.cpp:342:46: error: ‘AVStream {aka struct AVStream}’ has no member named ‘pts’
             videoPTS = (double) videoStream->pts.val * videoStream->time_base.num / videoStream->time_base.den;
                                              ^

and a huge number of warnings for deprecation.

video.cpp: In function ‘void closeVideo(AVFormatContext*, AVStream*)’:
video.cpp:60:23: warning: ‘AVStream::codec’ is deprecated [-Wdeprecated-declarations]
     avcodec_close(st->codec);
                       ^
In file included from video.cpp:9:0:
./FFmpeg/libavformat/avformat.h:876:21: note: declared here
     AVCodecContext *codec;
                     ^
video.cpp:60:23: warning: ‘AVStream::codec’ is deprecated [-Wdeprecated-declarations]
     avcodec_close(st->codec);
                       ^
In file included from video.cpp:9:0:
./FFmpeg/libavformat/avformat.h:876:21: note: declared here
     AVCodecContext *codec;
                     ^
video.cpp:60:23: warning: ‘AVStream::codec’ is deprecated [-Wdeprecated-declarations]
     avcodec_close(st->codec);
                       ^
In file included from video.cpp:9:0:
./FFmpeg/libavformat/avformat.h:876:21: note: declared here
     AVCodecContext *codec;
                     ^
video.cpp: In function ‘AVFrame* alloc_picture(AVPixelFormat, int, int)’:
video.cpp:80:12: warning: ‘int avpicture_get_size(AVPixelFormat, int, int)’ is deprecated [-Wdeprecated-declarations]
     size = avpicture_get_size(pix_fmt, width, height);
            ^
In file included from video.cpp:8:0:
./FFmpeg/libavcodec/avcodec.h:5228:5: note: declared here
 int avpicture_get_size(enum AVPixelFormat pix_fmt, int width, int height);
     ^
video.cpp:80:12: warning: ‘int avpicture_get_size(AVPixelFormat, int, int)’ is deprecated [-Wdeprecated-declarations]
     size = avpicture_get_size(pix_fmt, width, height);
            ^
In file included from video.cpp:8:0:
./FFmpeg/libavcodec/avcodec.h:5228:5: note: declared here
 int avpicture_get_size(enum AVPixelFormat pix_fmt, int width, int height);
     ^
video.cpp:80:53: warning: ‘int avpicture_get_size(AVPixelFormat, int, int)’ is deprecated [-Wdeprecated-declarations]
     size = avpicture_get_size(pix_fmt, width, height);
                                                     ^
In file included from video.cpp:8:0:
./FFmpeg/libavcodec/avcodec.h:5228:5: note: declared here
 int avpicture_get_size(enum AVPixelFormat pix_fmt, int width, int height);
     ^
video.cpp:87:5: warning: ‘int avpicture_fill(AVPicture*, const uint8_t*, AVPixelFormat, int, int)’ is deprecated [-Wdeprecated-declarations]
     avpicture_fill((AVPicture *) picture, picture_buf, pix_fmt, WIDTH, HEIGHT);
     ^
In file included from video.cpp:8:0:
./FFmpeg/libavcodec/avcodec.h:5213:5: note: declared here
 int avpicture_fill(AVPicture *picture, const uint8_t *ptr,
     ^
video.cpp:87:5: warning: ‘int avpicture_fill(AVPicture*, const uint8_t*, AVPixelFormat, int, int)’ is deprecated [-Wdeprecated-declarations]
     avpicture_fill((AVPicture *) picture, picture_buf, pix_fmt, WIDTH, HEIGHT);
     ^
In file included from video.cpp:8:0:
./FFmpeg/libavcodec/avcodec.h:5213:5: note: declared here
 int avpicture_fill(AVPicture *picture, const uint8_t *ptr,
     ^
video.cpp:87:78: warning: ‘int avpicture_fill(AVPicture*, const uint8_t*, AVPixelFormat, int, int)’ is deprecated [-Wdeprecated-declarations]
     avpicture_fill((AVPicture *) picture, picture_buf, pix_fmt, WIDTH, HEIGHT);
                                                                              ^
In file included from video.cpp:8:0:
./FFmpeg/libavcodec/avcodec.h:5213:5: note: declared here
 int avpicture_fill(AVPicture *picture, const uint8_t *ptr,
     ^
video.cpp: In function ‘void openVideo(AVFormatContext*, AVStream*)’:
video.cpp:96:13: warning: ‘AVStream::codec’ is deprecated [-Wdeprecated-declarations]
     c = st->codec;
             ^
In file included from video.cpp:9:0:
./FFmpeg/libavformat/avformat.h:876:21: note: declared here
     AVCodecContext *codec;
                     ^
video.cpp:96:13: warning: ‘AVStream::codec’ is deprecated [-Wdeprecated-declarations]
     c = st->codec;
             ^
In file included from video.cpp:9:0:
./FFmpeg/libavformat/avformat.h:876:21: note: declared here
     AVCodecContext *codec;
                     ^
video.cpp:96:13: warning: ‘AVStream::codec’ is deprecated [-Wdeprecated-declarations]
     c = st->codec;
             ^
In file included from video.cpp:9:0:
./FFmpeg/libavformat/avformat.h:876:21: note: declared here
     AVCodecContext *codec;
                     ^
video.cpp: In function ‘AVStream* addVideoStream(AVFormatContext*, AVCodecID)’:
video.cpp:151:21: warning: ‘AVStream::codec’ is deprecated [-Wdeprecated-declarations]
     codec = stream->codec;
                     ^
In file included from video.cpp:9:0:
./FFmpeg/libavformat/avformat.h:876:21: note: declared here
     AVCodecContext *codec;
                     ^
video.cpp:151:21: warning: ‘AVStream::codec’ is deprecated [-Wdeprecated-declarations]
     codec = stream->codec;
                     ^
In file included from video.cpp:9:0:
./FFmpeg/libavformat/avformat.h:876:21: note: declared here
     AVCodecContext *codec;
                     ^
video.cpp:151:21: warning: ‘AVStream::codec’ is deprecated [-Wdeprecated-declarations]
     codec = stream->codec;
                     ^
In file included from video.cpp:9:0:
./FFmpeg/libavformat/avformat.h:876:21: note: declared here
     AVCodecContext *codec;
                     ^
video.cpp: In function ‘void write_video_frame(AVFormatContext*, AVStream*)’:
video.cpp:202:13: warning: ‘AVStream::codec’ is deprecated [-Wdeprecated-declarations]
     c = st->codec;
             ^
In file included from video.cpp:9:0:
./FFmpeg/libavformat/avformat.h:876:21: note: declared here
     AVCodecContext *codec;
                     ^
video.cpp:202:13: warning: ‘AVStream::codec’ is deprecated [-Wdeprecated-declarations]
     c = st->codec;
             ^
In file included from video.cpp:9:0:
./FFmpeg/libavformat/avformat.h:876:21: note: declared here
     AVCodecContext *codec;
                     ^
video.cpp:202:13: warning: ‘AVStream::codec’ is deprecated [-Wdeprecated-declarations]
     c = st->codec;
             ^
In file included from video.cpp:9:0:
./FFmpeg/libavformat/avformat.h:876:21: note: declared here
     AVCodecContext *codec;
                     ^
video.cpp:256:20: warning: ‘AVCodecContext::coded_frame’ is deprecated [-Wdeprecated-declarations]
             if (c->coded_frame->pts != AV_NOPTS_VALUE)
                    ^
In file included from video.cpp:8:0:
./FFmpeg/libavcodec/avcodec.h:2723:35: note: declared here
     attribute_deprecated AVFrame *coded_frame;
                                   ^
video.cpp:256:20: warning: ‘AVCodecContext::coded_frame’ is deprecated [-Wdeprecated-declarations]
             if (c->coded_frame->pts != AV_NOPTS_VALUE)
                    ^
In file included from video.cpp:8:0:
./FFmpeg/libavcodec/avcodec.h:2723:35: note: declared here
     attribute_deprecated AVFrame *coded_frame;
                                   ^
video.cpp:256:20: warning: ‘AVCodecContext::coded_frame’ is deprecated [-Wdeprecated-declarations]
             if (c->coded_frame->pts != AV_NOPTS_VALUE)
                    ^
In file included from video.cpp:8:0:
./FFmpeg/libavcodec/avcodec.h:2723:35: note: declared here
     attribute_deprecated AVFrame *coded_frame;
                                   ^
video.cpp:257:42: warning: ‘AVCodecContext::coded_frame’ is deprecated [-Wdeprecated-declarations]
                 pkt.pts= av_rescale_q(c->coded_frame->pts, c->time_base, st->time_base);
                                          ^
In file included from video.cpp:8:0:
./FFmpeg/libavcodec/avcodec.h:2723:35: note: declared here
     attribute_deprecated AVFrame *coded_frame;
                                   ^
video.cpp:257:42: warning: ‘AVCodecContext::coded_frame’ is deprecated [-Wdeprecated-declarations]
                 pkt.pts= av_rescale_q(c->coded_frame->pts, c->time_base, st->time_base);
                                          ^
In file included from video.cpp:8:0:
./FFmpeg/libavcodec/avcodec.h:2723:35: note: declared here
     attribute_deprecated AVFrame *coded_frame;
                                   ^
video.cpp:257:42: warning: ‘AVCodecContext::coded_frame’ is deprecated [-Wdeprecated-declarations]
                 pkt.pts= av_rescale_q(c->coded_frame->pts, c->time_base, st->time_base);
                                          ^
In file included from video.cpp:8:0:
./FFmpeg/libavcodec/avcodec.h:2723:35: note: declared here
     attribute_deprecated AVFrame *coded_frame;
                                   ^
video.cpp:258:19: warning: ‘AVCodecContext::coded_frame’ is deprecated [-Wdeprecated-declarations]
             if(c->coded_frame->key_frame)
                   ^
In file included from video.cpp:8:0:
./FFmpeg/libavcodec/avcodec.h:2723:35: note: declared here
     attribute_deprecated AVFrame *coded_frame;
                                   ^
video.cpp:258:19: warning: ‘AVCodecContext::coded_frame’ is deprecated [-Wdeprecated-declarations]
             if(c->coded_frame->key_frame)
                   ^
In file included from video.cpp:8:0:
./FFmpeg/libavcodec/avcodec.h:2723:35: note: declared here
     attribute_deprecated AVFrame *coded_frame;
                                   ^
video.cpp:258:19: warning: ‘AVCodecContext::coded_frame’ is deprecated [-Wdeprecated-declarations]
             if(c->coded_frame->key_frame)
                   ^
In file included from video.cpp:8:0:
./FFmpeg/libavcodec/avcodec.h:2723:35: note: declared here
     attribute_deprecated AVFrame *coded_frame;
                                   ^
video.cpp:357:40: warning: ‘AVStream::codec’ is deprecated [-Wdeprecated-declarations]
         av_freep(&context->streams[i]->codec);
                                        ^
In file included from video.cpp:9:0:
./FFmpeg/libavformat/avformat.h:876:21: note: declared here
     AVCodecContext *codec;
                     ^
video.cpp:357:40: warning: ‘AVStream::codec’ is deprecated [-Wdeprecated-declarations]
         av_freep(&context->streams[i]->codec);
                                        ^
In file included from video.cpp:9:0:
./FFmpeg/libavformat/avformat.h:876:21: note: declared here
     AVCodecContext *codec;
                     ^
video.cpp:357:40: warning: ‘AVStream::codec’ is deprecated [-Wdeprecated-declarations]
         av_freep(&context->streams[i]->codec);
                                        ^
In file included from video.cpp:9:0:
./FFmpeg/libavformat/avformat.h:876:21: note: declared here
     AVCodecContext *codec;
                     ^
video.cpp:337:38: warning: ignoring return value of ‘int avformat_write_header(AVFormatContext*, AVDictionary**)’, declared with attribute warn_unused_result [-Wunused-result]
     avformat_write_header(context, 0);
                                      ^

I have also defined a few macros to redefine those who have been omited. In a modern ffmpeg API, they must be replaced.

Could someone please help me solving errors and deprecation warnings to comply with recent ffmpeg API?


问:
How to make a NURBS surface with NxN Control Points in Three.js
Yesterday I was trying to draw a Math function in 3D [ F(x,y) ].
How I did it? I calculated some points (x, y, z) in the space and I draw a white point there.

Here the example:

The first problem:
When I move the scenario (using Orbital Control), the performance is too bad!
So, I was looking for a solution and I realiced that NURBS surfaces could be my solution. But, the problem here is that I can't find a way to define a lot of Control Points.
I was thinking to create a NURBS surface with 50 x 50 control points (as the previous image), but I only can create a NURB surface with 3 x 4 points.
Here the code:

```<code>var nsControlPoints = [
    [
        new THREE.Vector4 ( -150, 0, 150, 1 ),
        new THREE.Vector4 ( 150, 0, 150, 1 ),
        new THREE.Vector4 ( 150, 0, -150, 1 ),
        new THREE.Vector4 ( -150, 0, -150, 1 ),
        new THREE.Vector4 ( -150, 0, 150, 1 )
    ],
    [
        new THREE.Vector4 ( -50, 50, 50, 1 ),
        new THREE.Vector4 ( 50, 50, 50, 1 ),
        new THREE.Vector4 ( 50, 50, -50, 1 ),
        new THREE.Vector4 ( -50, 50, -50, 1 ),
        new THREE.Vector4 ( -50, 50, 50, 1 )
    ],
    [
        new THREE.Vector4 ( -100, -50, 100, 1 ),
        new THREE.Vector4 ( 100, -50, 100, 1 ),
        new THREE.Vector4 ( 100, -50, -100, 1 ),
        new THREE.Vector4 ( -100, -50, -100, 1 ),
        new THREE.Vector4 ( -100, -50, 100, 1 )
    ],
];

var degree1 = 2;
var degree2 = 3;
var knots1 = [0, 0, 0, 1, 1, 1];
var knots2 = [0, 0, 0, 0, 1, 1, 1, 1];
var nurbsSurface = new THREE.NURBSSurface(degree1, degree2, knots1, knots2, nsControlPoints);

var map = new THREE.TextureLoader().load( 'styles/grid.jpg' );
map.wrapS = map.wrapT = THREE.RepeatWrapping;
map.anisotropy = 16;

getSurfacePoint = function(u, v) {
    return nurbsSurface.getPoint(u, v);
};

var geometry = new THREE.ParametricGeometry( getSurfacePoint, 20, 20 );
var material = new THREE.MeshLambertMaterial( { map: map, side: THREE.DoubleSide } );
var object = new THREE.Mesh( geometry, material );
object.position.set( - 200, 100, 0 );
object.scale.multiplyScalar( 1 );
group.add( object );
</code>```

Result:

The Question:
Do you know if there is a way to say something like: "Hey NURBS Surface, you should take this 50x50 array/matrix of vectors and draw it!"?

The second problem:
What about those points where the function doesn't exists?

The Question:
Can I draw kind of plane in function of a Math function?

答: An abstraction above THREE but verburbs is an open source library built to work with NURB surfaces. Here is a screen shot from one of their examples detailing what you're talking about. I have no affiliation with the codebase.

Body:
Yesterday I was trying to draw a Math function in 3D [ F(x,y) ].
How I did it? I calculated some points (x, y, z) in the space and I draw a white point there.

Here the example:

The first problem:
When I move the scenario (using Orbital Control), the performance is too bad!
So, I was looking for a solution and I realiced that NURBS surfaces could be my solution. But, the problem here is that I can't find a way to define a lot of Control Points.
I was thinking to create a NURBS surface with 50 x 50 control points (as the previous image), but I only can create a NURB surface with 3 x 4 points.
Here the code:

var nsControlPoints = [
    [
        new THREE.Vector4 ( -150, 0, 150, 1 ),
        new THREE.Vector4 ( 150, 0, 150, 1 ),
        new THREE.Vector4 ( 150, 0, -150, 1 ),
        new THREE.Vector4 ( -150, 0, -150, 1 ),
        new THREE.Vector4 ( -150, 0, 150, 1 )
    ],
    [
        new THREE.Vector4 ( -50, 50, 50, 1 ),
        new THREE.Vector4 ( 50, 50, 50, 1 ),
        new THREE.Vector4 ( 50, 50, -50, 1 ),
        new THREE.Vector4 ( -50, 50, -50, 1 ),
        new THREE.Vector4 ( -50, 50, 50, 1 )
    ],
    [
        new THREE.Vector4 ( -100, -50, 100, 1 ),
        new THREE.Vector4 ( 100, -50, 100, 1 ),
        new THREE.Vector4 ( 100, -50, -100, 1 ),
        new THREE.Vector4 ( -100, -50, -100, 1 ),
        new THREE.Vector4 ( -100, -50, 100, 1 )
    ],
];

var degree1 = 2;
var degree2 = 3;
var knots1 = [0, 0, 0, 1, 1, 1];
var knots2 = [0, 0, 0, 0, 1, 1, 1, 1];
var nurbsSurface = new THREE.NURBSSurface(degree1, degree2, knots1, knots2, nsControlPoints);

var map = new THREE.TextureLoader().load( 'styles/grid.jpg' );
map.wrapS = map.wrapT = THREE.RepeatWrapping;
map.anisotropy = 16;

getSurfacePoint = function(u, v) {
    return nurbsSurface.getPoint(u, v);
};

var geometry = new THREE.ParametricGeometry( getSurfacePoint, 20, 20 );
var material = new THREE.MeshLambertMaterial( { map: map, side: THREE.DoubleSide } );
var object = new THREE.Mesh( geometry, material );
object.position.set( - 200, 100, 0 );
object.scale.multiplyScalar( 1 );
group.add( object );

Result:

The Question:
Do you know if there is a way to say something like: "Hey NURBS Surface, you should take this 50x50 array/matrix of vectors and draw it!"?

The second problem:
What about those points where the function doesn't exists?

The Question:
Can I draw kind of plane in function of a Math function?


问:
SQL - converting table returned from USER DEFINED FUNCTION to array
I have a UDF that takes a space-delimited string and returns a table containing rows the individual strings. Something like this:

```<code>SplitTextReturnTable('Emmanuel John Ahmed', ' ')
</code>```

// returns a table containing three rows having Emmanuel, John and Ahmed.

What I want to do is use each of the returned string to perform a search in a table to retrieve rows with data matching the strings, something similar to a for-each-statement that searches the table with each of the returned strings. Here is a pseudo code of what I want.

```<code>DECLARE @myArray ARRAY;
SET @myArray = ConvertToArray(SplitTextReturnTable('Emmanuel John Ahmed', ' '))
SELECT * FROM Customers WHERE Customers.Fullname LIKE + '%' + @myArray[0] + '%' or Customers.Fullname LIKE + '%' + @myArray[1] + '%' or Customers.Fullname LIKE + '%' + @myArray[2] + '%'
</code>```

Any help would be appreciated. I would also like to know if there's a better way to perform database searching more effectively.

Thanks.

答:
Why does your split function only return one row for this input? It doesn't seem to be splitting at all! What you probably want it to do is to fix it to return a table with 3 rows that you can then join on. i.e. something like

```<code>SELECT c.*
FROM Customers c
JOIN dbo.SplitTextReturnTable('Emmanuel John Ahmed', ' ') s
ON c.Fullname LIKE '%' + s.value + '%'
</code>```

Regarding the second part of your question you might want to investigate Full Text Search. LIKE with leading wildcards is inherently slow.

ContentLicense: CC BY-SA 2.5

Body:
I have a UDF that takes a space-delimited string and returns a table containing rows the individual strings. Something like this:

SplitTextReturnTable('Emmanuel John Ahmed', ' ')

// returns a table containing three rows having Emmanuel, John and Ahmed.

What I want to do is use each of the returned string to perform a search in a table to retrieve rows with data matching the strings, something similar to a for-each-statement that searches the table with each of the returned strings. Here is a pseudo code of what I want.

DECLARE @myArray ARRAY;
SET @myArray = ConvertToArray(SplitTextReturnTable('Emmanuel John Ahmed', ' '))
SELECT * FROM Customers WHERE Customers.Fullname LIKE + '%' + @myArray[0] + '%' or Customers.Fullname LIKE + '%' + @myArray[1] + '%' or Customers.Fullname LIKE + '%' + @myArray[2] + '%'

Any help would be appreciated. I would also like to know if there's a better way to perform database searching more effectively.

Thanks.

Body:
Why does your split function only return one row for this input? It doesn't seem to be splitting at all! What you probably want it to do is to fix it to return a table with 3 rows that you can then join on. i.e. something like

SELECT c.*
FROM Customers c
JOIN dbo.SplitTextReturnTable('Emmanuel John Ahmed', ' ') s
ON c.Fullname LIKE '%' + s.value + '%'

Regarding the second part of your question you might want to investigate Full Text Search. LIKE with leading wildcards is inherently slow.


问:
Why won't my function return largest even if numbers are negative
I need to create a function that returns the largest even number in a list. I created this but it doesn't work for negative numbers and I'm not sure why.</p>

```<code>def largest_even(list_int):
large = False
print(list_int)
for i in list_int:
    if i % 2 == 0:
        i = large
for i in list_int:
    if i % 2 == 0:
        if i > large:
            large = i
return large
</code>```

答:
If you're looking for largest even, then dcg's answer is right

If you're asking why your code doesn't work:

First, it looks like you have nested for, so don't reuse same variable i inside nested loop unless you have a good reason to

Second, this i = large should be large = i

Rewrite:

```<code>def largest_even(list_int):
    large = False
    for i in list_int:
        if i % 2 == 0:
            large = i
        for j in list_int:
            if j % 2 == 0:
                if j > large:
                    large = j
    return large
</code>```

Body:
I need to create a function that returns the largest even number in a list. I created this but it doesn't work for negative numbers and I'm not sure why.

def largest_even(list_int):
large = False
print(list_int)
for i in list_int:
    if i % 2 == 0:
        i = large
for i in list_int:
    if i % 2 == 0:
        if i > large:
            large = i
return large

Body:
If you're looking for largest even, then dcg's answer is right

If you're asking why your code doesn't work:

First, it looks like you have nested for, so don't reuse same variable i inside nested loop unless you have a good reason to

Second, this i = large should be large = i

Rewrite:

def largest_even(list_int):
    large = False
    for i in list_int:
        if i % 2 == 0:
            large = i
        for j in list_int:
            if j % 2 == 0:
                if j > large:
                    large = j
    return large


问:
Expandable Tableview with last row of every section has Add Button - Swift
I struck in tableview. I need tableview of collapse and Expand looks like Below,

]2

I need to add 2 buttons for last row of every section.
Could you guide me how to design the below design in ios swift?

答:
Best way is take Two Button in one cell, and return that cell when indexPath.row = lastRow
And add tap gesture on header view for collapse view


问:
How Do I Set The Value Of A String In Android?
I have a string and a button as follows:

```<code>String message = "Hello World"

button.OnClickListener(......){

   message = "123456789";
}
</code>```

So here is what I want,

When the app starts the string is "Hello World" but when the user clicks the button it changes to "123456789" and I want the string to change permanently for lifetime.

So when the user restarts the application or reinstall it the string is still
"123456789".I think this comes under Shared Preferences.

Please Help,I really need this

答:
You can save that string in Shared Preferences, and get it all the from there. If is no value, you can get default value from resources or you can provide your own default String. Note that you can do that for lifetime. If user delete the app or clear cache, your view will display default value, Hello World.

Edit

You can use android:allowBackup="true" from manifest in order to keep old Shared Preference values.

Body:
I have a string and a button as follows:

String message = "Hello World"

button.OnClickListener(......){

   message = "123456789";
}

So here is what I want,

When the app starts the string is "Hello World" but when the user clicks the button it changes to "123456789" and I want the string to change permanently for lifetime.

So when the user restarts the application or reinstall it the string is still
"123456789".I think this comes under Shared Preferences.

Please Help,I really need this


答:
The random index range have to be 0 <= yourArraySize</p>

```<code>static String randomWord()
    {
        String[] randomWords = {"dog", "cat", "monkey"};
        return randomWords[ThreadLocalRandom.current().nextInt(0, randomWords.length + 1)];
    }
</code>```

Title: How to use method to output a random string from array?

Body:
How can I fix the code so my method compiles correctly to output a random string from the array I created into the main method?

class Main
{
  public static void main (String[] args)
  {
   randomWord();
   System.out.println (random);
  }

  static String[] randomWord()
  {
    String[] randomWords = {"dog", "cat", "monkey"}
    String random = randomWords[(int)(Math.random() * randomWords.length)];
    return random;
  }
}

Body:
The random index range have to be 0 <= yourArraySize

static String randomWord()
    {
        String[] randomWords = {"dog", "cat", "monkey"};
        return randomWords[ThreadLocalRandom.current().nextInt(0, randomWords.length + 1)];
    }


问:
OpenCV iOS Drawing Bounding Box
I'm trying to draw a box around a foot in a photo. I can do it with other objects, including ones that aren't fully in the image (I have pasted my code below). However, when I try to use it with a foot, it draws the contour perfectly but the rectangle is always the around the full image. I have attached pictures below of the result. Is there any way to change my code to fix this, or is there any other method possible of drawing a box around the foot?

Original Image

Contour and Bounding Box

```<code>RNG rng(12345);
Mat threshold_output;
vector<vector<cv::Point> > contours;
vector<Vec4i> hierarchy;

Mat srcImage;
UIImageToMat(image, srcImage);
cvtColor(srcImage, srcImage, CV_BGR2GRAY);
blur(srcImage, srcImage, cv::Size(3,3));

threshold(srcImage, threshold_output, 100, 255, THRESH_BINARY );
findContours(threshold_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0) );

vector<vector<cv::Point> > contours_poly( contours.size() );
vector<cv::Rect> boundRect( contours.size() );

for( int i = 0; i < contours.size(); i++ ) {
    approxPolyDP( Mat(contours[i]), contours_poly[i], 3, true );
    boundRect[i] = boundingRect( Mat(contours_poly[i]) );
}

Mat drawing = Mat::zeros( threshold_output.size(), CV_8UC3 );
for( int i = 0; i< contours.size(); i++ )
{
    if (contourArea(contours[i]) < 1000) {
        continue;
    }
    Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) );
    drawContours(drawing, contours_poly, i, color, 1, 8, vector<Vec4i>(), 0, cv::Point());
    rectangle(drawing, boundRect[i].tl(), boundRect[i].br(), color, 2, 8, 0 );
    cout << "Height:" << boundRect[i].height << " Width: " << boundRect[i].width << endl;
}

return MatToUIImage(drawing);
</code>```

答:
Since the bottom part of the foot reaches the image boundary, the contour seems to wrap around the perimeter of the image and thereby create a large bounding box that includes the entire image.

A quick and dirty solution will be to set the border pixels of the image to zero before applying findContours(). For a better solution, you have to think about the actual problem that you are trying to solve.

Title: OpenCV iOS Drawing Bounding Box

Body:
I'm trying to draw a box around a foot in a photo. I can do it with other objects, including ones that aren't fully in the image (I have pasted my code below). However, when I try to use it with a foot, it draws the contour perfectly but the rectangle is always the around the full image. I have attached pictures below of the result. Is there any way to change my code to fix this, or is there any other method possible of drawing a box around the foot?

Original Image

Contour and Bounding Box

RNG rng(12345);
Mat threshold_output;
vector<vector<cv::Point> > contours;
vector<Vec4i> hierarchy;

Mat srcImage;
UIImageToMat(image, srcImage);
cvtColor(srcImage, srcImage, CV_BGR2GRAY);
blur(srcImage, srcImage, cv::Size(3,3));

threshold(srcImage, threshold_output, 100, 255, THRESH_BINARY );
findContours(threshold_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0) );

vector<vector<cv::Point> > contours_poly( contours.size() );
vector<cv::Rect> boundRect( contours.size() );

for( int i = 0; i < contours.size(); i++ ) {
    approxPolyDP( Mat(contours[i]), contours_poly[i], 3, true );
    boundRect[i] = boundingRect( Mat(contours_poly[i]) );
}

Mat drawing = Mat::zeros( threshold_output.size(), CV_8UC3 );
for( int i = 0; i< contours.size(); i++ )
{
    if (contourArea(contours[i]) < 1000) {
        continue;
    }
    Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255) );
    drawContours(drawing, contours_poly, i, color, 1, 8, vector<Vec4i>(), 0, cv::Point());
    rectangle(drawing, boundRect[i].tl(), boundRect[i].br(), color, 2, 8, 0 );
    cout << "Height:" << boundRect[i].height << " Width: " << boundRect[i].width << endl;
}

return MatToUIImage(drawing);


答:
One of your issues is that you're setting i to False, and then attempting to check if your current number is greater than False, which is not giving you the desired input. Instead, try the following one-liner:

```<code>def largest_even(list_int):
    return max([i for i in list_int if not i%2])
</code>```

```<code>>>> largest_even([1, 3, 5, 7, 9, 333, 4])
4
>>> largest_even([1, 3, 5, 7, 9, 332, 4])
332
>>>
</code>```

Title: Why won't my function return largest even if numbers are negative

Body:
One of your issues is that you're setting i to False, and then attempting to check if your current number is greater than False, which is not giving you the desired input. Instead, try the following one-liner:

def largest_even(list_int):
    return max([i for i in list_int if not i%2])

>>> largest_even([1, 3, 5, 7, 9, 333, 4])
4
>>> largest_even([1, 3, 5, 7, 9, 332, 4])
332
>>>


问:
Can I know in which point we need to validate the JWT expiration?
I am quite new to JWT based authentication. And im quite confused about the refresh token mechanism. In my case, I have designed my application as,

 1. User will login to the application, and when the login is successful then it will go to the authentication server and sign a jwt and will pass it to the client.

 2. And then the client will store the refresh token and the short lived token in the local storage

 3. Once the resource server is called the token will be sent through the header. and will get validated.

 My question is, in which point should we request another token using the refresh token mechanism. Should we check whether the short lived token is invlaid before sending the request to the resource server. or should we get a new token once the validation fails in resource server? or is there any better way to handle this?

答:
A Refresh Token is a special kind of token that can be used to obtain a renewed access token —that allows accessing a protected resource— at any time.

Although Access Tokens can be renewed at any time using Refresh Tokens, they should be renewed when old ones have expired, or when getting access to a new resource for the first time. Refresh Tokens never expire OR have very long expiration time.


答:
Here is a simple approach where all numbers are printed in different lines

var button = document.querySelector("button");
button.addEventListener("click", function() {
  //iterate all inputs, get their values, and join them separated by a line break
  document.getElementById("output").innerHTML =
 [].slice.call(document.querySelectorAll("input")).map( s => s.value ).join( "
" );
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
</div>

<button>Check</button>
<div id="output"></div></code>```

Title: How to get the values of few input fields in java script and write them on web?

Body:
I would like to take all values from all input fields and write them on the web.

Here is my code:

var button = document.querySelector("button");
button.addEventListener("click", function() {

  var inputs = document.querySelectorAll("input").value;
  for (i = 0; i < inputs.length; i++) {
    inputs[i];
  }

  var output = document.getElementById("output");
  output.innerHTML = "To sa: " + inputs;
});

  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">

<button>Check</button>

Body:
Here is a simple approach where all numbers are printed in different lines

var button = document.querySelector("button");
button.addEventListener("click", function() {
  //iterate all inputs, get their values, and join them separated by a line break
  document.getElementById("output").innerHTML =
 [].slice.call(document.querySelectorAll("input")).map( s => s.value ).join( "<br>" );
});

<div>
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
</div>

<button>Check</button>
<div id="output"></div>