text:
Q: Why can't I connect to postgres from Perl? I believe i have set up Pg properly, but my script doesn't seem to be connecting to the database. I am testing with:

$database="networkem";
$user="postgres";
$password="";
$host="localhost";

$dbh = DBI->connect("DBI:Pg:dbname=$dbname;host=$host", $user, $password);

My pg_hba reads:

host  all  postgres   127.0.0.1  255.255.255.255   trust

I can use psql just fine via command-line and have started postmaster with -i option. What am I missing?
I also tried with another user that works fine via psql:

$user="jimbo"; $password="p2ssw0rd";

with pg_hba reading:

host    all    jimbo   127.0.0.1    255.255.255.255    trust

A: Rather than play 20 questions to debug your setup, DBI->errstr will say why the connection failed.
my $dbh = DBI->connect(...) or die DBI->errstr;

Though if I had to guess... since Postgres authenticates based on host and login user, I suspect the confusion lies between the user name you're giving to the Postgres connection and the Unix user you're logged in as.

A: Besides Schwern's excellent response, you can also check PostgreSQL log which, depending on the options selected in postgresql.conf may tell you a lot about what was wrong.

A: It is recommended that you use the 'listen_addresses' configuration option in your postgresql.conf instead of '-i' on the command line. For example:
listen_addresses = '*'

Try executing the following command as the same user you are running your perl script with:
psql -U postgres -h localhost networkem

The '-h localhost' forces a network connection instead of a Unix socket connection.  If that command works, your perl script should also work.

A: I had the same issue. The hint above for trying "-h localhost" confirmed that I had a problem connecting over the network.
Adding the following to pg_hba.conf fixed the problem.
host all postgres 127.0.0.1/32 trust

A: DBI may be connecting to either the IPv4 or IPv6 postgresql server interface, depending on how things are configured.
So you may need both of these lines in pg_hba.conf:
IPv4:
host  all  <user>  127.0.0.1/32  trust

IPv6:
host  all  <user>  ::1/128       trust


text:
Q: Probability of independent exponential random variables I'm working on a problem from Klenke's book on probability theory:
I want to prove that if $X$ and $Y$ are independent exponentially distributed random variables with parameters $\theta$ and $\rho$ respectively, then
$$
\mathrm{P}\left(X < Y\right) = {\theta \over \theta + \rho}
$$
I'm having trouble proving this; I want to avoid using conditional probability because Klenke introduces this problem way before conditional probability. I'm guessing the densities of $X$ or $Y$ may come into play but I'm not sure how.
Any suggestions ?.

A: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
&\int_{0}^{\infty}\int_{0}^{\infty}
\pars{\theta\expo{-\theta x}}\pars{\rho\expo{-\rho y}}\bracks{x < y}
\,\dd x\,\dd y =
\theta\rho\int_{0}^{\infty}\expo{-\rho y}\
\overbrace{\int_{0}^{y}
\expo{-\theta x}\,\dd x}^{\ds{\expo{-\theta y} - 1 \over -\theta}}\
\,\dd y
\\[5mm] = &\
\rho\int_{0}^{\infty}\bracks{\expo{-\rho y} - \expo{-\pars{\rho + \theta}y}}
\dd y =
1 - {\rho \over \rho + \theta} = \bbx{\theta \over \rho + \theta}
\end{align}

A: Hint
Use the fact that for every borel measurable set $B\subset \mathbb{R}^2$ we have:
\begin{align}
\mathbb{P}((X,Y)\in B)  = \iint_B f_{X, Y} (x, y) \, dx\,dy
\end{align}
Where $f_{X, Y} (x, y)$ is the joint density of $(X, Y) $. But we know $X$ and $Y$ are independent, so $f_{X, Y} (x, y)=f_X(x) f_Y(y) $.
You must choose $B$ such that:
\begin{align}
(X, Y) \in B \Longleftrightarrow X<Y
\end{align}
I'll leave the choice of $B$ and the integration that comes after that for you.

A: \begin{align}
\Pr(X<Y) & = \int_0^\infty \left( \int_x^\infty \rho\theta e^{-\theta x} e^{-\rho y} \, dy \right) \,dx = \int_0^\infty \left( \theta e^{-\theta x} e^{-\rho x}  \right) \, dx \\[10pt]
& = \theta \int_0^\infty e^{-(\theta+\rho)x} \,dx = \frac\theta{\theta+\rho}.
\end{align}
This is a bit simpler than evaluating the iteratted integral in the opposite order.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sorting A ListView By Column Currently I use a custom sorter on the listview, and i can sort the listview each time i click on the FIRST column, but it won't sort by other columns.
SortStyle: Variable to determine whether it is Ascending Sort, or Descending.
if (e.Column == 0)
{
    if (SortStyle == 0)
    {
        List.ListViewItemSorter = customSortDsc;
        SortStyle = 1;
    }
    else
    {
        List.ListViewItemSorter = customSortAsc;
        SortStyle = 0;
    }
}

This works fine when sorting for the first column, but if you were to do it on any other column, it would just sort by the first column. Is there a way to sort by the column clicked?

A: I sort using column name to set any sorting specifics that may need to be handled based on data type stored in the column and or if the column has already been sorted on(asc/desc). Here's a snippet from my ColumnClick event handler.
private void listView_ColumnClick(object sender, ColumnClickEventArgs e)
    {
        ListViewItemComparer sorter = GetListViewSorter(e.Column);

        listView.ListViewItemSorter = sorter;
        listView.Sort();
    }

    private ListViewItemComparer GetListViewSorter(int columnIndex)
    {
        ListViewItemComparer sorter = (ListViewItemComparer)listView.ListViewItemSorter;
        if (sorter == null)
        {
            sorter = new ListViewItemComparer();
        }

        sorter.ColumnIndex = columnIndex;

        string columnName = packagedEstimateListView.Columns[columnIndex].Name;
        switch (columnName)
        {
            case ApplicationModel.DisplayColumns.DateCreated:
            case ApplicationModel.DisplayColumns.DateUpdated:
                sorter.ColumnType = ColumnDataType.DateTime;
                break;
            case ApplicationModel.DisplayColumns.NetTotal:
            case ApplicationModel.DisplayColumns.GrossTotal:
                sorter.ColumnType = ColumnDataType.Decimal;
                break;
            default:
                sorter.ColumnType = ColumnDataType.String;
                break;
        }

        if (sorter.SortDirection == SortOrder.Ascending)
        {
            sorter.SortDirection = SortOrder.Descending;
        }
        else
        {
            sorter.SortDirection = SortOrder.Ascending;
        }

        return sorter;
    }

Below is my ListViewItemComparer
public class ListViewItemComparer : IComparer
{
    private int _columnIndex;
    public int ColumnIndex
    {
        get
        {
            return _columnIndex;
        }
        set
        {
            _columnIndex = value;
        }
    }

    private SortOrder _sortDirection;
    public SortOrder SortDirection
    {
        get
        {
            return _sortDirection;
        }
        set
        {
            _sortDirection = value;
        }
    }

    private ColumnDataType _columnType;
    public ColumnDataType ColumnType
    {
        get
        {
            return _columnType;
        }
        set
        {
            _columnType = value;
        }
    }

    public ListViewItemComparer()
    {
        _sortDirection = SortOrder.None;
    }

    public int Compare(object x, object y)
    {
        ListViewItem lviX = x as ListViewItem;
        ListViewItem lviY = y as ListViewItem;

        int result;

        if (lviX == null && lviY == null)
        {
            result = 0;
        }
        else if (lviX == null)
        {
            result = -1;
        }

        else if (lviY == null)
        {
            result = 1;
        }

        switch (ColumnType)
        {
            case ColumnDataType.DateTime:
                DateTime xDt = DataParseUtility.ParseDate(lviX.SubItems[ColumnIndex].Text);
                DateTime yDt = DataParseUtility.ParseDate(lviY.SubItems[ColumnIndex].Text);
                result = DateTime.Compare(xDt, yDt);
                break;

            case ColumnDataType.Decimal:
                Decimal xD = DataParseUtility.ParseDecimal(lviX.SubItems[ColumnIndex].Text.Replace("$", string.Empty).Replace(",", string.Empty));
                Decimal yD = DataParseUtility.ParseDecimal(lviY.SubItems[ColumnIndex].Text.Replace("$", string.Empty).Replace(",", string.Empty));
                result = Decimal.Compare(xD, yD);
                break;
            case ColumnDataType.Short:
                short xShort = DataParseUtility.ParseShort(lviX.SubItems[ColumnIndex].Text);
                short yShort = DataParseUtility.ParseShort(lviY.SubItems[ColumnIndex].Text);
                result = xShort.CompareTo(yShort);
                break;
            case ColumnDataType.Int:
                int xInt = DataParseUtility.ParseInt(lviX.SubItems[ColumnIndex].Text);
                int yInt = DataParseUtility.ParseInt(lviY.SubItems[ColumnIndex].Text);
                return xInt.CompareTo(yInt);
                break;
            case ColumnDataType.Long:
                long xLong = DataParseUtility.ParseLong(lviX.SubItems[ColumnIndex].Text);
                long yLong = DataParseUtility.ParseLong(lviY.SubItems[ColumnIndex].Text);
                return xLong.CompareTo(yLong);
                break;
            default:

                result = string.Compare(
                    lviX.SubItems[ColumnIndex].Text,
                    lviY.SubItems[ColumnIndex].Text,
                    false);

                break;
        }

        if (SortDirection == SortOrder.Descending)
        {
            return -result;
        }
        else
        {
            return result;
        }
    }
}

A: Made minor changes to the article here to accommodate sorting of both string and numeric values in ListView.
Form1.cs contains
using System;
using System.Windows.Forms;

namespace ListView
{
    public partial class Form1 : Form
    {
        Random rnd = new Random();
        private ListViewColumnSorter lvwColumnSorter;

        public Form1()
        {
            InitializeComponent();
            // Create an instance of a ListView column sorter and assign it to the ListView control.
            lvwColumnSorter = new ListViewColumnSorter();
            this.listView1.ListViewItemSorter = lvwColumnSorter;

            InitListView();
        }

        private void InitListView()
        {
            listView1.View = View.Details;
            listView1.GridLines = true;
            listView1.FullRowSelect = true;

            //Add column header
            listView1.Columns.Add("Name", 100);
            listView1.Columns.Add("Price", 70);
            listView1.Columns.Add("Trend", 70);

            for (int i = 0; i < 10; i++)
            {
                listView1.Items.Add(AddToList("Name" + i.ToString(), rnd.Next(1, 100).ToString(), rnd.Next(1, 100).ToString()));
            }
        }

