问:
Are my debug statements correct? Is the class being used correctly? I am not currently getting errors but also am getting no output
I am tasked to write a program that accesses an outside text file that contains basketball player names and scores. I have always had issues reading and writing from txt files regardless of language. Once the txt file is read from, the program is supposed to output the average scores for all players as well as the player name of the highest scorer. I am getting several errors thrown from my code which won't run. Are my debug statements correct? Is the class being used correctly? Here is what I have:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BasketBallScore
{
public partial class BasketballStats : Form
{

    private string score;

    public BasketballStats()
    {
        InitializeComponent();
    }

    public class BasketballController
    {
        public class Entry
        {
            public int Value { get; set; }
            public string Name { get; set; }
        }
        BasketballController(string filename)
        {
            this.filename = filename;
        }
        private string filename;
        private List<Entry> data = new List<Entry>();
        public List<Entry> Data
        {
            get
            {
                // Clear data
                data.Clear();
                // Iterate through lines
                foreach (string line in System.IO.File.ReadLines(filename))
                {
                    // Split by space
                    List<string> parts = line.Trim().Split(' ').ToList();
                    if (parts.Count() < 2)
                        continue;
                    // Number is last space separated string
                    int number = int.Parse(parts.Last());
                    // Remove number
                    parts.RemoveAt(parts.Count() - 1);
                    // Name is any previous word joined by space
                    string name = string.Join(" ", parts).Trim();

                    // Add number and name to data
                    data.Add(new Entry() { Name = name, Value = number });
                }
                // Sort from greater value to smaller
                data.Sort(Comparer<Entry>.Create(
                    (l, r) => r.Value.CompareTo(l.Value)));
                return data;
            }
            set
            {
                using (var writer = new System.IO.StreamWriter(filename))
                {
                    foreach (var entry in value)
                    {
                        writer.WriteLine(string.Format("{0} {1}", entry.Name, entry.Value));
                    }
                }
                data = value;
            }
        }
        public double Average
        {
            get
            {
                // Read file if data is empty, otherwise reuse its value
                var src = (data.Count() == 0) ? Data : data;
                if (src.Count() == 0)
                    return 0.0;
                // Return average
                return src.Average(x => x.Value);
            }
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void BtnCreateFile_Click(object sender, EventArgs e)
    {
        score = "basketBallScore.txt";
        if (File.Exists(score))
        {
            Console.WriteLine("FileName: {0}", score);
            Console.WriteLine("Attributes: {0}",
                File.GetAttributes(score));
            Console.WriteLine("Created: {0}",
                File.GetCreationTime(score));
            Console.WriteLine("Last Accessed: {0}",
                File.GetLastAccessTime(score));

            DirectoryInfo dir = new DirectoryInfo(".");
            Console.WriteLine("Current Directory: \n{0} \n",
                Directory.GetCurrentDirectory());
            Console.WriteLine("File Name".PadRight(52) +
                "Size".PadRight(10) + "Creation Time");
            foreach (FileInfo fil in dir.GetFiles("*.*"))
            {
                string name = fil.Name;
                long size = fil.Length;
                DateTime creationTime = fil.CreationTime;
                Console.WriteLine("{0} {1,12:NO} {2, 20:g} ", name.PadRight(45),
                    size, creationTime);
            }
        }

        else
        {
            Console.WriteLine("{0} not found - using current" +
                "directory:", score);
        }
        Console.ReadKey();
    }

    private void CalcAverage_Click(object sender, EventArgs e)
    {
        var c = new BasketballController("basketBallScore.txt");
        Debug.WriteLine(string.Format("Average {0}", c.Average));
        Debug.WriteLine(string.Format("First {0} {1}", c.Data.First().Name, c.Data.First().Value));
        Debug.WriteLine(string.Format("Last {0} {1}", c.Data.Last().Name, c.Data.Last().Value));
    }
}
</code>```

}

This is what the text file contains:

```<code>Lebron James        31
Steph Curry         12
Kyrie Irving        37
Kevin Durant        9
Paul George         35
Klay Thompson       8
J.R.Smith           12
Zaza Pachulia       4
Tristan Thompson    10
Draymond Green      2
</code>```

The program will access the file but will not give any output beyond the verification of the the data file. This is an updated version of a previous program. This was what I had previously:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;

namespace TextFiles
{
public partial class BasketBallStats : Form
{
    List<int> marks = new List<int>();

public BasketBallStats()
{
    InitializeComponent();
}

// Form load event handler used to construct
// object of the Streamwriter class, sending the
// new filename as an argument. Enclosed in
// try...catch block.
public class BasketballController
{
    public class Entry
    {
        public int Value { get; set; }
        public string Name { get; set; }
    }
    BasketballController(string filename)
    {
        this.filename = filename;
    }
    private string filename;
    private List<Entry> data = new List<Entry>();
    public List<Entry> Data
    {
        get
        {
            // Clear data
            data.Clear();
            // Iterate through lines
            foreach (string line in System.IO.File.ReadLines(filename))
            {
                // Split by space
                List<string> parts = line.Trim().Split(' ').ToList();
                if (parts.Count() < 2)
                    continue;
                // Number is last space separated string
                int number = int.Parse(parts.Last());
                // Remove number
                parts.RemoveAt(parts.Count() - 1);
                // Name is any previous word joined by space
                string name = string.Join(" ", parts).Trim();

                // Add number and name to data
                data.Add(new Entry() { Name = name, Value = number });
            }
            // Sort from greater value to smaller
            data.Sort(Comparer<Entry>.Create(
                (l, r) => r.Value.CompareTo(l.Value)));
            return data;
        }
        set
        {
            using (var writer = new System.IO.StreamWriter(filename))
            {
                foreach (var entry in value)
                {
                    writer.WriteLine(string.Format("{0} {1}", entry.Name, entry.Value));
                }
            }
            data = value;
        }
    }
    public double Average
    {
        get
        {
            // Read file if data is empty, otherwise reuse its value
            var src = (data.Count() == 0) ? Data : data;
            if (src.Count() == 0)
                return 0.0;
            // Return average
            return src.Average(x => x.Value);
        }
    }
}

private string score;

public List<int> Marks { get => Marks1; set => Marks1 = value; }
public List<int> Marks1 { get => marks; set => marks = value; }

private void BasketBallStats_Load(object sender, EventArgs e)
{

}

private void BtnCreateFile_Click(object sender, EventArgs e)
{
    score = "basketBallScore.txt";
    if (File.Exists(score))
    {
        Console.WriteLine("FileName: {0}", score);
        Console.WriteLine("Attributes: {0}",
            File.GetAttributes(score));
        Console.WriteLine("Created: {0}",
            File.GetCreationTime(score));
        Console.WriteLine("Last Accessed: {0}",
            File.GetLastAccessTime(score));

        DirectoryInfo dir = new DirectoryInfo(".");
        Console.WriteLine("Current Directory: \n{0} \n",
            Directory.GetCurrentDirectory());
        Console.WriteLine("File Name".PadRight(52) +
            "Size".PadRight(10) + "Creation Time");
        foreach (FileInfo fil in dir.GetFiles("*.*"))
        {
            string name = fil.Name;
            long size = fil.Length;
            DateTime creationTime = fil.CreationTime;
            Console.WriteLine("{0} {1,12:NO} {2, 20:g} ", name.PadRight(45),
                size, creationTime);
        }
    }

    else
    {
        Console.WriteLine("{0} not found - using current" +
            "directory:", score);
    }
    Console.ReadKey();
}

private void BtnWriteFile_Click(object sender, EventArgs e)
{
    try
    {
        var WriteToFile = new System.IO.StreamWriter("basketBallScore.txt"); //create textfile in default directory
        WriteToFile.Write(listView1.Text + ", " + listView1.Text + ", " + listView1.Text + ", " + listView1.Text);
        WriteToFile.Close();
        Marks.Add(Convert.ToInt32(listView1.Text)); //add to list
    }

    catch (System.IO.DirectoryNotFoundException)
    {
        lblMessage.Text = "File did not close properly: ";    //add error message
    }
}

private void ManipulateFile_Click(object sender, EventArgs e)
{
    int[] hoursArray = new int[30];
    StreamReader fileSR = new StreamReader("basketBallScore.txt");
    int counter = 0;
    string line = "";
    line = fileSR.ReadLine();
    while (line != null)
    {
        hoursArray[counter] = int.Parse(line);
        counter = counter + 1;
        line = fileSR.ReadLine();
    }
    fileSR.Close();

    int total = 0;
    double average = 0;
    for (int index = 0; index < hoursArray.Length; index++)
    {
        total = total + hoursArray[index];
    }
    average = (double)total / hoursArray.Length;

    int high = hoursArray[0];
    for (int index = 1; index < hoursArray.Length; index++)
    {
        if (hoursArray[index] > high)
        {
            high = hoursArray[index];
        }
    }
    Console.WriteLine("Highest number is: " + high);
    Console.WriteLine("The average is: " + average);
    Console.ReadLine();
}

private void BasketBallStats_Load_1(object sender, EventArgs e)
{

}

private void CalcAverage_Click(object sender, EventArgs e)
{
    int totalmarks = 0;
    foreach (int m in Marks)
        totalmarks += m;

    MessageBox.Show("Average Is: " + totalmarks / Marks.Count);
}

private void Button1_Click(object sender, EventArgs e)
{
    var c = new BasketballController("basketBallScore.txt");
    Debug.WriteLine(string.Format("Average {0}", c.Average));
    Debug.WriteLine(string.Format("First {0} {1}", c.Data.First().Name, c.Data.First().Value));
    Debug.WriteLine(string.Format("Last {0} {1}", c.Data.Last().Name, c.Data.Last().Value));
    }
  }
}
</code>```

答:
I was able to code a program that does exactly what I needed it to do. Here is what I have:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;

namespace BasketballScores
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void BtnOutputData_Click(object sender, EventArgs e)
    {
        try
        {
            string path = "basketBallScore.txt";
            var c = new BasketballPlayer(path);
            ListView1.Items.Add(string.Format("\r\nAverage {0}", c.Average));
            ListView1.Items.Add(string.Format("\r\nFirst {0} {1}", c.Data.First().Name, c.Data.First().Value));
            ListView1.Items.Add(string.Format("\r\nLast {0} {1}", c.Data.Last().Name, c.Data.Last().Value));
            using (StreamWriter sw = File.AppendText(path))
            {
                foreach (ListViewItem item in ListView1.Items)
                {
                    sw.WriteLine(item.Text);
                    for (int i = 1; i < item.SubItems.Count; i++)
                    {
                        sw.WriteLine(item.SubItems[i].Text);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            lblMessage.Text = ex.Message;
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void ListView1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
  }
}
</code>```

This is a class I have with the code:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BasketballScores
{
class BasketballPlayer
{
    public class Entry
    {
        public int Value { get; set; }
        public string Name { get; set; }
    }
public BasketballPlayer(string filename)
    {
        this.filename = filename;
    }
    private string filename;
    private List<Entry> data = new List<Entry>();
    public List<Entry> Data
    {
        get
        {
            // Clear data
            data.Clear();
            // Iterate through lines
            foreach (string line in System.IO.File.ReadLines(filename))
            {
                // Split by space
                List<string> parts = line.Trim().Split(' ').ToList();
                if (parts.Count() < 2)
                    continue;
                // Number is last space separated string
                int number = int.Parse(parts.Last());
                // Remove number
                parts.RemoveAt(parts.Count() - 1);
                // Name is any previous word joined by space
                string name = string.Join(" ", parts).Trim();

                // Add number and name to data
                data.Add(new Entry() { Name = name, Value = number });
            }
            // Sort from greater value to smaller
            data.Sort(Comparer<Entry>.Create(
                (l, r) => r.Value.CompareTo(l.Value)));
            return data;
        }
        set
        {
            using (var writer = new System.IO.StreamWriter(filename))
            {
                foreach (var entry in value)
                {
                    writer.WriteLine(string.Format("{0} {1}", entry.Name, entry.Value));
                }
            }
            data = value;
        }
    }
    public double Average
    {
        get
        {
            // Read file if data is empty, otherwise reuse its value
            var src = (data.Count() == 0) ? Data : data;
            if (src.Count() == 0)
                return 0.0;
            // Return average
            return src.Average(x => x.Value);
        }
    }
  }
}
</code>```

Body:
I am tasked to write a program that accesses an outside text file that contains basketball player names and scores. I have always had issues reading and writing from txt files regardless of language. Once the txt file is read from, the program is supposed to output the average scores for all players as well as the player name of the highest scorer. I am getting several errors thrown from my code which won't run. Are my debug statements correct? Is the class being used correctly? Here is what I have:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BasketBallScore
{
public partial class BasketballStats : Form
{

    private string score;

    public BasketballStats()
    {
        InitializeComponent();
    }

    public class BasketballController
    {
        public class Entry
        {
            public int Value { get; set; }
            public string Name { get; set; }
        }
        BasketballController(string filename)
        {
            this.filename = filename;
        }
        private string filename;
        private List<Entry> data = new List<Entry>();
        public List<Entry> Data
        {
            get
            {
                // Clear data
                data.Clear();
                // Iterate through lines
                foreach (string line in System.IO.File.ReadLines(filename))
                {
                    // Split by space
                    List<string> parts = line.Trim().Split(' ').ToList();
                    if (parts.Count() < 2)
                        continue;
                    // Number is last space separated string
                    int number = int.Parse(parts.Last());
                    // Remove number
                    parts.RemoveAt(parts.Count() - 1);
                    // Name is any previous word joined by space
                    string name = string.Join(" ", parts).Trim();

                    // Add number and name to data
                    data.Add(new Entry() { Name = name, Value = number });
                }
                // Sort from greater value to smaller
                data.Sort(Comparer<Entry>.Create(
                    (l, r) => r.Value.CompareTo(l.Value)));
                return data;
            }
            set
            {
                using (var writer = new System.IO.StreamWriter(filename))
                {
                    foreach (var entry in value)
                    {
                        writer.WriteLine(string.Format("{0} {1}", entry.Name, entry.Value));
                    }
                }
                data = value;
            }
        }
        public double Average
        {
            get
            {
                // Read file if data is empty, otherwise reuse its value
                var src = (data.Count() == 0) ? Data : data;
                if (src.Count() == 0)
                    return 0.0;
                // Return average
                return src.Average(x => x.Value);
            }
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void BtnCreateFile_Click(object sender, EventArgs e)
    {
        score = "basketBallScore.txt";
        if (File.Exists(score))
        {
            Console.WriteLine("FileName: {0}", score);
            Console.WriteLine("Attributes: {0}",
                File.GetAttributes(score));
            Console.WriteLine("Created: {0}",
                File.GetCreationTime(score));
            Console.WriteLine("Last Accessed: {0}",
                File.GetLastAccessTime(score));

            DirectoryInfo dir = new DirectoryInfo(".");
            Console.WriteLine("Current Directory: \n{0} \n",
                Directory.GetCurrentDirectory());
            Console.WriteLine("File Name".PadRight(52) +
                "Size".PadRight(10) + "Creation Time");
            foreach (FileInfo fil in dir.GetFiles("*.*"))
            {
                string name = fil.Name;
                long size = fil.Length;
                DateTime creationTime = fil.CreationTime;
                Console.WriteLine("{0} {1,12:NO} {2, 20:g} ", name.PadRight(45),
                    size, creationTime);
            }
        }

        else
        {
            Console.WriteLine("{0} not found - using current" +
                "directory:", score);
        }
        Console.ReadKey();
    }

    private void CalcAverage_Click(object sender, EventArgs e)
    {
        var c = new BasketballController("basketBallScore.txt");
        Debug.WriteLine(string.Format("Average {0}", c.Average));
        Debug.WriteLine(string.Format("First {0} {1}", c.Data.First().Name, c.Data.First().Value));
        Debug.WriteLine(string.Format("Last {0} {1}", c.Data.Last().Name, c.Data.Last().Value));
    }
}

}

This is what the text file contains:

Lebron James        31
Steph Curry         12
Kyrie Irving        37
Kevin Durant        9
Paul George         35
Klay Thompson       8
J.R.Smith           12
Zaza Pachulia       4
Tristan Thompson    10
Draymond Green      2

The program will access the file but will not give any output beyond the verification of the the data file. This is an updated version of a previous program. This was what I had previously:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;

namespace TextFiles
{
public partial class BasketBallStats : Form
{
    List<int> marks = new List<int>();

public BasketBallStats()
{
    InitializeComponent();
}

// Form load event handler used to construct
// object of the Streamwriter class, sending the
// new filename as an argument. Enclosed in
// try...catch block.
public class BasketballController
{
    public class Entry
    {
        public int Value { get; set; }
        public string Name { get; set; }
    }
    BasketballController(string filename)
    {
        this.filename = filename;
    }
    private string filename;
    private List<Entry> data = new List<Entry>();
    public List<Entry> Data
    {
        get
        {
            // Clear data
            data.Clear();
            // Iterate through lines
            foreach (string line in System.IO.File.ReadLines(filename))
            {
                // Split by space
                List<string> parts = line.Trim().Split(' ').ToList();
                if (parts.Count() < 2)
                    continue;
                // Number is last space separated string
                int number = int.Parse(parts.Last());
                // Remove number
                parts.RemoveAt(parts.Count() - 1);
                // Name is any previous word joined by space
                string name = string.Join(" ", parts).Trim();

                // Add number and name to data
                data.Add(new Entry() { Name = name, Value = number });
            }
            // Sort from greater value to smaller
            data.Sort(Comparer<Entry>.Create(
                (l, r) => r.Value.CompareTo(l.Value)));
            return data;
        }
        set
        {
            using (var writer = new System.IO.StreamWriter(filename))
            {
                foreach (var entry in value)
                {
                    writer.WriteLine(string.Format("{0} {1}", entry.Name, entry.Value));
                }
            }
            data = value;
        }
    }
    public double Average
    {
        get
        {
            // Read file if data is empty, otherwise reuse its value
            var src = (data.Count() == 0) ? Data : data;
            if (src.Count() == 0)
                return 0.0;
            // Return average
            return src.Average(x => x.Value);
        }
    }
}

private string score;

public List<int> Marks { get => Marks1; set => Marks1 = value; }
public List<int> Marks1 { get => marks; set => marks = value; }

private void BasketBallStats_Load(object sender, EventArgs e)
{

}

private void BtnCreateFile_Click(object sender, EventArgs e)
{
    score = "basketBallScore.txt";
    if (File.Exists(score))
    {
        Console.WriteLine("FileName: {0}", score);
        Console.WriteLine("Attributes: {0}",
            File.GetAttributes(score));
        Console.WriteLine("Created: {0}",
            File.GetCreationTime(score));
        Console.WriteLine("Last Accessed: {0}",
            File.GetLastAccessTime(score));

        DirectoryInfo dir = new DirectoryInfo(".");
        Console.WriteLine("Current Directory: \n{0} \n",
            Directory.GetCurrentDirectory());
        Console.WriteLine("File Name".PadRight(52) +
            "Size".PadRight(10) + "Creation Time");
        foreach (FileInfo fil in dir.GetFiles("*.*"))
        {
            string name = fil.Name;
            long size = fil.Length;
            DateTime creationTime = fil.CreationTime;
            Console.WriteLine("{0} {1,12:NO} {2, 20:g} ", name.PadRight(45),
                size, creationTime);
        }
    }

    else
    {
        Console.WriteLine("{0} not found - using current" +
            "directory:", score);
    }
    Console.ReadKey();
}

private void BtnWriteFile_Click(object sender, EventArgs e)
{
    try
    {
        var WriteToFile = new System.IO.StreamWriter("basketBallScore.txt"); //create textfile in default directory
        WriteToFile.Write(listView1.Text + ", " + listView1.Text + ", " + listView1.Text + ", " + listView1.Text);
        WriteToFile.Close();
        Marks.Add(Convert.ToInt32(listView1.Text)); //add to list
    }

    catch (System.IO.DirectoryNotFoundException)
    {
        lblMessage.Text = "File did not close properly: ";    //add error message
    }
}

private void ManipulateFile_Click(object sender, EventArgs e)
{
    int[] hoursArray = new int[30];
    StreamReader fileSR = new StreamReader("basketBallScore.txt");
    int counter = 0;
    string line = "";
    line = fileSR.ReadLine();
    while (line != null)
    {
        hoursArray[counter] = int.Parse(line);
        counter = counter + 1;
        line = fileSR.ReadLine();
    }
    fileSR.Close();

    int total = 0;
    double average = 0;
    for (int index = 0; index < hoursArray.Length; index++)
    {
        total = total + hoursArray[index];
    }
    average = (double)total / hoursArray.Length;

    int high = hoursArray[0];
    for (int index = 1; index < hoursArray.Length; index++)
    {
        if (hoursArray[index] > high)
        {
            high = hoursArray[index];
        }
    }
    Console.WriteLine("Highest number is: " + high);
    Console.WriteLine("The average is: " + average);
    Console.ReadLine();
}

private void BasketBallStats_Load_1(object sender, EventArgs e)
{

}

private void CalcAverage_Click(object sender, EventArgs e)
{
    int totalmarks = 0;
    foreach (int m in Marks)
        totalmarks += m;

    MessageBox.Show("Average Is: " + totalmarks / Marks.Count);
}

private void Button1_Click(object sender, EventArgs e)
{
    var c = new BasketballController("basketBallScore.txt");
    Debug.WriteLine(string.Format("Average {0}", c.Average));
    Debug.WriteLine(string.Format("First {0} {1}", c.Data.First().Name, c.Data.First().Value));
    Debug.WriteLine(string.Format("Last {0} {1}", c.Data.Last().Name, c.Data.Last().Value));
    }
  }
}

Body:
I was able to code a program that does exactly what I needed it to do. Here is what I have:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;

namespace BasketballScores
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void BtnOutputData_Click(object sender, EventArgs e)
    {
        try
        {
            string path = "basketBallScore.txt";
            var c = new BasketballPlayer(path);
            ListView1.Items.Add(string.Format("\r\nAverage {0}", c.Average));
            ListView1.Items.Add(string.Format("\r\nFirst {0} {1}", c.Data.First().Name, c.Data.First().Value));
            ListView1.Items.Add(string.Format("\r\nLast {0} {1}", c.Data.Last().Name, c.Data.Last().Value));
            using (StreamWriter sw = File.AppendText(path))
            {
                foreach (ListViewItem item in ListView1.Items)
                {
                    sw.WriteLine(item.Text);
                    for (int i = 1; i < item.SubItems.Count; i++)
                    {
                        sw.WriteLine(item.SubItems[i].Text);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            lblMessage.Text = ex.Message;
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void ListView1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
  }
}

This is a class I have with the code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BasketballScores
{
class BasketballPlayer
{
    public class Entry
    {
        public int Value { get; set; }
        public string Name { get; set; }
    }
public BasketballPlayer(string filename)
    {
        this.filename = filename;
    }
    private string filename;
    private List<Entry> data = new List<Entry>();
    public List<Entry> Data
    {
        get
        {
            // Clear data
            data.Clear();
            // Iterate through lines
            foreach (string line in System.IO.File.ReadLines(filename))
            {
                // Split by space
                List<string> parts = line.Trim().Split(' ').ToList();
                if (parts.Count() < 2)
                    continue;
                // Number is last space separated string
                int number = int.Parse(parts.Last());
                // Remove number
                parts.RemoveAt(parts.Count() - 1);
                // Name is any previous word joined by space
                string name = string.Join(" ", parts).Trim();

                // Add number and name to data
                data.Add(new Entry() { Name = name, Value = number });
            }
            // Sort from greater value to smaller
            data.Sort(Comparer<Entry>.Create(
                (l, r) => r.Value.CompareTo(l.Value)));
            return data;
        }
        set
        {
            using (var writer = new System.IO.StreamWriter(filename))
            {
                foreach (var entry in value)
                {
                    writer.WriteLine(string.Format("{0} {1}", entry.Name, entry.Value));
                }
            }
            data = value;
        }
    }
    public double Average
    {
        get
        {
            // Read file if data is empty, otherwise reuse its value
            var src = (data.Count() == 0) ? Data : data;
            if (src.Count() == 0)
                return 0.0;
            // Return average
            return src.Average(x => x.Value);
        }
    }
  }
}


来源: stackexchange

问:
How to override save() method of modelform class and added missing information?
I just started to learn Django and I had a question.

I'm trying to automatically add the missing information, when saving form data. I get to change/add the desired "cleaned_data" information by overriding save() method of modelform class, but changes are not recorded in the database. Actually, how to write the modified information? This is code:

```<code>def save(self, commit = True, *args, **kwargs):
    temp = ServiceMethods(url = self.cleaned_data.get('url'), wsdl_url = self.cleaned_data.get('wsdl_url'))

    if not temp.get_wsdl_url():
        temp.make_wsdl_url()

    if temp.get_wsdl_url():
        temp.make_wsdl()
        self.cleaned_data['wsdl_url'] = temp.get_wsdl_url()
        self.cleaned_data['wsdl_description'] = temp.get_wsdl_description()

    super(ServiceForm, self).save(commit = commit, *args, **kwargs)
</code>```

And model:

```<code>class Services(models.Model):
    name                = models.CharField('Имя', max_length=256)
    url                 = models.URLField('Ссылка', unique = True)
    wsdl_url            = models.URLField('Ссылка на WSDL-документ', blank=True)
    description         = models.TextField('Описание сервиса',blank=True)
    wsdl_description    = models.TextField('WSDL описание', blank=True, editable=False)
    added               = models.DateTimeField('Добавлено', auto_now_add=True)
</code>```

TIA

答: Try setting the data on self.instance instead of in self.cleaned_data, and let me know if that works.

ContentLicense: CC BY-SA 2.5

Body:
I just started to learn Django and I had a question.

I'm trying to automatically add the missing information, when saving form data. I get to change/add the desired "cleaned_data" information by overriding save() method of modelform class, but changes are not recorded in the database. Actually, how to write the modified information? This is code:

def save(self, commit = True, *args, **kwargs):
    temp = ServiceMethods(url = self.cleaned_data.get('url'), wsdl_url = self.cleaned_data.get('wsdl_url'))

    if not temp.get_wsdl_url():
        temp.make_wsdl_url()

    if temp.get_wsdl_url():
        temp.make_wsdl()
        self.cleaned_data['wsdl_url'] = temp.get_wsdl_url()
        self.cleaned_data['wsdl_description'] = temp.get_wsdl_description()

    super(ServiceForm, self).save(commit = commit, *args, **kwargs)

And model:

class Services(models.Model):
    name                = models.CharField('Имя', max_length=256)
    url                 = models.URLField('Ссылка', unique = True)
    wsdl_url            = models.URLField('Ссылка на WSDL-документ', blank=True)
    description         = models.TextField('Описание сервиса',blank=True)
    wsdl_description    = models.TextField('WSDL описание', blank=True, editable=False)
    added               = models.DateTimeField('Добавлено', auto_now_add=True)

TIA


问:
ui router back button issue
i am working on web app that uses ui-router version 0.3.2 and angular 1.5. i am having an issue with back button, when i hit the back button the url updates to appropriate state url, but does not reloads / renders the page. The controller of the new state (updated url) does not get executed. Following is my state config

```<code>$stateProvider
.state('home', {
  url: '/',
  reloadOnSearch: false,
  templateUrl: 'homePage.html',
  controller:'homeController'
})
.state('home.overView', {
  url:'overView',
  reloadOnSearch: false,
  views: {
    ovSB: {
      templateUrl: 'searchParameterBarTemplate.html',
      controller: 'searchParameterBarController'
    }
  }
})
.state('home.overView.result', {
  url:'/:docType?abc&xyz&type&user&temp1&temp2',
  abstract: true,
  reloadOnSearch: false,
  templateUrl: 'resultViewTemplate.html',
  controller : 'resultPanelController'
})
.state('home.overView.result.dashboard', {
  url:'',
  reloadOnSearch: false,
  views: {
    'chart': {
      templateUrl: 'chart-template.html',
      controller: 'chart-Controller'
    },
    'oVGrid': {
      templateUrl: 'ov-grid-template.html',
      controller: 'ov-grid-controller'
    },
    'filterGrid': {
      templateUrl: 'filter-stats-template.html',
      controller: 'filter-stats-controller'
    }
  }
})
.state('home.delta',{
  reloadOnSearch: false,
  url:'Delta',

  views:{
    pcSB:{
      templateUrl: 'search-parameterbar-delta-template.html',
      controller : 'search-parameterBar-delta-controller'
    }
  }
})
.state('home.delta.result',{
  url:'/:docType?xyz_1&abc_1&xyz_2&abc_2',

  reloadOnSearch: false,
  templateUrl: 'delta-template.html',
  controller : 'delta-controller'
})
.state('home.details', {
  url: 'details',

  views: {
    detailsSB: {
      templateUrl: 'search-paramBar-details-template.html',
      controller: 'search-paramBar-details-controller'
    }
  }
})
.state('home.details.result', {
  url: '/:documentType?abc&xyz&user&temp1&temp2',
  abstract: true,
  templateUrl: 'details-view-template.html',
  controller: 'details-view-controller'
})
.state('home.details.result.dashboard',{
  url:'',
  views:{
    perGraph : {
      controller :'per-graph-controller',
      templateUrl: 'per-graph-template.html'
    },
    detailsGrid: {
      controller: 'details-grid-controller',
      templateUrl: 'details-grid-controller-template.html'
    }
  }
});
</code>```

So for example if i navigate from home.overview.result.dashboard (url -> localhost:12345/overview/doctype?abc&xyz&user&temp1&temp2) state to home.details.result.dashboard state with url localhost:12345/details/doctype?abc&xyz&user&temp1&temp2 and hit backbutton, the url updates to localhost:12345/overview/doctype?abc&xyz&user&temp1&temp2 however it does not reloads/renders the page.

I believe I can you use this solution and trigger the reload, but I am looking for a better solution than this which adheres to ui router. is there something i am missing with state config / doing wrong? Any help pertaining to this would be highly appreciated.
Thank you

答:
it will be firing $stateChangeStart event. use location directive to rout it . please refer the below snippet

```<code>$rootScope.$on('$routeChangeStart', function (event,next) {
    $location.path(next.$$route.originalPath);
});
</code>```

this can resolve your problem. but its not the perfect solution

ContentLicense: CC BY-SA 3.0

Title: ui router back button issue

Body:
i am working on web app that uses ui-router version 0.3.2 and angular 1.5. i am having an issue with back button, when i hit the back button the url updates to appropriate state url, but does not reloads / renders the page. The controller of the new state (updated url) does not get executed. Following is my state config

$stateProvider
.state('home', {
  url: '/',
  reloadOnSearch: false,
  templateUrl: 'homePage.html',
  controller:'homeController'
})
.state('home.overView', {
  url:'overView',
  reloadOnSearch: false,
  views: {
    ovSB: {
      templateUrl: 'searchParameterBarTemplate.html',
      controller: 'searchParameterBarController'
    }
  }
})
.state('home.overView.result', {
  url:'/:docType?abc&xyz&type&user&temp1&temp2',
  abstract: true,
  reloadOnSearch: false,
  templateUrl: 'resultViewTemplate.html',
  controller : 'resultPanelController'
})
.state('home.overView.result.dashboard', {
  url:'',
  reloadOnSearch: false,
  views: {
    'chart': {
      templateUrl: 'chart-template.html',
      controller: 'chart-Controller'
    },
    'oVGrid': {
      templateUrl: 'ov-grid-template.html',
      controller: 'ov-grid-controller'
    },
    'filterGrid': {
      templateUrl: 'filter-stats-template.html',
      controller: 'filter-stats-controller'
    }
  }
})
.state('home.delta',{
  reloadOnSearch: false,
  url:'Delta',

  views:{
    pcSB:{
      templateUrl: 'search-parameterbar-delta-template.html',
      controller : 'search-parameterBar-delta-controller'
    }
  }
})
.state('home.delta.result',{
  url:'/:docType?xyz_1&abc_1&xyz_2&abc_2',

  reloadOnSearch: false,
  templateUrl: 'delta-template.html',
  controller : 'delta-controller'
})
.state('home.details', {
  url: 'details',

  views: {
    detailsSB: {
      templateUrl: 'search-paramBar-details-template.html',
      controller: 'search-paramBar-details-controller'
    }
  }
})
.state('home.details.result', {
  url: '/:documentType?abc&xyz&user&temp1&temp2',
  abstract: true,
  templateUrl: 'details-view-template.html',
  controller: 'details-view-controller'
})
.state('home.details.result.dashboard',{
  url:'',
  views:{
    perGraph : {
      controller :'per-graph-controller',
      templateUrl: 'per-graph-template.html'
    },
    detailsGrid: {
      controller: 'details-grid-controller',
      templateUrl: 'details-grid-controller-template.html'
    }
  }
});

So for example if i navigate from home.overview.result.dashboard (url -> localhost:12345/overview/doctype?abc&xyz&user&temp1&temp2) state to home.details.result.dashboard state with url localhost:12345/details/doctype?abc&xyz&user&temp1&temp2 and hit backbutton, the url updates to localhost:12345/overview/doctype?abc&xyz&user&temp1&temp2 however it does not reloads/renders the page.

I believe I can you use this solution and trigger the reload, but I am looking for a better solution than this which adheres to ui router. is there something i am missing with state config / doing wrong? Any help pertaining to this would be highly appreciated.
Thank you

Body:
it will be firing $stateChangeStart event. use location directive to rout it . please refer the below snippet

$rootScope.$on('$routeChangeStart', function (event,next) {
    $location.path(next.$$route.originalPath);
});

this can resolve your problem. but its not the perfect solution


问:
Play Sounds of Varying Varying Pitch Asynchronously and Concurrently
My goal is to use Python to play sounds with the following requirements in a computer game context.

Take some input WAV file and randomly Vary the pitch to +/- 50% of original. Changing the sample rate seems to be an easy way to do this with PyDub.

Play the sound.

Be able to call this function rapidly so that long and short duration sounds overlap in actual playback.

I have spent over 24 work-hours searching for a way to meet all these requirements. I have done this before in Visual Basic and I was surprised at how difficult it is in Python.

Here is what I know so far:

PyGame.Mixer can play overlapping sounds concurrently, but it must play them all at the same sample rate. There doesn't appear to be a way to vary pitch.

PyDub can vary pitch by changing samplerate, but it can't play overlapping sounds with its basic playback. And, I have to write the output sound to file then immediately load it back, which feels wasteful.

WinSound can play PyDub's varying-samplerate sounds, but not with concurrent playback, not even with threading.

Playsound package does not work with python 3.6.

PyAudio can play PyDub's varying-samplerate sounds with concurrent playback if I use Threading, however, any more than a couple times and it causes horrible memory problems that quickly make Python crash.

My question: How can I achieve my 3 goals above without causing problems?

Here is the best result that I have so far (this is the PyAudio version which causes a crash if tested more than once or twice):

```<code>from pydub import AudioSegment
from random import random, seed
from time import sleep
import os
import threading
import pyaudio
import wave

def PlayAsyncWithRandPitch(WavPath):
    MyBaseFilename = os.path.basename(WavPath)
    sound = AudioSegment.from_file(WavPath, format="wav")
    seed()
    octaves = ((random()-0.50))
    print("random octave factor for this sound is: "+str(octaves))
    print("current sound frame rate:"+str(sound.frame_rate))
    new_sample_rate = int(sound.frame_rate * (2.0 ** octaves))
    print("new sound frame rate:"+str(new_sample_rate))
    newpitchsound = sound._spawn(sound.raw_data, overrides={'frame_rate': new_sample_rate})
    MyTotalNewPath = os.getcwd()+"\\Soundfiles\\Temp\\Mod_"+MyBaseFilename
    newpitchsound.export(MyTotalNewPath, format="wav")
    SoundThread = threading.Thread(target=PAPlay, args=(MyTotalNewPath,))
    SoundThread.start()
#=======================================================================================

#This function is just code for playing a sound in PyAudio
def PAPlay(filename):
    CHUNK = 1024
    wf = wave.open(filename, 'rb')
    p = pyaudio.PyAudio()
    stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                    channels=wf.getnchannels(),
                    rate=wf.getframerate(),
                    output=True)
    data = wf.readframes(CHUNK)
    while data != '':
        stream.write(data)
        data = wf.readframes(CHUNK)
    stream.stop_stream()
    stream.close()
    p.terminate()
    return

if __name__ == "__main__":
    #Example sounds to test if more than one can play at once
    PlayAsyncWithRandPitch(os.getcwd()+'\\Soundfiles\\RifleMiss.WAV')
    sleep(0.2)
    PlayAsyncWithRandPitch(os.getcwd()+'\\Soundfiles\\splash.wav')
    sleep(0.2)
    PlayAsyncWithRandPitch(os.getcwd()+'\\Soundfiles\\sparkhit1.WAV')
    sleep(5.0)
</code>```

Thank you in advance for your kind help!

答:
This method seems kind of dubious. I explained how I do varispeed using Java to a C++ person on the following link.

The main idea is to use linear interpolation to get values from between the samples, and to progress through the sample data at a rate other than 1 by 1. If you are going 150% and need sample 0, then sample 1.5 (half way between 1 and 2), interpolate the value.

Body:
My goal is to use Python to play sounds with the following requirements in a computer game context.

Take some input WAV file and randomly Vary the pitch to +/- 50% of original. Changing the sample rate seems to be an easy way to do this with PyDub.

Play the sound.

Be able to call this function rapidly so that long and short duration sounds overlap in actual playback.

I have spent over 24 work-hours searching for a way to meet all these requirements. I have done this before in Visual Basic and I was surprised at how difficult it is in Python.

Here is what I know so far:

PyGame.Mixer can play overlapping sounds concurrently, but it must play them all at the same sample rate. There doesn't appear to be a way to vary pitch.

PyDub can vary pitch by changing samplerate, but it can't play overlapping sounds with its basic playback. And, I have to write the output sound to file then immediately load it back, which feels wasteful.

WinSound can play PyDub's varying-samplerate sounds, but not with concurrent playback, not even with threading.

Playsound package does not work with python 3.6.

PyAudio can play PyDub's varying-samplerate sounds with concurrent playback if I use Threading, however, any more than a couple times and it causes horrible memory problems that quickly make Python crash.

My question: How can I achieve my 3 goals above without causing problems?

Here is the best result that I have so far (this is the PyAudio version which causes a crash if tested more than once or twice):

from pydub import AudioSegment
from random import random, seed
from time import sleep
import os
import threading
import pyaudio
import wave

def PlayAsyncWithRandPitch(WavPath):
    MyBaseFilename = os.path.basename(WavPath)
    sound = AudioSegment.from_file(WavPath, format="wav")
    seed()
    octaves = ((random()-0.50))
    print("random octave factor for this sound is: "+str(octaves))
    print("current sound frame rate:"+str(sound.frame_rate))
    new_sample_rate = int(sound.frame_rate * (2.0 ** octaves))
    print("new sound frame rate:"+str(new_sample_rate))
    newpitchsound = sound._spawn(sound.raw_data, overrides={'frame_rate': new_sample_rate})
    MyTotalNewPath = os.getcwd()+"\\Soundfiles\\Temp\\Mod_"+MyBaseFilename
    newpitchsound.export(MyTotalNewPath, format="wav")
    SoundThread = threading.Thread(target=PAPlay, args=(MyTotalNewPath,))
    SoundThread.start()
#=======================================================================================

#This function is just code for playing a sound in PyAudio
def PAPlay(filename):
    CHUNK = 1024
    wf = wave.open(filename, 'rb')
    p = pyaudio.PyAudio()
    stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                    channels=wf.getnchannels(),
                    rate=wf.getframerate(),
                    output=True)
    data = wf.readframes(CHUNK)
    while data != '':
        stream.write(data)
        data = wf.readframes(CHUNK)
    stream.stop_stream()
    stream.close()
    p.terminate()
    return

if __name__ == "__main__":
    #Example sounds to test if more than one can play at once
    PlayAsyncWithRandPitch(os.getcwd()+'\\Soundfiles\\RifleMiss.WAV')
    sleep(0.2)
    PlayAsyncWithRandPitch(os.getcwd()+'\\Soundfiles\\splash.wav')
    sleep(0.2)
    PlayAsyncWithRandPitch(os.getcwd()+'\\Soundfiles\\sparkhit1.WAV')
    sleep(5.0)

Thank you in advance for your kind help!


问:
Map relational database to XML in C#
I have an application that needs to map relational database to XML.
The issue is that the database structure is given (I cannot change it) and the XML Schema is given (comes from WSDL).

I need to let the user of my application to tell the system that a given column in a table is mapped to a given element in the schema. Then my application needs to crate XMLs based on the database data.

Is there a technology that can help me? is there a C# control for that.

Thanks

答: Select...For sounds simpler; but LINQ in your C# is probably another option.</p>

OwnerDisplayName: Ragoler

Title: Map relational database to XML in C#

LastEditorDisplayName: Fabian Steeg


问:
Django Queryset two problems
my queryset :

```<code>Status.objects.filter(date__gte='2017-07-05', date__lt='2017-07-09', type='X').update(value=F('value') + 1)
</code>```

my database :

```<code>date       | value | value1 | value2 | type
2017-07-05 |   0   |    0   |    0   |  X
2017-07-06 |   0   |    0   |    0   |  X
2017-07-07 |   0   |    0   |    0   |  X
2017-07-08 |   0   |    0   |    0   |  X
2017-07-09 |   0   |    0   |    0   |  X
2017-07-10 |   0   |    0   |    0   |  X
</code>```

I have two question, but my above queryset don't work.

1 - How update field "value" in date range ?

2 - How to replace "value" with a variable ?

update(value=F('value') + 1)

I need to dynamically select field (value1, value2, valuse3) from the database to change value.

答:
you can path a field name with a variable using this.</p>

```<code>somename='some_field'  #value.value1,... in your case
Status.objects.filter(Q(date__gte='2017-07-05'), Q(date__lt='2017-07-09'), Q(type='X')).update(**{somename: F(somename)+1})
</code>```

Title: Django Queryset two problems

Body:
my queryset :

Status.objects.filter(date__gte='2017-07-05', date__lt='2017-07-09', type='X').update(value=F('value') + 1)

my database :

date       | value | value1 | value2 | type
2017-07-05 |   0   |    0   |    0   |  X
2017-07-06 |   0   |    0   |    0   |  X
2017-07-07 |   0   |    0   |    0   |  X
2017-07-08 |   0   |    0   |    0   |  X
2017-07-09 |   0   |    0   |    0   |  X
2017-07-10 |   0   |    0   |    0   |  X

I have two question, but my above queryset don't work.

1 - How update field "value" in date range ?

2 - How to replace "value" with a variable ?

update(value=F('value') + 1)

I need to dynamically select field (value1, value2, valuse3) from the database to change value.

Body:
you can path a field name with a variable using this.

somename='some_field'  #value.value1,... in your case
Status.objects.filter(Q(date__gte='2017-07-05'), Q(date__lt='2017-07-09'), Q(type='X')).update(**{somename: F(somename)+1})


问:
Make field mandatory in import
I have one mandatory  field in my entity X, but while importing data, I can create records even if I dont give that mandatory field a value, which is not good.
How could I make that field mandatory even while importing?

Thanks in advance,

答:
Business rules with scope of "Entity" is the simplest no code solution to enforce this scenario.

For example, bulk data import, workflows, plugins, API/SDK calls would bypass the CRM forms and therefore would also bypass any JavaScript or form Business Rule validations you might have configured. These type of server-side validation had typically required plugins or synchronous workflows.

Luckily, business rules now have a new scope “Entity” which applies at the server level instead of the form level. What this means is that these business rules, just like plugins and sync workflows, will execute even if you are not using a CRM form in your transaction because they happen on the platform (server side) instead of the form (browser/client side).

Link to learn more: https://community.dynamics.com/crm/b/gonzaloruiz/archive/2016/08/15/business-rules-vs-sync-workflows-in-crm

Title: Make field mandatory in import


问:
Partial dependency
Suppose we have a relation R(A,B,C,D,E) with candidate keys {A,B} , {C,D} and let E be a non prime attribute.

If there is a dependency C->E then it is partial dependency as E depends on a part of candidate key {C,D}

Is dependency BC->E partial?

答:
If there is a dependency C->E then it is partial dependency as E depends on a part of candidate key {C,D}

That "as" is unsound. It doesn't appeal to the definition of "partial functional dependency". We need to memorize & apply definitions exactly. (What published academic reference(s) are you using?)

FD X → Y is partial when it holds and some proper/smaller subset of X also determines Y. If all X attributes are in the relation then FD X → Y is partial when some proper/smaller subset of X also determines Y. (Because Armstrong's axioms say that the subset FD implies the X FD.)

Here FD C → E is partial when {} → E. (Ie when all rows have the same E value.) Armstrong's axioms say certain other FDs also hold since AB & CD are keys. The combined FDs that hold can't make E prime. But it turns out that we still can't know whether {} → E holds. So if C → E then we can't know whether C partially determines E.

Is dependency BC->E partial?

Here FD BC → E is partial when some proper/smaller subset of BC determines E. Ie when B → E, C → E or {} → E. It turns out that we can't know whether any of those four FDs hold. So we can't know whether BC → E, let alone whether it is partial. Although if B → E or C → E then FD BC → E is partial. (Because B & C are proper/smaller subsets of BC.)

(Normally we know a cover for the FDs that hold, which determines all FDs that hold, which determines the CKs and the non-prime attributes. Then because we know all the FDs that hold, we can determine which ones are partial. CKs are irrelevant to whether a FD is partial.)

Title: Partial dependency


问:
Add a page to SSRS report
I want to add a page to SSRS report, which can be toggle on/off based on a radio button selection.

The reason I want to add a page is so I can add additional report logic information for the functional users.  Is it possible to add a page (with several text boxes) in SSRS report and show/hide based on parameter value?

NOTE:*  One approach I could use is to add a rectangle and control its visibility via parameter.  However, when hidden, it leaves a blank space behind.  Is there a way to get rid of this blank space?

答: You can do this with a table component. Add a detail row and a footer row and set the dataset to read from SELECT 1=1. You can put a rectangle in the rows and build out your report in the first row and then optionally show/hide the footer row.</p>

Title: Add a page to SSRS report


问:
DICOM image viewing on Web app
I need to know if DICOM image needs to be shown on Browser, which approach should be followed?
My Image server is some where else on cloud. need to access the dicom image, paint in canvas, if user edits then upload the edited image to server.
Need to have good performance as well, as DICOM images are very huge in size(~1gb)
Which is the best way to do this?</p>

答:
1) DICOM images aren't usually modified by users. (maybe annotations or window/center values), but it's different.

2) Most DICOM images are ~1Mb, so yours are very special. I doubt that most standard viewers would load them.

3) No display is able to show 1Gb at a time, so it's enough to send a small-resolution version of image (max 1mpx), and just send updates for zoomed areas.

Given all this, you'll have to explain better your question.

Title: DICOM image viewing on Web app


问:
Creating new records in dataframe based on character
I have fields in a pandas dataframe like the sample data below.  The values in one of the fields are fractions with the form something/count(something).  I would like to split the values like the example output below, and create new records.  Basically the numerator and the denominator.  Some of the values even have multiple /, like count(something)/count(thing)/count(dog).  So I'd want to split that value in to 3 records.  Any tips on how to do this would be greatly appreciated.</p>

```<code>Sample Data:

SampleDf=pd.DataFrame([['tom','sum(stuff)/count(things)'],['bob','count(things)/count(stuff)']],columns=['ReportField','OtherField'])

Example Output:

OutputDf=pd.DataFrame([['tom1','sum(stuff)'],['tom2','count(things)'],['bob1','count(things)'],['bob2','count(stuff)']],columns=['ReportField','OtherField'])
</code>```

答:
There might be a better way but try this,

```<code>df = df.set_index('ReportField')
df = pd.DataFrame(df.OtherField.str.split('/', expand = True).stack().reset_index(-1, drop = True)).reset_index()
</code>```

You get

```<code>    ReportField 0
0   tom         sum(stuff)
1   tom         count(things)
2   bob         count(things)
3   bob         count(stuff)
</code>```

Body:
I have fields in a pandas dataframe like the sample data below.  The values in one of the fields are fractions with the form something/count(something).  I would like to split the values like the example output below, and create new records.  Basically the numerator and the denominator.  Some of the values even have multiple /, like count(something)/count(thing)/count(dog).  So I'd want to split that value in to 3 records.  Any tips on how to do this would be greatly appreciated.

Sample Data:

SampleDf=pd.DataFrame([['tom','sum(stuff)/count(things)'],['bob','count(things)/count(stuff)']],columns=['ReportField','OtherField'])

Example Output:

OutputDf=pd.DataFrame([['tom1','sum(stuff)'],['tom2','count(things)'],['bob1','count(things)'],['bob2','count(stuff)']],columns=['ReportField','OtherField'])

Body:
There might be a better way but try this,

df = df.set_index('ReportField')
df = pd.DataFrame(df.OtherField.str.split('/', expand = True).stack().reset_index(-1, drop = True)).reset_index()

You get

    ReportField 0
0   tom         sum(stuff)
1   tom         count(things)
2   bob         count(things)
3   bob         count(stuff)


问:
Android Async Problems?
I have a function which returns a list after doing an operation on 700 images.
The function takes some time and hence the app freezes. How to overcome this problem?
I am returning a list of all the images to be displayed so I am stuck now.
Any suggestions with a code will be helpful.</p>

答:
So you have 1x main UI and 700x images that you want to manage?

You could have a variable of public view in the UI thread called "finishedImages", then the same method in each of the 700x return data threads that:

```<code>increments finishedImages
if finishedImages == 700

 then run 1x public method to do the update of the UI
</code>```

. Only then will it update the UI on your background asychtasks.

Title: Android Async Problems?

Body:
So you have 1x main UI and 700x images that you want to manage?

You could have a variable of public view in the UI thread called "finishedImages", then the same method in each of the 700x return data threads that:

increments finishedImages
if finishedImages == 700

 then run 1x public method to do the update of the UI

. Only then will it update the UI on your background asychtasks.


问:
Save data in python
I'm a little stuck here. I'm running a twitter api request loop and I need to store these tweets in a csv file. I'm doing something like:

```<code>for tweet in tweepy.Cursor(api.search,q=search+ lang="en").items(num_tweets):
    data = tweet.text
    print (tweet.text)
</code>```

My question is what's the easiest way to save tweets in this format:

```<code>["Hello world. I love Reddit!", "Lorem ipsum dolor sit amaet."]
</code>```

答:
You mean saving the tweets list to csv?

Alternative way using pandas:

```<code>import pandas
df = pandas.DataFrame(data={'tweets':tweet_list})
df.to_csv('./tweets.csv',index=False)
</code>```

See http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html for more.

Title: Save data in python

Body:
I'm a little stuck here. I'm running a twitter api request loop and I need to store these tweets in a csv file. I'm doing something like:

for tweet in tweepy.Cursor(api.search,q=search+ lang="en").items(num_tweets):
    data = tweet.text
    print (tweet.text)

My question is what's the easiest way to save tweets in this format:

["Hello world. I love Reddit!", "Lorem ipsum dolor sit amaet."]

Body:
You mean saving the tweets list to csv?

Alternative way using pandas:

import pandas
df = pandas.DataFrame(data={'tweets':tweet_list})
df.to_csv('./tweets.csv',index=False)

See http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html for more.


问:
Nodejs : passport-local-mongoose's .plugin(...) doesn't do anything
I'm trying to use passport-local-mongoose in order to register users in my MongoDB database. However it seems like it's not doing what it is supposed to.

Model:

```<code>var userSchema = new mongoose.Schema({
    email: {
        type: String,
        ...
    },
});

userSchema.plugin(passportLocalMongoose, {usernameField: 'email'});

userSchema.statics = {
    ...
}

userSchema.methods = {
    ...
}

var User = mongoose.model('User', userSchema);
module.exports = User;
</code>```

Controller:

```<code>exports.registerAction = async (req, res, next) => {
    const user = new User({ email: req.body.email });
    User.register(user, req.body.password, function() {
        res.send('It works!');
    });
</code>```

As I understand it, Passport is supposed to implement the register method on User, but here User.register stays undefined.

What am I doing wrong?

答:
I found the solution by myself.

The userSchema.plugin(...) call has to be made after defininguserSchema.statics = {…} and userSchema.methods = {…}.

I guess .plugin(...) tries to use the statics or methods property (or both), and initializes them as an new object. Then, when we call userSchema.statics = {…} (or methods), it simply erases what .plugin(...) had created.

Body:
I'm trying to use passport-local-mongoose in order to register users in my MongoDB database. However it seems like it's not doing what it is supposed to.

Model:

var userSchema = new mongoose.Schema({
    email: {
        type: String,
        ...
    },
});

userSchema.plugin(passportLocalMongoose, {usernameField: 'email'});

userSchema.statics = {
    ...
}

userSchema.methods = {
    ...
}

var User = mongoose.model('User', userSchema);
module.exports = User;

Controller:

exports.registerAction = async (req, res, next) => {
    const user = new User({ email: req.body.email });
    User.register(user, req.body.password, function() {
        res.send('It works!');
    });

As I understand it, Passport is supposed to implement the register method on User, but here User.register stays undefined.

What am I doing wrong?


问:
Get result back from comint-redirect-send-command
I want to read the output of a buffer after process started by comint finishes.

```<code>(comint-redirect-send-command-to-process
                 command-string ;; tested to work in the commint buffer
                 output-buffer-name ;; random text
                 buffer-process ;; (get-buffer-process (current-buffer))
                 nil ;; don't echo input back
                 t) ;; don't show output buffer immediatly
</code>```

This sexp is evaluated in a buffer running a comint process. I want to read all the text of output-buffer-name once the process has finished.

I have tried applying the solution posted to this question: sleep in emacs lisp by adding this below the process start command:

```<code>(defun on-status-change (process status)
        (message "status done"))

(set-process-sentinel buffer-process 'on-status-change)
</code>```

This message does not appear in *Messages*.

There is no prompt in the output-buffer text, but I can write a function that returns t when the output is finished based on the full output text.

How can I react to the buffer finishing/changing, or how can I force comint to run this function synchronously.

The source for comint-redirect-send-command-to-process is here on line 3717

答:
If anyone else has a similar issue, I ended up "solving" this.

```<code>(while (not comint-redirect-completed)
  (sleep-for 0.01))
</code>```

comint-redirect-completed’s value is nil

Documentation:
  Non-nil if redirection has completed in the current buffer.

Obviously not a great solution, but I couldn't get anything else working.

Body:
I want to read the output of a buffer after process started by comint finishes.

(comint-redirect-send-command-to-process
                 command-string ;; tested to work in the commint buffer
                 output-buffer-name ;; random text
                 buffer-process ;; (get-buffer-process (current-buffer))
                 nil ;; don't echo input back
                 t) ;; don't show output buffer immediatly

This sexp is evaluated in a buffer running a comint process. I want to read all the text of output-buffer-name once the process has finished.

I have tried applying the solution posted to this question: sleep in emacs lisp by adding this below the process start command:

(defun on-status-change (process status)
        (message "status done"))

(set-process-sentinel buffer-process 'on-status-change)

This message does not appear in *Messages*.

There is no prompt in the output-buffer text, but I can write a function that returns t when the output is finished based on the full output text.

How can I react to the buffer finishing/changing, or how can I force comint to run this function synchronously.

The source for comint-redirect-send-command-to-process is here on line 3717

Body:
If anyone else has a similar issue, I ended up "solving" this.

(while (not comint-redirect-completed)
  (sleep-for 0.01))

comint-redirect-completed’s value is nil

Documentation:
  Non-nil if redirection has completed in the current buffer.

Obviously not a great solution, but I couldn't get anything else working.


问:
Firebase on Android - I want to disable firebase notifications on Android client
I'm using Firebase console to send notifications to users.
However I want to let users disable notifications.
How can I disable them?

I am able to handle (and stop) notifications through FirebaseMessagingService only when the app is in foreground. But I cannot stop notifications when the app is in background.

答:
I had this problem.and solved by use below code:

Enable Firebase Notifications:

```<code>FirebaseInstanceId.getInstance().getToken();
</code>```

Disable Firebase Notifications:
  deleteInstanceId() is a blocking call. It cannot be called on the main thread.

```<code>FirebaseInstanceId.getInstance().deleteInstanceId();
</code>```

Body:
I had this problem.and solved by use below code:

Enable Firebase Notifications:

FirebaseInstanceId.getInstance().getToken();

Disable Firebase Notifications:
  deleteInstanceId() is a blocking call. It cannot be called on the main thread.

FirebaseInstanceId.getInstance().deleteInstanceId();


问:
Unexpected error when using a reference of vector in a third pary function
I am supposed to input an array of values for x in the below third party function.

```<code>bool MyNLP::get_starting_point(Index n, bool init_x, double* x,
                           bool init_z, double* z_L, double* z_U,
                           Index m, bool init_lambda,
                           double* lambda)
{
      //example
      x[0] =0.5;
      x[1] =1.5;

      //similarly other values also initialized.

      return true;
}
</code>```

I got the correct result.

NEXT CASE

Now instead of entering values of x directly, I used vector of values which is a member of class nlp.

```<code>class nlp
{
std::vector<double> m_val;

public:
std::vector<double>& get_val()
{
     m_val.push_back(0.5);
     m_val.push_back(1.5);
     return m_val;
}
}
</code>```

I called function get_val inside the thied party function.

```<code>bool MyNLP::get_starting_point(Index n, bool init_x, double* x,
                           bool init_z, double* z_L, double* z_U,
                           Index m, bool init_lambda,
                           double* lambda)
{
      //example
      //x = &(m_nlp->get_val()).at(0);
      std::vector<double>& values = m_nlp->get_val();
      x = &values.at(0);
      assert(x[0] == 0.5);
      assert(x[1] == 1.5);

      //similarly other values also initialized.

      return true;
}
</code>```

I initialized the x with the same values as before in the first case, but the output was different. My assertions didn't fail too. I don't have clue about what is happening here.

What could  be the reason for two different outputs?

答:
In your first version you're indirecting through x to modify the elements of the caller's array.

In the second program you're reassigning the local pointer variable x to point to the data in the vector. This has no effect on the caller's array, since x was passed by value, not by reference.

You need to copy the values from the vector to the array.

```<code>bool MyNLP::get_starting_point(Index n, bool init_x, double* x,
                           bool init_z, double* z_L, double* z_U,
                           Index m, bool init_lambda,
                           double* lambda)
{
      //example
      //x = &(m_nlp->get_val()).at(0);
      std::vector<double>& values = m_nlp->get_val();
      for (int i = 0; i < values.size(); i++) {
        x[i] = values[i];
      }

      return true;
}
</code>```

Another option is to change the code so x is passed by referenced: double *&x. But this will require changes to the callers: they shouldn't allocate memory for the pointer they pass, because it will not be freed (unless you add delete[] x to this function). And they'll have to pass a pointer variable, not an array that's implicitly decayed to a pointer.

Body:
I am supposed to input an array of values for x in the below third party function.

bool MyNLP::get_starting_point(Index n, bool init_x, double* x,
                           bool init_z, double* z_L, double* z_U,
                           Index m, bool init_lambda,
                           double* lambda)
{
      //example
      x[0] =0.5;
      x[1] =1.5;

      //similarly other values also initialized.

      return true;
}

I got the correct result.

NEXT CASE

Now instead of entering values of x directly, I used vector of values which is a member of class nlp.

class nlp
{
std::vector<double> m_val;

public:
std::vector<double>& get_val()
{
     m_val.push_back(0.5);
     m_val.push_back(1.5);
     return m_val;
}
}

I called function get_val inside the thied party function.

bool MyNLP::get_starting_point(Index n, bool init_x, double* x,
                           bool init_z, double* z_L, double* z_U,
                           Index m, bool init_lambda,
                           double* lambda)
{
      //example
      //x = &(m_nlp->get_val()).at(0);
      std::vector<double>& values = m_nlp->get_val();
      x = &values.at(0);
      assert(x[0] == 0.5);
      assert(x[1] == 1.5);

      //similarly other values also initialized.

      return true;
}

I initialized the x with the same values as before in the first case, but the output was different. My assertions didn't fail too. I don't have clue about what is happening here.

What could  be the reason for two different outputs?

Body:
In your first version you're indirecting through x to modify the elements of the caller's array.

In the second program you're reassigning the local pointer variable x to point to the data in the vector. This has no effect on the caller's array, since x was passed by value, not by reference.

You need to copy the values from the vector to the array.

bool MyNLP::get_starting_point(Index n, bool init_x, double* x,
                           bool init_z, double* z_L, double* z_U,
                           Index m, bool init_lambda,
                           double* lambda)
{
      //example
      //x = &(m_nlp->get_val()).at(0);
      std::vector<double>& values = m_nlp->get_val();
      for (int i = 0; i < values.size(); i++) {
        x[i] = values[i];
      }

      return true;
}

Another option is to change the code so x is passed by referenced: double *&x. But this will require changes to the callers: they shouldn't allocate memory for the pointer they pass, because it will not be freed (unless you add delete[] x to this function). And they'll have to pass a pointer variable, not an array that's implicitly decayed to a pointer.


问:
Unable to start process c:\Program Files\dotnet\dotnet.exe
I am making crud operation in asp.net core and yesterday everything was working fine for me. Today morning when I start work on tutorial I have got error which says Unable to start process c:\Program Files\dotnet\dotnet.exe.

I have tried the link to resolve the error but not getting success.
Please help me. Thanks in advance I will appriciate your help :)

HttpFailure_11-07-23.html Says:

答:
Run as admin for this type of error for those looking for an answer.
  - right click and set "properties" to run as administrator</p>


问:
Windows App. Thread Aborting Issue
I'm working on an application that has to make specific decisions based on files that are placed into a folder being watched by a file watcher.

Part of this decision making process involves renaming files before moving them off to another folder to be processed.

Since I'm working with files of all different sizes I created an object that checks the file in a seperate thread to verify that it is "available" and when it is it fires an event.

When I run the rename code from inside this available event it works.

```<code>public void RenameFile_Test()
{
    string psFilePath = @"C:\File1.xlsx";
    tgt_File target = new FileObject(psFilePath);
    target.FileAvailable += new FileEventHandler(OnFileAvailable);
    target.FileUnAvailable += new FileEventHandler(OnFileUnavailable);
}

private void OnFileAvailable(object source, FileEventArgs e)
{
    ((FileObject)source).RenameFile(@"C:\File2.xlsx");
}
</code>```

The problem I'm running into is that when the extensions are different from the source file and the rename to file I am making a call to a conversion factory that returns a factory object based on the type of conversion and then converts the file accordingly before doing the rename.  When I run that particular piece of code in unit test it works, the factory object is returned, and the conversion happens correctly.

But when I run it within the process I get up to the...

```<code>        moExcelApp = new Application();
</code>```

part of converting an .xls or .xlsx to a .csv and i get a "Thread was being Aborted" error.

Any thoughts?

Update:

There is a bit more information and a bit of map of how the application works currently.

Client Application running FSW

On File Created event Creates a FileObject passing in the path of the file.

On construction the file is validated: if file exists is true then,

```<code>Thread toAvailableCheck = new Thread(new ThreadStart(AvailableCheck));
toAvailableCheck.Start();
</code>```

The AvailableCheck Method repeatedly tries to open a streamreader to the file until the reader is either created or the number of attempts times out.  If the reader is opened, it fires the FileAvailable event, if not it fires the FileUnAvailable event, passing back itself in the event.

The client application is wired to catch those events from inside the Oncreated event of the FSW.

the OnFileAvailable method then calls the rename functionality which contains the excel interop call.

If the file is being renamed (not converted, extensions stay the same) it does a move to change the name from the old file name to the new, and if its a conversion it runs a conversion factory object which returns the correct type of conversion based on the extensions of the source file and the destination file name.

If it is a simple rename it works w/o a problem.  If its a conversion (which is the XLS to CSV object that is returned as a part of the factory) the very first thing it does is create a new application object.  That is where the application bombs.

When i test the factory and conversion/rename process outside of the thread and in its own unit test the process works w/o a problem.

Update:

I tested the Excel Interop inside a thread by doing this:

```<code>[TestMethod()]
public void ExcelInteropTest()
{
    Thread toExcelInteropThreadTest = new Thread(new ThreadStart(Instantiate_App));
    toExcelInteropThreadTest.Start();
}

private void Instantiate_App()
{
    Application moExcelApp = new Application();
    moExcelApp.Quit();
}
</code>```

And on the line where the application is instatntiated I got the 'A first chance exception of type 'System.Threading.ThreadAbortException' error.

So I added;

```<code>toExcelInteropThreadTest.SetApartmentState(ApartmentState.MTA);
</code>```

after the thread instantiation and before the thread start call and still got the same error.  I'm getting the notion that I'm going to have to reconsider the design.

答:
Somebody is calling Thread.Abort().  That could be the CLR, trying to shut your program down because of an unhandled exception.  The reason you might see the ThreadAbortException instead of the real exception is because you are using a COM server (like Excel) in a thread that isn't a single threaded apartment.  Check the docs for Thread.SetApartmentState().  Threadpool threads like the ones that FileSystemWatcher uses to raise events cannot be STA.

Also check the Output window for debugger notifications and use Debug + Exceptions, Thrown box to make the debugger stop on the first exception.

Title: Windows App. Thread Aborting Issue

Body:
I'm working on an application that has to make specific decisions based on files that are placed into a folder being watched by a file watcher.

Part of this decision making process involves renaming files before moving them off to another folder to be processed.

Since I'm working with files of all different sizes I created an object that checks the file in a seperate thread to verify that it is "available" and when it is it fires an event.

When I run the rename code from inside this available event it works.

public void RenameFile_Test()
{
    string psFilePath = @"C:\File1.xlsx";
    tgt_File target = new FileObject(psFilePath);
    target.FileAvailable += new FileEventHandler(OnFileAvailable);
    target.FileUnAvailable += new FileEventHandler(OnFileUnavailable);
}

private void OnFileAvailable(object source, FileEventArgs e)
{
    ((FileObject)source).RenameFile(@"C:\File2.xlsx");
}

The problem I'm running into is that when the extensions are different from the source file and the rename to file I am making a call to a conversion factory that returns a factory object based on the type of conversion and then converts the file accordingly before doing the rename.  When I run that particular piece of code in unit test it works, the factory object is returned, and the conversion happens correctly.

But when I run it within the process I get up to the...

        moExcelApp = new Application();

part of converting an .xls or .xlsx to a .csv and i get a "Thread was being Aborted" error.

Any thoughts?

Update:

There is a bit more information and a bit of map of how the application works currently.

Client Application running FSW

On File Created event Creates a FileObject passing in the path of the file.

On construction the file is validated: if file exists is true then,

Thread toAvailableCheck = new Thread(new ThreadStart(AvailableCheck));
toAvailableCheck.Start();

The AvailableCheck Method repeatedly tries to open a streamreader to the file until the reader is either created or the number of attempts times out.  If the reader is opened, it fires the FileAvailable event, if not it fires the FileUnAvailable event, passing back itself in the event.

The client application is wired to catch those events from inside the Oncreated event of the FSW.

the OnFileAvailable method then calls the rename functionality which contains the excel interop call.

If the file is being renamed (not converted, extensions stay the same) it does a move to change the name from the old file name to the new, and if its a conversion it runs a conversion factory object which returns the correct type of conversion based on the extensions of the source file and the destination file name.

If it is a simple rename it works w/o a problem.  If its a conversion (which is the XLS to CSV object that is returned as a part of the factory) the very first thing it does is create a new application object.  That is where the application bombs.

When i test the factory and conversion/rename process outside of the thread and in its own unit test the process works w/o a problem.

Update:

I tested the Excel Interop inside a thread by doing this:

[TestMethod()]
public void ExcelInteropTest()
{
    Thread toExcelInteropThreadTest = new Thread(new ThreadStart(Instantiate_App));
    toExcelInteropThreadTest.Start();
}

private void Instantiate_App()
{
    Application moExcelApp = new Application();
    moExcelApp.Quit();
}

And on the line where the application is instatntiated I got the 'A first chance exception of type 'System.Threading.ThreadAbortException' error.

So I added;

toExcelInteropThreadTest.SetApartmentState(ApartmentState.MTA);

after the thread instantiation and before the thread start call and still got the same error.  I'm getting the notion that I'm going to have to reconsider the design.


问:
pinch and zoom on apple mapkit swift
I have been able to implement MapKit into my app, but it currently looks the map in one static position.

I have been struggling to add the pinch and zoom functionality as well as the ability to allow users to explore other regions on the map.

Here is what my current code looks like:

```<code>import UIKit
import MapKit
import CoreLocation

class HotPlacesViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {

@IBOutlet weak var mapView: MKMapView!

var locationManager = CLLocationManager()
let newPin = MKPointAnnotation()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.

    // Setup the location services delegate in this class.
    locationManager.delegate = self

    // This little method requests the users permission for location services whilst in this view controller.
    if CLLocationManager.authorizationStatus() == .notDetermined {
        self.locationManager.requestAlwaysAuthorization()
    let alert = UIAlertController(title: "You can change this option in the Settings App", message: "So keep calm your selection is not permanent. ",
                                  preferredStyle: .alert)

        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))

        self.present(alert, animated: true, completion: nil)
    }

    locationManager.distanceFilter = kCLDistanceFilterNone
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.startUpdatingLocation()

}

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

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

}

// Drops the pin on the users current location.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    mapView.removeAnnotation(newPin)

    let location = locations.last! as CLLocation
    let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))

    // Set the region on the map.
    mapView.setRegion(region, animated: true)

    newPin.coordinate = location.coordinate
    mapView.addAnnotation(newPin)

}
</code>```

}

答:
```<code>let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
mapView.setRegion(region, animated: true)
</code>```

Set span for zoom in MapKit

Title: pinch and zoom on apple mapkit swift

Body:
I have been able to implement MapKit into my app, but it currently looks the map in one static position.

I have been struggling to add the pinch and zoom functionality as well as the ability to allow users to explore other regions on the map.

Here is what my current code looks like:

import UIKit
import MapKit
import CoreLocation

class HotPlacesViewController: UIViewController, CLLocationManagerDelegate, MKMapViewDelegate {

@IBOutlet weak var mapView: MKMapView!

var locationManager = CLLocationManager()
let newPin = MKPointAnnotation()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.

    // Setup the location services delegate in this class.
    locationManager.delegate = self

    // This little method requests the users permission for location services whilst in this view controller.
    if CLLocationManager.authorizationStatus() == .notDetermined {
        self.locationManager.requestAlwaysAuthorization()
    let alert = UIAlertController(title: "You can change this option in the Settings App", message: "So keep calm your selection is not permanent. ",
                                  preferredStyle: .alert)

        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))

        self.present(alert, animated: true, completion: nil)
    }

    locationManager.distanceFilter = kCLDistanceFilterNone
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.startUpdatingLocation()

}

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

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

}

// Drops the pin on the users current location.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    mapView.removeAnnotation(newPin)

    let location = locations.last! as CLLocation
    let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))

    // Set the region on the map.
    mapView.setRegion(region, animated: true)

    newPin.coordinate = location.coordinate
    mapView.addAnnotation(newPin)

}

}

Body:
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
mapView.setRegion(region, animated: true)

Set span for zoom in MapKit


问:
Algorithm that finds the N-th most frequent number in the array
I want to write an algorithm that finds the n-th most frequent number in an array.
I have a solution but not optimal (testing numbers i've already tested)
I wonder if there is a more optimal solution?
Here is my Solution :</p>

```<code>most_freq_element(a,n){
final_cnt = 0, curr_cnt = 1, final_freq_num = -1, curr_freq_num = -1;
for(i = 0; i < n-1; i++)
{
    if (a[i]!=-1){
        curr_freq_num = a[i];
        for(j =i+1; j < n; j++){
            if(curr_freq_num == a[j] && final_freq_num != curr_freq_num){
                curr_cnt++;
            }
        }
        if(final_cnt < curr_cnt){
            final_cnt = curr_cnt;
            curr_cnt = 1;
            final_freq_num = curr_freq_num;
        }
    }
}
printf("Num = %d and times = %d", final_freq_num, final_cnt);
}

nth_most_frequent_element(a,n,k){
if(k==1){
    return most_freq_element(a,n);
}
else{
    for (i=0;i<k;i++){
        int most_freq_num = most_freq_element(a,n);

        for(i = 0; i < n-1; i++){
            if (a[i]==most_freq_num){
                a[i]=-1;
            }
        }
    }
    return most_freq_element(a,n);
}
}
</code>```

答:
How about this ? Worst complexity is O(2.N.logN + k.min(k,d)), d: number of unique values in a</p>

```<code>most_freq_element(a[0..n-1],n,k)
{
  count[0..k], value[0..k];   // k + 1 elements
  i, j, l;

  qsort(a, n)

  j = 0;
  l = 0;
  value[0] = a[0];
  count[0] = 1;
  for (i = 1; i < n; ++i)
  {
     if (a[i] != value[j])
     {
        if (++l > k) l = k;
        j = l;
        value[j] = a[i];
        count[j] = 0;
     }

     ++count[j];

     while (j > 0 && count[j] > count[j - 1])
     {
        swap(count[j], count[j - 1]);
        swap(value[j], value[j - 1]);
        --j;
     }
  }
  printf("Num = %d and times = %d", value[k - 1], count[k - 1]);
}
</code>```

Body:
I want to write an algorithm that finds the n-th most frequent number in an array.
I have a solution but not optimal (testing numbers i've already tested)
I wonder if there is a more optimal solution?
Here is my Solution :

most_freq_element(a,n){
final_cnt = 0, curr_cnt = 1, final_freq_num = -1, curr_freq_num = -1;
for(i = 0; i < n-1; i++)
{
    if (a[i]!=-1){
        curr_freq_num = a[i];
        for(j =i+1; j < n; j++){
            if(curr_freq_num == a[j] && final_freq_num != curr_freq_num){
                curr_cnt++;
            }
        }
        if(final_cnt < curr_cnt){
            final_cnt = curr_cnt;
            curr_cnt = 1;
            final_freq_num = curr_freq_num;
        }
    }
}
printf("Num = %d and times = %d", final_freq_num, final_cnt);
}

nth_most_frequent_element(a,n,k){
if(k==1){
    return most_freq_element(a,n);
}
else{
    for (i=0;i<k;i++){
        int most_freq_num = most_freq_element(a,n);

        for(i = 0; i < n-1; i++){
            if (a[i]==most_freq_num){
                a[i]=-1;
            }
        }
    }
    return most_freq_element(a,n);
}
}

Body:
How about this ? Worst complexity is O(2.N.logN + k.min(k,d)), d: number of unique values in a

most_freq_element(a[0..n-1],n,k)
{
  count[0..k], value[0..k];   // k + 1 elements
  i, j, l;

  qsort(a, n)

  j = 0;
  l = 0;
  value[0] = a[0];
  count[0] = 1;
  for (i = 1; i < n; ++i)
  {
     if (a[i] != value[j])
     {
        if (++l > k) l = k;
        j = l;
        value[j] = a[i];
        count[j] = 0;
     }

     ++count[j];

     while (j > 0 && count[j] > count[j - 1])
     {
        swap(count[j], count[j - 1]);
        swap(value[j], value[j - 1]);
        --j;
     }
  }
  printf("Num = %d and times = %d", value[k - 1], count[k - 1]);
}


问:
How to have clusters of stacked bars
So here is how my data set looks like :

```<code>In [1]: df1=pd.DataFrame(np.random.rand(4,2),index=["A","B","C","D"],columns=["I","J"])

In [2]: df2=pd.DataFrame(np.random.rand(4,2),index=["A","B","C","D"],columns=["I","J"])

In [3]: df1
Out[3]:
          I         J
A  0.675616  0.177597
B  0.675693  0.598682
C  0.631376  0.598966
D  0.229858  0.378817

In [4]: df2
Out[4]:
          I         J
A  0.939620  0.984616
B  0.314818  0.456252
C  0.630907  0.656341
D  0.020994  0.538303
</code>```

I want to have stacked bar plot for each dataframe but since they have same index, I'd like to have 2 stacked bars per index.

I've tried to plot both on the same axes :

```<code>In [5]: ax = df1.plot(kind="bar", stacked=True)

In [5]: ax2 = df2.plot(kind="bar", stacked=True, ax = ax)
</code>```

But it overlaps.

Then I tried to concat the two dataset first :

```<code>pd.concat(dict(df1 = df1, df2 = df2),axis = 1).plot(kind="bar", stacked=True)
</code>```

but here everything is stacked

My best try is :

```<code> pd.concat(dict(df1 = df1, df2 = df2),axis = 0).plot(kind="bar", stacked=True)
</code>```

Which gives :

This is basically what I want, except that I want the bar ordered as

(df1,A) (df2,A) (df1,B) (df2,B) etc...

I guess there is a trick but I can't found it !

After @bgschiller's answer I got this :

Which is almost what I want. I would like the bar to be clustered by index, in order to have something visually clear.

Bonus : Having the x-label not redundant, something like :

```<code>df1 df2    df1 df2
_______    _______ ...
   A          B
</code>```

答:
Altair can be helpful here. Here is the produced plot.

Imports

```<code>import pandas as pd
import numpy as np
from altair import *
</code>```

Dataset creation

```<code>df1=pd.DataFrame(10*np.random.rand(4,2),index=["A","B","C","D"],columns=["I","J"])
df2=pd.DataFrame(10*np.random.rand(4,2),index=["A","B","C","D"],columns=["I","J"])
</code>```

Preparing dataset

```<code>def prep_df(df, name):
    df = df.stack().reset_index()
    df.columns = ['c1', 'c2', 'values']
    df['DF'] = name
    return df

df1 = prep_df(df1, 'DF1')
df2 = prep_df(df2, 'DF2')

df = pd.concat([df1, df2])
</code>```

Altair plot

```<code>Chart(df).mark_bar().encode(y=Y('values', axis=Axis(grid=False)),
                            x='c2:N',
                            column=Column('c1:N') ,
                            color='DF:N').configure_facet_cell( strokeWidth=0.0).configure_cell(width=200, height=200)
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to have clusters of stacked bars

Body:
So here is how my data set looks like :

In [1]: df1=pd.DataFrame(np.random.rand(4,2),index=["A","B","C","D"],columns=["I","J"])

In [2]: df2=pd.DataFrame(np.random.rand(4,2),index=["A","B","C","D"],columns=["I","J"])

In [3]: df1
Out[3]:
          I         J
A  0.675616  0.177597
B  0.675693  0.598682
C  0.631376  0.598966
D  0.229858  0.378817

In [4]: df2
Out[4]:
          I         J
A  0.939620  0.984616
B  0.314818  0.456252
C  0.630907  0.656341
D  0.020994  0.538303

I want to have stacked bar plot for each dataframe but since they have same index, I'd like to have 2 stacked bars per index.

I've tried to plot both on the same axes :

In [5]: ax = df1.plot(kind="bar", stacked=True)

In [5]: ax2 = df2.plot(kind="bar", stacked=True, ax = ax)

But it overlaps.

Then I tried to concat the two dataset first :

pd.concat(dict(df1 = df1, df2 = df2),axis = 1).plot(kind="bar", stacked=True)

but here everything is stacked

My best try is :

 pd.concat(dict(df1 = df1, df2 = df2),axis = 0).plot(kind="bar", stacked=True)

Which gives :

This is basically what I want, except that I want the bar ordered as

(df1,A) (df2,A) (df1,B) (df2,B) etc...

I guess there is a trick but I can't found it !

After @bgschiller's answer I got this :

Which is almost what I want. I would like the bar to be clustered by index, in order to have something visually clear.

Bonus : Having the x-label not redundant, something like :

df1 df2    df1 df2
_______    _______ ...
   A          B

Body:
Altair can be helpful here. Here is the produced plot.

Imports

import pandas as pd
import numpy as np
from altair import *

Dataset creation

df1=pd.DataFrame(10*np.random.rand(4,2),index=["A","B","C","D"],columns=["I","J"])
df2=pd.DataFrame(10*np.random.rand(4,2),index=["A","B","C","D"],columns=["I","J"])

Preparing dataset

def prep_df(df, name):
    df = df.stack().reset_index()
    df.columns = ['c1', 'c2', 'values']
    df['DF'] = name
    return df

df1 = prep_df(df1, 'DF1')
df2 = prep_df(df2, 'DF2')

df = pd.concat([df1, df2])

Altair plot

Chart(df).mark_bar().encode(y=Y('values', axis=Axis(grid=False)),
                            x='c2:N',
                            column=Column('c1:N') ,
                            color='DF:N').configure_facet_cell( strokeWidth=0.0).configure_cell(width=200, height=200)