问:
why my data is add in two tables instead of one table in Asp.net mvc
I have two classes they are name Good and Category.but I have a so weird problem . in fact, when I submit my form to controller for adding good entity.one record add in good and one record add in category but i don't want to add any data in category. my controller get three argument good entity and HttpPostedFileBase file, IEnumerable<HttpPostedFileBase> files

```<code>  public class Good
    {
        public Good()
        {
            Images = new List<ImageList>();
            Category = new Category();
        }

        [Key]
        public int ProductId { get; set; }
        [Display(Name = "نام کالا")]
        public string Name { get; set; }
        [Display(Name = "نام تصویر")]
        public string ImageName { get; set; }
        public string LargeImageName { get; set; }
        [Display(Name = "نام لاتین")]
        public string EnglishName { get; set; }
        [Display(Name = "قیمت")]
        public string Price { get; set; }
        [AllowHtml]
        [Display(Name = "توضیح مختصر")]
        public string ShortDescription { get; set; }

        [Display(Name = "کلمات کلیدی")]
        public string Keyword { get; set; }
        [Display(Name = "تعداد بازدید")]
        public int PageVisit { get; set; }
        [Display(Name = "وضعیت")]
        public Boolean Status { get; set; }
        //Fk

        public int CategoryId { get; set; }
        [ForeignKey("CategoryId")]
        public Category Category { get; set; }

        public virtual ICollection<ImageList> Images { get; set; }

    }
</code>```

===============

```<code>public class Category
    {
        [Key]
        public int Id { get; set; }
        [Display(Name = "نام مجموعه")]
        public string CategoryName { get; set; }
        [Display(Name = "نام انگلیسی مجموعه")]
        public string EnglishName { get; set; }

        //navigation
        public virtual ICollection<Good> Good { get; set; }

    }
</code>```

=============================

```<code>  [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ProductId,Name,ImageName,LargeImageName,EnglishName,Price,ShortDescription,Keyword,PageVisit,Status,CategoryId")] Good good, HttpPostedFileBase file, IEnumerable<HttpPostedFileBase> files)
    {

        if (ModelState.IsValid)
        {
            if (file != null)
            {
                if (file.ContentLength > 0)
                {
                    var versions = new Dictionary<string, string>();
                    var checkSizeImage = ImageBuilder.Current.LoadImageInfo(file, null);
                    var setting = new ResizeSettings
                    {
                        MaxWidth = 600,
                        MaxHeight = 300,
                        Format = "jpg,png"
                    };

                    var path = Server.MapPath("/UploadFiles/Images/GoodGallery/");
                    versions.Add("_small", "maxwidth=270&maxheight=180&format=jpg");
                    versions.Add("_large", "maxwidth=600&maxheight=400&format=jpg");

                    foreach (var suffix in versions.Keys)
                    {
                        file.InputStream.Seek(0, System.IO.SeekOrigin.Begin);
                        ImageBuilder.Current.Build(new ImageJob(file.InputStream, path + file.FileName + suffix, new Instructions(versions[suffix]), false, true));
                    }

                    //good. = DateTime.Now.ToString();
                    var dotPosition = file.FileName.IndexOf('.');
                    var largeFileName = file.FileName.Insert(dotPosition, ".jpg_large");
                    var fileName = file.FileName.Insert(dotPosition, ".jpg_small");
                    good.LargeImageName = largeFileName;
                    good.ImageName = fileName;

                }
            }
            else
            {
                good.LargeImageName = "No_Image.png";
                good.ImageName = "No_Image.png";
            }
            if (files != null)
            {
                foreach (var file2 in files)
                {
                    if (file2 != null && file2.ContentLength > 0)
                    {
                        var versions = new Dictionary<string, string>();

                        var path = Server.MapPath("/UploadFiles/Images/GoodGallery/");
                        versions.Add("_small", "maxwidth=270&maxheight=180&format=jpg");
                        versions.Add("_large", "maxwidth=600&maxheight=400&format=jpg");
                        foreach (var suffix in versions.Keys)
                        {
                            file2.InputStream.Seek(0, System.IO.SeekOrigin.Begin);
                            ImageBuilder.Current.Build(new ImageJob(file2.InputStream, path + file2.FileName + suffix, new Instructions(versions[suffix]), false, true));
                        }

                        var dotPosition = file2.FileName.IndexOf('.');
                        var largeFileName = file2.FileName.Insert(dotPosition, ".jpg_large");
                        var smallfileName = file2.FileName.Insert(dotPosition, ".jpg_small");
                        good.Images.Add(new ImageList { LargeImageName = largeFileName, SmallImageName = smallfileName });

                    }
                }
            }
            else
            {
                good.Images.Add(new ImageList { LargeImageName = "No_Image.png", SmallImageName = "No_Image.png" });
            }
            ViewBag.Message = "فایل با موفقیت آپلود شد.";
        }

        db.Goods.Add(good);
        db.SaveChanges();

        ViewBag.CategoryId = new SelectList(db.Categories, "Id", "CategoryName", good.CategoryId);
        return View(good);

    }
</code>```

答:
As Good has a property called category and you have already implemented category class like that and made a foreign key thats why.implement in different way or Foreign key implementation in entity framework is like that -- if you dont want the inserting of the row , you should stop foriegn key

please check design , you can go through https://samsaffron.com/archive/2012/01/16/that-annoying-insert-problem-getting-data-into-the-db-using-dapper

Body:
I have two classes they are name Good and Category.but I have a so weird problem . in fact, when I submit my form to controller for adding good entity.one record add in good and one record add in category but i don't want to add any data in category. my controller get three argument good entity and HttpPostedFileBase file, IEnumerable<HttpPostedFileBase> files

  public class Good
    {
        public Good()
        {
            Images = new List<ImageList>();
            Category = new Category();
        }

        [Key]
        public int ProductId { get; set; }
        [Display(Name = "نام کالا")]
        public string Name { get; set; }
        [Display(Name = "نام تصویر")]
        public string ImageName { get; set; }
        public string LargeImageName { get; set; }
        [Display(Name = "نام لاتین")]
        public string EnglishName { get; set; }
        [Display(Name = "قیمت")]
        public string Price { get; set; }
        [AllowHtml]
        [Display(Name = "توضیح مختصر")]
        public string ShortDescription { get; set; }

        [Display(Name = "کلمات کلیدی")]
        public string Keyword { get; set; }
        [Display(Name = "تعداد بازدید")]
        public int PageVisit { get; set; }
        [Display(Name = "وضعیت")]
        public Boolean Status { get; set; }
        //Fk

        public int CategoryId { get; set; }
        [ForeignKey("CategoryId")]
        public Category Category { get; set; }

        public virtual ICollection<ImageList> Images { get; set; }

    }

===============

public class Category
    {
        [Key]
        public int Id { get; set; }
        [Display(Name = "نام مجموعه")]
        public string CategoryName { get; set; }
        [Display(Name = "نام انگلیسی مجموعه")]
        public string EnglishName { get; set; }

        //navigation
        public virtual ICollection<Good> Good { get; set; }

    }

=============================

  [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "ProductId,Name,ImageName,LargeImageName,EnglishName,Price,ShortDescription,Keyword,PageVisit,Status,CategoryId")] Good good, HttpPostedFileBase file, IEnumerable<HttpPostedFileBase> files)
    {

        if (ModelState.IsValid)
        {
            if (file != null)
            {
                if (file.ContentLength > 0)
                {
                    var versions = new Dictionary<string, string>();
                    var checkSizeImage = ImageBuilder.Current.LoadImageInfo(file, null);
                    var setting = new ResizeSettings
                    {
                        MaxWidth = 600,
                        MaxHeight = 300,
                        Format = "jpg,png"
                    };

                    var path = Server.MapPath("/UploadFiles/Images/GoodGallery/");
                    versions.Add("_small", "maxwidth=270&maxheight=180&format=jpg");
                    versions.Add("_large", "maxwidth=600&maxheight=400&format=jpg");

                    foreach (var suffix in versions.Keys)
                    {
                        file.InputStream.Seek(0, System.IO.SeekOrigin.Begin);
                        ImageBuilder.Current.Build(new ImageJob(file.InputStream, path + file.FileName + suffix, new Instructions(versions[suffix]), false, true));
                    }

                    //good. = DateTime.Now.ToString();
                    var dotPosition = file.FileName.IndexOf('.');
                    var largeFileName = file.FileName.Insert(dotPosition, ".jpg_large");
                    var fileName = file.FileName.Insert(dotPosition, ".jpg_small");
                    good.LargeImageName = largeFileName;
                    good.ImageName = fileName;

                }
            }
            else
            {
                good.LargeImageName = "No_Image.png";
                good.ImageName = "No_Image.png";
            }
            if (files != null)
            {
                foreach (var file2 in files)
                {
                    if (file2 != null && file2.ContentLength > 0)
                    {
                        var versions = new Dictionary<string, string>();

                        var path = Server.MapPath("/UploadFiles/Images/GoodGallery/");
                        versions.Add("_small", "maxwidth=270&maxheight=180&format=jpg");
                        versions.Add("_large", "maxwidth=600&maxheight=400&format=jpg");
                        foreach (var suffix in versions.Keys)
                        {
                            file2.InputStream.Seek(0, System.IO.SeekOrigin.Begin);
                            ImageBuilder.Current.Build(new ImageJob(file2.InputStream, path + file2.FileName + suffix, new Instructions(versions[suffix]), false, true));
                        }

                        var dotPosition = file2.FileName.IndexOf('.');
                        var largeFileName = file2.FileName.Insert(dotPosition, ".jpg_large");
                        var smallfileName = file2.FileName.Insert(dotPosition, ".jpg_small");
                        good.Images.Add(new ImageList { LargeImageName = largeFileName, SmallImageName = smallfileName });

                    }
                }
            }
            else
            {
                good.Images.Add(new ImageList { LargeImageName = "No_Image.png", SmallImageName = "No_Image.png" });
            }
            ViewBag.Message = "فایل با موفقیت آپلود شد.";
        }

        db.Goods.Add(good);
        db.SaveChanges();

        ViewBag.CategoryId = new SelectList(db.Categories, "Id", "CategoryName", good.CategoryId);
        return View(good);

    }