        private ListViewItem AddToList(string name, string price, string trend)
        {
            string[] array = new string[3];
            array[0] = name;
            array[1] = price;
            array[2] = trend;

            return (new ListViewItem(array));
        }

        private void listView1_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            // Determine if clicked column is already the column that is being sorted.
            if (e.Column == lvwColumnSorter.SortColumn)
            {
                // Reverse the current sort direction for this column.
                if (lvwColumnSorter.Order == SortOrder.Ascending)
                {
                    lvwColumnSorter.Order = SortOrder.Descending;
                }
                else
                {
                    lvwColumnSorter.Order = SortOrder.Ascending;
                }
            }
            else
            {
                // Set the column number that is to be sorted; default to ascending.
                lvwColumnSorter.SortColumn = e.Column;
                lvwColumnSorter.Order = SortOrder.Ascending;
            }

            // Perform the sort with these new sort options.
            this.listView1.Sort();
        }

    }
}

ListViewColumnSorter.cs contains
using System;
using System.Collections;
using System.Windows.Forms;

///
/// This class is an implementation of the 'IComparer' interface.
///
public class ListViewColumnSorter : IComparer
{
    ///
    /// Specifies the column to be sorted
    ///
    private int ColumnToSort;
    ///
    /// Specifies the order in which to sort (i.e. 'Ascending').
    ///
    private SortOrder OrderOfSort;
    ///
    /// Case insensitive comparer object
    ///
    private CaseInsensitiveComparer ObjectCompare;

    ///
    /// Class constructor.  Initializes various elements
    ///
    public ListViewColumnSorter()
    {
        // Initialize the column to '0'
        ColumnToSort = 0;

        // Initialize the sort order to 'none'
        OrderOfSort = SortOrder.None;

        // Initialize the CaseInsensitiveComparer object
        ObjectCompare = new CaseInsensitiveComparer();
    }

    ///
    /// This method is inherited from the IComparer interface.  It compares the two objects passed using a case insensitive comparison.
    ///
    /// <param name="x">First object to be compared</param>
    /// <param name="y">Second object to be compared</param>
    /// <returns>The result of the comparison. "0" if equal, negative if 'x' is less than 'y' and positive if 'x' is greater than 'y'</returns>
    public int Compare(object x, object y)
    {
        int compareResult;
        ListViewItem listviewX, listviewY;

        // Cast the objects to be compared to ListViewItem objects
        listviewX = (ListViewItem)x;
        listviewY = (ListViewItem)y;

        decimal num = 0;
        if (decimal.TryParse(listviewX.SubItems[ColumnToSort].Text, out num))
        {
            compareResult = decimal.Compare(num, Convert.ToDecimal(listviewY.SubItems[ColumnToSort].Text));
        }
        else
        {
            // Compare the two items
            compareResult = ObjectCompare.Compare(listviewX.SubItems[ColumnToSort].Text, listviewY.SubItems[ColumnToSort].Text);
        }

        // Calculate correct return value based on object comparison
        if (OrderOfSort == SortOrder.Ascending)
        {
            // Ascending sort is selected, return normal result of compare operation
            return compareResult;
        }
        else if (OrderOfSort == SortOrder.Descending)
        {
            // Descending sort is selected, return negative result of compare operation
            return (-compareResult);
        }
        else
        {
            // Return '0' to indicate they are equal
            return 0;
        }
    }

    ///
    /// Gets or sets the number of the column to which to apply the sorting operation (Defaults to '0').
    ///
    public int SortColumn
    {
        set
        {
            ColumnToSort = value;
        }
        get
        {
            return ColumnToSort;
        }
    }

    ///
    /// Gets or sets the order of sorting to apply (for example, 'Ascending' or 'Descending').
    ///
    public SortOrder Order
    {
        set
        {
            OrderOfSort = value;
        }
        get
        {
            return OrderOfSort;
        }
    }

}

A: i used this trick
private void lv_TavComEmpty_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            ListView lv = (ListView)sender;

            //propriety SortOrder make me some problem on graphic layout
            //i use this tag to set last order
            if (lv.Tag == null || (int)lv.Tag > 0)
            //if (lv.Sorting == SortOrder.Ascending)
            {
                ListViewItem[] tmp = lv.Items.Cast<ListViewItem>().OrderBy(t => t.SubItems[e.Column].Text).ToArray();
                lv.Items.Clear();
                lv.Items.AddRange(tmp);

                lv.Tag = -1;
                //lv.Sorting = SortOrder.Descending;
            }
            else
            {
                ListViewItem[] tmp = lv.Items.Cast<ListViewItem>().OrderByDescending(t => t.SubItems[e.Column].Text).ToArray();
                lv.Items.Clear();
                lv.Items.AddRange(tmp);

                lv.Tag = +1;
                //lv.Sorting = SortOrder.Ascending;
            }
        }

A: Forget about your custom sorter. Start over using the code at the following page. It will show you how to define a class that inherits from the IComparer interface. Each line is commented out, so you can actually see what is happening. The only potential complication is how you are retrieving your Listview Items from your Listview control. Get those squared away and all you need to do is copy and paste the IComparer interface class and the columnClick method.
http://support.microsoft.com/kb/319401

A: If you are starting out with a ListView, do yourself a huge favour and use an ObjectListView instead. ObjectListView is an open source wrapper around .NET WinForms ListView, which makes the ListView much easier to use and solves lots of common problems for you. Sorting by column click is one of the many things it handles for you automatically.
Seriously, you will never regret using an ObjectListView instead of a normal ListView.

*

*ObjectListView Home Page

*ObjectListView Nuget Package

A: My solution is a class to sort listView items when you click on column header.
You can specify the type of each column.
listView.ListViewItemSorter = new ListViewColumnSorter();
listView.ListViewItemSorter.ColumnsTypeComparer.Add(0, DateTime);
listView.ListViewItemSorter.ColumnsTypeComparer.Add(1, int);

That's it !
The C# class :
using System.Collections;
using System.Collections.Generic;
using EDV;

namespace System.Windows.Forms
{
    ///
    /// Cette classe est une implémentation de l'interface 'IComparer' pour le tri des items de ListView. Adapté de http://support.microsoft.com/kb/319401.
    ///
    /// <remarks>Intégré par EDVariables.</remarks>
    public class ListViewColumnSorter : IComparer
    {
        ///
        /// Spécifie la colonne à trier
        ///
        private int ColumnToSort;
        ///
        /// Spécifie l'ordre de tri (en d'autres termes 'Croissant').
        ///
        private SortOrder OrderOfSort;
        ///
        /// Objet de comparaison ne respectant pas les majuscules et minuscules
        ///
        private CaseInsensitiveComparer ObjectCompare;

        ///
        /// Constructeur de classe.  Initialise la colonne sur '0' et aucun tri
        ///
        public ListViewColumnSorter()
            : this(0, SortOrder.None) { }

        ///
        /// Constructeur de classe.  Initializes various elements
        /// <param name="columnToSort">Spécifie la colonne à trier</param>
        /// <param name="orderOfSort">Spécifie l'ordre de tri</param>
        ///
        public ListViewColumnSorter(int columnToSort, SortOrder orderOfSort)
        {
            // Initialise la colonne
            ColumnToSort = columnToSort;

            // Initialise l'ordre de tri
            OrderOfSort = orderOfSort;

            // Initialise l'objet CaseInsensitiveComparer
            ObjectCompare = new CaseInsensitiveComparer();

            // Dictionnaire de comparateurs
            ColumnsComparer = new Dictionary<int, IComparer>();
            ColumnsTypeComparer = new Dictionary<int, Type>();

        }

        ///
        /// Cette méthode est héritée de l'interface IComparer.  Il compare les deux objets passés en effectuant une comparaison
        ///qui ne tient pas compte des majuscules et des minuscules.
        ///
Si le comparateur n'existe pas dans ColumnsComparer, CaseInsensitiveComparer est utilisé.
        ///
        /// <param name="x">Premier objet à comparer</param>
        /// <param name="x">Deuxième objet à comparer</param>
        /// <returns>Le résultat de la comparaison. "0" si équivalent, négatif si 'x' est inférieur à 'y'
        ///et positif si 'x' est supérieur à 'y'</returns>
        public int Compare(object x, object y)
        {
            int compareResult;
            ListViewItem listviewX, listviewY;

            // Envoit les objets à comparer aux objets ListViewItem
            listviewX = (ListViewItem)x;
            listviewY = (ListViewItem)y;

            if (listviewX.SubItems.Count < ColumnToSort + 1 || listviewY.SubItems.Count < ColumnToSort + 1)
                return 0;

            IComparer objectComparer = null;
            Type comparableType = null;
            if (ColumnsComparer == null || !ColumnsComparer.TryGetValue(ColumnToSort, out objectComparer))
                if (ColumnsTypeComparer == null || !ColumnsTypeComparer.TryGetValue(ColumnToSort, out comparableType))
                    objectComparer = ObjectCompare;

            // Compare les deux éléments
            if (comparableType != null) {
                //Conversion du type
                object valueX = listviewX.SubItems[ColumnToSort].Text;
                object valueY = listviewY.SubItems[ColumnToSort].Text;
                if (!edvTools.TryParse(ref valueX, comparableType) || !edvTools.TryParse(ref valueY, comparableType))
                    return 0;
                compareResult = (valueX as IComparable).CompareTo(valueY);
            }
            else
                compareResult = objectComparer.Compare(listviewX.SubItems[ColumnToSort].Text, listviewY.SubItems[ColumnToSort].Text);

            // Calcule la valeur correcte d'après la comparaison d'objets
            if (OrderOfSort == SortOrder.Ascending) {
                // Le tri croissant est sélectionné, renvoie des résultats normaux de comparaison
                return compareResult;
            }
            else if (OrderOfSort == SortOrder.Descending) {
                // Le tri décroissant est sélectionné, renvoie des résultats négatifs de comparaison
                return (-compareResult);
            }
            else {
                // Renvoie '0' pour indiquer qu'ils sont égaux
                return 0;
            }
        }

        ///
        /// Obtient ou définit le numéro de la colonne à laquelle appliquer l'opération de tri (par défaut sur '0').
        ///
        public int SortColumn
        {
            set
            {
                ColumnToSort = value;
            }
            get
            {
                return ColumnToSort;
            }
        }

