问:
from dataGridView1.Rows.Clear() until end to my code
Please Let me explain of there is something weird going on to my codes with my visual studio pro. There are no error messages of disconnected loops. It seems like I give up to check something wrong all files of my point of sales project. So until code below works fine.

```<code> private void button1_Click(object sender, EventArgs e)
        {
            try
            {

                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {

                    MySqlCommand cmd = new MySqlCommand();
                    cmd.Connection = con;

                    cmd.CommandText = "Insert into salesproducts(saleid,productname,qty,grosstotal)values(@saleid,@productname,@qty,@grosstotal)";
                    cmd.Parameters.AddWithValue("@saleid", lbinvoice.Text);
                    cmd.Parameters.AddWithValue("@productname", dataGridView1.Rows[i].Cells[2].Value);
                    cmd.Parameters.AddWithValue("@qty", dataGridView1.Rows[i].Cells[3].Value);
                    cmd.Parameters.AddWithValue("@grosstotal", dataGridView1.Rows[i].Cells[4].Value);

                    MySqlCommand cmd1 = new MySqlCommand();
                    cmd1.Connection = con;
                    cmd1.CommandText = "insert into salesmain(id,date,time,cashername,qty,grosstotal)values(@id,@date,@time,@cashername,@qty,@grosstotal)";
                    cmd1.Parameters.AddWithValue("@id", lbinvoice.Text);
                    cmd1.Parameters.AddWithValue("@date", lbldate.Text);
                    cmd1.Parameters.AddWithValue("@time", lbltime.Text);
                    cmd1.Parameters.AddWithValue("@cashername", label6.Text);
                    cmd1.Parameters.AddWithValue("@qty", lbitems.Text);

                    cmd1.Parameters.AddWithValue("@grosstotal", lbtotal.Text);

                    con.Open();
                   int x = cmd.ExecuteNonQuery();
                   int y = cmd1.ExecuteNonQuery();

                    MessageBox.Show("Record added ..........");

                    updatedb();

                   }

               }

           catch (Exception ex)
          {
              //MessageBox.Show(ex.Message);
        }

       finally
      {
          con.Close();
      }
    }

// everything worked fine of project till now......
</code>```

but after add these codes from
like this now then nothing worked.

```<code>                    updatedb();

        //Nothing worked from here...

                    dataGridView1.Rows.Clear();
                    lbtotal.Text = "0";
                    lbitems.Text = "0";
                    txtno.Focus();
                    totalPrice = 0;

                con.Close();
                invoice();
     }
           }
        catch (Exception ex)
        {
            //MessageBox.Show(ex.Message);
        }

        finally
        {
            con.Close();
        }
       }
</code>```

Sorry, I couldn't display the picture wholly screenshot or there is no permission here whatever. Please click down the below links.

Please watch the sales window here

then please watch this one to know whats not work

I hope to find a solution without adding extra codes of files. Thanks

答:
Sorry, it's not completely given codes to clarify the updateb() and invoice(). So for that reason, it's better off up like all codes in my specific file. So up like this.

```<code>using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace superpos3
{
    public partial class salesn : Form
    {
        public salesn()
        {
            InitializeComponent();
        }

       public static int totalPrice = 0;
        public static int payment = 0;
        public static int balance = 0;

        MySqlConnection con = new MySqlConnection("server= localhost; database =superpos;  username= root; password=; ");

        public void invoice()
        {

            con.Open();
            string query = "select max(id) from salesmain ";
            MySqlCommand cmd2 = new MySqlCommand(query, con);
            MySqlDataReader dr;
            dr = cmd2.ExecuteReader();
            if (dr.Read())
            {
                string val = dr[0].ToString();
                if (val == "")
                {
                    lbinvoice.Text = "1";

                }
                else
                {
                    int a;

                    a = int.Parse(dr[0].ToString());
                    a = a + 1;
                    lbinvoice.Text = a.ToString();

                }
                con.Close();
            }

        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void txtno_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                txtqty.Enabled = true;
                txtqty.Focus();
            }
        }

        private void txtqty_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {

                try
                {

                    string txt = "select * from products where id='" + txtno.Text + "'";
                    MySqlCommand cmd = new MySqlCommand(txt, con);
                    con.Open();
                    MySqlDataReader r = cmd.ExecuteReader();
                    while (r.Read())
                    {
                        int price = int.Parse(txtqty.Text.ToString()) * int.Parse(r[4].ToString());
                        totalPrice = totalPrice + price;
                        //discount
                        // totalPrice = totalPrice - totalPrice* Payment.discount/100;

                        dataGridView1.Rows.Add(dataGridView1.RowCount, r[0], r[1], txtqty.Text.Trim(), r[4], price);

                    }
                    lbitems.Text = " " + (dataGridView1.RowCount - 1) + "";
                    lbtotal.Text = " " + totalPrice + " ";

                    con.Close();

                }

                catch (Exception ee)
                {
                    MessageBox.Show(ee.Message, "Error From Database");
                }

                txtno.Focus();
                txtno.Clear();

                txtqty.Enabled = false;
                txtqty.Clear();

            }

        }

        private void txtqty_TextChanged(object sender, EventArgs e)
        {

        }
        private string name;

        public string Staffname
        {
            get { return name; }
            set { name = value; }

        }

      public void updatedb()
        {

            for (int row = 0; row < dataGridView1.Rows.Count; row++)
            {

                string itmno = dataGridView1.Rows[row].Cells[1].Value.ToString();
                string itmqty = dataGridView1.Rows[row].Cells[3].Value.ToString();

                string t = "select * from products where id= '"+ itmno + "'";

                string oldqty = "", newqty = "";

                Connnew.DbSearch(t);

                while (Connnew.dr.Read())
                {

                    oldqty = Connnew.dr[5].ToString();
                    newqty = (int.Parse(oldqty) - int.Parse(itmqty)).ToString();
                }

                string t2 = "update products SET qty = '" + newqty + "' WHERE id = '" + itmno + "'";
                //t2 = t2.Replace("{0}", itmno);
                //t2 = t2.Replace("{2}", newqty);
                Connnew.DbUpdate(t2);
            }

        }

        private void salesn_Load(object sender, EventArgs e)
        {
            label6.Text = Staffname;
            lbldate.Text = DateTime.Today.ToString("dd/MM/yyyy");
            lbltime.Text = DateTime.Now.ToShortTimeString();

            invoice();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {

                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {

                    MySqlCommand cmd = new MySqlCommand();
                    cmd.Connection = con;

                    cmd.CommandText = "Insert into salesproducts(saleid,productname,qty,grosstotal)values(@saleid,@productname,@qty,@grosstotal)";
                    cmd.Parameters.AddWithValue("@saleid", lbinvoice.Text);
                    cmd.Parameters.AddWithValue("@productname", dataGridView1.Rows[i].Cells[2].Value);
                    cmd.Parameters.AddWithValue("@qty", dataGridView1.Rows[i].Cells[3].Value);
                    cmd.Parameters.AddWithValue("@grosstotal", dataGridView1.Rows[i].Cells[4].Value);

                    MySqlCommand cmd1 = new MySqlCommand();
                    cmd1.Connection = con;
                    cmd1.CommandText = "insert into salesmain(id,date,time,cashername,qty,grosstotal)values(@id,@date,@time,@cashername,@qty,@grosstotal)";
                    cmd1.Parameters.AddWithValue("@id", lbinvoice.Text);
                    cmd1.Parameters.AddWithValue("@date", lbldate.Text);
                    cmd1.Parameters.AddWithValue("@time", lbltime.Text);
                    cmd1.Parameters.AddWithValue("@cashername", label6.Text);
                    cmd1.Parameters.AddWithValue("@qty", lbitems.Text);

                    cmd1.Parameters.AddWithValue("@grosstotal", lbtotal.Text);

                    con.Open();
                   int x = cmd.ExecuteNonQuery();
                   int y = cmd1.ExecuteNonQuery();

                    MessageBox.Show("Record added ..........");
                    updatedb();
                    dataGridView1.Rows.Clear();
                    lbtotal.Text = "0";
                    lbitems.Text = "0";
                    txtno.Focus();
                    totalPrice = 0;

                    con.Close();
                    invoice();

                }
               }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }

            finally
            {
                con.Close();
            }
           }

        private void button2_Click(object sender, EventArgs e)
        {
            pay p = new pay();
            p.Show();
        }

        private void label6_Click(object sender, EventArgs e)
        {

        }
    }
}
</code>```

And I'm seeing everything is fine and still not find the issue of those.

And the connected with above related to Connnew.DbSearch(t) that "Connnew" is like:

```<code>using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
namespace superpos3
{
    class Connnew
    {

        public static MySqlConnection con = new MySqlConnection("server= localhost; database =superpos; username= root; password=; ");
        public static MySqlCommand poscmd = new MySqlCommand();
        public static MySqlDataReader dr;

        public static void DbSearch(string txt)
        {

            con.Close();
            poscmd.Connection = con;
            poscmd.CommandText = txt;
            con.Open();
            dr = poscmd.ExecuteReader();
        }

        public static void DbUpdate(string txt)
        {
            con.Close();
            poscmd.Connection = con;
            poscmd.CommandText = txt;
            con.Open();
            poscmd.ExecuteNonQuery();
        }
    }
}
</code>```

Please let me know what is here the issue of the structure of codes or what is really going wrong.