来源: stackexchange

问:
retrieve data from database and insert those values to another table in database c#
I'm getting error in connection open like "The connection is already opened". It is telling to close the opened connection of while loop(reading data from table). But any way the data's have to inserted to data base while reading. How to solve?</p>

```<code>private bool iscompanyExist(string comname)
{
    string query = "select * from Ageingrpt where Companyname='" + comname + "' group by Companyname having sum(current)>0 or sum('a1-30')>0 or sum('a31-60')>0 or sum('a61-90')>0 or sum('a90g')>0 ;";
    MySqlCommand cmd = new MySqlCommand(query, cnn);
    MySqlDataReader reader1;
    cnn.Open();
    reader1 = cmd.ExecuteReader();
    if (reader1.HasRows)
    {
        cnn.Close();
        return true;
    }
    else
    {
        cnn.Close();
        return false;
    }
}

private void Ageingcalc()
{
    string duedate = null;
    string compname = null, outstanding = null;
    //90<
    string query = "select c.address1,sum(p.OutstandingAmt) from invoice i,payment p,customer c where p.invoiceNo=i.invoiceNo and i.cid=c.cid and p.OutstandingAmt>0 and i.dueDate<'" + DateTime.Now + "'   group by c.address1 ;";
    MySqlCommand cmd = new MySqlCommand(query, cnn);
    MySqlDataReader reader;
    cnn.Open(); //open1
    reader = cmd.ExecuteReader();
    while (reader.Read())
    {
        compname = reader[0].ToString();
        outstanding = reader[1].ToString();
        if (iscompanyExist(compname) == true)
        {
            cnn.Open();
            query = "update Ageingrpt set a90g='" + outstanding + "';";
            cmd = new MySqlCommand(query, cnn);
            MySqlDataReader reader2 = cmd.ExecuteReader(); // query will be executed and data saved to the db
            cnn.Close();
        }
        else
        {
            cnn.Open();
            query = "insert into Ageingrpt  values('" + compname + "',0,0,0,0,'" + outstanding + "',0); ";
            cmd = new MySqlCommand(query, cnn);
            cmd.ExecuteReader(); // query will be executed and data saved to the db
            cnn.Close();
        }
    }

    cnn.Close();
}
</code>```

答:
This is worked for me.I have used DataTable to store the retrieved data.   </p>