        ///
        /// Obtient ou définit l'ordre de tri à appliquer (par exemple, 'croissant' ou 'décroissant').
        ///
        public SortOrder Order
        {
            set
            {
                OrderOfSort = value;
            }
            get
            {
                return OrderOfSort;
            }
        }

        ///
        /// Dictionnaire de comparateurs par colonne.
        ///
Pendant le tri, si le comparateur n'existe pas dans ColumnsComparer, CaseInsensitiveComparer est utilisé.
        ///
        public Dictionary<int, IComparer> ColumnsComparer { get; set; }

        ///
        /// Dictionnaire de comparateurs par colonne.
        ///
Pendant le tri, si le comparateur n'existe pas dans ColumnsTypeComparer, CaseInsensitiveComparer est utilisé.
        ///
        public Dictionary<int, Type> ColumnsTypeComparer { get; set; }
    }
}

Initializing a ListView :
    <var>Visual.WIN.ctrlListView.OnShown</var>  :
    eventSender.Columns.Clear();
    eventSender.SmallImageList = edvWinForm.ImageList16;
    eventSender.ListViewItemSorter = new ListViewColumnSorter();
    var col = eventSender.Columns.Add("Répertoire");
    col.Width = 160;
    col.ImageKey = "Domain";
    col = eventSender.Columns.Add("Fichier");
    col.Width = 180;
    col.ImageKey = "File";
    col = eventSender.Columns.Add("Date");
    col.Width = 120;
    col.ImageKey = "DateTime";
    eventSender.ListViewItemSorter.ColumnsTypeComparer.Add(col.Index, DateTime);
    col = eventSender.Columns.Add("Position");
    col.TextAlign = HorizontalAlignment.Right;
    col.Width = 80;
    col.ImageKey = "Num";
    eventSender.ListViewItemSorter.ColumnsTypeComparer.Add(col.Index, Int32);

Fill a ListView :
<var>Visual.WIN.cmdSearch.OnClick</var>  :
//non récursif et sans fonction
    ..ctrlListView:Items.Clear();
    ..ctrlListView:Sorting = SortOrder.None;
    var group = ..ctrlListView:Groups.Add(DateTime.Now.ToString()
                , Path.Combine(..cboDir:Text, ..ctrlPattern1:Text) + " contenant " + ..ctrlSearch1:Text);
    var perf =  Environment.TickCount;

    var files = new DirectoryInfo(..cboDir:Text).GetFiles(..ctrlPattern1:Text)
    var search = ..ctrlSearch1:Text;
    var ignoreCase = ..Search.IgnoreCase;
    //var result = new StringBuilder();
    var dirLength : int = ..cboDir:Text.Length;
    var position : int;
    var added : int = 0;
    for(var i : int = 0; i < files.Length; i++){
        var file = files[i];
        if(search == ""
        || (position = File.ReadAllText(file.FullName).IndexOf(String(search)
                            , StringComparison(ignoreCase ? StringComparison.InvariantCultureIgnoreCase : StringComparison.InvariantCulture))) > =0) {

        //  result.AppendLine(file.FullName.Substring(dirLength) + "\tPos : " + pkvFile.Value);
            var item = ..ctrlListView:Items.Add(file.FullName.Substring(dirLength));
            item.SubItems.Add(file.Name);
            item.SubItems.Add(File.GetLastWriteTime(file.FullName).ToString());
            item.SubItems.Add(position.ToString("# ### ##0"));
            item.Group = group;
            ++added;
        }
    }
    group.Header += " : " + added + "/" + files.Length + " fichier(s)"
                + "  en " + (Environment.TickCount - perf).ToString("# ##0 msec");

On ListView column click :
<var>Visual.WIN.ctrlListView.OnColumnClick</var>  :
// Déterminer si la colonne sélectionnée est déjà la colonne triée.
var sorter = eventSender.ListViewItemSorter;
if ( eventArgs.Column == sorter .SortColumn )
{
    // Inverser le sens de tri en cours pour cette colonne.
    if (sorter.Order == SortOrder.Ascending)
    {
        sorter.Order = SortOrder.Descending;
    }
    else
    {
        sorter.Order = SortOrder.Ascending;
    }
}
else
{
    // Définir le numéro de colonne à trier ; par défaut sur croissant.
    sorter.SortColumn = eventArgs.Column;
    sorter.Order = SortOrder.Ascending;
}

// Procéder au tri avec les nouvelles options.
eventSender.Sort();

Function edvTools.TryParse used above
class edvTools {
    ///
    /// Tente la conversion d'une valeur suivant un type EDVType
    ///
    /// <param name="pValue">Référence de la valeur à convertir</param>
    /// <param name="pType">Type EDV en sortie</param>
    /// <returns></returns>
    public static bool TryParse(ref object pValue, System.Type pType)
    {
        int lIParsed;
        double lDParsed;
        string lsValue;
        if (pValue == null) return false;
        if (pType.Equals(typeof(bool))) {
            bool lBParsed;
            if (pValue is bool) return true;
            if (double.TryParse(pValue.ToString(), out lDParsed)) {
                pValue = lDParsed != 0D;
                return true;
            }
            if (bool.TryParse(pValue.ToString(), out lBParsed)) {
                pValue = lBParsed;
                return true;
            }
            else
                return false;
        }
        if (pType.Equals(typeof(Double))) {
            if (pValue is Double) return true;
            if (double.TryParse(pValue.ToString(), out lDParsed)
                || double.TryParse(pValue.ToString().Replace(NumberDecimalSeparatorNOT, NumberDecimalSeparator), out lDParsed)) {
                pValue = lDParsed;
                return true;
            }
            else
                return false;
        }
        if (pType.Equals(typeof(int))) {
            if (pValue is int) return true;
            if (Int32.TryParse(pValue.ToString(), out lIParsed)) {
                pValue = lIParsed;
                return true;
            }
            else if (double.TryParse(pValue.ToString(), out lDParsed)) {
                pValue = (int)lDParsed;
                return true;
            }
            else
                return false;
        }
        if (pType.Equals(typeof(Byte))) {
            if (pValue is byte) return true;
            byte lByte;
            if (Byte.TryParse(pValue.ToString(), out lByte)) {
                pValue = lByte;
                return true;
            }
            else if (double.TryParse(pValue.ToString(), out lDParsed)) {
                pValue = (byte)lDParsed;
                return true;
            }
            else
                return false;
        }
        if (pType.Equals(typeof(long))) {
            long lLParsed;
            if (pValue is long) return true;
            if (long.TryParse(pValue.ToString(), out lLParsed)) {
                pValue = lLParsed;
                return true;
            }
            else if (double.TryParse(pValue.ToString(), out lDParsed)) {
                pValue = (long)lDParsed;
                return true;
            }
            else
                return false;
        }
        if (pType.Equals(typeof(Single))) {
            if (pValue is float) return true;
            Single lSParsed;
            if (Single.TryParse(pValue.ToString(), out lSParsed)
                || Single.TryParse(pValue.ToString().Replace(NumberDecimalSeparatorNOT, NumberDecimalSeparator), out lSParsed)) {
                pValue = lSParsed;
                return true;
            }
            else
                return false;
        }
        if (pType.Equals(typeof(DateTime))) {
            if (pValue is DateTime) return true;
            DateTime lDTParsed;
            if (DateTime.TryParse(pValue.ToString(), out lDTParsed)) {
                pValue = lDTParsed;
                return true;
            }
            else if (pValue.ToString().Contains("UTC")) //Date venant de JScript
            {
                if (_MonthsUTC == null) InitMonthsUTC();
                string[] lDateParts = pValue.ToString().Split(' ');
                lDTParsed = new DateTime(int.Parse(lDateParts[5]), _MonthsUTC[lDateParts[1]], int.Parse(lDateParts[2]));
                lDateParts = lDateParts[3].ToString().Split(':');
                pValue = lDTParsed.AddSeconds(int.Parse(lDateParts[0]) * 3600 + int.Parse(lDateParts[1]) * 60 + int.Parse(lDateParts[2]));
                return true;
            }
            else
                return false;

        }
        if (pType.Equals(typeof(Array))) {
            if (pValue is System.Collections.ICollection || pValue is System.Collections.ArrayList)
                return true;
            return pValue is System.Data.DataTable
                || pValue is string && (pValue as string).StartsWith("<");
        }
        if (pType.Equals(typeof(DataTable))) {
            return pValue is System.Data.DataTable
                || pValue is string && (pValue as string).StartsWith("<");

        }
        if (pType.Equals(typeof(System.Drawing.Bitmap))) {
            return pValue is System.Drawing.Image || pValue is byte[];

        }
        if (pType.Equals(typeof(System.Drawing.Image))) {
            return pValue is System.Drawing.Image || pValue is byte[];

        }
        if (pType.Equals(typeof(System.Drawing.Color))) {
            if (pValue is System.Drawing.Color) return true;
            if (pValue is System.Drawing.KnownColor) {
                pValue = System.Drawing.Color.FromKnownColor((System.Drawing.KnownColor)pValue);
                return true;
            }

            int lARGB;
            if (!int.TryParse(lsValue = pValue.ToString(), out lARGB)) {
                if (lsValue.StartsWith("Color [A=", StringComparison.InvariantCulture)) {
                    foreach (string lsARGB in lsValue.Substring("Color [".Length, lsValue.Length - "Color []".Length).Split(','))
                        switch (lsARGB.TrimStart().Substring(0, 1)) {
                            case "A":
                                lARGB = int.Parse(lsARGB.Substring(2)) * 0x1000000;
                                break;
                            case "R":
                                lARGB += int.Parse(lsARGB.TrimStart().Substring(2)) * 0x10000;
                                break;
                            case "G":
                                lARGB += int.Parse(lsARGB.TrimStart().Substring(2)) * 0x100;
                                break;
                            case "B":
                                lARGB += int.Parse(lsARGB.TrimStart().Substring(2));
                                break;
                            default:
                                break;
                        }
                    pValue = System.Drawing.Color.FromArgb(lARGB);
                    return true;
                }
                if (lsValue.StartsWith("Color [", StringComparison.InvariantCulture)) {
                    pValue = System.Drawing.Color.FromName(lsValue.Substring("Color [".Length, lsValue.Length - "Color []".Length));
                    return true;
                }
                return false;
            }
            pValue = System.Drawing.Color.FromArgb(lARGB);
            return true;
        }
        if (pType.IsEnum) {
            try {
                if (pValue == null) return false;
                if (pValue is int || pValue is byte || pValue is ulong || pValue is long || pValue is double)
                    pValue = Enum.ToObject(pType, pValue);
                else
                    pValue = Enum.Parse(pType, pValue.ToString());
            }
            catch {
                return false;
            }
        }
        return true;
    }
}