Body:
Please Let me explain of there is something weird going on to my codes with my visual studio pro. There are no error messages of disconnected loops. It seems like I give up to check something wrong all files of my point of sales project. So until code below works fine.

 private void button1_Click(object sender, EventArgs e)
        {
            try
            {

                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {

                    MySqlCommand cmd = new MySqlCommand();
                    cmd.Connection = con;

                    cmd.CommandText = "Insert into salesproducts(saleid,productname,qty,grosstotal)values(@saleid,@productname,@qty,@grosstotal)";
                    cmd.Parameters.AddWithValue("@saleid", lbinvoice.Text);
                    cmd.Parameters.AddWithValue("@productname", dataGridView1.Rows[i].Cells[2].Value);
                    cmd.Parameters.AddWithValue("@qty", dataGridView1.Rows[i].Cells[3].Value);
                    cmd.Parameters.AddWithValue("@grosstotal", dataGridView1.Rows[i].Cells[4].Value);

                    MySqlCommand cmd1 = new MySqlCommand();
                    cmd1.Connection = con;
                    cmd1.CommandText = "insert into salesmain(id,date,time,cashername,qty,grosstotal)values(@id,@date,@time,@cashername,@qty,@grosstotal)";
                    cmd1.Parameters.AddWithValue("@id", lbinvoice.Text);
                    cmd1.Parameters.AddWithValue("@date", lbldate.Text);
                    cmd1.Parameters.AddWithValue("@time", lbltime.Text);
                    cmd1.Parameters.AddWithValue("@cashername", label6.Text);
                    cmd1.Parameters.AddWithValue("@qty", lbitems.Text);

                    cmd1.Parameters.AddWithValue("@grosstotal", lbtotal.Text);

                    con.Open();
                   int x = cmd.ExecuteNonQuery();
                   int y = cmd1.ExecuteNonQuery();

                    MessageBox.Show("Record added ..........");

                    updatedb();

                   }

               }

           catch (Exception ex)
          {
              //MessageBox.Show(ex.Message);
        }

       finally
      {
          con.Close();
      }
    }

// everything worked fine of project till now......

but after add these codes from
like this now then nothing worked.

                    updatedb();

        //Nothing worked from here...

                    dataGridView1.Rows.Clear();
                    lbtotal.Text = "0";
                    lbitems.Text = "0";
                    txtno.Focus();
                    totalPrice = 0;

                con.Close();
                invoice();
     }
           }
        catch (Exception ex)
        {
            //MessageBox.Show(ex.Message);
        }

        finally
        {
            con.Close();
        }
       }

Sorry, I couldn't display the picture wholly screenshot or there is no permission here whatever. Please click down the below links.

Please watch the sales window here

then please watch this one to know whats not work

I hope to find a solution without adding extra codes of files. Thanks

Body:
Sorry, it's not completely given codes to clarify the updateb() and invoice(). So for that reason, it's better off up like all codes in my specific file. So up like this.

using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace superpos3
{
    public partial class salesn : Form
    {
        public salesn()
        {
            InitializeComponent();
        }

       public static int totalPrice = 0;
        public static int payment = 0;
        public static int balance = 0;

        MySqlConnection con = new MySqlConnection("server= localhost; database =superpos;  username= root; password=; ");

        public void invoice()
        {

            con.Open();
            string query = "select max(id) from salesmain ";
            MySqlCommand cmd2 = new MySqlCommand(query, con);
            MySqlDataReader dr;
            dr = cmd2.ExecuteReader();
            if (dr.Read())
            {
                string val = dr[0].ToString();
                if (val == "")
                {
                    lbinvoice.Text = "1";

                }
                else
                {
                    int a;

                    a = int.Parse(dr[0].ToString());
                    a = a + 1;
                    lbinvoice.Text = a.ToString();

                }
                con.Close();
            }

        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void txtno_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                txtqty.Enabled = true;
                txtqty.Focus();
            }
        }

        private void txtqty_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {

                try
                {

                    string txt = "select * from products where id='" + txtno.Text + "'";
                    MySqlCommand cmd = new MySqlCommand(txt, con);
                    con.Open();
                    MySqlDataReader r = cmd.ExecuteReader();
                    while (r.Read())
                    {
                        int price = int.Parse(txtqty.Text.ToString()) * int.Parse(r[4].ToString());
                        totalPrice = totalPrice + price;
                        //discount
                        // totalPrice = totalPrice - totalPrice* Payment.discount/100;

                        dataGridView1.Rows.Add(dataGridView1.RowCount, r[0], r[1], txtqty.Text.Trim(), r[4], price);

                    }
                    lbitems.Text = " " + (dataGridView1.RowCount - 1) + "";
                    lbtotal.Text = " " + totalPrice + " ";

                    con.Close();

                }

                catch (Exception ee)
                {
                    MessageBox.Show(ee.Message, "Error From Database");
                }

                txtno.Focus();
                txtno.Clear();

                txtqty.Enabled = false;
                txtqty.Clear();

            }

        }

        private void txtqty_TextChanged(object sender, EventArgs e)
        {

        }
        private string name;

        public string Staffname
        {
            get { return name; }
            set { name = value; }

        }

      public void updatedb()
        {

            for (int row = 0; row < dataGridView1.Rows.Count; row++)
            {

                string itmno = dataGridView1.Rows[row].Cells[1].Value.ToString();
                string itmqty = dataGridView1.Rows[row].Cells[3].Value.ToString();

                string t = "select * from products where id= '"+ itmno + "'";

                string oldqty = "", newqty = "";

                Connnew.DbSearch(t);

                while (Connnew.dr.Read())
                {

                    oldqty = Connnew.dr[5].ToString();
                    newqty = (int.Parse(oldqty) - int.Parse(itmqty)).ToString();
                }

                string t2 = "update products SET qty = '" + newqty + "' WHERE id = '" + itmno + "'";
                //t2 = t2.Replace("{0}", itmno);
                //t2 = t2.Replace("{2}", newqty);
                Connnew.DbUpdate(t2);
            }

        }

        private void salesn_Load(object sender, EventArgs e)
        {
            label6.Text = Staffname;
            lbldate.Text = DateTime.Today.ToString("dd/MM/yyyy");
            lbltime.Text = DateTime.Now.ToShortTimeString();

            invoice();

        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {

                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {

                    MySqlCommand cmd = new MySqlCommand();
                    cmd.Connection = con;

                    cmd.CommandText = "Insert into salesproducts(saleid,productname,qty,grosstotal)values(@saleid,@productname,@qty,@grosstotal)";
                    cmd.Parameters.AddWithValue("@saleid", lbinvoice.Text);
                    cmd.Parameters.AddWithValue("@productname", dataGridView1.Rows[i].Cells[2].Value);
                    cmd.Parameters.AddWithValue("@qty", dataGridView1.Rows[i].Cells[3].Value);
                    cmd.Parameters.AddWithValue("@grosstotal", dataGridView1.Rows[i].Cells[4].Value);

                    MySqlCommand cmd1 = new MySqlCommand();
                    cmd1.Connection = con;
                    cmd1.CommandText = "insert into salesmain(id,date,time,cashername,qty,grosstotal)values(@id,@date,@time,@cashername,@qty,@grosstotal)";
                    cmd1.Parameters.AddWithValue("@id", lbinvoice.Text);
                    cmd1.Parameters.AddWithValue("@date", lbldate.Text);
                    cmd1.Parameters.AddWithValue("@time", lbltime.Text);
                    cmd1.Parameters.AddWithValue("@cashername", label6.Text);
                    cmd1.Parameters.AddWithValue("@qty", lbitems.Text);

                    cmd1.Parameters.AddWithValue("@grosstotal", lbtotal.Text);

                    con.Open();
                   int x = cmd.ExecuteNonQuery();
                   int y = cmd1.ExecuteNonQuery();

                    MessageBox.Show("Record added ..........");
                    updatedb();
                    dataGridView1.Rows.Clear();
                    lbtotal.Text = "0";
                    lbitems.Text = "0";
                    txtno.Focus();
                    totalPrice = 0;

                    con.Close();
                    invoice();

                }
               }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }

            finally
            {
                con.Close();
            }
           }

        private void button2_Click(object sender, EventArgs e)
        {
            pay p = new pay();
            p.Show();
        }

        private void label6_Click(object sender, EventArgs e)
        {

        }
    }
}

And I'm seeing everything is fine and still not find the issue of those.

And the connected with above related to Connnew.DbSearch(t) that "Connnew" is like:

using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
namespace superpos3
{
    class Connnew
    {

        public static MySqlConnection con = new MySqlConnection("server= localhost; database =superpos; username= root; password=; ");
        public static MySqlCommand poscmd = new MySqlCommand();
        public static MySqlDataReader dr;

        public static void DbSearch(string txt)
        {

            con.Close();
            poscmd.Connection = con;
            poscmd.CommandText = txt;
            con.Open();
            dr = poscmd.ExecuteReader();
        }

        public static void DbUpdate(string txt)
        {
            con.Close();
            poscmd.Connection = con;
            poscmd.CommandText = txt;
            con.Open();
            poscmd.ExecuteNonQuery();
        }
    }
}

Please let me know what is here the issue of the structure of codes or what is really going wrong.


来源: stackexchange

问:
How can I delete a technical indicator without re-rendering the chart?
How can I delete a built-in technical indicator without re-rendering the chart in Anychart?</p>

答:
Every technical indicator is a single or set of usual series. So, you can remove them as a series using removeSeries() and removeSeriesAt() methods.

For details, check the sample.

ContentLicense: CC BY-SA 4.0


问:
How to use check_password function in django
I'm a beginner in Django. I have a signup form with only 2 fields. Username and Password. The password is encrypted using the pbkdf2_sha256 algorithm.
I want to login using the username and password.so the password that I'm inputting in the login page must be checked with the encrypted password. How to do that?. Also, please explain what authenticate and check_password function does?</p>

```<code>def save(request):
    if request.method == 'POST':
       name = request.POST.get('name')
       password = request.POST.get('pass')
       enc_pass = pbkdf2_sha256.encrypt(password,rounds=12000,salt_size = 32)
       a = signup(username = name, password = enc_pass)
       a.save()
   return render(request,'save.html')
def login(request):
   if request.method  == 'POST':

       username        = request.POST.get('user')
       password1          = request.POST.get('password1')
       p = check_password(password=password1)
      if signup.objects.filter(username__exact=username).exists() and p is True:
           return HttpResponse("Success")
     else:
           return HttpResponse("Invalid Credentials")
   return render(request, 'login.html')
</code>```

答:
check_password does not work like this. To make it work, you need to use Django's own authentication system. If you are concerned about using pbkdf2_sha256, Django provides this hasher. To use this with you own auth system, add it to settings:

```<code>PASSWORD_HASHERS = [
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.Argon2PasswordHasher',
]
</code>```

And in django authentication, you do not need to hash it manually, django will take care of it itself. All you need to do is save the user like this:

```<code>from django.contrib.auth.models import User

user = User.objects.create_user(username=username, email=email, password=password, #.. other required fields)
</code>```

And to check password:

```<code>user = User.objects.get(username=username)
user.check_password(password)
</code>```

More information can be found in documentation

Body:
I'm a beginner in Django. I have a signup form with only 2 fields. Username and Password. The password is encrypted using the pbkdf2_sha256 algorithm.
I want to login using the username and password.so the password that I'm inputting in the login page must be checked with the encrypted password. How to do that?. Also, please explain what authenticate and check_password function does?

def save(request):
    if request.method == 'POST':
       name = request.POST.get('name')
       password = request.POST.get('pass')
       enc_pass = pbkdf2_sha256.encrypt(password,rounds=12000,salt_size = 32)
       a = signup(username = name, password = enc_pass)
       a.save()
   return render(request,'save.html')
def login(request):
   if request.method  == 'POST':

       username        = request.POST.get('user')
       password1          = request.POST.get('password1')
       p = check_password(password=password1)
      if signup.objects.filter(username__exact=username).exists() and p is True:
           return HttpResponse("Success")
     else:
           return HttpResponse("Invalid Credentials")
   return render(request, 'login.html')

Body:
check_password does not work like this. To make it work, you need to use Django's own authentication system. If you are concerned about using pbkdf2_sha256, Django provides this hasher. To use this with you own auth system, add it to settings:

PASSWORD_HASHERS = [
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.Argon2PasswordHasher',
]

And in django authentication, you do not need to hash it manually, django will take care of it itself. All you need to do is save the user like this:

from django.contrib.auth.models import User

user = User.objects.create_user(username=username, email=email, password=password, #.. other required fields)

And to check password:

user = User.objects.get(username=username)
user.check_password(password)

More information can be found in documentation


问:
C++ Passing vector to a function that is already passed
```<code>#include<bits/stdc++.h>
using namespace std;

void func(vector<int> &vect)
{
   vect.push_back(30);
   extra_func(vect);
}

void extra_func(vector<int> &vect)
{
   vect.push_back(40);
}

int main(){
    vector<int> vect;
    vect.push_back(10);
    vect.push_back(20);

    func(vect);

    for (int i=0; i<vect.size(); i++)
       cout << vect[i] << " ";

    return 0;
}
</code>```

I want to pass a vector again to other function that has been passed. But this seems to not work. How could I implement something like this

答:
The problem arises as you are calling extra_func without func knowing about it so you must initialize extra_func before func
Your code should be like

```<code>#include<bits/stdc++.h>
using namespace std;

void extra_func(vector<int> &vect)
{
   vect.push_back(40);
}

void func(vector<int> &vect)
{
   vect.push_back(30);
   extra_func(vect);
}

int main(){
    vector<int> vect;
    vect.push_back(10);
    vect.push_back(20);

    func(vect);

    for (int i=0; i<vect.size(); i++)
       cout << vect[i] << " ";

    return 0;
}
</code>```

Body:
#include<bits/stdc++.h>
using namespace std;

void func(vector<int> &vect)
{
   vect.push_back(30);
   extra_func(vect);
}

void extra_func(vector<int> &vect)
{
   vect.push_back(40);
}

int main(){
    vector<int> vect;
    vect.push_back(10);
    vect.push_back(20);

    func(vect);

    for (int i=0; i<vect.size(); i++)
       cout << vect[i] << " ";

    return 0;
}

I want to pass a vector again to other function that has been passed. But this seems to not work. How could I implement something like this

Body:
The problem arises as you are calling extra_func without func knowing about it so you must initialize extra_func before func
Your code should be like

#include<bits/stdc++.h>
using namespace std;

void extra_func(vector<int> &vect)
{
   vect.push_back(40);
}

void func(vector<int> &vect)
{
   vect.push_back(30);
   extra_func(vect);
}

int main(){
    vector<int> vect;
    vect.push_back(10);
    vect.push_back(20);

    func(vect);

    for (int i=0; i<vect.size(); i++)
       cout << vect[i] << " ";

    return 0;
}


问:
Feature/Variable importance after a PCA analysis
I have performed a PCA analysis over my original dataset and from the compressed dataset transformed by the PCA I have also selected the number of PC I want to keep (they explain almost the 94% of the variance). Now I am struggling with the identification of the original features that are important in the reduced dataset.
How do I find out which feature is important and which is not among the remaining Principal Components after the dimension reduction?
Here is my code:

```<code>from sklearn.decomposition import PCA
pca = PCA(n_components=8)
pca.fit(scaledDataset)
projection = pca.transform(scaledDataset)
</code>```

Furthermore, I tried also to perform a clustering algorithm on the reduced dataset but surprisingly for me, the score is lower than on the original dataset. How is it possible?

答:
```<code># original_num_df the original numeric dataframe
# pca is the model
def create_importance_dataframe(pca, original_num_df):

    # Change pcs components ndarray to a dataframe
    importance_df  = pd.DataFrame(pca.components_)

    # Assign columns
    importance_df.columns  = original_num_df.columns

    # Change to absolute values
    importance_df =importance_df.apply(np.abs)

    # Transpose
    importance_df=importance_df.transpose()

    # Change column names again

    ## First get number of pcs
    num_pcs = importance_df.shape[1]

    ## Generate the new column names
    new_columns = [f'PC{i}' for i in range(1, num_pcs + 1)]

    ## Now rename
    importance_df.columns  =new_columns

    # Return importance df
    return importance_df

# Call function to create importance df
importance_df  =create_importance_dataframe(pca, original_num_df)

# Show first few rows
display(importance_df.head())

# Sort depending on PC of interest

## PC1 top 10 important features
pc1_top_10_features = importance_df['PC1'].sort_values(ascending = False)[:10]
print(), print(f'PC1 top 10 feautres are \n')
display(pc1_top_10_features )

## PC2 top 10 important features
pc2_top_10_features = importance_df['PC2'].sort_values(ascending = False)[:10]
print(), print(f'PC2 top 10 feautres are \n')
display(pc2_top_10_features )
</code>```

Body:
I have performed a PCA analysis over my original dataset and from the compressed dataset transformed by the PCA I have also selected the number of PC I want to keep (they explain almost the 94% of the variance). Now I am struggling with the identification of the original features that are important in the reduced dataset.
How do I find out which feature is important and which is not among the remaining Principal Components after the dimension reduction?
Here is my code:

from sklearn.decomposition import PCA
pca = PCA(n_components=8)
pca.fit(scaledDataset)
projection = pca.transform(scaledDataset)

Furthermore, I tried also to perform a clustering algorithm on the reduced dataset but surprisingly for me, the score is lower than on the original dataset. How is it possible?


问:
Pygame bug, music will not play properly as it just loops the beginning part
I'm working on a basic shooter game in Pygame (I'm following a tutorial.) I decided to add background music to keep things nice.
Code (quite long!):