```<code> private void Ageingcalc()
            {
                string duedate = null;
                string compname = null, outstanding = null;

                //90<
                string query = "select c.address1,sum(p.OutstandingAmt) as outstanding from invoice i,payment p,customer c where p.invoiceNo=i.invoiceNo and i.cid=c.cid and p.OutstandingAmt>0 and i.dueDate<'" + DateTime.Now + "'   group by c.address1 ;";
                MySqlCommand cmd = new MySqlCommand(query, cnn);
                MySqlDataReader reader;
                cnn.Open();
                MySqlDataAdapter da = new MySqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                da.Fill(dt);
                da.Dispose();
                cnn.Close();

                foreach (DataRow row in dt.Rows)
                {

                    if (iscompanyExist(row["address1"].ToString()) == true)
                    {
                        cnn.Open();
                        MessageBox.Show(row["address1"].ToString());
                        query = "update Ageingrpt set a90g='" + row["outstanding"].ToString() + "';";
                        cmd = new MySqlCommand(query, cnn);
                        MySqlDataReader reader2 = cmd.ExecuteReader(); // query will be executed and data saved to the db
                        cnn.Close();
                    }
                    else
                    {
                        cnn.Open();
                        MessageBox.Show(row["address1"].ToString());
                        query = "insert into Ageingrpt  values('" + row["address1"].ToString() + "',0,0,0,0,'" + row["outstanding"].ToString() + "',0); ";
                        cmd = new MySqlCommand(query, cnn);
                        MySqlDataReader reader2 = cmd.ExecuteReader(); // query will be executed and data saved to the db
                        cnn.Close();
                    }

                }

            }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm getting error in connection open like "The connection is already opened". It is telling to close the opened connection of while loop(reading data from table). But any way the data's have to inserted to data base while reading. How to solve?

private bool iscompanyExist(string comname)
{
    string query = "select * from Ageingrpt where Companyname='" + comname + "' group by Companyname having sum(current)>0 or sum('a1-30')>0 or sum('a31-60')>0 or sum('a61-90')>0 or sum('a90g')>0 ;";
    MySqlCommand cmd = new MySqlCommand(query, cnn);
    MySqlDataReader reader1;
    cnn.Open();
    reader1 = cmd.ExecuteReader();
    if (reader1.HasRows)
    {
        cnn.Close();
        return true;
    }
    else
    {
        cnn.Close();
        return false;
    }
}

private void Ageingcalc()
{
    string duedate = null;
    string compname = null, outstanding = null;
    //90<
    string query = "select c.address1,sum(p.OutstandingAmt) from invoice i,payment p,customer c where p.invoiceNo=i.invoiceNo and i.cid=c.cid and p.OutstandingAmt>0 and i.dueDate<'" + DateTime.Now + "'   group by c.address1 ;";
    MySqlCommand cmd = new MySqlCommand(query, cnn);
    MySqlDataReader reader;
    cnn.Open(); //open1
    reader = cmd.ExecuteReader();
    while (reader.Read())
    {
        compname = reader[0].ToString();
        outstanding = reader[1].ToString();
        if (iscompanyExist(compname) == true)
        {
            cnn.Open();
            query = "update Ageingrpt set a90g='" + outstanding + "';";
            cmd = new MySqlCommand(query, cnn);
            MySqlDataReader reader2 = cmd.ExecuteReader(); // query will be executed and data saved to the db
            cnn.Close();
        }
        else
        {
            cnn.Open();
            query = "insert into Ageingrpt  values('" + compname + "',0,0,0,0,'" + outstanding + "',0); ";
            cmd = new MySqlCommand(query, cnn);
            cmd.ExecuteReader(); // query will be executed and data saved to the db
            cnn.Close();
        }
    }

    cnn.Close();
}

Body:
This is worked for me.I have used DataTable to store the retrieved data.

 private void Ageingcalc()
            {
                string duedate = null;
                string compname = null, outstanding = null;

                //90<
                string query = "select c.address1,sum(p.OutstandingAmt) as outstanding from invoice i,payment p,customer c where p.invoiceNo=i.invoiceNo and i.cid=c.cid and p.OutstandingAmt>0 and i.dueDate<'" + DateTime.Now + "'   group by c.address1 ;";
                MySqlCommand cmd = new MySqlCommand(query, cnn);
                MySqlDataReader reader;
                cnn.Open();
                MySqlDataAdapter da = new MySqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                da.Fill(dt);
                da.Dispose();
                cnn.Close();

                foreach (DataRow row in dt.Rows)
                {

                    if (iscompanyExist(row["address1"].ToString()) == true)
                    {
                        cnn.Open();
                        MessageBox.Show(row["address1"].ToString());
                        query = "update Ageingrpt set a90g='" + row["outstanding"].ToString() + "';";
                        cmd = new MySqlCommand(query, cnn);
                        MySqlDataReader reader2 = cmd.ExecuteReader(); // query will be executed and data saved to the db
                        cnn.Close();
                    }
                    else
                    {
                        cnn.Open();
                        MessageBox.Show(row["address1"].ToString());
                        query = "insert into Ageingrpt  values('" + row["address1"].ToString() + "',0,0,0,0,'" + row["outstanding"].ToString() + "',0); ";
                        cmd = new MySqlCommand(query, cnn);
                        MySqlDataReader reader2 = cmd.ExecuteReader(); // query will be executed and data saved to the db
                        cnn.Close();
                    }

                }

            }


问:
vim replaces lines when I move to a new line
I'm using Terminal.app on Mac 10.6.6 and want to upgrade vim. Should I install it in /usr/local?

I'm asking because my native vim install is messed up for some reason. Sometimes, when I open it and move up and down, the whole line changes to another line on the screen, like dancing chairs. But if I type :q it quits fine because nothing actually gets changed (cause I'm just moving the cursor around), but I can't see what I'm doing because when I move to a new line, that line gets replaced with another line about 6 lines below, but it's random.

$TERM = xterm-color

I installed Mercurial & ack via CPAN (for which I installed File:Next) yesterday, so maybe that did it. I have MacVim, but I want vim to work too cause I use it for Git, etc.

答:
Try running vim -u "NONE" to load your Vim without your .vimrc, this might be the culprit in this case. If everything works like it should you can try re-enabling things one by one so you can see what caused it.

If you want to update your Vim I can recommend homebrew which has a so called formula with a regularly updated Vim.

ContentLicense: CC BY-SA 2.5


问:
Displaying specific url text when opening new window in Javascript
I have an interesting situation.  I have an application that opens up a new window/tab when a button is clicked.  When it opens, a pre-made html page is displayed to the user and a specific url is set.  My question is, how do I set the url of the window?  I don't want the window to link to another page or site, just display the url I tell it to.  Is this even possible?

Here's what I have so far:

JS

```<code>getSingleResults(screening){
    let url = this.router.url;
    if(screening.isTrue){
        url += "/urlIWantToDisplay";
    }
    this.patientService.getPatientResults(screening.id).subscribe(result => {
        let newWindow = window.open(url).document.write(result);
    })
}
</code>```

HTML

```<code><button type="button" class="in-line btn" (click)="getSingleResults(screening)"><i class="glyphicon glyphicon-search"></i></button>
</code>```

However, in the address bar, I'm still seeing about:blank instead of the url I want to display.

答:
Nope, you can't do that.. because it would be a huge security flaw.. Can you imagine changing the URL bar to facebook.com but having control over its content? That's never gonna happen.
If you ever manage to do something like that you can get your prize at https://www.google.com/about/appsecurity/chrome-rewards/</p>

Body:
I have an interesting situation.  I have an application that opens up a new window/tab when a button is clicked.  When it opens, a pre-made html page is displayed to the user and a specific url is set.  My question is, how do I set the url of the window?  I don't want the window to link to another page or site, just display the url I tell it to.  Is this even possible?

Here's what I have so far:

JS

getSingleResults(screening){
    let url = this.router.url;
    if(screening.isTrue){
        url += "/urlIWantToDisplay";
    }
    this.patientService.getPatientResults(screening.id).subscribe(result => {
        let newWindow = window.open(url).document.write(result);
    })
}

HTML

<button type="button" class="in-line btn" (click)="getSingleResults(screening)"></button>

However, in the address bar, I'm still seeing about:blank instead of the url I want to display.


问:
Matlab/Simulink: run batch of simulations in parallel?
I have to run a series of simulations and save the results. Since by default Matlab only uses one core, I wonder if it is possible to open multiple worker tasks and assign different simulation runs to them?</p>

答:
I aso have the same problem but I did not manage to really understand how to make it in MatLab. The documentation in matlab is too advanced to get to know how to make it.

Since I am working with Ubuntu I find a way to do the work calling the unix command from MatLab and using the parallel GNU command

So I mange to run my simulation in parallel with 4 cores.

```<code>unix('parallel --progress -j4 flow > /dev/null :::: Pool.txt','-echo')
</code>```

you can find more info in the link
Shell, run four processes parallel

Details of the syntaxis can be found at https://www.gnu.org/software/parallel/
but breifly I can tell you

--progress shows a status of the progress

-j4 tells the amount or jobs in parallel you want to have

flow is the name of my simulator

/dev/null was just to avoid the screen run output of the simulator to show up

Pool.txt  is a file I made with the required simulator input that is basically the path and the main simulator file.

echo I do not remember now what was it for :D

Body:
I aso have the same problem but I did not manage to really understand how to make it in MatLab. The documentation in matlab is too advanced to get to know how to make it.

Since I am working with Ubuntu I find a way to do the work calling the unix command from MatLab and using the parallel GNU command

So I mange to run my simulation in parallel with 4 cores.

unix('parallel --progress -j4 flow > /dev/null :::: Pool.txt','-echo')

you can find more info in the link
Shell, run four processes parallel

Details of the syntaxis can be found at https://www.gnu.org/software/parallel/
but breifly I can tell you

--progress shows a status of the progress

-j4 tells the amount or jobs in parallel you want to have

flow is the name of my simulator

/dev/null was just to avoid the screen run output of the simulator to show up

Pool.txt  is a file I made with the required simulator input that is basically the path and the main simulator file.

echo I do not remember now what was it for :D


问:
How do I join the selected items in multiple list boxes with the user text entered in text box in c#?
Goal:Is to display Project name, formed by joining list box selected items with user entered text in the text box and display it as a label.

Description: I am creating a windows for App, which has two listboxes displaying Firstname-lbA & Lastname- lbB along with a textbox for the user to enter packet name.

For example: If I select an item(first name)from the listbox A i.e. "XXX", select an item(last name)from the listbox B i.e. "YYY" and enter text in the Textbox i.e. "PKT-100" & click create button I would want to display the Project name as XXX-YYY-PKT-100.

checking conditions:
If no Item in lbA is selected then display:YYY-PKT-100.
If no Item in Lb B is seleected then display :XXX-PKT-100.
If no Text is entered the display: XXX-YYY.
No spaces/double dashes are allowed.

I'd really appreciate if someone could help me with your suggestions.

Thanks!!

Code:

```<code>FirstNamespace Project
{
    public partial class ProjectTool : Form
    {
        public List<FirstName> ltfirstname { get; set; }
        public List<LastName> ltlastname { get; set; }

        public FirstName SelectedFirstname => (FirstName)lbGetFirstName.SelectedItem
        public LastName SelectedLastname => (LastName)lbGetLastName.SelectedItem;

        public projecTool()
        {
            InitializeComponent();

            ltfirstname = GetFirstNames();
            lbGetFirstName.DataSource = ltfirstname;

            ltlastname  = GetLastNames();
            lbGetLastName.DataSource = ltlastname;

        }

        public List<FirstName> GetFirstNames()
        {
            List<FirstName> fnames = new List<FirstName>();
            using (StreamReader sr = new StreamReader("D:\\FirstNames.csv"))
            {
                string line;
                try
                {
                    while ((line = sr.ReadLine()) != null)
                    {
                        string[] columns = line.Replace("\"","").Split(',');
                        if (columns.Length >= 1)
                        {
                            var name = new FirstName();
                            name.FirstName = columns[0];
                            fnames.Add(name);
                        }
                    }
                }
                catch (Exception ex) { }
                return fnames;
            }
        }
        public List<LastName> GetlastNames()
        {
            List<LastName> lnames = new List<LastName>();
            using (StreamReader sr = new StreamReader("D:\\LastNames.csv"))
            {
                string line;
                try
                {
                    while ((line = sr.ReadLine()) != null)
                    {
                        string[] columns = line.Replace("\"","").Split(',');
                        if (columns.Length >= 1)
                        {
                            var lname = new LastName();
                            lname.LastName = columns[0];
                            lnames.Add(lname);
                        }
                    }
                }
                catch (Exception ex) { }
                return lnames;
            }
        }

        public void CreateprojectName()
        {
            // Create project name as Firstname-Lastname-Packetname
                //if project name already exists then check for correctness/update.
                // Check -> if there are double dashes/spaces in the Project name
        }

        private void lbGetFirstName_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
        private void lbGetlastName_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
        private void txtPacketName_TextChanged(object sender, EventArgs e)
        {

        }
        private void create_projectname_button1_Click(object sender, EventArgs e)
        {

        }
    }
}
</code>```

答:
Its quite simple for listBox use SelectedItem & for textBox use Text property.</p>

```<code>private void create_projectname_button1_Click(object sender, EventArgs e)
{
    if (lbGetFirstName.SelectedItems.Count==0)
    {
        label1.Text = "YYY-PKT-100";
    }
    if (lbGetlastName.SelectedItems.Count==0)
    {
        label1.Text = "XXX-PKT-100";
    }
    if (string.IsNullOrWhiteSpace(textBox1.Text))
    {
        label1.Text = "XXX-YYY";
    }
    else
    {
        label1.Text = lbGetFirstName.SelectedItem + "-" + listBox2.SelectedItem + "-" + lbGetlastName.Text;
    }
}
</code>```

Body:
Goal:Is to display Project name, formed by joining list box selected items with user entered text in the text box and display it as a label.

Description: I am creating a windows for App, which has two listboxes displaying Firstname-lbA & Lastname- lbB along with a textbox for the user to enter packet name.

For example: If I select an item(first name)from the listbox A i.e. "XXX", select an item(last name)from the listbox B i.e. "YYY" and enter text in the Textbox i.e. "PKT-100" & click create button I would want to display the Project name as XXX-YYY-PKT-100.

checking conditions:
If no Item in lbA is selected then display:YYY-PKT-100.
If no Item in Lb B is seleected then display :XXX-PKT-100.
If no Text is entered the display: XXX-YYY.
No spaces/double dashes are allowed.

I'd really appreciate if someone could help me with your suggestions.

Thanks!!

Code:

FirstNamespace Project
{
    public partial class ProjectTool : Form
    {
        public List<FirstName> ltfirstname { get; set; }
        public List<LastName> ltlastname { get; set; }

        public FirstName SelectedFirstname => (FirstName)lbGetFirstName.SelectedItem
        public LastName SelectedLastname => (LastName)lbGetLastName.SelectedItem;

        public projecTool()
        {
            InitializeComponent();

            ltfirstname = GetFirstNames();
            lbGetFirstName.DataSource = ltfirstname;

            ltlastname  = GetLastNames();
            lbGetLastName.DataSource = ltlastname;

        }

        public List<FirstName> GetFirstNames()
        {
            List<FirstName> fnames = new List<FirstName>();
            using (StreamReader sr = new StreamReader("D:\\FirstNames.csv"))
            {
                string line;
                try
                {
                    while ((line = sr.ReadLine()) != null)
                    {
                        string[] columns = line.Replace("\"","").Split(',');
                        if (columns.Length >= 1)
                        {
                            var name = new FirstName();
                            name.FirstName = columns[0];
                            fnames.Add(name);
                        }
                    }
                }
                catch (Exception ex) { }
                return fnames;
            }
        }
        public List<LastName> GetlastNames()
        {
            List<LastName> lnames = new List<LastName>();
            using (StreamReader sr = new StreamReader("D:\\LastNames.csv"))
            {
                string line;
                try
                {
                    while ((line = sr.ReadLine()) != null)
                    {
                        string[] columns = line.Replace("\"","").Split(',');
                        if (columns.Length >= 1)
                        {
                            var lname = new LastName();
                            lname.LastName = columns[0];
                            lnames.Add(lname);
                        }
                    }
                }
                catch (Exception ex) { }
                return lnames;
            }
        }

        public void CreateprojectName()
        {
            // Create project name as Firstname-Lastname-Packetname
                //if project name already exists then check for correctness/update.
                // Check -> if there are double dashes/spaces in the Project name
        }

        private void lbGetFirstName_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
        private void lbGetlastName_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
        private void txtPacketName_TextChanged(object sender, EventArgs e)
        {

        }
        private void create_projectname_button1_Click(object sender, EventArgs e)
        {

        }
    }
}

Body:
Its quite simple for listBox use SelectedItem & for textBox use Text property.

private void create_projectname_button1_Click(object sender, EventArgs e)
{
    if (lbGetFirstName.SelectedItems.Count==0)
    {
        label1.Text = "YYY-PKT-100";
    }
    if (lbGetlastName.SelectedItems.Count==0)
    {
        label1.Text = "XXX-PKT-100";
    }
    if (string.IsNullOrWhiteSpace(textBox1.Text))
    {
        label1.Text = "XXX-YYY";
    }
    else
    {
        label1.Text = lbGetFirstName.SelectedItem + "-" + listBox2.SelectedItem + "-" + lbGetlastName.Text;
    }
}


问:
Excel 2010 cannot paste into a form textbox
I have a textbox within a frame on my form. A user wants to copy and paste data into this textbox, but they are unable to do so. They can copy but when they try a right click or CTRL + V nothing happens.

I've looked at the textbox properties and don't see anything that is preventing this. The data they are copying is Arial 10.  The textbox is formatted as Arial Regular 10.

Is there something on the form or frame that is preventing the paste feature from not working?

Thanks for the help....

答:
To be able to paste into a textbox in a frame, you have to first be in Edit mode:

Right click on the textbox

Hover over Textbox Object

In the submenu, select Edit

Now you can change the text inside the box, including pasting text from other sources.

UPDATE:

When the textbox has focus, you can copy a cell's value into it, but not the reference to the cell itself. Click on the cell whose value you want to copy, then copy the text from the formula bar at the top of the screen and paste that into your textbox.


问:
Comparing keys in HashMap and Values
I have a HashMap as follows-

```<code>HashMap<String, Integer> BC = new HashMap<String, Integer>();
</code>```

which stores as keys- "tokens/tages" and as values- "frequency of each tokens/tags".

Example-

```<code>"the/at" 153
"that/cs" 45
"Ann/np" 3
</code>```

I now parse through each key and check whether for same token say "the" whether it's associated with more than one tag and then take the largest of the two.

Example-

```<code>"the/at" 153
"the/det" 80
</code>```

Then I take the key- "the/at" with value - 153.

The code that I have written to do so is as follows-

```<code>private HashMap<String, Integer> Unigram_Tagger = new HashMap<String, Integer>();