A: I can see that this question was originally posted 5 yrs ago when programmers had to work harder to get their desired results.
With Visual Studio 2012 and beyond, a lazy programmer can go the Design View for the Listview properties settings, and click on Properties->Sorting, choose Ascending.
There are plenty of other properties features to obtain the various results a lazy (aka smart) programmer can leverage.

A: Late to the party, here is a short one. It has these limitations:

*

*It only does a plain string sort of the SubItems' Texts

*It uses the ListView's Tag

*It assumes all clicked columns will be filled

You can register & unregister any ListView to its service; make sure the Sorting is set to None..:
public static class LvSort
{
    static List<ListView> LVs = new List<ListView>();
    public static void registerLV(ListView lv)
    {
        if (!LVs.Contains(lv) && lv is ListView)
        {
            LVs.Add(lv);
            lv.ColumnClick +=Lv_ColumnClick;
        }
    }
    public static void unRegisterLV(ListView lv)
    {
        if (LVs.Contains(lv) && lv is ListView)
        {
            LVs.Remove(lv);
            lv.ColumnClick -=Lv_ColumnClick;
        }
    }

    private static void Lv_ColumnClick(object sender, ColumnClickEventArgs e)
    {
        ListView lv = sender as ListView;
        if (lv == null) return;
        int c = e.Column;
        bool asc = (lv.Tag == null) || ( lv.Tag.ToString() != c+"");
        var items = lv.Items.Cast<ListViewItem>().ToList();
        var sorted =  asc ? items.OrderByDescending(x => x.SubItems[c].Text).ToList() :
                            items.OrderBy(x => x.SubItems[c].Text).ToList();
        lv.Items.Clear();
        lv.Items.AddRange(sorted.ToArray());
        if (asc) lv.Tag = c+""; else lv.Tag = null;
    }
}

To register simply do..:
public Form1()
{
    InitializeComponent();
    LvSort.registerLV(yourListView1);
}

Update:
Here is a slightly extended version that will let you sort all sorts of data types using any sorting rule you come up with. All you need to do is write a special string conversion for your data, add it to the function list and mark your columns. To do so simply put the column names appended with a marker string in the columns' Tags.
I have added one for sorting DataTimes and one for integers.
This version will also sort jagged ListViews, i.e. those with different numbers of subitems.
public static class LvCtl
{
    static List<ListView> LVs = new List<ListView>();

    delegate string  StringFrom (string s);

    static Dictionary<string, StringFrom> funx = new Dictionary<string, StringFrom>();

    public static void registerLV(ListView lv)
    {
        if (!LVs.Contains(lv) && lv is ListView)
        {
            LVs.Add(lv);
            lv.ColumnClick +=Lv_ColumnClick;

            funx.Add("", stringFromString);
            for (int i = 0; i <  lv.Columns.Count; i++)
            {
                if (lv.Columns[i].Tag == null) continue;
                string n = lv.Columns[i].Tag.ToString();
                if (n == "") continue;
                if (n.Contains("__date")) funx.Add(n, stringFromDate);
                if (n.Contains("__int")) funx.Add(n, stringFromInt);
                else funx.Add(n, stringFromString);
            }

        }
    }

    static string stringFromString(string s)
    {
        return s;
    }
    static string stringFromInt(string s)
    {
        int i = 0;
        int.TryParse(s, out i);
        return i.ToString("00000") ;
    }
    static string stringFromDate(string s)
    {
        DateTime dt = Convert.ToDateTime(s);
        return dt.ToString("yyyy.MM.dd HH.mm.ss");
    }

    private static void Lv_ColumnClick(object sender, ColumnClickEventArgs e)
    {
        ListView lv = sender as ListView;
        if (lv == null) return;

        int c = e.Column;
        string nt = lv.Columns[c].Tag != null ? lv.Columns[c].Tag.ToString() : "";
        string n = nt.Replace("__", "§").Split('§')[0];

        bool asc = (lv.Tag == null) || ( lv.Tag.ToString() != c+"");
        var items = lv.Items.Cast<ListViewItem>().ToList();
        var sorted =  asc?
            items.OrderByDescending(x =>  funx[nt]( c < x.SubItems.Count ?
                                    x.SubItems[c].Text: "")).ToList() :
            items.OrderBy(x => funx[nt](c < x.SubItems.Count ?
                          x.SubItems[c].Text : "")).ToList();
        lv.Items.Clear();
        lv.Items.AddRange(sorted.ToArray());
        if (asc) lv.Tag = c+""; else lv.Tag = null;
    }

    public static void unRegisterLV(ListView lv)
    {
        if (LVs.Contains(lv) && lv is ListView)
        {
            LVs.Remove(lv);
            lv.ColumnClick -=Lv_ColumnClick;
        }
    }
}

A: i would recommend you to you datagridview, for heavy stuff..  it's  include a lot of auto feature listviwe does not

A: Use the ListView.SortExpression.

When multiple columns are sorted, this
  property contains a comma-separated
  list of the fields to sort by.

A: You can use a manual sorting algorithm like this
public void ListItemSorter(object sender, ColumnClickEventArgs e)
    {
        ListView list = (ListView)sender;
        int total = list.Items.Count;
        list.BeginUpdate();
        ListViewItem[] items = new ListViewItem[total];
        for (int i = 0; i < total; i++)
        {
            int count = list.Items.Count;
            int minIdx = 0;
            for (int j = 1; j < count; j++)
                if (list.Items[j].SubItems[e.Column].Text.CompareTo(list.Items[minIdx].SubItems[e.Column].Text) < 0)
                    minIdx = j;
            items[i] = list.Items[minIdx];
            list.Items.RemoveAt(minIdx);
        }
        list.Items.AddRange(items);
        list.EndUpdate();
    }

this method uses selection sort in O^2 order and as Ascending. You can change the '>' with '<' for a descending or add an argument for this method.
It sorts any column that is clicked and works perfect for small amount of data.

A: Since this is still a top viewed thread, I thought I might note that I came up with a dynamic solution to sort the listview by column. Here's the code just in case someone else wants to use it as well. It pretty much just involves sending the listview items to a datatable, sorting the default view of the datatable by the column name (using the index of the clicked column), and then overwriting that table with the defaultview.totable() method. Then pretty much just add them back to the listview. And wa la, its a sorted listview by column.
public void SortListView(int Index)
    {
        DataTable TempTable = new DataTable();
        //Add column names to datatable from listview
        foreach (ColumnHeader iCol in MyListView.Columns)
        {
            TempTable.Columns.Add(iCol.Text);
        }
        //Create a datarow from each listviewitem and add it to the table
        foreach (ListViewItem Item in MyListView.Items)
        {
             DataRow iRow = TempTable.NewRow();
             // the for loop dynamically copies the data one by one instead of doing irow[i] = MyListView.Subitems[1]... so on
            for (int i = 0; i < MyListView.Columns.Count; i++)
            {
                if (i == 0)
                {
                    iRow[i] = Item.Text;
                }
                else
                {
                    iRow[i] = Item.SubItems[i].Text;
                }
            }
            TempTable.Rows.Add(iRow);
        }
        string SortType = string.Empty;
        //LastCol is a public int variable on the form, and LastSort is public string variable
        if (LastCol == Index)
        {
            if (LastSort == "ASC" || LastSort == string.Empty || LastSort == null)
            {
                SortType = "DESC";
                LastSort = "DESC";
            }
            else
            {
                SortType = "ASC";
                LastSort = "ASC";
            }
        }
        else
        {
            SortType = "DESC";
            LastSort = "DESC";
        }
        LastCol = Index;
        MyListView.Items.Clear();
        //Sort it based on the column text clicked and the sort type (asc or desc)
        TempTable.DefaultView.Sort = MyListView.Columns[Index].Text + " " + SortType;
        TempTable = TempTable.DefaultView.ToTable();
        //Create a listview item from the data in each row
        foreach (DataRow iRow in TempTable.Rows)
        {
            ListViewItem Item = new ListViewItem();
            List<string> SubItems = new List<string>();
            for (int i = 0; i < TempTable.Columns.Count; i++)
            {
                if (i == 0)
                {
                    Item.Text = iRow[i].ToString();
                }
                else
                {
                    SubItems.Add(iRow[i].ToString());
                }
            }
            Item.SubItems.AddRange(SubItems.ToArray());
            MyListView.Items.Add(Item);
        }
    }

This method is dynamic as it uses the existing column name and doesn't require you to know the index or name of each column or even how many columns are in the listview/datatable. You can call it by doing creating an event for the listview.columnclick and then SortListView(e.column).

A: Based on the example pointed by RedEye, here's a class that needs less code :
it assumes that columns are always sorted in the same way, so it handles the
ColumnClick event sink internally :
public class ListViewColumnSorterExt : IComparer {
    ///
    /// Specifies the column to be sorted
    ///
    private int ColumnToSort;
    ///
    /// Specifies the order in which to sort (i.e. 'Ascending').
    ///
    private SortOrder OrderOfSort;
    ///
    /// Case insensitive comparer object
    ///
    private CaseInsensitiveComparer ObjectCompare;

    private ListView listView;
    ///
    /// Class constructor.  Initializes various elements
    ///
    public ListViewColumnSorterExt(ListView lv) {
        listView = lv;
        listView.ListViewItemSorter = this;
        listView.ColumnClick += new ColumnClickEventHandler(listView_ColumnClick);

        // Initialize the column to '0'
        ColumnToSort = 0;

        // Initialize the sort order to 'none'
        OrderOfSort = SortOrder.None;

        // Initialize the CaseInsensitiveComparer object
        ObjectCompare = new CaseInsensitiveComparer();
    }

    private void listView_ColumnClick(object sender, ColumnClickEventArgs e) {
        ReverseSortOrderAndSort(e.Column, (ListView)sender);
    }