```<code>import pygame
from pygame import image as sprite

pygame.init()

dow = pygame.display.set_mode((1000, 700))

pygame.display.set_caption("PY.Touhou")

clock = pygame.time.Clock()
rightSprites = [sprite.load('ness-right1.png'),
                pygame.image.load('ness-right2.png'),
                pygame.image.load('ness-right3.png'),
                pygame.image.load('ness-right4.png'),
                pygame.image.load('ness-right5.png'),
                pygame.image.load('ness-right6.png'),
                pygame.image.load('ness-right7.png'),
                pygame.image.load('ness-right8.png')
                ]
leftSprites = [
    sprite.load('ness-left1.png'),
    sprite.load('ness-left2.png'),
    sprite.load('ness-left3.png'),
    sprite.load('ness-left4.png'),
    sprite.load('ness-left5.png'),
    sprite.load('ness-left6.png'),
    sprite.load('ness-left7.png'),
    sprite.load('ness-left8.png')
]

scene = pygame.image.load('bg.png')
idle = pygame.image.load('ness-idle.png')

class Player(object):
    def __init__(self, x_pos, y_pos, w, h):
        self.x_pos = x_pos
        self.y_pos = y_pos
        self.w = w
        self.h = h
        self.velocity = 15
        self.JUMPbool = False
        self.atleft = False
        self.atright = False
        self.steps = 0
        self.jumpheight = 12
        self.hitbox = (self.x_pos + 50, self.y_pos, 73, 227)
        self.still = True

    def move(self):
        if self.steps + 1 >= 24:
            self.steps = 0

        if not self.still:

            if self.atleft:
                dow.blit(leftSprites[self.steps // 4], (self.x_pos, self.y_pos))
                self.steps += 1

            elif self.atright:
                dow.blit(rightSprites[self.steps // 4], (self.x_pos, self.y_pos))
                self.steps += 1

        else:
            if self.atright:
                dow.blit(rightSprites[1], (self.x_pos, self.y_pos))
            else:
                dow.blit(leftSprites[1], (self.x_pos, self.y_pos))
        self.hitbox = (self.x_pos + 50, self.y_pos, 73, 227)
        # pygame.draw.rect(dow, (0, 0, 255), self.hitbox, 2)

class IceBullet(object):
    def __init__(self, x_pos, y_pos, radius, color, direction):
        self.x_pos = x_pos
        self.y_pos = y_pos
        self.radius = radius
        self.color = color
        self.direction = direction
        self.velocity = 8 * direction

    def summon(self):
        pygame.draw.circle(dow, self.color, (self.x_pos, self.y_pos), self.radius)

class EnemyCirno(object):
    erightSprites = [sprite.load('e-right%s.png' % pic) for pic in range(1, 9)]
    eleftSprites = [sprite.load('e-left%s.png' % pic) for pic in range(1, 9)]

    def __init__(self, x_pos, y_pos, w, h, ending):
        self.x_pos = x_pos
        self.y_pos = y_pos
        self.w = w
        self.h = h
        self.ending = ending
        self.path = [self.x_pos, self.ending]
        self.hitbox = (self.x_pos + 50, self.y_pos, 73, 227)
        self.steps = 0
        self.health = 20
        self.isAlive = True
        self.velocity = 4

    def summon(self):
        self.move()
        if self.isAlive:
            if self.steps + 1 >= 24:
                self.steps = 0
            if self.velocity > 0:
                dow.blit(self.erightSprites[self.steps // 4], (self.x_pos, self.y_pos))
                self.steps += 1
            else:
                dow.blit(self.eleftSprites[self.steps // 4], (self.x_pos, self.y_pos))
                self.steps += 1
            pygame.draw.rect(dow, (255, 10, 0), (100, 110, 400, 20))
            pygame.draw.rect(dow, (5, 255, 10), (100, 110, 200 - (20 * (10 - self.health)), 20))
            enemy_health = italicStyle.render('Enemy Health', 1, (255, 0, 0))
            dow.blit(enemy_health, (100, 150))
            self.hitbox = (self.x_pos + 50, self.y_pos, 73, 227)
        # pygame.draw.rect(dow, (0, 0, 0), self.hitbox, 2)

    def move(self):
        if self.velocity > 0:
            if self.x_pos + self.velocity < self.path[1]:
                self.x_pos += self.velocity
            else:
                self.velocity = self.velocity * -1
                self.steps = 0
        else:
            if self.x_pos - self.velocity > self.path[0]:
                self.x_pos += self.velocity
            else:
                self.velocity = self.velocity * -1
                self.steps = 0

    def hit(self):
        if self.health > 1:
            self.health -= 0.50
            hit = pygame.mixer.Sound('hit.wav')
            hit.play()
        else:
            self.isAlive = False
            dead = pygame.mixer.Sound('death_sound.wav')
            dead.play()

# Main starting loop.
letterStyle = pygame.font.SysFont('Bookman Old Style', 50)
italicStyle = pygame.font.SysFont('Bookman Old Style', 30, False, True)
cirno = Player(300, 470, 160, 233)
score = 0
evilCirno = EnemyCirno(50, 470, 160, 233, 800)
maxShots = 0
bullets = []
running = True
while running is True:
    clock.tick(24)
    pygame.time.delay(10)
    music = pygame.mixer.music.load('main_theme.wav') # And here is where the bug begins!
    pygame.mixer.music.play()
    for events in pygame.event.get():
        if events.type == pygame.QUIT:
            running = False
    key = pygame.key.get_pressed()

    def update_screen():
        dow.blit(scene, (0, 0))
        textdisplay = letterStyle.render('Score: ' + str(score), 1, (0, 255, 255))
        won = italicStyle.render("Enemy defeated!", 1, (10, 255, 19))
        dow.blit(textdisplay, (50, 30))
        if not evilCirno.isAlive:
            dow.blit(won, (100, 150))
        cirno.move()
        evilCirno.summon()
        for shot in bullets:
            shot.summon()

        pygame.display.update()

    if maxShots > 0:
        maxShots += 1
    if maxShots > 5:
        maxShots = 0
    for shot in bullets:
        if evilCirno.isAlive:
            if shot.y_pos - shot.radius < evilCirno.hitbox[1] + evilCirno.hitbox[3] and shot.y_pos + shot.radius > \
                    evilCirno.hitbox[1]:
                if shot.x_pos + shot.radius > evilCirno.hitbox[0] and shot.x_pos - shot.radius < evilCirno.hitbox[0] + \
                        evilCirno.hitbox[2]:
                    evilCirno.hit()
                    score += 50
                    bullets.pop(bullets.index(shot))

        if 1000 > shot.x_pos > 0:
            shot.x_pos += shot.velocity
        else:
            bullets.pop(bullets.index(shot))

    if key[pygame.K_z] and maxShots == 0:
        shoot = pygame.mixer.Sound('bullet.wav')
        shoot.play()
        if cirno.atleft:
            facing = -1
        else:
            facing = 1
        if len(bullets) < 5:
            bullets.append(
                IceBullet(round(cirno.x_pos + cirno.w // 2), round(cirno.y_pos + cirno.h // 1.2), 20, (0, 0, 255),
                          facing))

        maxShots = 1

    if key[pygame.K_LEFT] and cirno.x_pos > cirno.velocity:  # Will stop ASAP when reached
        cirno.x_pos -= cirno.velocity
        cirno.atleft = True
        cirno.atright = False
        cirno.still = False

    elif key[
        pygame.K_RIGHT] and cirno.x_pos < 1000 - cirno.velocity - cirno.w:  # If it goes past this, it will stop ASAP, as well
        cirno.x_pos += cirno.velocity
        cirno.atright = True
        cirno.atleft = False
        cirno.still = False
    else:
        cirno.steps = 0
        cirno.still = True
    if not cirno.JUMPbool:
        if key[pygame.K_UP]:
            cirno.JUMPbool = True
            cirno.steps = 0

    else:
        if cirno.jumpheight >= -12:  # What to do if pygame.K_SPACE is pressed down.

            cirno.y_pos -= (cirno.jumpheight * abs(cirno.jumpheight)) * 0.5
            cirno.jumpheight -= 1
        else:
            cirno.jumpheight = 12
            cirno.JUMPbool = False

    update_screen()

pygame.quit()
</code>```

So far, the music actually does play, as well as the sounds. Though the problem is that it just loops the beginning part of the music over and over (which is only the first few seconds), so what you get is just something that sounds like a broken MP3 player.
(for reference the music is 1:45. Even weirder is that I've seen people use it with no issues.)
Is there any way to fix this bug? Thanks for your help :)

答:
Do you see the bug here?

```<code>while running is True:
    [...]
    music = pygame.mixer.music.load('main_theme.wav')
    pygame.mixer.music.play()
</code>```

It's re-loading and re-playing replaying the music inside your code main loop.  That is every single updated frame of game-play,

Load and play  music outside your main loop:

```<code>music = pygame.mixer.music.load('main_theme.wav')
pygame.mixer.music.play()

while running is True:
    [...]
</code>```

Your code can then call the mixer.get_busy() function too see if the music has stopped, and do something about it.

You probably also want to investigate PyGame Sound mixer channels, so your sound effects mix in with the background music properly.

Body:
I'm working on a basic shooter game in Pygame (I'm following a tutorial.) I decided to add background music to keep things nice.
Code (quite long!):

import pygame
from pygame import image as sprite

pygame.init()

dow = pygame.display.set_mode((1000, 700))

pygame.display.set_caption("PY.Touhou")

clock = pygame.time.Clock()
rightSprites = [sprite.load('ness-right1.png'),
                pygame.image.load('ness-right2.png'),
                pygame.image.load('ness-right3.png'),
                pygame.image.load('ness-right4.png'),
                pygame.image.load('ness-right5.png'),
                pygame.image.load('ness-right6.png'),
                pygame.image.load('ness-right7.png'),
                pygame.image.load('ness-right8.png')
                ]
leftSprites = [
    sprite.load('ness-left1.png'),
    sprite.load('ness-left2.png'),
    sprite.load('ness-left3.png'),
    sprite.load('ness-left4.png'),
    sprite.load('ness-left5.png'),
    sprite.load('ness-left6.png'),
    sprite.load('ness-left7.png'),
    sprite.load('ness-left8.png')
]

scene = pygame.image.load('bg.png')
idle = pygame.image.load('ness-idle.png')