for(String curr_key: BC.keySet())
        {
            for(String next_key: BC.keySet())
            {
                if(curr_key.equals(next_key))
                    continue;
                else
                {
                    String[] split_key_curr_key = curr_key.split("/");
                    String[] split_key_next_key = next_key.split("/");

                    //out.println("CK- " + curr_key + ", NK- " + next_key);

                    if(split_key_curr_key[0].equals(split_key_next_key[0]))
                    {
                        int ck_v = 0, nk_v = 0;
                        ck_v = BC.get(curr_key);
                        nk_v = BC.get(next_key);

                        if(ck_v > nk_v)
                            Unigram_Tagger.put(curr_key, BC.get(curr_key));
                        else
                            Unigram_Tagger.put(next_key, BC.get(next_key));
                    }
                }
            }
        }
</code>```

But this code is taking too long to compute since the original HashMap 'BC' has 68442 entries which comes approximately to its square = 4684307364 times (plus some more).

My question is this- can I accomplish the same output using a more efficient method?

Thanks!

答:
The slowest part of your current method is due to the pairwise comparison of keys. First, define a Tuple class:

```<code>public class Tuple<X, Y> {
  public final X x;
  public final Y y;
  public Tuple(X x, Y y) {
    this.x = x;
    this.y = y;
  }
}
</code>```

Thus you can try an algorithm that does:

Initializes a new HashMap<String, Tuple<String, Integer>> result

Given input pair (key, value) from the old map, where key = "a/b", check whether result.keySet().contains(a) and result.keySet().contains(b).

If both a and b is not present, result.put(a, new Tuple<String, Integer>(b, value) and result.put(b, new Tuple<String, Integer>(a, value))

If a is present, compare value and v = result.get(a). If value > v, remove a and b from result and do step 3. Do the same for b. Otherwise, get the next key-value pair.

After you have iterated through the old hash map and inserted everything, then you can easily reconstruct the output you want by transforming the key-values in result.

Title: Comparing keys in HashMap and Values

Body:
I have a HashMap as follows-

HashMap<String, Integer> BC = new HashMap<String, Integer>();

which stores as keys- "tokens/tages" and as values- "frequency of each tokens/tags".

Example-

"the/at" 153
"that/cs" 45
"Ann/np" 3

I now parse through each key and check whether for same token say "the" whether it's associated with more than one tag and then take the largest of the two.

Example-

"the/at" 153
"the/det" 80

Then I take the key- "the/at" with value - 153.

The code that I have written to do so is as follows-

private HashMap<String, Integer> Unigram_Tagger = new HashMap<String, Integer>();

for(String curr_key: BC.keySet())
        {
            for(String next_key: BC.keySet())
            {
                if(curr_key.equals(next_key))
                    continue;
                else
                {
                    String[] split_key_curr_key = curr_key.split("/");
                    String[] split_key_next_key = next_key.split("/");

                    //out.println("CK- " + curr_key + ", NK- " + next_key);

                    if(split_key_curr_key[0].equals(split_key_next_key[0]))
                    {
                        int ck_v = 0, nk_v = 0;
                        ck_v = BC.get(curr_key);
                        nk_v = BC.get(next_key);

                        if(ck_v > nk_v)
                            Unigram_Tagger.put(curr_key, BC.get(curr_key));
                        else
                            Unigram_Tagger.put(next_key, BC.get(next_key));
                    }
                }
            }
        }

But this code is taking too long to compute since the original HashMap 'BC' has 68442 entries which comes approximately to its square = 4684307364 times (plus some more).

My question is this- can I accomplish the same output using a more efficient method?

Thanks!

Body:
The slowest part of your current method is due to the pairwise comparison of keys. First, define a Tuple class:

public class Tuple<X, Y> {
  public final X x;
  public final Y y;
  public Tuple(X x, Y y) {
    this.x = x;
    this.y = y;
  }
}

Thus you can try an algorithm that does:

Initializes a new HashMap<String, Tuple<String, Integer>> result

Given input pair (key, value) from the old map, where key = "a/b", check whether result.keySet().contains(a) and result.keySet().contains(b).

If both a and b is not present, result.put(a, new Tuple<String, Integer>(b, value) and result.put(b, new Tuple<String, Integer>(a, value))

If a is present, compare value and v = result.get(a). If value > v, remove a and b from result and do step 3. Do the same for b. Otherwise, get the next key-value pair.

After you have iterated through the old hash map and inserted everything, then you can easily reconstruct the output you want by transforming the key-values in result.


问:
What is the difference between explicit and implicit cursors in Oracle?
I am a bit rusty on my cursor lingo in PL/SQL. Anyone know this?</p>

答:
As stated in other answers, implicit cursors are easier to use and less error-prone.

And Implicit vs. Explicit Cursors in Oracle PL/SQL shows that implicit cursors are up to two times faster than explicit ones too.

It's strange that no one had yet mentioned Implicit FOR LOOP Cursor:

```<code>begin
  for cur in (
    select t.id from parent_trx pt inner join trx t on pt.nested_id = t.id
    where t.started_at > sysdate - 31 and t.finished_at is null and t.extended_code is null
  )
  loop
    update trx set finished_at=sysdate, extended_code = -1 where id = cur.id;
    update parent_trx set result_code = -1 where nested_id = cur.id;
  end loop cur;