    ///
    /// This method is inherited from the IComparer interface.  It compares the two objects passed using a case insensitive comparison.
    ///
    /// <param name="x">First object to be compared</param>
    /// <param name="y">Second object to be compared</param>
    /// <returns>The result of the comparison. "0" if equal, negative if 'x' is less than 'y' and positive if 'x' is greater than 'y'</returns>
    public int Compare(object x, object y) {
        int compareResult;
        ListViewItem listviewX, listviewY;

        // Cast the objects to be compared to ListViewItem objects
        listviewX = (ListViewItem)x;
        listviewY = (ListViewItem)y;

        // Compare the two items
        compareResult = ObjectCompare.Compare(listviewX.SubItems[ColumnToSort].Text, listviewY.SubItems[ColumnToSort].Text);

        // Calculate correct return value based on object comparison
        if (OrderOfSort == SortOrder.Ascending) {
            // Ascending sort is selected, return normal result of compare operation
            return compareResult;
        }
        else if (OrderOfSort == SortOrder.Descending) {
            // Descending sort is selected, return negative result of compare operation
            return (-compareResult);
        }
        else {
            // Return '0' to indicate they are equal
            return 0;
        }
    }

    ///
    /// Gets or sets the number of the column to which to apply the sorting operation (Defaults to '0').
    ///
    private int SortColumn {
        set {
            ColumnToSort = value;
        }
        get {
            return ColumnToSort;
        }
    }

    ///
    /// Gets or sets the order of sorting to apply (for example, 'Ascending' or 'Descending').
    ///
    private SortOrder Order {
        set {
            OrderOfSort = value;
        }
        get {
            return OrderOfSort;
        }
    }

    private void ReverseSortOrderAndSort(int column, ListView lv) {
        // Determine if clicked column is already the column that is being sorted.
        if (column == this.SortColumn) {
            // Reverse the current sort direction for this column.
            if (this.Order == SortOrder.Ascending) {
                this.Order = SortOrder.Descending;
            }
            else {
                this.Order = SortOrder.Ascending;
            }
        }
        else {
            // Set the column number that is to be sorted; default to ascending.
            this.SortColumn = column;
            this.Order = SortOrder.Ascending;
        }

        // Perform the sort with these new sort options.
        lv.Sort();
    }
}

Assuming you're happy with the sort options, the class properties are private.
The only code you need to write is :
in Form declarations
private ListViewColumnSorterExt listViewColumnSorter;

in Form constructor
listViewColumnSorter = new ListViewColumnSorterExt(ListView1);

... and you're done.
And what about a single sorter that handles multiple ListViews ?
public class MultipleListViewColumnSorter {
    private List<ListViewColumnSorterExt> sorters;

    public MultipleListViewColumnSorter() {
        sorters = new List<ListViewColumnSorterExt>();
    }

    public void AddListView(ListView lv) {
        sorters.Add(new ListViewColumnSorterExt(lv));
    }
}

in Form declarations
private MultipleListViewColumnSorter listViewSorter = new MultipleListViewColumnSorter();

in Form constructor
listViewSorter.AddListView(ListView1);
listViewSorter.AddListView(ListView2);
// ... and so on ...

A: I slightly modified the example from Microsoft: https://support.microsoft.com/en-us/kb/319401
This method will only sort once to sort ascending.  My modifications make it sort both ways.
public class ListViewItemComparer : IComparer
{
    private int col;
    bool bAsc = false;
    public ListViewItemComparer()
    {
        col = 0;
    }
    public ListViewItemComparer(int column, bool b)
    {
        col = column;
        bAsc = b;
    }
    public int Compare(object x, object y)
    {
        if (bAsc)
        {
            return String.Compare(((ListViewItem)x).SubItems[col].Text, ((ListViewItem)y).SubItems[col].Text);
            bAsc = false;
        }
        else
        {
            return String.Compare(((ListViewItem)y).SubItems[col].Text, ((ListViewItem)x).SubItems[col].Text);
            bAsc = true;
        }
    }

}

Then I create an object of this class whenever a column header is clicked
        bool sortAscending = false;
        private void inventoryList_ColumnClick(object sender, ColumnClickEventArgs e)
        {

            if (!sortAscending)
            {
                sortAscending = true;
            }
            else
            {
                sortAscending = false;
            }
            this.inventoryList.ListViewItemSorter = new ListViewItemComparer(e.Column, sortAscending);

        }

A: I used the same base class as that what the others seem to use only I altered it as to allow for string, date and numerical sorting.
You can initialize it using a backing-field like so:
private readonly ListViewColumnSorterExt fileSorter;
...
public Form1()
{
    InitializeComponent();
    fileSorter = new ListViewColumnSorterExt(myListView);
}

Here is the code:
public class ListViewColumnSorterExt : IComparer
{
    ///
    /// Specifies the column to be sorted
    ///
    private int ColumnToSort;
    ///
    /// Specifies the order in which to sort (i.e. 'Ascending').
    ///
    private SortOrder OrderOfSort;
    ///
    /// Case insensitive comparer object
    ///
    private CaseInsensitiveComparer ObjectCompare;

    private ListView listView;
    ///
    /// Class constructor.  Initializes various elements
    ///
    public ListViewColumnSorterExt(ListView lv)
    {
        listView = lv;
        listView.ListViewItemSorter = this;
        listView.ColumnClick += new ColumnClickEventHandler(listView_ColumnClick);

        // Initialize the column to '0'
        ColumnToSort = 0;

        // Initialize the sort order to 'none'
        OrderOfSort = SortOrder.None;

        // Initialize the CaseInsensitiveComparer object
        ObjectCompare = new CaseInsensitiveComparer();
    }

    private void listView_ColumnClick(object sender, ColumnClickEventArgs e)
    {
        ReverseSortOrderAndSort(e.Column, (ListView)sender);
    }

    ///
    /// This method is inherited from the IComparer interface.  It compares the two objects passed using a case insensitive comparison.
    ///
    /// <param name="x">First object to be compared</param>
    /// <param name="y">Second object to be compared</param>
    /// <returns>The result of the comparison. "0" if equal, negative if 'x' is less than 'y' and positive if 'x' is greater than 'y'</returns>
    public int Compare(object x, object y)
    {
        int compareResult;
        ListViewItem listviewX, listviewY;

        // Cast the objects to be compared to ListViewItem objects
        listviewX = (ListViewItem)x;
        listviewY = (ListViewItem)y;

        if (decimal.TryParse(listviewX.SubItems[ColumnToSort].Text, out decimal dx) && decimal.TryParse(listviewY.SubItems[ColumnToSort].Text, out decimal dy))
        {
            //compare the 2 items as doubles
            compareResult = decimal.Compare(dx, dy);
        }
        else if (DateTime.TryParse(listviewX.SubItems[ColumnToSort].Text, out DateTime dtx) && DateTime.TryParse(listviewY.SubItems[ColumnToSort].Text, out DateTime dty))
        {
            //compare the 2 items as doubles
            compareResult = DateTime.Compare(dtx, dty);
        }
        else
        {
            // Compare the two items
            compareResult = ObjectCompare.Compare(listviewX.SubItems[ColumnToSort].Text, listviewY.SubItems[ColumnToSort].Text);
        }
        // Calculate correct return value based on object comparison
        if (OrderOfSort == SortOrder.Ascending)
        {
            // Ascending sort is selected, return normal result of compare operation
            return compareResult;
        }
        else if (OrderOfSort == SortOrder.Descending)
        {
            // Descending sort is selected, return negative result of compare operation
            return (-compareResult);
        }
        else
        {
            // Return '0' to indicate they are equal
            return 0;
        }
    }

    ///
    /// Gets or sets the number of the column to which to apply the sorting operation (Defaults to '0').
    ///
    private int SortColumn
    {
        set
        {
            ColumnToSort = value;
        }
        get
        {
            return ColumnToSort;
        }
    }

    ///
    /// Gets or sets the order of sorting to apply (for example, 'Ascending' or 'Descending').
    ///
    private SortOrder Order
    {
        set
        {
            OrderOfSort = value;
        }
        get
        {
            return OrderOfSort;
        }
    }

    private void ReverseSortOrderAndSort(int column, ListView lv)
    {
        // Determine if clicked column is already the column that is being sorted.
        if (column == this.SortColumn)
        {
            // Reverse the current sort direction for this column.
            if (this.Order == SortOrder.Ascending)
            {
                this.Order = SortOrder.Descending;
            }
            else
            {
                this.Order = SortOrder.Ascending;
            }
        }
        else
        {
            // Set the column number that is to be sorted; default to ascending.
            this.SortColumn = column;
            this.Order = SortOrder.Ascending;
        }

        // Perform the sort with these new sort options.
        lv.Sort();
    }
}

If you'd like to assign icons in regards to the sort order then add an image list to the Listview and make sure you update the below sample to reflect the names of your images that you use for sorting (you can assign them any name when you import them). Update the above listView_ColumnClick to something like this:
private void listView_ColumnClick(object sender, ColumnClickEventArgs e)
{
    if (sender is ListView lv)
    {
        ReverseSortOrderAndSort(e.Column, lv);

        if (   lv.Columns[e.Column].ImageList.Images.Keys.Contains("Ascending")
            && lv.Columns[e.Column].ImageList.Images.Keys.Contains("Descending"))
        {
            switch (Order)
            {
                case SortOrder.Ascending:
                    lv.Columns[e.Column].ImageKey = "Ascending";
                    break;
                case SortOrder.Descending:
                    lv.Columns[e.Column].ImageKey = "Descending";
                    break;
                case SortOrder.None:
                    lv.Columns[e.Column].ImageKey = string.Empty;
                    break;

            }
        }

    }
}


text:
Q: Spring WebClient throw error based on response body I am using Spring WebClient to call REST API. I  want to throw an error based on the response. For example, if there is an error (400) with body
{"error": "error message1 "}

then I want to throw an error with "error message1". Same way if there is an error(400) with the body
{"error_code": "100020"}

then I want to throw an error with error_cde 100020.  I want to do it in a non-blocking way.
public Mono<Response> webclient1(...) {

 webClient.post().uri(createUserUri).header(CONTENT_TYPE, APPLICATION_JSON)
                .body(Mono.just(request), Request.class).retrieve()
                .onStatus(HttpStatus::isError, clientResponse -> {

                 //Error Handling

                }).bodyToMono(Response.class);
}

A: A body from ClientResponse should be extracted in a reactive way (javadoc) and lambda in onStatus method should return another Mono (javadoc). To sum up, take a look at below example
onStatus(HttpStatus::isError, response -> response
    .bodyToMono(Map.class)
    .flatMap(body -> {
        var message = body.toString(); // here you should probably use some JSON mapper
        return Mono.error(new Exception(message));
    })
);


text:
Q: Unity add force to ragdoll and stability Sorry for my bad english. I want to add force to ragdoll like this:
if (Physics.Raycast(this.transform.position, playerCamera.transform.forward, out hit, fireRange))
{
    if (hit.collider.tag == "Ragdoll")
    {
        hit.collider.gameObject.GetComponent<ForcePush>().OnRayPush(this.transform.position, hit.point, 6000f);
    }
}