class Player(object):
    def __init__(self, x_pos, y_pos, w, h):
        self.x_pos = x_pos
        self.y_pos = y_pos
        self.w = w
        self.h = h
        self.velocity = 15
        self.JUMPbool = False
        self.atleft = False
        self.atright = False
        self.steps = 0
        self.jumpheight = 12
        self.hitbox = (self.x_pos + 50, self.y_pos, 73, 227)
        self.still = True

    def move(self):
        if self.steps + 1 >= 24:
            self.steps = 0

        if not self.still:

            if self.atleft:
                dow.blit(leftSprites[self.steps // 4], (self.x_pos, self.y_pos))
                self.steps += 1

            elif self.atright:
                dow.blit(rightSprites[self.steps // 4], (self.x_pos, self.y_pos))
                self.steps += 1

        else:
            if self.atright:
                dow.blit(rightSprites[1], (self.x_pos, self.y_pos))
            else:
                dow.blit(leftSprites[1], (self.x_pos, self.y_pos))
        self.hitbox = (self.x_pos + 50, self.y_pos, 73, 227)
        # pygame.draw.rect(dow, (0, 0, 255), self.hitbox, 2)

class IceBullet(object):
    def __init__(self, x_pos, y_pos, radius, color, direction):
        self.x_pos = x_pos
        self.y_pos = y_pos
        self.radius = radius
        self.color = color
        self.direction = direction
        self.velocity = 8 * direction

    def summon(self):
        pygame.draw.circle(dow, self.color, (self.x_pos, self.y_pos), self.radius)

class EnemyCirno(object):
    erightSprites = [sprite.load('e-right%s.png' % pic) for pic in range(1, 9)]
    eleftSprites = [sprite.load('e-left%s.png' % pic) for pic in range(1, 9)]

    def __init__(self, x_pos, y_pos, w, h, ending):
        self.x_pos = x_pos
        self.y_pos = y_pos
        self.w = w
        self.h = h
        self.ending = ending
        self.path = [self.x_pos, self.ending]
        self.hitbox = (self.x_pos + 50, self.y_pos, 73, 227)
        self.steps = 0
        self.health = 20
        self.isAlive = True
        self.velocity = 4

    def summon(self):
        self.move()
        if self.isAlive:
            if self.steps + 1 >= 24:
                self.steps = 0
            if self.velocity > 0:
                dow.blit(self.erightSprites[self.steps // 4], (self.x_pos, self.y_pos))
                self.steps += 1
            else:
                dow.blit(self.eleftSprites[self.steps // 4], (self.x_pos, self.y_pos))
                self.steps += 1
            pygame.draw.rect(dow, (255, 10, 0), (100, 110, 400, 20))
            pygame.draw.rect(dow, (5, 255, 10), (100, 110, 200 - (20 * (10 - self.health)), 20))
            enemy_health = italicStyle.render('Enemy Health', 1, (255, 0, 0))
            dow.blit(enemy_health, (100, 150))
            self.hitbox = (self.x_pos + 50, self.y_pos, 73, 227)
        # pygame.draw.rect(dow, (0, 0, 0), self.hitbox, 2)

    def move(self):
        if self.velocity > 0:
            if self.x_pos + self.velocity < self.path[1]:
                self.x_pos += self.velocity
            else:
                self.velocity = self.velocity * -1
                self.steps = 0
        else:
            if self.x_pos - self.velocity > self.path[0]:
                self.x_pos += self.velocity
            else:
                self.velocity = self.velocity * -1
                self.steps = 0

    def hit(self):
        if self.health > 1:
            self.health -= 0.50
            hit = pygame.mixer.Sound('hit.wav')
            hit.play()
        else:
            self.isAlive = False
            dead = pygame.mixer.Sound('death_sound.wav')
            dead.play()

# Main starting loop.
letterStyle = pygame.font.SysFont('Bookman Old Style', 50)
italicStyle = pygame.font.SysFont('Bookman Old Style', 30, False, True)
cirno = Player(300, 470, 160, 233)
score = 0
evilCirno = EnemyCirno(50, 470, 160, 233, 800)
maxShots = 0
bullets = []
running = True
while running is True:
    clock.tick(24)
    pygame.time.delay(10)
    music = pygame.mixer.music.load('main_theme.wav') # And here is where the bug begins!
    pygame.mixer.music.play()
    for events in pygame.event.get():
        if events.type == pygame.QUIT:
            running = False
    key = pygame.key.get_pressed()

    def update_screen():
        dow.blit(scene, (0, 0))
        textdisplay = letterStyle.render('Score: ' + str(score), 1, (0, 255, 255))
        won = italicStyle.render("Enemy defeated!", 1, (10, 255, 19))
        dow.blit(textdisplay, (50, 30))
        if not evilCirno.isAlive:
            dow.blit(won, (100, 150))
        cirno.move()
        evilCirno.summon()
        for shot in bullets:
            shot.summon()

        pygame.display.update()

    if maxShots > 0:
        maxShots += 1
    if maxShots > 5:
        maxShots = 0
    for shot in bullets:
        if evilCirno.isAlive:
            if shot.y_pos - shot.radius < evilCirno.hitbox[1] + evilCirno.hitbox[3] and shot.y_pos + shot.radius > \
                    evilCirno.hitbox[1]:
                if shot.x_pos + shot.radius > evilCirno.hitbox[0] and shot.x_pos - shot.radius < evilCirno.hitbox[0] + \
                        evilCirno.hitbox[2]:
                    evilCirno.hit()
                    score += 50
                    bullets.pop(bullets.index(shot))

        if 1000 > shot.x_pos > 0:
            shot.x_pos += shot.velocity
        else:
            bullets.pop(bullets.index(shot))

    if key[pygame.K_z] and maxShots == 0:
        shoot = pygame.mixer.Sound('bullet.wav')
        shoot.play()
        if cirno.atleft:
            facing = -1
        else:
            facing = 1
        if len(bullets) < 5:
            bullets.append(
                IceBullet(round(cirno.x_pos + cirno.w // 2), round(cirno.y_pos + cirno.h // 1.2), 20, (0, 0, 255),
                          facing))

        maxShots = 1

    if key[pygame.K_LEFT] and cirno.x_pos > cirno.velocity:  # Will stop ASAP when reached
        cirno.x_pos -= cirno.velocity
        cirno.atleft = True
        cirno.atright = False
        cirno.still = False

    elif key[
        pygame.K_RIGHT] and cirno.x_pos < 1000 - cirno.velocity - cirno.w:  # If it goes past this, it will stop ASAP, as well
        cirno.x_pos += cirno.velocity
        cirno.atright = True
        cirno.atleft = False
        cirno.still = False
    else:
        cirno.steps = 0
        cirno.still = True
    if not cirno.JUMPbool:
        if key[pygame.K_UP]:
            cirno.JUMPbool = True
            cirno.steps = 0

    else:
        if cirno.jumpheight >= -12:  # What to do if pygame.K_SPACE is pressed down.

            cirno.y_pos -= (cirno.jumpheight * abs(cirno.jumpheight)) * 0.5
            cirno.jumpheight -= 1
        else:
            cirno.jumpheight = 12
            cirno.JUMPbool = False

    update_screen()

pygame.quit()

So far, the music actually does play, as well as the sounds. Though the problem is that it just loops the beginning part of the music over and over (which is only the first few seconds), so what you get is just something that sounds like a broken MP3 player.
(for reference the music is 1:45. Even weirder is that I've seen people use it with no issues.)
Is there any way to fix this bug? Thanks for your help :)

Body:
Do you see the bug here?

while running is True:
    [...]
    music = pygame.mixer.music.load('main_theme.wav')
    pygame.mixer.music.play()

It's re-loading and re-playing replaying the music inside your code main loop.  That is every single updated frame of game-play,

Load and play  music outside your main loop:

music = pygame.mixer.music.load('main_theme.wav')
pygame.mixer.music.play()

while running is True:
    [...]

Your code can then call the mixer.get_busy() function too see if the music has stopped, and do something about it.

You probably also want to investigate PyGame Sound mixer channels, so your sound effects mix in with the background music properly.


问:
How to access to the {window, location} in the gatsby-theme-material-ui-top-layout
How can I access to the {window, location} in the gatsby-theme-material-ui-top-layout/components/top-layout

Do I have to use gatsby-plugin-layout?

Can I use both instead gatsby-plugin-layout and gatsby-theme-material-ui?

答:
You don't need extra plugins to do that. You have a bunch of options to achieve this, but without any code provided it's difficult to guess which one fits your requirements or specifications. You can access the window object at any time, keeping in mind that your code may throw an error on build command, so:

Place your code inside a componentDidMount lifecycle or a useEffect hook which ensures the code doesn’t run unless it’s in the browser, where the window will be defined.

Use a condition before you execute your statement:

if (typeof window !== 'undefined') {
      //your code here
    }

Another option is that your code uses a third-party module/library that needs the window to be defined before, so, when Gatsby builds (compiles and bundles) all your assets, your code may throw an error due to the needs of the library and the undefinition of the window object at that moment, in that case, you need to change your webpack loader to null. In your gatsby-node.js:

exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => {
  if (stage === "build-html") {
    actions.setWebpackConfig({
      module: {
        rules: [
          {
            test: /bad-module/,
            use: loaders.null(),
          },
        ],
      },
    })
  }
}


问:
java.lang.OutOfMemoryError when saving a huge amount of records
I have a problem with saving a huge amount of records to database using CFWheels. Here is an example:

```<code><cfloop from="1" to="10000" index="i">
 <cfset var newUser = model("user").new()>
 <cfset newUser.name = "Test"&i>
 <cfset newUser.save()>
</cfloop>
</code>```

This causes java.lang.OutOfMemoryError

Please help me how to solve this problem.

答:
There are a couple fairly inefficient things going on here. First, it's generating 1,000 user objects, which isn't really a good idea to do in a single request in ColdFusion. Second, it's running 1,000 database queries, which isn't really a good idea to do in any programming language.

I would stop using model objects for a case like this and figure out how to condense the logic into a single database query. The ORM stuff in Wheels is generally very useful, but it has its limits in situations like this one.

For example, if you're using SQL Server 2008, you can do this inside your user model to keep everything under a single call to cfquery:

```<code><cffunction name="batchCreate">
    <cfquery datasource="#get('dataSourceName')#">
        INSERT INTO
            #this.tableName()# (#this.columnNameForProperty("name")#)
        VALUES
            <cfloop from="1" to="10000" index="i">
                (<cfqueryparam cfsqltype="cf_sql_varchar" value="Test#i#">)
                <cfif i lt 10000>,</cfif>
            </cfloop>
    </cfquery>
</cffunction>
</code>```

Of course, the query will look different if you're using MySQL or another database engine.

ContentLicense: CC BY-SA 3.0

Body:
I have a problem with saving a huge amount of records to database using CFWheels. Here is an example:

<cfloop from="1" to="10000" index="i">
 <cfset var newUser = model("user").new()>
 <cfset newUser.name = "Test"&i>
 <cfset newUser.save()>
</cfloop>

This causes java.lang.OutOfMemoryError

Please help me how to solve this problem.

Body:
There are a couple fairly inefficient things going on here. First, it's generating 1,000 user objects, which isn't really a good idea to do in a single request in ColdFusion. Second, it's running 1,000 database queries, which isn't really a good idea to do in any programming language.

I would stop using model objects for a case like this and figure out how to condense the logic into a single database query. The ORM stuff in Wheels is generally very useful, but it has its limits in situations like this one.

For example, if you're using SQL Server 2008, you can do this inside your user model to keep everything under a single call to cfquery:

<cffunction name="batchCreate">
    <cfquery datasource="#get('dataSourceName')#">
        INSERT INTO
            #this.tableName()# (#this.columnNameForProperty("name")#)
        VALUES
            <cfloop from="1" to="10000" index="i">
                (<cfqueryparam cfsqltype="cf_sql_varchar" value="Test#i#">)
                <cfif i lt 10000>,</cfif>
            </cfloop>
    </cfquery>
</cffunction>

Of course, the query will look different if you're using MySQL or another database engine.


问:
How to draw smooth curve according to given height
I want to drive a smooth curve that curve's 1/3 is outward 2/3 is inward.This is what I want to achieve.

So far , I tried this with adding 1 curve like :

```<code>  var height: CGFloat = UIScreen.main.bounds.height / 14
  let centerWidth = self.frame.width / 2
  let screenView = UIScreen.main.bounds
  let width = (screenView.width - (2*screenView.width/40)) / 10

     path.move(to: CGPoint(x: 0, y: 0)) // start top left
     path.addLine(to: CGPoint(x: (centerWidth - width * 2.5), y: 0)) // the beginning of the trough
           // first curve down
     path.addCurve(to: CGPoint(x: centerWidth   , y: height),
                     controlPoint1: CGPoint(x: (centerWidth - width * 1.33), y: 0), controlPoint2: CGPoint(x: centerWidth - width * 1.33  , y: height))
</code>```

But when I try this outward and inward curve's have same height. So I changed it and tried adding 2 curve like :

```<code>     path.move(to: CGPoint(x: 0, y: 0)) // start top left
    path.addLine(to: CGPoint(x: (centerWidth - width * 2.5), y: 0)) // the beginning of the trough
        // first curve down
    path.addCurve(to: CGPoint(x: centerWidth - width * 1.33 , y: height/3),
                  controlPoint1: CGPoint(x: (centerWidth - width * 1.33), y: 0), controlPoint2: CGPoint(x: centerWidth - width * 1.33 , y: height/3))

    path.addCurve(to: CGPoint(x: centerWidth, y: height),
                                    controlPoint1: CGPoint(x: centerWidth - width * 1.33 , y: height/3), controlPoint2: CGPoint(x: centerWidth - width , y: height  ))
</code>```

It similar to what I want but junction point doesnt look the curve is a single piece

I have tried so many things but cant draw what I want exacly.So How can I draw a curve that endpoint height's 1/3 gonna be outward and 2/3 inward that looks like a one piece.

I'm open to all kinds of ideas to draw.Regards

NOTE

I'm trying to customize tabbar's center button which height value  is UIScreen.main.bounds.height and width is `

```<code>let screenView = UIScreen.main.bounds
let width = (screenView.width - (2*screenView.width/40))`
</code>```

答:
As I look at your designer’s rendering, if you are breaking this into two separate Bézier curves, the key observation is that the top ⅓ curve is symmetrical (with respect to itself) as is the bottom ⅔ curve. And for symmetrical Bézier curves, a quad Bézier is easier to deal with.

And to make the inflection point seamless, you’ll want to ensure that two control points (one for the quad Bézier above the inflection point, the other for the quad Bézier below the inflection point) are collinear with the inflection point itself. E.g.:

It takes a little trigonometry to figure out the placement of these control points, e.g.

```<code>let center = CGPoint(x: view.bounds.midX, y: 200)
let radius: CGFloat = 140
let curveOffsetBottom: CGFloat = 30
let curveOffsetInflection: CGFloat = 50

greenCircularShapeLayer.path = UIBezierPath(arcCenter: center, radius: radius, startAngle: 0, endAngle: 2 * .pi, clockwise: true).cgPath

let h = radius + curveOffsetBottom + 50

let curveBottom = CGPoint(x: center.x,
                          y: center.y + radius + curveOffsetBottom)

let y0 = radius + curveOffsetBottom - h * 2 / 3
let t0 = asin(y0 / (radius + curveOffsetInflection))
let x0 = y0 / tan(t0)

let inflectionPoint = CGPoint(x: center.x - x0, y: center.y + y0)

let t1 = atan((curveBottom.x - inflectionPoint.x) / (curveBottom.y - inflectionPoint.y))

let t2 = 2 * (.pi / 2 - t1)

let x2 = (curveBottom.y - inflectionPoint.y) / tan(t2)
let x1 = x2 / 2

let cp1 = CGPoint(x: inflectionPoint.x - x1, y: curveBottom.y - h)
let cp2 = CGPoint(x: inflectionPoint.x + x2, y: curveBottom.y)

let curveTop = CGPoint(x: cp1.x - cp1.distance(to: inflectionPoint), y: curveBottom.y - h)

let path = UIBezierPath()
path.move(to: curveTop)
path.addQuadCurve(to: inflectionPoint, controlPoint: cp1)
path.addQuadCurve(to: curveBottom, controlPoint: cp2)

path.addLine(to: CGPoint(x: view.bounds.maxX, y: path.currentPoint.y))
path.addLine(to: CGPoint(x: view.bounds.maxX, y: view.bounds.maxY))
path.addLine(to: CGPoint(x: view.bounds.minX, y: view.bounds.maxY))
path.addLine(to: CGPoint(x: view.bounds.minX, y: curveTop.y))
path.close()

blackCurveShapeLayer.path = path.cgPath
</code>```

Where

```<code>extension CGPoint {
    func distance(to point: CGPoint) -> CGFloat {
        hypot(point.x - x, point.y - y)
    }
}
</code>```

Body:
I want to drive a smooth curve that curve's 1/3 is outward 2/3 is inward.This is what I want to achieve.

So far , I tried this with adding 1 curve like :

  var height: CGFloat = UIScreen.main.bounds.height / 14
  let centerWidth = self.frame.width / 2
  let screenView = UIScreen.main.bounds
  let width = (screenView.width - (2*screenView.width/40)) / 10

     path.move(to: CGPoint(x: 0, y: 0)) // start top left
     path.addLine(to: CGPoint(x: (centerWidth - width * 2.5), y: 0)) // the beginning of the trough
           // first curve down
     path.addCurve(to: CGPoint(x: centerWidth   , y: height),
                     controlPoint1: CGPoint(x: (centerWidth - width * 1.33), y: 0), controlPoint2: CGPoint(x: centerWidth - width * 1.33  , y: height))

But when I try this outward and inward curve's have same height. So I changed it and tried adding 2 curve like :

     path.move(to: CGPoint(x: 0, y: 0)) // start top left
    path.addLine(to: CGPoint(x: (centerWidth - width * 2.5), y: 0)) // the beginning of the trough
        // first curve down
    path.addCurve(to: CGPoint(x: centerWidth - width * 1.33 , y: height/3),
                  controlPoint1: CGPoint(x: (centerWidth - width * 1.33), y: 0), controlPoint2: CGPoint(x: centerWidth - width * 1.33 , y: height/3))

    path.addCurve(to: CGPoint(x: centerWidth, y: height),
                                    controlPoint1: CGPoint(x: centerWidth - width * 1.33 , y: height/3), controlPoint2: CGPoint(x: centerWidth - width , y: height  ))

It similar to what I want but junction point doesnt look the curve is a single piece

I have tried so many things but cant draw what I want exacly.So How can I draw a curve that endpoint height's 1/3 gonna be outward and 2/3 inward that looks like a one piece.

I'm open to all kinds of ideas to draw.Regards

NOTE

I'm trying to customize tabbar's center button which height value  is UIScreen.main.bounds.height and width is `

let screenView = UIScreen.main.bounds
let width = (screenView.width - (2*screenView.width/40))`

Body:
As I look at your designer’s rendering, if you are breaking this into two separate Bézier curves, the key observation is that the top ⅓ curve is symmetrical (with respect to itself) as is the bottom ⅔ curve. And for symmetrical Bézier curves, a quad Bézier is easier to deal with.

And to make the inflection point seamless, you’ll want to ensure that two control points (one for the quad Bézier above the inflection point, the other for the quad Bézier below the inflection point) are collinear with the inflection point itself. E.g.:

It takes a little trigonometry to figure out the placement of these control points, e.g.

let center = CGPoint(x: view.bounds.midX, y: 200)
let radius: CGFloat = 140
let curveOffsetBottom: CGFloat = 30
let curveOffsetInflection: CGFloat = 50

greenCircularShapeLayer.path = UIBezierPath(arcCenter: center, radius: radius, startAngle: 0, endAngle: 2 * .pi, clockwise: true).cgPath

let h = radius + curveOffsetBottom + 50

let curveBottom = CGPoint(x: center.x,
                          y: center.y + radius + curveOffsetBottom)

let y0 = radius + curveOffsetBottom - h * 2 / 3
let t0 = asin(y0 / (radius + curveOffsetInflection))
let x0 = y0 / tan(t0)

let inflectionPoint = CGPoint(x: center.x - x0, y: center.y + y0)

let t1 = atan((curveBottom.x - inflectionPoint.x) / (curveBottom.y - inflectionPoint.y))

let t2 = 2 * (.pi / 2 - t1)

let x2 = (curveBottom.y - inflectionPoint.y) / tan(t2)
let x1 = x2 / 2

let cp1 = CGPoint(x: inflectionPoint.x - x1, y: curveBottom.y - h)
let cp2 = CGPoint(x: inflectionPoint.x + x2, y: curveBottom.y)

let curveTop = CGPoint(x: cp1.x - cp1.distance(to: inflectionPoint), y: curveBottom.y - h)

let path = UIBezierPath()
path.move(to: curveTop)
path.addQuadCurve(to: inflectionPoint, controlPoint: cp1)
path.addQuadCurve(to: curveBottom, controlPoint: cp2)

path.addLine(to: CGPoint(x: view.bounds.maxX, y: path.currentPoint.y))
path.addLine(to: CGPoint(x: view.bounds.maxX, y: view.bounds.maxY))
path.addLine(to: CGPoint(x: view.bounds.minX, y: view.bounds.maxY))
path.addLine(to: CGPoint(x: view.bounds.minX, y: curveTop.y))
path.close()

blackCurveShapeLayer.path = path.cgPath

Where

extension CGPoint {
    func distance(to point: CGPoint) -> CGFloat {
        hypot(point.x - x, point.y - y)
    }
}


问:
Laravel Mix: Update a Node.js dependency
I am trying to compile webpack configuration files with Laravel Mix.

Following webpack episode on Laracasts Vue 2 series,

```<code>// Scripts

  "scripts": {
    "dev": "node node_modules/cross-env/bin/cross-env.js NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
  },
....

// mix
mix.js('resources/assets/js/app.js', 'public/js')
.sass('resources/assets/sass/app.scss', 'public/css')
.version();
</code>```

When I run $ npm run dev, I get an error:

```<code>npm ERR! Exit status 1

npm ERR! Failed at the @ dev script 'node node_modules/cross-env/bin/cross-env.js NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js'.

// Running

npm ERR! node v4.4.5
npm ERR! npm v2.15.5

// The error points to
let extractPlugin = new plugins.ExtractTextPlugin(
/Users/User/Code/project/node_modules/laravel-mix/setup/webpack.config.js:126
</code>```

The issue seems to be update a Node.js dependency: https://github.com/JeffreyWay/laravel-mix/issues/264

How do I update the Node.js dependency?

I am trying:

```<code>$ brew upgrade node : Error = node not installed
$ node -v = 2.15.5
$ npm -v = 4.4.5
$ brew install node // installs but throws error

Error: The `brew link` step did not complete successfully
The formula built, but is not symlinked into /usr/local
Could not symlink bin/node
Target /usr/local/bin/node
already exists. You may want to remove it:
  rm '/usr/local/bin/node'

To force the link and overwrite all conflicting files:
  brew link --overwrite node

To list all files that would be deleted:
  brew link --overwrite --dry-run node

Possible conflicting files are:
/usr/local/bin/node
...

**$ brew upgrade node // says node 7.5.0 already installed**
$ npm run dev // same error
$ node -v = 4.4.5
</code>```

I also ran $ brew install node which installed, but I got an error:

Error: The brew link step did not complete successfully.

  The formula built, but is not symlinked into /usr/local.

  Could not symlink bin/node.

  Target /usr/local/bin/node

  already exists. You may want to remove it:

  rm '/usr/local/bin/node'

To force the link and overwrite all conflicting files:

```<code>brew link --overwrite node
</code>```

To list all files that would be deleted:

```<code>brew link --overwrite --dry-run node
</code>```

答:
Im Using Windows 10
You can Download NVM for node it stands for node version manager
after you set it up, type this to your cmd

```<code>nvm version
nvm install node {version of node you want}
nvm use {version of node}
</code>```

hope this works for you
because it works for me

Body:
I am trying to compile webpack configuration files with Laravel Mix.

Following webpack episode on Laracasts Vue 2 series,

// Scripts

  "scripts": {
    "dev": "node node_modules/cross-env/bin/cross-env.js NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
  },
....

// mix
mix.js('resources/assets/js/app.js', 'public/js')
.sass('resources/assets/sass/app.scss', 'public/css')
.version();

When I run $ npm run dev, I get an error:

npm ERR! Exit status 1

npm ERR! Failed at the @ dev script 'node node_modules/cross-env/bin/cross-env.js NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js'.

// Running

npm ERR! node v4.4.5
npm ERR! npm v2.15.5

// The error points to
let extractPlugin = new plugins.ExtractTextPlugin(
/Users/User/Code/project/node_modules/laravel-mix/setup/webpack.config.js:126

The issue seems to be update a Node.js dependency: https://github.com/JeffreyWay/laravel-mix/issues/264

How do I update the Node.js dependency?

I am trying:

$ brew upgrade node : Error = node not installed
$ node -v = 2.15.5
$ npm -v = 4.4.5
$ brew install node // installs but throws error

Error: The `brew link` step did not complete successfully
The formula built, but is not symlinked into /usr/local
Could not symlink bin/node
Target /usr/local/bin/node
already exists. You may want to remove it:
  rm '/usr/local/bin/node'

To force the link and overwrite all conflicting files:
  brew link --overwrite node

To list all files that would be deleted:
  brew link --overwrite --dry-run node

Possible conflicting files are:
/usr/local/bin/node
...

**$ brew upgrade node // says node 7.5.0 already installed**
$ npm run dev // same error
$ node -v = 4.4.5

I also ran $ brew install node which installed, but I got an error:

Error: The brew link step did not complete successfully.

  The formula built, but is not symlinked into /usr/local.

  Could not symlink bin/node.

  Target /usr/local/bin/node

  already exists. You may want to remove it:

  rm '/usr/local/bin/node'

To force the link and overwrite all conflicting files:

brew link --overwrite node

To list all files that would be deleted:

brew link --overwrite --dry-run node

Body:
Im Using Windows 10
You can Download NVM for node it stands for node version manager
after you set it up, type this to your cmd

nvm version
nvm install node {version of node you want}
nvm use {version of node}

hope this works for you
because it works for me


问:
C Programming : Need to get output of the number of letters in a string. (Newbie)
I am trying to complete an assignment, part of the assignment is to print the output of the number of letters in a string.

I was trying to reverse engineer the code that the instructor gave us, but his code is not even working. Or am I doing something wrong or missing something?

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

int main() {
    char str1[13] = "Hello";
    char str2[13] = "World";

    /* concatenates str1 and str2 */
    strcat(str1, str2);
    printf("strcat(str1, str2): %s\n", str1);

    /* total lenghth of str1 after concatenation */
    len = strlen(str1);
    printf("strlen(str1) : %d\n", len);
    return 0;
}
</code>```

The errors I am getting is:

test2.c:13:5: error: use of undeclared identifier 'len'
    len = strlen(str1);
    ^
test2.c:14:35: error: use of undeclared identifier 'len'
    printf("strlen(str1) : %d\n", len);

If I am not using the right identifier, how do I know which identifier covers the specific commands?

I will also be incorporating the following code in my assignment, any suggestions are greatly appreciated.

```<code>char first[10] = "first";
char last[10] = "last";
char  full[20] = " ";

strcat(full, first);
strcat(full, " ");
strcat(full, last);
</code>```

Ultimately I need to print the name (first, last, and full name), and then print the number of characters of each.

Thank you for your assistance.

答:
Here you have not declared any data type for len and that is why you are getting the error. First declare you are desired data type , in this case you can check the documentation of strlen function. So try declaring the data type of len first, the return data type for strlen function is mainly size_t but you can use it as int for basic use. Here if you are not aware of data types and do not need to store the value you can alternately also use </p>

```<code>printf("strlen(str1) : %d\n", strlen(str1));
</code>```

Body:
I am trying to complete an assignment, part of the assignment is to print the output of the number of letters in a string.

I was trying to reverse engineer the code that the instructor gave us, but his code is not even working. Or am I doing something wrong or missing something?

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

int main() {
    char str1[13] = "Hello";
    char str2[13] = "World";

    /* concatenates str1 and str2 */
    strcat(str1, str2);
    printf("strcat(str1, str2): %s\n", str1);

    /* total lenghth of str1 after concatenation */
    len = strlen(str1);
    printf("strlen(str1) : %d\n", len);
    return 0;
}

The errors I am getting is:

test2.c:13:5: error: use of undeclared identifier 'len'
    len = strlen(str1);
    ^
test2.c:14:35: error: use of undeclared identifier 'len'
    printf("strlen(str1) : %d\n", len);

If I am not using the right identifier, how do I know which identifier covers the specific commands?

I will also be incorporating the following code in my assignment, any suggestions are greatly appreciated.

char first[10] = "first";
char last[10] = "last";
char  full[20] = " ";

strcat(full, first);
strcat(full, " ");
strcat(full, last);

Ultimately I need to print the name (first, last, and full name), and then print the number of characters of each.

Thank you for your assistance.

Body:
Here you have not declared any data type for len and that is why you are getting the error. First declare you are desired data type , in this case you can check the documentation of strlen function. So try declaring the data type of len first, the return data type for strlen function is mainly size_t but you can use it as int for basic use. Here if you are not aware of data types and do not need to store the value you can alternately also use

printf("strlen(str1) : %d\n", strlen(str1));


问:
Wordpress - Use image from URL as a post thumbnail
I want to use an external image from URL as a post thumbnail, BUT I don't want to download and store the image in my server

I'm found this code in other guy question:

```<code>
        $filename = "thumbnail_".$post_id".jpg";
        $upload_file = wp_upload_bits( $filename, null, @file_get_contents('http://example.com/image.jpg') );

        if ( ! $upload_file['error'] ) {
          $filename = $upload_file['file'];
          $wp_filetype = wp_check_filetype($filename, null );

          $attachment = array(
            'post_mime_type' => $wp_filetype['type'],
            'post_parent'    => $post_id,
            'post_title'     => preg_replace( '/\.[^.]+$/', '', $filename ),
            'post_content'   => '',
            'post_status'    => 'inherit'
          );

          $attachment_id = wp_insert_attachment( $attachment, $filename, $post_id );
          file_put_contents('attachment_id.txt', print_r($attachment_id, true));

          if ( ! is_wp_error( $attachment_id ) ) {
              require_once(ABSPATH . 'wp-admin/includes/image.php');

              $attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
              wp_update_attachment_metadata( $attachment_id, $attachment_data );
              set_post_thumbnail( $post_id, $attachment_id );
          }
        }

</code>```

It downloads the image to my server and also duplicates the image file in my uploads directory (I don't know why)

But I don't wanna download the image how can I achieve this?

答:
I haven't tested this but assuming you're always going to want the same file, this may help get you started:</p>

```<code>$filepath = 'http://example.com/'; //Change this to the actual file path...
$filename = 'image.jpg'; //Change this to the actual file name...
$filetype = wp_check_filetype( basename( $filename ), null );
$attachment = array(
    'guid'              => $filepath . $filename,
    'post_mime_type'    => $filetype['type'],
    'post_parent'       => $post_id,
    'post_title'        => preg_replace( '/\.[^.]+$/', '', $filename ),
    'post_content'      => '',
    'post_status'       => 'inherit'
);
$attachment_id = wp_insert_attachment( $attachment, $filename, $post_id );
if( !is_wp_error( $attachment_id ) ) {
    require_once(ABSPATH . 'wp-admin/includes/image.php');
    $attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
    wp_update_attachment_metadata( $attachment_id, $attachment_data );
    set_post_thumbnail( $post_id, $attachment_id );
}
</code>```

Body:
I want to use an external image from URL as a post thumbnail, BUT I don't want to download and store the image in my server

I'm found this code in other guy question:

        $filename = "thumbnail_".$post_id".jpg";
        $upload_file = wp_upload_bits( $filename, null, @file_get_contents('http://example.com/image.jpg') );

        if ( ! $upload_file['error'] ) {
          $filename = $upload_file['file'];
          $wp_filetype = wp_check_filetype($filename, null );

          $attachment = array(
            'post_mime_type' => $wp_filetype['type'],
            'post_parent'    => $post_id,
            'post_title'     => preg_replace( '/\.[^.]+$/', '', $filename ),
            'post_content'   => '',
            'post_status'    => 'inherit'
          );

          $attachment_id = wp_insert_attachment( $attachment, $filename, $post_id );
          file_put_contents('attachment_id.txt', print_r($attachment_id, true));

          if ( ! is_wp_error( $attachment_id ) ) {
              require_once(ABSPATH . 'wp-admin/includes/image.php');

              $attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
              wp_update_attachment_metadata( $attachment_id, $attachment_data );
              set_post_thumbnail( $post_id, $attachment_id );
          }
        }

It downloads the image to my server and also duplicates the image file in my uploads directory (I don't know why)

But I don't wanna download the image how can I achieve this?

Body:
I haven't tested this but assuming you're always going to want the same file, this may help get you started:

$filepath = 'http://example.com/'; //Change this to the actual file path...
$filename = 'image.jpg'; //Change this to the actual file name...
$filetype = wp_check_filetype( basename( $filename ), null );
$attachment = array(
    'guid'              => $filepath . $filename,
    'post_mime_type'    => $filetype['type'],
    'post_parent'       => $post_id,
    'post_title'        => preg_replace( '/\.[^.]+$/', '', $filename ),
    'post_content'      => '',
    'post_status'       => 'inherit'
);
$attachment_id = wp_insert_attachment( $attachment, $filename, $post_id );
if( !is_wp_error( $attachment_id ) ) {
    require_once(ABSPATH . 'wp-admin/includes/image.php');
    $attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
    wp_update_attachment_metadata( $attachment_id, $attachment_data );
    set_post_thumbnail( $post_id, $attachment_id );
}


问:
Is Try::Tiny still recommended for exception handling in Perl 5.14 or later?
The consensus of the Perl community seems to be that Try::Tiny is the preferred way to handle exceptions.

Perl 5.14 (which is the version I use) seems to solve the issues with eval that Try::Tiny addresses. Will Try::Tiny still provide any benefits for me?

答:
Try::Tiny is great, but requires semi colon on the last brace and does not permit the use of exception variable assignment and let alone the catching of exception class. TryCatch used to do a great job, but has been broken with the new version 0.006020 of Devel::Declare. Another great implementation is Syntax::Keyword::Try but it does not implement exception variable assignments or catching exception class.

There is a new module Nice::Try, which is a perfect replacement.

There is no need to have semi colon on the last brace like Try::Tiny.

You can also do exception variable assignment like

```<code>  try
  {
    # something
  }
  catch( $e )
  {
    # catch this in $e
  }
</code>```

It also works using class exception like

```<code>  try
  {
    # something
  }
  catch( Exception $e )
  {
    # catch this in $e
  }
</code>```

And it also supports finally. Its features set make it quite unique.

Full disclosure: I have developed this module when TryCatch got broken.

Body:
Try::Tiny is great, but requires semi colon on the last brace and does not permit the use of exception variable assignment and let alone the catching of exception class. TryCatch used to do a great job, but has been broken with the new version 0.006020 of Devel::Declare. Another great implementation is Syntax::Keyword::Try but it does not implement exception variable assignments or catching exception class.

There is a new module Nice::Try, which is a perfect replacement.

There is no need to have semi colon on the last brace like Try::Tiny.

You can also do exception variable assignment like

  try
  {
    # something
  }
  catch( $e )
  {
    # catch this in $e
  }

It also works using class exception like

  try
  {
    # something
  }
  catch( Exception $e )
  {
    # catch this in $e
  }

And it also supports finally. Its features set make it quite unique.

Full disclosure: I have developed this module when TryCatch got broken.


问:
Why does the pre-decrement cause strange changes?
I have the following code in C++

```<code>int factorial_recursivo(int factorial) {

 if(factorial <= 1) return 1;

 // To show all the factors in each iteration std::cout << factorial << std::endl;

 return factorial * factorial_recursivo(--factorial);

}
</code>```

However, if i write a number n, the result is the factorial of the number n-1.

If i change the last line of code the factorial_recursivo(--factorial) by factorial_recursivo(factorial - 1) works properly.

Why this happen? I even printed the factors in console and it correctly showed. Per example, with factoria_recursivo(5) i got 5 4 3 2, however the result was 24.

答:
The program has undefined behaviour because the operands of * are unsequenced, and so there are unsequenced read and writes of factorial.

The problem is essentially the same as the cases in this thread: Undefined behavior and sequence points

Body:
I have the following code in C++

int factorial_recursivo(int factorial) {

 if(factorial <= 1) return 1;

 // To show all the factors in each iteration std::cout << factorial << std::endl;

 return factorial * factorial_recursivo(--factorial);

}

However, if i write a number n, the result is the factorial of the number n-1.

If i change the last line of code the factorial_recursivo(--factorial) by factorial_recursivo(factorial - 1) works properly.

Why this happen? I even printed the factors in console and it correctly showed. Per example, with factoria_recursivo(5) i got 5 4 3 2, however the result was 24.


问:
pycharm does not connect with console with python3.8
```<code>"G:\Everything python\Scripts\python.exe" "C:/Users/dell/PycharmProjects/untitled8/python test.py"
No Python at 'C:\Program Files (x86)\Python38-32\python.exe'
Process finished with exit code 103
</code>```

Everytime I try to make any sort of code in pycharm.Even something basic like print(1).I get hit with this code.I tried uninstalling and reinstalling python and pycharm but it didn't work.[Please Help]

答:
In PyCharm, check File - Settings ... - Project - Project Interpretor. It's probably pointing to a location where you no longer have Python installed.

The reason this doesn't go away after a reinstall is because you probably didn't tell PyCharm to remove all previous settings. The reason this happens at all is because PyCharm supports (like any good Python IDE) multiple installations of Python and virtual environments.

Body:
"G:\Everything python\Scripts\python.exe" "C:/Users/dell/PycharmProjects/untitled8/python test.py"
No Python at 'C:\Program Files (x86)\Python38-32\python.exe'
Process finished with exit code 103

Everytime I try to make any sort of code in pycharm.Even something basic like print(1).I get hit with this code.I tried uninstalling and reinstalling python and pycharm but it didn't work.[Please Help]


问:
Can't clone private repo on github from SourceTree
A similar issue is described here however, my symptoms are a little different and none of the steps there seemed to work.  Nor does the suggestion here work.

I'm attempting to use SourceTree to clone a private repo belonging to github organization of which I am a part.  I have full permissions to view and commit to the repo, I can see it online when I log in, AND I can clone just fine with the command line and also via the github desktop application.  It only fails in SourceTree.

Further, it is not bad credentials or anything like that, because I can clone, commit and push to my other non-private repos on github using SourceTree with my github credentials.

From the "Clone a Repository" dialog I enter the source URL, which looks something like this:

```<code>https://github.com/MyOrgName/reponame.git
</code>```

I tab off of that field and it populates the destination path and name fields, but at the bottom of the dialog is a yellow exclamation point with this error:

```<code>This is not a valid source path / URL
</code>```

If I click the error message, it brings up the "Details" dialog, which states the following (twice for some reason):

```<code>remote: Repository not found.
fatal: repository 'https://github.com/MyOrgName/reponame.git/' not found
remote: Repository not found.
fatal: repository 'https://github.com/MyOrgName/reponame.git/' not found
</code>```

I have also tried this by adding my username to the url like so:

```<code>https://myusername@github.com/MyOrgName/reponame.git
</code>```

but no luck there either.

答:
It happens because Sourcetree didn't get some private access from Github while authenticating. So the solution is very simple.

Login to your Github account on any browser.

From the top right corner select SETTINGS.

Now select DEVELOPER SETTINGS.

From  DEVELOPER SETTINGS select PERSONAL ACCESS TOKEN.

Now from PERSONAL ACCESS TOKEN select GENERATE TOKEN.

Fill Note as Sourcetree and Check All Scopes from the checkbox as shown in the below screenshots.

After Click on Generate Token.

Now Open Sourcetree.

Click on Options in Tools menu & Click add Account.

Select options as shown below screenshot.

Enter username as your Github account username and password as Generated Token from Github.

Click on SAVE now you might see all your repository are visible and can clone too.

Hope it helps.

Body:
A similar issue is described here however, my symptoms are a little different and none of the steps there seemed to work.  Nor does the suggestion here work.

I'm attempting to use SourceTree to clone a private repo belonging to github organization of which I am a part.  I have full permissions to view and commit to the repo, I can see it online when I log in, AND I can clone just fine with the command line and also via the github desktop application.  It only fails in SourceTree.

Further, it is not bad credentials or anything like that, because I can clone, commit and push to my other non-private repos on github using SourceTree with my github credentials.

From the "Clone a Repository" dialog I enter the source URL, which looks something like this:

https://github.com/MyOrgName/reponame.git

I tab off of that field and it populates the destination path and name fields, but at the bottom of the dialog is a yellow exclamation point with this error:

This is not a valid source path / URL

If I click the error message, it brings up the "Details" dialog, which states the following (twice for some reason):

remote: Repository not found.
fatal: repository 'https://github.com/MyOrgName/reponame.git/' not found
remote: Repository not found.
fatal: repository 'https://github.com/MyOrgName/reponame.git/' not found

I have also tried this by adding my username to the url like so:

https://myusername@github.com/MyOrgName/reponame.git

but no luck there either.


答:
You code doesn't compile because func() doesn't know about extra_func(). You either need a function declaration (sometimes called a function prototype) or to rearrange your functions.

```<code>void extra_func(vector<int> &); // declaration

void func(vector<int> &vect)
{
   vect.push_back(30);
   extra_func(vect);
}

void extra_func(vector<int> &vect) // definition
{
   vect.push_back(40);
}
</code>```

or

```<code>void extra_func(vector<int> &vect) // now it's visible to func()
{
   vect.push_back(40);
}

void func(vector<int> &vect)
{
   vect.push_back(30);
   extra_func(vect);
}
</code>```

Title: C++ Passing vector to a function that is already passed

Body:
#include<bits/stdc++.h>
using namespace std;

void func(vector<int> &vect)
{
   vect.push_back(30);
   extra_func(vect);
}

void extra_func(vector<int> &vect)
{
   vect.push_back(40);
}

int main(){
    vector<int> vect;
    vect.push_back(10);
    vect.push_back(20);

    func(vect);

    for (int i=0; i<vect.size(); i++)
       cout << vect[i] << " ";

    return 0;
}

I want to pass a vector again to other function that has been passed. But this seems to not work. How could I implement something like this

Body:
You code doesn't compile because func() doesn't know about extra_func(). You either need a function declaration (sometimes called a function prototype) or to rearrange your functions.

void extra_func(vector<int> &); // declaration

void func(vector<int> &vect)
{
   vect.push_back(30);
   extra_func(vect);
}

void extra_func(vector<int> &vect) // definition
{
   vect.push_back(40);
}

or

void extra_func(vector<int> &vect) // now it's visible to func()
{
   vect.push_back(40);
}

void func(vector<int> &vect)
{
   vect.push_back(30);
   extra_func(vect);
}