end;
</code>```

Another example on SO: PL/SQL FOR LOOP IMPLICIT CURSOR.

It's way more shorter than explicit form.

This also provides a nice workaround for updating multiple tables from CTE.

OwnerDisplayName: Brian

LastEditorDisplayName: Brian

Body:
As stated in other answers, implicit cursors are easier to use and less error-prone.

And Implicit vs. Explicit Cursors in Oracle PL/SQL shows that implicit cursors are up to two times faster than explicit ones too.

It's strange that no one had yet mentioned Implicit FOR LOOP Cursor:

begin
  for cur in (
    select t.id from parent_trx pt inner join trx t on pt.nested_id = t.id
    where t.started_at > sysdate - 31 and t.finished_at is null and t.extended_code is null
  )
  loop
    update trx set finished_at=sysdate, extended_code = -1 where id = cur.id;
    update parent_trx set result_code = -1 where nested_id = cur.id;
  end loop cur;
end;

Another example on SO: PL/SQL FOR LOOP IMPLICIT CURSOR.

It's way more shorter than explicit form.

This also provides a nice workaround for updating multiple tables from CTE.


问:
How to handle lightning (ambient, diffuse, specular) for point spheres in openGL

Initial situation

I want to visualize simulation data in openGL.
My data consists of particle positions (x, y, z) where each particle has some properties (like density, temperature, ...) which will be used for coloring. Those (SPH) particles (100k to several millions), grouped together, actually represent planets, in case you wonder. I want to render those particles as small 3D spheres and add ambient, diffuse and specular lighting.

Status quo and questions

In MY case: In which coordinate frame do I do the lightning calculations? Which way is the "best" to pass the various components through the pipeline?

I saw that it is common to do it in view space which is also very intuitive. However: The normals at the different fragment positions are calculated in the fragment shader in clip space coordinates (see appended fragment shader). Can I actually convert them "back" into view space to do the lightning calculations in view space for all the fragments? Would there be any advantage compared to doing it in clip space?

It would be easier to get the normals in view space if I would use meshes for each sphere but I think with several million particles this would decrease performance drastically, so better do it with sphere intersection, would you agree?

PS: I don't need a model matrix since all the particles are already in place.

```<code>//VERTEX SHADER

#version 330 core
layout (location = 0) in vec3 position;
layout (location = 2) in float density;

uniform float radius;
uniform vec3 lightPos;
uniform vec3 viewPos;

out vec4 lightDir;
out vec4 viewDir;
out vec4 viewPosition;
out vec4 posClip;
out float vertexColor;

// transformation matrices
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

void main()
{
    lightDir        = projection * view * vec4(lightPos - position, 1.0f);
    viewDir         = projection * view * vec4(viewPos - position, 1.0f);
    viewPosition    = projection * view * vec4(lightPos, 1.0f);
    posClip         = projection * view * vec4(position, 1.0f);

    gl_Position = posClip;
    gl_PointSize = radius;

    vertexColor = density;

}
</code>```

I know that projective divion happens for the gl_Position variable, does that actually happen to ALL vec4's which are passed from the vertex to the fragment shader? If not, maybe the calculations in the fragment shader would be wrong?

And the fragment shader where the normals and diffuse/specular lightning calculations in clip space:

```<code>//FRAGMENT SHADER

#version 330 core

in float vertexColor;
in vec4 lightDir;
in vec4 viewDir;
in vec4 posClip;
in vec4 viewPosition;

uniform vec3 lightColor;

vec4 colormap(float x); // returns vec4(r, g, b, a)

out vec4 vFragColor;

void main(void)
{
    // AMBIENT LIGHT
    float ambientStrength = 0.0;
    vec3 ambient = ambientStrength * lightColor;

    // Normal calculation done in clip space (first from texture (gl_PointCoord 0 to 1) coord to NDC( -1 to 1))
    vec3 normal;
    normal.xy = gl_PointCoord * 2.0 - vec2(1.0);    // transform from 0->1 point primitive coords to NDC -1->1
    float mag = dot(normal.xy, normal.xy);          // sqrt(x=1) = sqrt(x)
    if (mag > 1.0)                                  // discard fragments outside sphere
        discard;
    normal.z = sqrt(1.0 - mag);                     // because x^2 + y^2 + z^2 = 1

    // DIFFUSE LIGHT
    float diff = max(0.0, dot(vec3(lightDir), normal));
    vec3 diffuse = diff * lightColor;

    // SPECULAR LIGHT
    float specularStrength = 0.1;
    vec3 viewDir = normalize(vec3(viewPosition) - vec3(posClip));
    vec3 reflectDir = reflect(-vec3(lightDir), normal);
    float shininess = 64;
    float spec = pow(max(dot(vec3(viewDir), vec3(reflectDir)), 0.0), shininess);
    vec3 specular = specularStrength * spec * lightColor;

     vFragColor = colormap(vertexColor / 8) * vec4(ambient + diffuse + specular, 1);

}
</code>```

Now this actually "kind of" works but i have the feeling that also the sides of the sphere which do NOT face the light source are being illuminated, which shouldn't happen. How can I fix this?

Some weird effect: In this moment the light source is actually BEHIND the left planet (it just peaks out a little bit at the top left), bit still there are diffuse and specular effects going on. This side should be actually pretty dark! =(

Also at this moment I get some glError: 1282 error in the fragment shader and I don't know where it comes from since the shader program actually compiles and runs, any suggestions? :)

答:
The things that you are drawing aren't actually spheres. They just look like them from afar. This is absolutely ok if you are fine with that. If you need geometrically correct spheres (with correct sizes and with a correct projection), you need to do proper raycasting. This seems to be a comprehensive guide on this topic.

1. What coordinate system?

In the end, it is up to you. The coordinate system just needs to fulfill some requirements. It must be angle-preserving (because lighting is all about angles). And if you need distance-based attenuation, it should also be distance-preserving. The world and the view coordinate systems usually fulfill these requirements. Clip space is not suited for lighting calculations as neither angles nor distances are preserved. Furthermore, gl_PointCoord is in none of the usual coordinate systems. It is its own coordinate system and you should only use it together with other coordinate systems if you know their relation.

2. Meshes or what?

Meshes are absolutely not suited to render spheres. As mentioned above, raycasting or some screen-space approximation are better choices. Here is an example shader that I used in my projects:

```<code>#version 330

out vec4 result;

in fData
{
    vec4 toPixel; //fragment coordinate in particle coordinates
    vec4 cam;     //camera position in particle coordinates
    vec4 color;   //sphere color
    float radius; //sphere radius
} frag;

uniform mat4 p; //projection matrix