public void OnRayPush(Vector3 firePos, Vector3 hitPos, float pushForce)
{

    Vector3 incomeVector = ((hitPos) - (firePos));

    incomeVector = incomeVector.normalized;

    rigidbody.AddForceAtPosition((incomeVector) * pushForce, hitPos);

}

When I play ragdoll is distorted like in the screenshot:

I don't know the reason. Is force too strong?
But i want to throw strongly. How can i fix this stability problem ?
Please help.
Thanks


text:
Q: SciPy Newton Method I need to find the roots of a quite complicated equation and I've read that python has a set of function that can help. I tried to figure out how they work but I failed pretty bad. The examples that I saw are all quite simple instead I need to find the roots of this function:

With B and K real positive numbers. Can anyone help ?

A: Here are two solutions, the second is probably the simpler and more correct way of solving the problem.
The trick is that you have to get the function f to remember the values of K and B. One way of doing this is to make it an inner function of another function. The outer function is used to set K and B. These are in the variable scope of the inner function that is returned. This way the inner f function can remember the values. The returned function is then simply passed on to the Newton-Raphson method, and it finds the root.
from scipy.misc import factorial
from scipy.optimize import newton
import numpy as np

def get_f(K=1, B=1):
    def f(x):
        return np.exp(-B*(np.power(B, x))-factorial(x)*K)
    return f

f = get_f(K=2, B=3)
print newton(f, 3, maxiter=1000)

A user commented that the newton function has an args argument, which can be used to pass extra arguments to the Newton-Raphson function. If the function has the form f(x, a, b, c...), then a, b, c... are extra arguments that can be given in args.
The same solution would then look like this:
from scipy.misc import factorial
from scipy.optimize import newton
import numpy as np

def f(x, K, B):
    return np.exp(-B*(np.power(B, x))-factorial(x)*K)

print newton(f, 3, args=(2, 3), maxiter=1000)


text:
Q: Pandas Python new column dataframe I have problems with initializing a new column in a dataframe, called df
I want to do:
df['new_column'] = 0

to have all values to zero..
But then is gives me:

A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead

.. so, when I then want to work on it it **** up...
I looked up on the net but didn't really find something useful..
I am a beginner in pandas so sorry if the answer is obvious but I really don't know how to do this basic thing..
Thanks!

A: I'm guessing this is because your df is already a view on some other dataframe like:
df = DF.iloc[100:]

in this case pandas will not really copy the data but just keep a reference to the old one. In my mind this is not very transparent and I have shot myself in the foot a couple of times with that.
a work around is to enfoce a copy of the dataframe to be sure it owns its own data:
df = df.copy()

so in your case you might want to do:
df = df.copy()
df['new_column'] = 0

I hope that does the trick for you


text:
Q: Ansible 2.7 : How to list files from unarchive Need to unarchive a .zip file then list the unpacked files. This is to select some pattern of files and use them in rest of the code
My playbook yaml snippet is
- name: uarchive the opar zip
  unarchive:
   src: "{{opar_download_path}}/opar.zip"
   dest: "{{opar_download_path}}"
   remote_src: yes
   list_files: yes

I am not able to find details of how to use the result from "list_files",ie how to store the list of files to a variable. I was referring below document
https://docs.ansible.com/ansible/latest/modules/unarchive_module.html

A: The list_files: yes includes additional response attribute called files. For better understanding, try to print the output unarchived_list.files, as shown below:
- name: unarchive the opar zip
  unarchive:
   src: "{{opar_download_path}}/opar.zip"
   dest: "{{opar_download_path}}"
   remote_src: yes
   list_files: yes
  register: unarchived_list

- name: print unarchived folder list of files
  debug: msg="{{unarchived_list.files}}"

More information on registering variables can be found here: https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#registering-variables


text:
Q: Angular 4 Reactive Form Validator Required shows error on touch when value is preset The issue I am having is that the form is showing an error for an input field. I don't know why it is showing and its probably due to a lack of understanding. So I have a component called edit team. Inside this edit team component I have an input field with a value that is set to the current team name. If I put focus on the input text field and then remove focus to lets say the background then the form triggers a "required" error even with the value preset and unchanged.

    Name
    <input tabindex="0" type="text" placeholder="Please enter the team name" title="Please enter the team name" required value=""
               id="name" class="form-control" name="name" formControlName="name" [value]="nameValue">

    // This is the condition for when the error is shown.
    // So when the input field is touched, check if an error
    // exists for the validator required.

Team name is required.

This is the constructor and the ngOnIt method for the component. The subscription is for an observable within the team service, when the team changes so do the values.
constructor(private fb: FormBuilder,
              private teamService: TeamService,
              private router: Router,
              public modalService: ModalService) { }

  ngOnInit() {
    this.teamService.teamChange.subscribe(result => {
      this.team = result;
      this.nameValue = this.team.name;
      this.descriptionValue = this.team.description;
    });

    this.editTeamFormGroup = this.fb.group({
      'name': [ this.nameValue, Validators.required ],
      'description': [ this.descriptionValue, Validators.required ]
    });
  }

Note: No errors within the console. The validation works as expected if I add characters to the preset value and change focus to another element.

A: It's because the way you setup the form. As this.teamService.teamChange is asynchronous, you cannot guarantee this.nameValue is setup before this.editTeamFormGroup is created.
If you wait until you get necessary information then initiate the form group, thing will be working properly. And don't use [value] together with formControlName in <input> unless you have a good reason to.
Template
<form [formGroup]="editTeamFormGroup" *ngIf="editTeamFormGroup">
...

    Name
    <input tabindex="0" type="text" placeholder="Please enter the team name" title="Please enter the team name" required value=""
               id="name" class="form-control" name="name" formControlName="name">

</form>

Code behind
ngOnInit() {
    this.teamService.teamChange.subscribe(result => {
      this.team = result;
      this.nameValue = this.team.name;
      this.descriptionValue = this.team.description;

      this.editTeamFormGroup = this.fb.group({
        'name': [ this.nameValue, Validators.required ],
        'description': [ this.descriptionValue, Validators.required ]
      });
    });
}


text:
Q: LINQ: Select single value from object array, by id Take the following example class:
public class Questions
{
    public Int32 QuestionId { get; set; }
    public String Question { get; set; }
    public String Answer { get; set; }
}

And the following array:
var questionArray = new Questions[]
{
    new Questions {QuestionId = 1, Question = "How old are you?", Answer = "32"},
    new Questions {QuestionId = 2, Question = "What is your name?", Answer = "John"},
    new Questions {QuestionId = 3, Question = "How tall are you?", Answer = "6'"}
};

Using LINQ, I want to get the Answer for a specified QuestionId. For example, if I gave QuestionId 2, the result would be 'John'.
I want to be able to pull out the answer to a specific question to populate a separate DTO. ie:
var person = new PersonDto {Name = <single line LINQ goes here>};

So far I have only managed to get an answer using the following:
foreach (var q in questionArray.Where(q => q.QuestionId == 2))
{
    var answer = q.Answer;
}

Is this possible in 1 line of code?

A: It is possible using for e.g. Single from Linq, Single will throw exception when there will be more than one answer.
var answer = questionArray.Single(x=>x.QuestionId == 2).Answer;

This answer assumes that there is only one answer to one question (and it is always present). You can add SingleOrDefault and check for null if you are not sure if answer exists. Or you can add Where clause to get more than one answer, like:
var answers = questionArray.Where(x=>x.QuestionId == 2).Select(x=>x.Answer);

Above snippet will not fail if there is no answer to question and it will return empty sequence for it. You can test it for having a value and run First on it.

A: You are using the Wrong(tm) datatype. For lookups like these, use a Dictionary.
public class Question // Class names should be a singular form noun
{
    public int Id { get; set; } // QuestionId is redundant
    public string Question { get; set; }
    public string Answer { get; set; }
}

var questions = new Question[]
{
    new Questions {Id = 1, Question = "How old are you?", Answer = "32"},
    new Questions {Id = 2, Question = "What is your name?", Answer = "John"},
    new Questions {Id = 3, Question = "How tall are you?", Answer = "6'"}
}.ToDictionary(q => q.Id, q => q);

var answerToQuestionNumberTwo = questions[2].Answer;

EDIT: Clarification, the reason a dictionary is "better" here is because it is both more readable and is faster. You want to construct a collection meant for associating a question with a given ID, enabling you to do lookups on question objects to query their properties. This is the raison d'être of the Dictionary data structure and it has a lookup time complexity of O(1) (compared to O(n) of the Where/First/Single LINQ methods).


text:
Q: Substituir todos os caracteres de uma string por outro caracter def getGuessedWord(secretWord, lettersGuessed):
    secretWord_copy = ""
    for i in secretWord:
        print(i)
        secretWord_copy = secretWord.replace(i," _ ")
    print(secretWord_copy)
secretWord = 'apple'

Estou tentando substituir cada caracter de secretWord por " - "  mas o código acima só substitui o último:
appl _
O que está errado?
O resultado deveria ser _ _ _ _ _

A: Me desculpem a pergunta, mas pra que serviria o segundo parametro (lettersGuessed) da função getGuessedWord. Porque pelo o que eu estou vendo ela não esta sendo usada. E pelo o que eu entendi da função, basta fazer o seguinte para obter o mesmo resultado:
    def getGuessedWord(secretWord):
        print (len (secretWord) * ' _ ')

A: Você está sempre substituindo secretWord sem modificá-la.
def getGuessedWord(secretWord, lettersGuessed):
    secretWord_copy = ""
    for i in secretWord:
        print(i)
        secretWord_copy = secretWord.replace(i," _ ")
        secretWord = secretWord_copy
    print(secretWord_copy)
secretWord = 'apple'

Sem alterar secretWord:
def getGuessedWord(secretWord, lettersGuessed):
    secretWord_copy = secretWord
    for i in secretWord:
        print(i)
        secretWord_copy = secretWord_copy.replace(i,"_")
    print(secretWord_copy)
    print(secretWord)
secretWord = 'apple'


text:
Q: Genetic Algorithm From Desktop Application To MVC I have implemented a GA .NET C# Desktop application with the classes:

*

*Population

*Individuals

*Genes

*static class to control the DB access

*static fitness function class

*GA class to start the process and draw the loops