void main(void)
{
    vec3 v = frag.toPixel.xyz - frag.cam.xyz;
    vec3 e = frag.cam.xyz;
    float ev = dot(e, v);
    float vv = dot(v, v);
    float ee = dot(e, e);
    float rr = frag.radius * frag.radius;

    float radicand = ev * ev - vv * (ee - rr);
    if(radicand < 0)
        discard;

    float rt = sqrt(radicand);

    float lambda = max(0, (-ev - rt) / vv); //first intersection on the ray
    float lambda2 = (-ev + rt) / vv;  //second intersection on the ray
    if(lambda2 < lambda) //if the first intersection is behind the camera
        discard;

    vec3 hit = lambda * v; //intersection point
    vec3 normal = (frag.cam.xyz + hit) / frag.radius;

    vec4 proj = p * vec4(hit, 1); //intersection point in clip space
    gl_FragDepth = ((gl_DepthRange.diff * proj.z / proj.w) + gl_DepthRange.near + gl_DepthRange.far) / 2.0;

    vec3 vNormalized = -normalize(v);
    float nDotL = dot(vNormalized, normal);
    vec3 c = frag.color.rgb * nDotL + vec3(0.5, 0.5, 0.5) * pow(nDotL, 120);

    result = vec4(c, frag.color.a);
}
</code>```

3. Perspective division

Perspective division is not applied to your attributes. The GPU does perspective division on the data that you pass via gl_Position on the way to transforming them to screen space. But you will never actually see this perspective-divided position unless you do it yourself.

4. Light in the dark

This might be the result of you mixing different coordinate systems or doing lighting calculations in clip space. Btw, the specular part is usually not multiplied by the material color. This is light that gets reflected directly at the surface. It does not penetrate the surface (which would absorb some colors depending on the material). That's why those highlights are usually white (or whatever light color you have), even on black objects.

Body:
Initial situation

I want to visualize simulation data in openGL.
My data consists of particle positions (x, y, z) where each particle has some properties (like density, temperature, ...) which will be used for coloring. Those (SPH) particles (100k to several millions), grouped together, actually represent planets, in case you wonder. I want to render those particles as small 3D spheres and add ambient, diffuse and specular lighting.

Status quo and questions

In MY case: In which coordinate frame do I do the lightning calculations? Which way is the "best" to pass the various components through the pipeline?

I saw that it is common to do it in view space which is also very intuitive. However: The normals at the different fragment positions are calculated in the fragment shader in clip space coordinates (see appended fragment shader). Can I actually convert them "back" into view space to do the lightning calculations in view space for all the fragments? Would there be any advantage compared to doing it in clip space?

It would be easier to get the normals in view space if I would use meshes for each sphere but I think with several million particles this would decrease performance drastically, so better do it with sphere intersection, would you agree?

PS: I don't need a model matrix since all the particles are already in place.

//VERTEX SHADER

#version 330 core
layout (location = 0) in vec3 position;
layout (location = 2) in float density;

uniform float radius;
uniform vec3 lightPos;
uniform vec3 viewPos;

out vec4 lightDir;
out vec4 viewDir;
out vec4 viewPosition;
out vec4 posClip;
out float vertexColor;

// transformation matrices
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

void main()
{
    lightDir        = projection * view * vec4(lightPos - position, 1.0f);
    viewDir         = projection * view * vec4(viewPos - position, 1.0f);
    viewPosition    = projection * view * vec4(lightPos, 1.0f);
    posClip         = projection * view * vec4(position, 1.0f);

    gl_Position = posClip;
    gl_PointSize = radius;

    vertexColor = density;

}

I know that projective divion happens for the gl_Position variable, does that actually happen to ALL vec4's which are passed from the vertex to the fragment shader? If not, maybe the calculations in the fragment shader would be wrong?

And the fragment shader where the normals and diffuse/specular lightning calculations in clip space:

//FRAGMENT SHADER

#version 330 core

in float vertexColor;
in vec4 lightDir;
in vec4 viewDir;
in vec4 posClip;
in vec4 viewPosition;

uniform vec3 lightColor;

vec4 colormap(float x); // returns vec4(r, g, b, a)

out vec4 vFragColor;

void main(void)
{
    // AMBIENT LIGHT
    float ambientStrength = 0.0;
    vec3 ambient = ambientStrength * lightColor;

    // Normal calculation done in clip space (first from texture (gl_PointCoord 0 to 1) coord to NDC( -1 to 1))
    vec3 normal;
    normal.xy = gl_PointCoord * 2.0 - vec2(1.0);    // transform from 0->1 point primitive coords to NDC -1->1
    float mag = dot(normal.xy, normal.xy);          // sqrt(x=1) = sqrt(x)
    if (mag > 1.0)                                  // discard fragments outside sphere
        discard;
    normal.z = sqrt(1.0 - mag);                     // because x^2 + y^2 + z^2 = 1

    // DIFFUSE LIGHT
    float diff = max(0.0, dot(vec3(lightDir), normal));
    vec3 diffuse = diff * lightColor;

    // SPECULAR LIGHT
    float specularStrength = 0.1;
    vec3 viewDir = normalize(vec3(viewPosition) - vec3(posClip));
    vec3 reflectDir = reflect(-vec3(lightDir), normal);
    float shininess = 64;
    float spec = pow(max(dot(vec3(viewDir), vec3(reflectDir)), 0.0), shininess);
    vec3 specular = specularStrength * spec * lightColor;

     vFragColor = colormap(vertexColor / 8) * vec4(ambient + diffuse + specular, 1);

}

Now this actually "kind of" works but i have the feeling that also the sides of the sphere which do NOT face the light source are being illuminated, which shouldn't happen. How can I fix this?

Some weird effect: In this moment the light source is actually BEHIND the left planet (it just peaks out a little bit at the top left), bit still there are diffuse and specular effects going on. This side should be actually pretty dark! =(

Also at this moment I get some glError: 1282 error in the fragment shader and I don't know where it comes from since the shader program actually compiles and runs, any suggestions? :)

Body:
The things that you are drawing aren't actually spheres. They just look like them from afar. This is absolutely ok if you are fine with that. If you need geometrically correct spheres (with correct sizes and with a correct projection), you need to do proper raycasting. This seems to be a comprehensive guide on this topic.

1. What coordinate system?

In the end, it is up to you. The coordinate system just needs to fulfill some requirements. It must be angle-preserving (because lighting is all about angles). And if you need distance-based attenuation, it should also be distance-preserving. The world and the view coordinate systems usually fulfill these requirements. Clip space is not suited for lighting calculations as neither angles nor distances are preserved. Furthermore, gl_PointCoord is in none of the usual coordinate systems. It is its own coordinate system and you should only use it together with other coordinate systems if you know their relation.

2. Meshes or what?

Meshes are absolutely not suited to render spheres. As mentioned above, raycasting or some screen-space approximation are better choices. Here is an example shader that I used in my projects:

#version 330

out vec4 result;

in fData
{
    vec4 toPixel; //fragment coordinate in particle coordinates
    vec4 cam;     //camera position in particle coordinates
    vec4 color;   //sphere color
    float radius; //sphere radius
} frag;

uniform mat4 p; //projection matrix

void main(void)
{
    vec3 v = frag.toPixel.xyz - frag.cam.xyz;
    vec3 e = frag.cam.xyz;
    float ev = dot(e, v);
    float vv = dot(v, v);
    float ee = dot(e, e);
    float rr = frag.radius * frag.radius;

    float radicand = ev * ev - vv * (ee - rr);
    if(radicand < 0)
        discard;

    float rt = sqrt(radicand);

    float lambda = max(0, (-ev - rt) / vv); //first intersection on the ray
    float lambda2 = (-ev + rt) / vv;  //second intersection on the ray
    if(lambda2 < lambda) //if the first intersection is behind the camera
        discard;

    vec3 hit = lambda * v; //intersection point
    vec3 normal = (frag.cam.xyz + hit) / frag.radius;

    vec4 proj = p * vec4(hit, 1); //intersection point in clip space
    gl_FragDepth = ((gl_DepthRange.diff * proj.z / proj.w) + gl_DepthRange.near + gl_DepthRange.far) / 2.0;

    vec3 vNormalized = -normalize(v);
    float nDotL = dot(vNormalized, normal);
    vec3 c = frag.color.rgb * nDotL + vec3(0.5, 0.5, 0.5) * pow(nDotL, 120);

    result = vec4(c, frag.color.a);
}

3. Perspective division

Perspective division is not applied to your attributes. The GPU does perspective division on the data that you pass via gl_Position on the way to transforming them to screen space. But you will never actually see this perspective-divided position unless you do it yourself.

4. Light in the dark

This might be the result of you mixing different coordinate systems or doing lighting calculations in clip space. Btw, the specular part is usually not multiplied by the material color. This is light that gets reflected directly at the surface. It does not penetrate the surface (which would absorb some colors depending on the material). That's why those highlights are usually white (or whatever light color you have), even on black objects.


问:
UINavigationBar slides away instead of staying on place
I created demo project to show the problem.

We have two view controllers inside UINavigationController.

MainViewController which is the root.

```<code>class MainViewController: UIViewController {

    lazy var button: UIButton = {
        let button = UIButton()
        button.setTitle("Detail", for: .normal)
        return button
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.title = "Main"
        view.backgroundColor = .blue
        view.addSubview(button)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        button.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        button.widthAnchor.constraint(equalToConstant: 150).isActive = true
        button.heightAnchor.constraint(equalToConstant: 42).isActive = true
        button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
    }

    @objc func buttonTapped(_ sender: UIButton) {
        navigationController?.pushViewController(DetailViewController(), animated: true)
    }
}
</code>```

And DetailViewController which is pushed.

```<code>class DetailViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(true, animated: animated)
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.setNavigationBarHidden(false, animated: animated)
    }
}
</code>```

As you can see I want to hide UINavigationBar in DetailViewController:

Question

The problem is that, UINavigationBar slides away instead of stay of his place together with whole MainViewController. How can I change that behavior and keep pop gesture?

答:
in your MainViewController add that method

```<code>override func viewDidAppear(_ animated: Bool) {
        UIView.animate(withDuration: 0) {
            self.navigationController?.setNavigationBarHidden(false, animated: false)
        }
    }
</code>```

and replace your method with below method in DetailViewController

```<code> override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    navigationController?.setNavigationBarHidden(true, animated: animated)
}
</code>```

Body:
I created demo project to show the problem.

We have two view controllers inside UINavigationController.

MainViewController which is the root.

class MainViewController: UIViewController {

    lazy var button: UIButton = {
        let button = UIButton()
        button.setTitle("Detail", for: .normal)
        return button
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.title = "Main"
        view.backgroundColor = .blue
        view.addSubview(button)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        button.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
        button.widthAnchor.constraint(equalToConstant: 150).isActive = true
        button.heightAnchor.constraint(equalToConstant: 42).isActive = true
        button.addTarget(self, action: #selector(buttonTapped(_:)), for: .touchUpInside)
    }

    @objc func buttonTapped(_ sender: UIButton) {
        navigationController?.pushViewController(DetailViewController(), animated: true)
    }
}

And DetailViewController which is pushed.

class DetailViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(true, animated: animated)
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.setNavigationBarHidden(false, animated: animated)
    }
}

As you can see I want to hide UINavigationBar in DetailViewController:

Question

The problem is that, UINavigationBar slides away instead of stay of his place together with whole MainViewController. How can I change that behavior and keep pop gesture?

Body:
in your MainViewController add that method

override func viewDidAppear(_ animated: Bool) {
        UIView.animate(withDuration: 0) {
            self.navigationController?.setNavigationBarHidden(false, animated: false)
        }
    }

and replace your method with below method in DetailViewController

 override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    navigationController?.setNavigationBarHidden(true, animated: animated)
}


问:
Output of the dplyr summarize() fundtion
Is there a convenient way to have dplyr::summarize_all() output the results in a more readable format without having to manually rearrange it after the fact?

Ultimately, I'd like to be able to port the output of summarize more easily to tables in Word, etc.

I would like to avoid the work of doing something like what's below.

Thank you

Example:

```<code>library(dplyr)
library(e1071) # for skewness() function
# make fake data
a <- rnorm(20)
b <- rnorm(20)
c <- rnorm(20)
x <- rnorm(20)
y <- rnorm(20)
z <- rnorm(20)