I want to migrate these classes to my .NET MVC application but really confused with how are multiple clients going to access these classes without sharing them. I have looked into Singleton classes but did not understand the concept.
Any suggestions ?

A: For anyone who is dealing with the same issue. I have implement the solution by:

*

*Put all your classes in a separate Folder

*Then, at the controller with each request: create new instance of a master class that further creates new instances of the others as needed.

*If you have a class that shall be shared with these instances, save
its reference in Session["Key"]


text:
Q: How referencing instance method 'encode' on 'Array' can conform to 'Encodable' I am having CoreData entity which name is "Lekarstvo". The structure of this entity is the same as the structure of the JSON. I want to transfer this information to the JSON file. How can I do it? Right now I am having this error and I really don't know how to fix it.

Referencing instance method 'encode' on 'Array' requires that 'Lekarstvo' conform to 'Encodable'

func getAllData() {

     var userArr :[Lekarstvo] = []

      do{
               userArr =  try moc.fetch(Lekarstvo.fetchRequest())

      }catch{
              print(error)
      }

        guard let encoded = try? JSONEncoder().encode(userArr) else {return}
            if let jsonString = String(data: encoded, encoding: .utf8) {
                print(jsonString)
            }

            guard let url = URL(string: "https://api.myjson.com/bins/vw7sg") else {return}
                        var request = URLRequest(url: url)
                            request.addValue("application/json", forHTTPHeaderField: "Content-Type")

                            request.httpMethod = "PUT"
                            request.httpBody = encoded

A: Make sure your struct/class conforms to Codable (or Encodable) + all it's subfields need to conform to the same protocol.
struct Lekarstvo: Codable {
...
}

A: I solved my problem by adding this for loop and it works now.
  for data in userArr as! [NSManagedObject] {
        let dossi = LecarstvO(id: data.value(forKey: "id") as! Int,
                              kgPazient: data.value(forKey: "kgPazient") as! Int,
                              goPazient: data.value(forKey: "goPazient") as! Int,
                              fromMin: data.value(forKey: "fromMin") as! CGFloat,
                              toMin: data.value(forKey: "toMin") as! CGFloat,
                              fromMax: data.value(forKey: "fromMax") as! CGFloat,
                              toMax: data.value(forKey: "toMax") as! CGFloat,
                              isMin: data.value(forKey: "isMin") as! Bool,
                              isMax: data.value(forKey: "isMax") as! Bool,
                              mjarka: data.value(forKey: "mjarka") as! String,
                              maxDoza: data.value(forKey: "maxDoza") as! CGFloat,
                              firstDoza: data.value(forKey: "firstDoza") as! CGFloat,
                              priemI: data.value(forKey: "priemI") as! Int,
                              priemII: data.value(forKey: "priemII") as! Int,
                              opis: data.value(forKey: "opis") as! String,
                              lekarstvo: data.value(forKey: "lekarstvo") as! String,
                              grupa: data.value(forKey: "grupa") as! String)
                     self.model.database.append(dossi)
    }

A: for data in userArr as! [NSManagedObject]


text:
Q: PySpark: Creating RDD->DF->Parquet with a schema that has 1000's of fields but rows with variable number of columns I am trying to read an ElasticSearch index which has millions of docs each having variable number of fields. I have a schema that has 1000's of fields each with its own name and type.
Now when I create a RDD trough ES-Hadoop connector and later convert into a DataFrame by specifying the schema, it fails saying -

Input row doesn't have expected number of values required by the
  schema

I have a few questions.
1. Is it possible to have a RDD/DF with rows containing variable number of fields? If not, what is the alternative other than adding null value for missing fields in each column?

*I see that by default Spark converts everything into StringType as I use sc.newAPIHadoopRDD() call. How can I typecast them to correct type based on the field name that I have in my schema? Some kind of mapping?

*I want to write this in Parquet format with schema added into the file. What happens to those missing fields compared to the schema which has 1000's of fields.

A: *

*You cannot have a variable number of columns, but you can use one column of a collection type like an Array or a Map, which in python corresponds with a dictionary. This allows you to store variable-length data in your column. Otherwise yes, you need to have a value for every column in your schema. You would typically fill missing values with nulls.

*If you already have a dataframe, and you have a function get_column_type that obtains the type name from the column name, you can recast the whole dataframe like this:
import pyspark.sql.functions as F
select_expressions = [ F.col(column_name).cast(get_column_type(column_name)) for column_name in column_list]
recasted_df = df.select(*select_expressions)

*The parquet file will have whatever columns you have in your dataframe.  If you want the 1000 fields in the file, they will have to be in the dataframe, so you would have to fill the missing values with nulls or some other value.
Now, if you put all those points together you probably want to do something like this:

*

*Read each elastic doc into a row with an id field and doc field of type MapType.

*explode the doc field so now you have 3 columns: id, key and value, with one row for each key in each doc. At this point you can write to parquet file and be done with the process.

If you want the dataframe with the full schema, you have to follow these extra steps:

*

*Pivot the result to generate one only row for each id, and a column for each key in the doc with its corresponding value: pivoted_df = df.groupBy('id').pivot('key').agg(F.first('value')

*This dataframe has all the fields present in the data. If you know the full schema, you can add dummy columns for the ones that are missing: df = df.withColumn('new_column', lit(None).cast(StringType())

*Finally recast the columns with code in point 2, and drop column id. You can write this to parquet and it will have all the columns in your big schema.


text:
Q: Disable an input source for an application I have 'English' and '2-Set Korean' input sources enabled on my Macbook Pro with macOS Monterey Version 12.4. For Emacs.app, I would like to enable only English and disable the other(s) since Emacs has its own multilingual environment including input methods. Would it be possible to disable other input sources only on an application without changing the system input source set?
Background:
I am currently using a "remapper" daemon that I've written myself to (sort of) disable the Caps Lock key only on GNU Emacs.app (and yes, I've checked on "Automatically switch to a document's input source" in the Keyboard Preferences). I am quite happy with this hack, but sometimes the system input source changes to 2-Set Korean for reasons I don't know when I type things very fast. In that case, I have to use the mouse to change the input source back to English. This is nuisance, and I thought it would be convenient if I could completely disable all input sources but English on Emacs.app.


text:
Q: How to bind object(data) and ViewHolder(listview row) in android? i need a some help , executing fallowing task. can any one help to sort out this ?
I have list view . each row contains

*

*Title (Textview)

*sub title(TextView)

*Progress bar

*progress count(TextView)

*Download/ Cancel(ToggleButton)

while loading adapter i passed List . from where am displaying title , subtitle for each row.
here is myadapter code , generating views for each row.
My problem is that . In run time when i entered download button, its goes to downloadQueue to download, and updates respective progress bar . But Whwn am scrolling down the listview., progress bar visible for other row instead current row where i started Downloading. Can some one tell me t, how to bind view and state object so that it wont misplace progressbar.
`
@Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final int pos= position;
        final StateViewHolder viewHolder;
        final State state = stateList.get(pos) ;
        if (convertView == null) {
             inflater = LayoutInflater.from(context);
            convertView = inflater.inflate(R.layout.adapter_view, null);
            TextView title = (TextView) convertView.findViewById(R.id.text);
            TextView subTitle = (TextView) convertView.findViewById(R.id.subText);
            TextView progresstext = (TextView) convertView.findViewById(R.id.progressText);
            ProgressBar progressBar = (ProgressBar) convertView.findViewById(R.id.progress);
            ImageView cancel = (ImageView) convertView.findViewById(R.id.cancel);
            ImageView download = (ImageView) convertView.findViewById(R.id.download);
             viewHolder = new StateViewHolder(title, subTitle, progresstext, download, cancel, progressBar);
             hashMap.put(state, viewHolder);
             convertView.setTag(viewHolder);
             Log.i("DownloadAdapter", "InGetView");
        }else{
            viewHolder = (StateViewHolder)convertView.getTag();
        }
         state.setViewHolder(viewHolder);
        viewHolder.getDownload().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                     viewHolder.getDownload().setVisibility(View.GONE);
                     viewHolder.getCancel().setVisibility(View.VISIBLE);
                     Log.i("DownloadAdapter", ""+state.getName());
                    DownloadQueue.addToQueue(state);
                }
            });
         viewHolder.getCancel().setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                     viewHolder.getCancel().setVisibility(View.GONE);
                     viewHolder.getDownload().setVisibility(View.VISIBLE);
                    DownloadQueue.RemoveFromQueue(state);
                }
            });

        viewHolder.getTitle().setText(state.getName());
        viewHolder.getSubTitle().setText(state.getEffective());
        return convertView;
    }
}

Thanking you,
Srinivas
`

A: When you use a view holder to reuse your row view, then you need to explicitly set all views everytime.  In other words, you need to set every element in that row including your Title, Subtitle, Progress count text view, progress bar, and download Image view toggle.
What you are seeing is when one row sets the progress bar as visible, another row may be reusing that (thus you would see the progress bar on that row too).  So you need to explicitly set the progress bar to not be visible for the rows that aren't downloading.
So at the bottom of your getView method, make sure you have logic to set every view:
viewHolder.getTitle().setText(state.getName());
viewHolder.getSubTitle().setText(state.getEffective());
viewHolder.getProgressBar().setVisibility(isImageDownloading);
viewHolder.getProgressCount().setText("example");


text:
Q: Optimize LEFT JOINS ORDER BY on multiple varchar columns I tried to optimize a MySQL query which sort multiple varchar columns:
SELECT *
FROM tickets
LEFT OUTER JOIN customers ON customers.id = tickets.customer_id
LEFT OUTER JOIN locations ON locations.id = tickets.location_id
ORDER BY customers.name, locations.name;

The ORDER BY statement seems to cost lot of time(~100ms) for a small database of ~6000 tickets, ~40 customers and ~400 locations.
I already reduced the length of varchar columns, which had significantly speed up the query(2x faster).
Do you have any solutions to optimize the query execution time?
Many thanks!

A: You should have indexes on the customers.name and locations.name columns.
Additionally, ensure that customers.id, tickets.customer_id, locations.id, and tickets.location_id are all indexed.


text:
Q: Why is MySQL Workbench is reporting different number of writes per second at the same time on the same database? I am working on a project with MySQL Workbench on a server that I remote into with Windows remote desktop. Sometimes I will also connect to the server with MySQL Workbench on my local machine.
When I go to server status, the number of InnoDb Writes per Second is different depending on whether I am using MySQL Workbench on the remote server or on my local machine.
Here is a screen shot of what it looks like, the left status is on my local machine, the right is on the remote desktop.

It would be nice to be able see accurate live numbers of writes per second.

A: Perhaps that figure is a snapshot with a tight granularity, reading the number of writes once then again after some portion of a second, and multiplying up to get a "per second" value. In that case I would expect the figures to differ every time unless you somehow request an update of both at exactly the same fraction of a second.
If the figure is an average taken over a larger timeframe (multiple seconds instead of one or a fraction there-of) then the figures would be closer to each other.
You can see a similar effect looking at CPU use on any unix-a-like system by running two copies of a top variant in separate terminals. The same for disk and network IO with iotop and iftop or equivalents. They will almost always show slightly different figures as they poll for updated data at slightly different times, especially if you turn the update frequency as fast as you can read.


text:
Q: apt-offline only install specific packages apt-offline seems like a really great option if you have a server that does not have network connectivity and you want to install a few packages on it.
The problem I have is that I only want to install a few packages and there seem to only be options for an upload or an upgrade and to also install the few packages I want. How do I get apt-offline to only create an install database for the packages I want to install?

A: You can install other packages. If you use apt-offline with the --install-packages option like for example:

sudo apt-offline set package-offline.sig --install-packages package_name

It will create a signature for the installation of package_name and its dependencies.


text:
Q: Span and pattern matching The span function is defined below. I am curious as to how (ys, zs) is pattern matched with (x:ys, zs) where there is already an 'x' and a cons. I some how believed pattern matching would be an in-place replacement, but this blows my mind and had my jaw dropped. This is really beautiful.
I am curious as to if this construct and more is explained in any book (I am currently reading Real World Haskell Chapter 4 and wonder if this book or any other explains this in detail). Sorry if I come off as naive, but to me, this is a fine pattern matching construct and I would love to know more.
span p []            = ([],[])
span p xs@(x:xs')
            | p x       =  (x:ys,zs)
            | otherwise =  ([],xs)
                           where (ys,zs) = span p xs'

A: Much of pattern syntax can also be used for expressions, so that you can use the same syntax for taking apart data with a pattern as you use for building it with an expression.
Note that since Haskell values are immutable, there are no in place replacements.
The part (x:ys,zs) is not itself a pattern, but is an expression that builds a new value from the values x, ys and zs, which themselves come from patterns.
x comes from the pattern xs@(x:xs') and is bound to the first element of the list passed as the second argument of span. This also binds xs' to the remainder of the list, and xs to the original whole. (The @ means "match the pattern to the right but also give a name bound to the whole, and is an exception to the rule that patterns can also be used as expressions.)
ys and zs come from the pattern (ys,zs) in where (ys,zs) = span p xs'. They are bound to the first and second element of the tuple returned from a recursive call of span p xs' with the remainder of the list after x has been removed.
Putting this together, the expression (x:ys,zs) makes a tuple that is the same as the one returned from the recursive span p xs', except that x has been consed to the first tuple element.
Someone else will have to answer about books, I learned Haskell too long ago to have read them. But if everything else fails, you can read the precise definitions in the Haskell report.

A: you're right, this is beautiful. It is the closest thing to Prolog's TRMC, in Haskell.
Let me explain. That definition is equivalent to
span p xs = case xs of
             (x:t) | p x -> let (ys,zs) = span p t in
                            (x:ys,zs)   -- value1
             _           -> ([],xs)     -- value2 constructed from known parts

Because Haskell is lazy, value1 is constructed and returned immediately, without any intermediate recursive calls, just as the simple value2. At this point x is already known (it was bound as part of pattern matching) but ys and zs are not calculated yet — just their definition is retained alongside the value1 with two "holes" in it, (x:_,_). Only if either of the "holes" values will be demanded later, their values will be calculated by making the further call to span and filling those holes with the destructured result (let bindings are pattern matches too).
This is known as guarded recursion in Haskell - the recursive call is guarded against by the constructor(s) - here, (,) and (:) - creating value with hole(s), to be filled later as needed.
Incidentally, in Prolog this is written as
span(P,[], [],[]).       % -- two "inputs", two "outputs"
span(P,XS, A,B):-
  XS = [X|T],
  ( call(P,X) ->         % -- predicate P holds for X:
      A=[X|YS], B=ZS,    % --   first, the value with holes is created
      span(P,T, YS,ZS)   % --   then, the holes are filled
    ;                    % -- else:
      A=[], B=XS ).      % --   output values are set


text:
Q: Как обрабатывать математическую функцию? В общем на вход будет вводиться математическое выражение, в котором будет вычисляться Y и есть X (при помощи цикла будет пробегаться по списку иксов и подставляться). После с помощью списков x-ов и y-ов будет построен график.
Как безопаснее всё это сделать? Подскажите

A: Рекомендую взглянуть на SymPy
Простой пример выражения:
from sympy.parsing.sympy_parser import parse_expr
func = parse_expr( "x + y" )
print( func ) #  x + y
print( func.args ) # x, y
x, y = func.args
print( func.n( subs={x:1, y:2} ) ) # 3.0000000


text:
Q: Why @PreUpdate run in every query in JPA? I'm using @PreUpdate annotation in an entity class in Spring project as follow:
@Entity
public class Room {
   @Id
   @GeneratedValue
   private Long id;

   // Other fields and Getters and Setters

   @PreUpdate
   public void preUpdate(){
         System.out.println("pre Update");
   }
}

Now in every query, preUpdate method called, Even query to another entities. Is this logic is correct? I think It's a bit illogical.

A: A query triggers a flush of the first level cache.
This in turn triggers calls to preUpdate of the entities considered dirty, i.e. in need of flushing.
The reason for the flush is that JPA can't really tell how the changed state of entities might affect the result of the query.
So if you have for example a process where you load a bunch fo entities, then change them one by one based on some additional query you are basically alternate between editing and querying and causing flushes and therefore calls to preUpdate all the time.
So as far as we can tell from your question this seems to be completely as expected.


text:
Q: How to prevent my "push" from putting everything in one array? I have input fields, which are created based on my arrays in my JSON file.
However, when I insert something in my input fields, it goes right until I start inserting stuff in the input fields that aren't part of the other input fields. Don't worry, more explaining to come.
This is how my JSON looks like:
{
  "main_object": {
    "id": "5",
    "getExerciseTitle": "TestFor",
    "language": "nl_NL",
    "application": "lettergrepen",
    "main_object": {
      "title": "TestFor",
      "language": "nl_NL",
      "exercises": [{
          "word": "test",
          "syllables": [
            "test01",
            "test02",
            "test03",
            ""
          ]
        },
        {
          "word": "tesst",
          "syllables": [
            "test11",
            "test12",
            "",
            ""
          ]
        }
      ]
    },
    "dataType": "json"
  }
}

As you can see I have multiple arrays called syllables. What I am trying to do is: Create the push until it reaches the matched array in JSON, it should then change the input fields to buttons. However, when I go over to the next input fields that are linked to the second array, instead of starting the push from 0 it keeps on going.
A picture for you to see what I mean (note the console.log() too).

So: Instead of having the push start over it keeps on adding it to the already existing array. I want this NOT to happen so I can later on make a check that checks whether the push equals the array and then assign all the desired input fields to green buttons.
This is how my code looks like right now:
var x = [];

function prepareCheck() {
  $.getJSON('json_files/jsonData_' + ID + '.json', function(json) {
    $(document).on('change', '.syl-input', function() {
      var rowCounter = $(this).parent().parent().parent().parent().attr('id');
      var inputCounter = $(this).attr('id');
      var jsyl = json.main_object.main_object.exercises[rowCounter].syllables[inputCounter];
      var jsylall = json.main_object.main_object.exercises[rowCounter].syllables;
      var valueInput = $(this).val();
      console.log(jsylall);
      if (valueInput == jsyl) {
        var correctInput = $('<input/>', {
          'class': 'form-control',
          'type': 'text',
          'id': 'button' + CBC++,
          'value': valueInput
        });
        console.log(jsyl);
        x.push(valueInput);

        if (valueInput == '') {
          x.remove($(this).val());
        };
        console.log(x);

        $(this).replaceWith(correctInput);
        S.playRight();
        S.addRight();
      } else if ($.inArray(valueInput, jsylall) >= -1) {
        $(this).css({
          'color': '#e00413'
        });
        S.playWrong();
        S.addWrong();
      }

    });
  });
}

Question: How can I reset x.push again? so I can keep on checking whether the input fields have the desired words/length to change them to green buttons?


text:
Q: How to get EntityManager in class using abstract classes I have an abstract class like
class Importer
{
    public static function getInstance($url)
    {

    }

    protected function saveUser(User $user)
    {
        //here I want to use doctrine to save persist my User Entity
    }
}

and another class that extends that one
class XmlImporter extends Importer()
{
    public function processUser()
    {
         //do something with my data
         parent::processUser($user);
    }
}

pretty much standard situation. The problem is in saveUser I need to save my user on db (I am using mongo), so, how can I get the entity manager? I thougth I could use a service but I don't know where to receive it, in the child class or in the parent? Any other best practice I could follow.
thanks

A: It's very bad architecture if you need to get entity manager in your entity. Entity is the object like associated array. Everything what it need to do is to control internal properties. Entities can be used in different managers.
It will be better if you will create another service layer to control entities.
For example:
class User
{

    /* @ORM ... */
    private $id
    /* @ORM ... */
    private $name

    public function getId() {...}
    public function setName($name) {...}
    public function getName() {...}

    public function __toString()
    {
        return sprintf(
            'User [id: %s, name: "%s"',
            $this->getId() ? $this->getId() : '-',
            $this->getName()
        )
    }

}

class UserModel
{

    /** @var ContainerInterface */
    protected $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    protected function getEntityManager()
    {
        $em = $this->container->get('doctrine')->getManagerForClass('AppBundle:User');
        /** @var EntityManager $em */
        return $em;
    }

    protected function validatePersistFlush(User $user)
    {
        // validate
        $errors = $this->container->get('validator')->validate($user);
        if (count($errors)) {
            throw new \Exception(sprintf(
                '%s is not valid: %s',
                $user,
                (string)$errors
            ));
        }

        // persist
        $this->getEntityManager()->persist($user);

        // flush
        $this->getEntityManager()->flush($user);

    }

    public function create($name)
    {
        $user = new User();
        $user->setName($name);
        $this->validatePersistFlush($user)
        return $user;
    }

    public rename(User $user, $newName)
    {
        $user->setName($newName);
        $this->validatePersistFlush($user)
        return $user;
    }

}