# create dataframe
dat = data.frame(a, b, c, x, y, z)

# run summarize()
descriptives <- dat %>% summarize_all(funs(mean, sd, skewness))
descriptives

# rearrange descriptives
matrix(descriptives, 6, 3,
    dimnames = list(c("a", "b", "c", "x", "y", "z"),
    c("mean", "SD", "skew")), byrow = FALSE)

# RETURNS
#  mean       SD        skew
#a 0.1533271  0.8106499 -0.02879986
#b -0.5117311 0.5608904 -0.2668225
#c 0.1267941  0.8214882 -0.4260682
#x 0.05337055 0.9817041 -0.1932566
#y -0.1091145 0.9050062 -0.3409686
#z -0.3195788 0.8833493 -0.6663437
</code>```

答:
you need to rearrange your data in a tidy format, Read up
https://cran.r-project.org/web/packages/tidyr/vignettes/tidy-data.html
I did a quick melt, using the reshape2 package. You can do this using tidyr and the equivalent function would be gather(). Here's a handy reference -http://tidyr.tidyverse.org/
my brain is still too used to reshape2, slowly training my self to use tidyr

```<code>library(reshape2)
library(dplyr)
library(e1071)
descriptives <-melt(dat) %>%
group_by(variable) %>%
summarize_all(funs(mean, sd, skewness))
</code>```

Body:
Is there a convenient way to have dplyr::summarize_all() output the results in a more readable format without having to manually rearrange it after the fact?

Ultimately, I'd like to be able to port the output of summarize more easily to tables in Word, etc.

I would like to avoid the work of doing something like what's below.

Thank you

Example:

library(dplyr)
library(e1071) # for skewness() function
# make fake data
a <- rnorm(20)
b <- rnorm(20)
c <- rnorm(20)
x <- rnorm(20)
y <- rnorm(20)
z <- rnorm(20)

# create dataframe
dat = data.frame(a, b, c, x, y, z)

# run summarize()
descriptives <- dat %>% summarize_all(funs(mean, sd, skewness))
descriptives

# rearrange descriptives
matrix(descriptives, 6, 3,
    dimnames = list(c("a", "b", "c", "x", "y", "z"),
    c("mean", "SD", "skew")), byrow = FALSE)

# RETURNS
#  mean       SD        skew
#a 0.1533271  0.8106499 -0.02879986
#b -0.5117311 0.5608904 -0.2668225
#c 0.1267941  0.8214882 -0.4260682
#x 0.05337055 0.9817041 -0.1932566
#y -0.1091145 0.9050062 -0.3409686
#z -0.3195788 0.8833493 -0.6663437

Body:
you need to rearrange your data in a tidy format, Read up
https://cran.r-project.org/web/packages/tidyr/vignettes/tidy-data.html
I did a quick melt, using the reshape2 package. You can do this using tidyr and the equivalent function would be gather(). Here's a handy reference -http://tidyr.tidyverse.org/
my brain is still too used to reshape2, slowly training my self to use tidyr

library(reshape2)
library(dplyr)
library(e1071)
descriptives <-melt(dat) %>%
group_by(variable) %>%
summarize_all(funs(mean, sd, skewness))


问:
Django's BooleanField showing incorrect value in edit mode
DJango: 1.24

DB: MySQL

Column Type: Bit

Code: models.BooleanField(db_column='InStock')

The checkbox always shows checked no matter what the value is (1 or 0). The value gets saved correctly but when it renders the edit page, it always checked.

Any pointers?

答: You haven't provided much details so I'm guessing that you mean that you have a form and it doesn't have required=False set for the BooleanField.


问:
Approach for implementing the Goertzel filter in AudioKit?
I don't believe AudioKit (4.0+) has a Goertzel filter, but thought I could start with AKFrequencyTracker and create one.

This AKGoertzelTracker class would be initialized with an array of one or more desired frequencies to detect and a desired minimum amplitude, then a method (e.g. frequenciesDetected) would return a subset of those frequencies that are currently being detected by using the Goertzel algorithm for each one.

I can find various implementations of the Goertzel filter on SO, but I'm not sure where to put it within the AudioKit framework. Any direction or help would be greatly appreciated. Thanks!

答: Its a filter, so I would say you should model it after one of the other filters in AudioKit (that are not based off Apple's filters). So, open up the Nodes/Effects/Filters in AudioKit and find an examples that has four files.  A swift interface, an Objective-C header, an Objective-C implementation, and finally the C++ DSP Kernel.  Find the filter that is most like your own in terms of inputs or controls.  Then, make your modifications. That's a start and then you can ask more specific questions to us here on Stack Overflow.</p>


问:
Shortcut alt+enter is not working in Android Studio
alt +  enterfor importing was work normally maybe until I updated Android Studio,
my version now is2.3.3

as this screenshot, I can't press alt +  enter at all, knowing that I have tested them on other programs and they are working normally

答: I faced the same problem and was sure that the problem is in Android Studio. But when I reinstalled it I realized that it did not helped. So I decided to test my keyboard. I found that my left Alt is not working with Enter and right Alt somewhy is turning on Ctrl key. That is why Alt+Enter was not working in any combinations. Problem was solved by reinstalling keyboard driver. Hope it will helps somebody.</p>

ContentLicense: CC BY-SA 4.0


问:
Scrollview inside Relativelayout is not scrolling properly in android
In my screen design, I have an Action Bar and Bottom Bar (which basically a Linearlayout). In mid of the screen, I have few textviews and 4-5 buttons. I want to add the scroll in the middle part of the screen. But it is not working.

My code is here:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <TextView
                android:id="@+id/toAddrdrop"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="20dp"
                android:textColor="@android:color/black"
                android:textSize="16sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/fromAddrDrop"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/toAddrdrop"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="10dp"
                android:textColor="@android:color/black"
                android:textSize="16sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/distanceToCoverDrop"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/fromAddrDrop"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="10dp"
                android:textColor="@android:color/black"
                android:textSize="16sp"
                android:textStyle="bold" />

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/distanceToCoverDrop"
                android:orientation="vertical">

                <Button
                    android:id="@+id/drop_confirm"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="40dp"
                    android:background="@drawable/button_active"
                    android:text="Drop Confirm" />

                <Button
                    android:id="@+id/sai_out_drop"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="40dp"
                    android:background="@drawable/button_active"
                    android:text="Sai Out" />

                <Button
                    android:id="@+id/customer_in_drop"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="40dp"
                    android:background="@drawable/button_active"
                    android:text="Customer In" />

                <Button
                    android:id="@+id/customer_out_drop"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="40dp"
                    android:background="@drawable/button_active"
                    android:text="Customer Out" />

                <Button
                    android:id="@+id/customer_new_drop"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="40dp"
                    android:background="@drawable/button_active"
                    android:text="Customer new" />

                <Button
                    android:id="@+id/customer_new_drop22"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="40dp"
                    android:background="@drawable/button_active"
                    android:text="Customer new 22" />
            </LinearLayout>

        </LinearLayout>
    </ScrollView>

    <LinearLayout
        android:id="@+id/buttombardrop"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_alignParentBottom="true"
        android:background="#33B5E5"
        android:orientation="horizontal">

        <Button
            android:id="@+id/callButton_drop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@android:color/transparent"
            android:drawableTop="@android:drawable/ic_menu_call"
            android:paddingTop="8dp"
            android:text="Call"
            android:textColor="#FFFFFF" />

        <View
            android:layout_width="1dp"
            android:layout_height="match_parent"
            android:background="#ffffff" />

        <Button
            android:id="@+id/mapButton_drop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@android:color/transparent"
            android:drawableTop="@android:drawable/ic_menu_mapmode"
            android:paddingTop="8dp"
            android:text="Map"
            android:textColor="#FFFFFF" />

    </LinearLayout >

</RelativeLayout>
</code>```

I have observed that, I am able to scroll a bit till 4 buttons. How can I fix the scrollview.
Please help!!

答:
You should beware that RelativeLayout behaves unexpected many times. so you should use LinearLayout.

Just replace your code by

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ScrollView

        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:id="@+id/toAddrdrop"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="20dp"
                android:textColor="@android:color/black"
                android:textSize="16sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/fromAddrDrop"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/toAddrdrop"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="10dp"
                android:textColor="@android:color/black"
                android:textSize="16sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/distanceToCoverDrop"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/fromAddrDrop"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="10dp"
                android:textColor="@android:color/black"
                android:textSize="16sp"
                android:textStyle="bold" />

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/distanceToCoverDrop"
                android:orientation="vertical">

                <Button
                    android:id="@+id/drop_confirm"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="40dp"
                    android:background="@drawable/button_active"
                    android:text="Drop Confirm" />

                <Button
                    android:id="@+id/sai_out_drop"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="40dp"
                    android:background="@drawable/button_active"
                    android:text="Sai Out" />

                <Button
                    android:id="@+id/customer_in_drop"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="40dp"
                    android:background="@drawable/button_active"
                    android:text="Customer In" />

                <Button
                    android:id="@+id/customer_out_drop"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="40dp"
                    android:background="@drawable/button_active"
                    android:text="Customer Out" />

                <Button
                    android:id="@+id/customer_new_drop"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="40dp"
                    android:background="@drawable/button_active"
                    android:text="Customer new" />

                <Button
                    android:id="@+id/customer_new_drop22"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="40dp"
                    android:background="@drawable/button_active"
                    android:text="Customer new 22" />
            </LinearLayout>

        </LinearLayout>
    </ScrollView>

    <LinearLayout
        android:id="@+id/buttombardrop"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:background="#33B5E5"
        android:orientation="horizontal">

        <Button
            android:id="@+id/callButton_drop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@android:color/transparent"
            android:drawableTop="@android:drawable/ic_menu_call"
            android:paddingTop="8dp"
            android:text="Call"
            android:textColor="#FFFFFF" />

        <View
            android:layout_width="1dp"
            android:layout_height="match_parent"
            android:background="#ffffff" />

        <Button
            android:id="@+id/mapButton_drop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@android:color/transparent"
            android:drawableTop="@android:drawable/ic_menu_mapmode"
            android:paddingTop="8dp"
            android:text="Map"
            android:textColor="#FFFFFF" />

    </LinearLayout >

</LinearLayout>
</code>```

Body:
In my screen design, I have an Action Bar and Bottom Bar (which basically a Linearlayout). In mid of the screen, I have few textviews and 4-5 buttons. I want to add the scroll in the middle part of the screen. But it is not working.

My code is here:

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <TextView
                android:id="@+id/toAddrdrop"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="20dp"
                android:textColor="@android:color/black"
                android:textSize="16sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/fromAddrDrop"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/toAddrdrop"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="10dp"
                android:textColor="@android:color/black"
                android:textSize="16sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/distanceToCoverDrop"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/fromAddrDrop"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="10dp"
                android:textColor="@android:color/black"
                android:textSize="16sp"
                android:textStyle="bold" />

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/distanceToCoverDrop"
                android:orientation="vertical">

                <Button
                    android:id="@+id/drop_confirm"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="40dp"
                    android:background="@drawable/button_active"
                    android:text="Drop Confirm" />

                <Button
                    android:id="@+id/sai_out_drop"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="40dp"
                    android:background="@drawable/button_active"
                    android:text="Sai Out" />

                <Button
                    android:id="@+id/customer_in_drop"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="40dp"
                    android:background="@drawable/button_active"
                    android:text="Customer In" />

                <Button
                    android:id="@+id/customer_out_drop"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="40dp"
                    android:background="@drawable/button_active"
                    android:text="Customer Out" />

                <Button
                    android:id="@+id/customer_new_drop"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="40dp"
                    android:background="@drawable/button_active"
                    android:text="Customer new" />

                <Button
                    android:id="@+id/customer_new_drop22"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="40dp"
                    android:background="@drawable/button_active"
                    android:text="Customer new 22" />
            </LinearLayout>

        </LinearLayout>
    </ScrollView>

    <LinearLayout
        android:id="@+id/buttombardrop"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_alignParentBottom="true"
        android:background="#33B5E5"
        android:orientation="horizontal">

        <Button
            android:id="@+id/callButton_drop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@android:color/transparent"
            android:drawableTop="@android:drawable/ic_menu_call"
            android:paddingTop="8dp"
            android:text="Call"
            android:textColor="#FFFFFF" />

        <View
            android:layout_width="1dp"
            android:layout_height="match_parent"
            android:background="#ffffff" />

        <Button
            android:id="@+id/mapButton_drop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@android:color/transparent"
            android:drawableTop="@android:drawable/ic_menu_mapmode"
            android:paddingTop="8dp"
            android:text="Map"
            android:textColor="#FFFFFF" />

    </LinearLayout >

</RelativeLayout>

I have observed that, I am able to scroll a bit till 4 buttons. How can I fix the scrollview.
Please help!!

Body:
You should beware that RelativeLayout behaves unexpected many times. so you should use LinearLayout.

Just replace your code by

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ScrollView

        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:id="@+id/toAddrdrop"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="20dp"
                android:textColor="@android:color/black"
                android:textSize="16sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/fromAddrDrop"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/toAddrdrop"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="10dp"
                android:textColor="@android:color/black"
                android:textSize="16sp"
                android:textStyle="bold" />

            <TextView
                android:id="@+id/distanceToCoverDrop"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@id/fromAddrDrop"
                android:layout_marginLeft="20dp"
                android:layout_marginTop="10dp"
                android:textColor="@android:color/black"
                android:textSize="16sp"
                android:textStyle="bold" />

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/distanceToCoverDrop"
                android:orientation="vertical">

                <Button
                    android:id="@+id/drop_confirm"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="40dp"
                    android:background="@drawable/button_active"
                    android:text="Drop Confirm" />

                <Button
                    android:id="@+id/sai_out_drop"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="40dp"
                    android:background="@drawable/button_active"
                    android:text="Sai Out" />

                <Button
                    android:id="@+id/customer_in_drop"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="40dp"
                    android:background="@drawable/button_active"
                    android:text="Customer In" />

                <Button
                    android:id="@+id/customer_out_drop"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="40dp"
                    android:background="@drawable/button_active"
                    android:text="Customer Out" />

                <Button
                    android:id="@+id/customer_new_drop"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="40dp"
                    android:background="@drawable/button_active"
                    android:text="Customer new" />

                <Button
                    android:id="@+id/customer_new_drop22"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_marginTop="40dp"
                    android:background="@drawable/button_active"
                    android:text="Customer new 22" />
            </LinearLayout>

        </LinearLayout>
    </ScrollView>

    <LinearLayout
        android:id="@+id/buttombardrop"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:background="#33B5E5"
        android:orientation="horizontal">

        <Button
            android:id="@+id/callButton_drop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@android:color/transparent"
            android:drawableTop="@android:drawable/ic_menu_call"
            android:paddingTop="8dp"
            android:text="Call"
            android:textColor="#FFFFFF" />

        <View
            android:layout_width="1dp"
            android:layout_height="match_parent"
            android:background="#ffffff" />

        <Button
            android:id="@+id/mapButton_drop"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="@android:color/transparent"
            android:drawableTop="@android:drawable/ic_menu_mapmode"
            android:paddingTop="8dp"
            android:text="Map"
            android:textColor="#FFFFFF" />

    </LinearLayout >

</LinearLayout>


问:
AMP form amp_source_origin error cors header
I am getting error in AMP Form

```<code> <form class="innler-left" method="post" action-xhr="//mydoma.com/ xxxx/xxx/xxx/send.php" target="_top">
</code>```

On submit getting below error in console.

```<code>Response must contain the AMP-Access-Control-Allow-Source-Origin header
Form submission failed: Error:
Response must contain the AMP-Access-Control-Allow-Source-Origin header _reported_
</code>```

Once user submit the form it goes it php file in where I put the following header

```<code>header('HTTP/1.1 200 OK');
header("access-control-allow-credentials:true");
header("AMP-Same-Origin: true");
header("Access-Control-Allow-Origin:".$_SERVER['HTTP_ORIGIN']);
header("amp-access-control-allow-source-origin: https://".$_SERVER['HTTP_HOST']);
header("Access-Control-Expose-Headers: AMP-Access-Control-Allow-Source-Origin");
header("access-control-allow-headers:Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token");
header("access-control-allow-methods:POST, GET, OPTIONS");
header("Content-Type: application/json");
</code>```

I got it working offline on local machine but once i upload files, it not working :(

tried https://github.com/ampproject/amphtml/blob/master/spec/amp-cors-requests.md

POST __amp_source_origin is not matching!

答:
I was also facing the same issue to fix this, make sure your URL start with https. And try to replace the following line in your code :

```<code>header("Access-Control-Allow-Origin:".$_SERVER['HTTP_ORIGIN']);
</code>```

with

```<code>header("Access-Control-Allow-Origin: ". str_replace('.', '-','https://www.example.com') .".cdn.ampproject.org");
</code>```

Note : Replace https://www.example.com with your AMP website URL

Hope it helps.

Body:
I am getting error in AMP Form

 <form class="innler-left" method="post" action-xhr="//mydoma.com/ xxxx/xxx/xxx/send.php" target="_top">

On submit getting below error in console.

Response must contain the AMP-Access-Control-Allow-Source-Origin header
Form submission failed: Error:
Response must contain the AMP-Access-Control-Allow-Source-Origin header _reported_

Once user submit the form it goes it php file in where I put the following header

header('HTTP/1.1 200 OK');
header("access-control-allow-credentials:true");
header("AMP-Same-Origin: true");
header("Access-Control-Allow-Origin:".$_SERVER['HTTP_ORIGIN']);
header("amp-access-control-allow-source-origin: https://".$_SERVER['HTTP_HOST']);
header("Access-Control-Expose-Headers: AMP-Access-Control-Allow-Source-Origin");
header("access-control-allow-headers:Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token");
header("access-control-allow-methods:POST, GET, OPTIONS");
header("Content-Type: application/json");

I got it working offline on local machine but once i upload files, it not working :(

tried https://github.com/ampproject/amphtml/blob/master/spec/amp-cors-requests.md

POST __amp_source_origin is not matching!

Body:
I was also facing the same issue to fix this, make sure your URL start with https. And try to replace the following line in your code :

header("Access-Control-Allow-Origin:".$_SERVER['HTTP_ORIGIN']);

with

header("Access-Control-Allow-Origin: ". str_replace('.', '-','https://www.example.com') .".cdn.ampproject.org");

Note : Replace https://www.example.com with your AMP website URL

Hope it helps.