问:
SelectIndexChanged not working (C# desktop)
**The autopostback-fix does not work! **

I have a GUI that looks like:

I want to show the details of a cat when it's clicked on.

I used this code for it:

```<code>private void listBox_Cats_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            // Get the currently selected item in the ListBox.
            Cat cat = listBox_Cats.SelectedItem as Cat;
            if (cat != null)
            {
                tb_ID.Text = cat.ID.ToString();
                tb_Name.Text = cat.Name.ToString();
                tb_DateArrived.Text = cat.DateArrived.ToString();
                tb_IsAdopted.Text = cat.IsAdopted.ToString();
                tb_adoptedBy.Text = cat.AdoptedBy.ToString();
            }
        }
</code>```

When running however, nothing seems to work. What am I doing wrong?

EDIT

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

using System.Data.SqlClient;

using IntegrationTool;

namespace IntegrationTool
{

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            SqlConnection conn = new SqlConnection("Server=.\\SQLEXPRESS;Database=CatShelter;Integrated Security=true");
            conn.Open();
            SqlCommand cmd = new SqlCommand("SELECT * FROM [dbo].[cats]", conn);
            SqlDataReader reader = cmd.ExecuteReader();

            List<Cat> cats = new List<Cat>();

            while (reader.Read())
            {
                Cat c = new Cat();
                c.ID = (int)reader["CatID"];
                c.Name = (string)reader["Name"];
                c.DateArrived = (DateTime)reader["DateArrived"];
                c.IsAdopted = (string)reader["IsAdopted"];
                c.AdoptedBy = (string)reader["AdoptedBy"];

                cats.Add(c);
            }

            foreach (Cat c in cats)
            {
                Console.WriteLine(c.Name);
            }

            reader.Close();
            conn.Close();

            if (Debugger.IsAttached)
            {
                Console.ReadLine();
            }

            listBox_Cats.DataSource = cats;
            listBox_Cats.DisplayMember = "Name";
            listBox_Cats.ValueMember = "ID";

        }

        private void listBox_Cats_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            // Get the currently selected item in the ListBox.
            Cat cat = listBox_Cats.SelectedItem as Cat;
            if (cat != null)
            {
                Console.WriteLine(cat.Name);
                tb_ID.Text = cat.ID.ToString();
                tb_Name.Text = cat.Name.ToString();
                tb_DateArrived.Text = cat.DateArrived.ToString();
                tb_IsAdopted.Text = cat.IsAdopted.ToString();
                tb_adoptedBy.Text = cat.AdoptedBy.ToString();
            }
        }
   }
}

namespace IntegrationTool
</code>```

{

```<code>  partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Windows Form Designer generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.listBox_Cats = new System.Windows.Forms.ListBox();
        this.groupBox1 = new System.Windows.Forms.GroupBox();
        this.label1 = new System.Windows.Forms.Label();
        this.label2 = new System.Windows.Forms.Label();
        this.label3 = new System.Windows.Forms.Label();
        this.label4 = new System.Windows.Forms.Label();
        this.groupBox2 = new System.Windows.Forms.GroupBox();
        this.button2 = new System.Windows.Forms.Button();
        this.cb_VetCheck = new System.Windows.Forms.CheckBox();
        this.label5 = new System.Windows.Forms.Label();
        this.tb_Comment = new System.Windows.Forms.TextBox();
        this.tb_ID = new System.Windows.Forms.TextBox();
        this.tb_DateArrived = new System.Windows.Forms.TextBox();
        this.tb_IsAdopted = new System.Windows.Forms.TextBox();
        this.tb_adoptedBy = new System.Windows.Forms.TextBox();
        this.groupBox3 = new System.Windows.Forms.GroupBox();
        this.label6 = new System.Windows.Forms.Label();
        this.tb_Name = new System.Windows.Forms.TextBox();
        this.groupBox1.SuspendLayout();
        this.groupBox2.SuspendLayout();
        this.groupBox3.SuspendLayout();
        this.SuspendLayout();
        //
        // listBox_Cats
        //
        this.listBox_Cats.FormattingEnabled = true;
        this.listBox_Cats.Location = new System.Drawing.Point(16, 35);
        this.listBox_Cats.Name = "listBox_Cats";
        this.listBox_Cats.Size = new System.Drawing.Size(137, 316);
        this.listBox_Cats.TabIndex = 0;
        //
        // groupBox1
        //
        this.groupBox1.Controls.Add(this.tb_Name);
        this.groupBox1.Controls.Add(this.label6);
        this.groupBox1.Controls.Add(this.tb_adoptedBy);
        this.groupBox1.Controls.Add(this.tb_IsAdopted);
        this.groupBox1.Controls.Add(this.tb_DateArrived);
        this.groupBox1.Controls.Add(this.tb_ID);
        this.groupBox1.Controls.Add(this.label4);
        this.groupBox1.Controls.Add(this.label3);
        this.groupBox1.Controls.Add(this.label2);
        this.groupBox1.Controls.Add(this.label1);
        this.groupBox1.Location = new System.Drawing.Point(252, 31);
        this.groupBox1.Name = "groupBox1";
        this.groupBox1.Size = new System.Drawing.Size(409, 190);
        this.groupBox1.TabIndex = 1;
        this.groupBox1.TabStop = false;
        this.groupBox1.Text = "Details";
        //
        // label1
        //
        this.label1.AutoSize = true;
        this.label1.Location = new System.Drawing.Point(6, 35);
        this.label1.Name = "label1";
        this.label1.Size = new System.Drawing.Size(24, 13);
        this.label1.TabIndex = 0;
        this.label1.Text = "ID: ";
        //
        // label2
        //
        this.label2.AutoSize = true;
        this.label2.Location = new System.Drawing.Point(6, 95);
        this.label2.Name = "label2";
        this.label2.Size = new System.Drawing.Size(69, 13);
        this.label2.TabIndex = 1;
        this.label2.Text = "Date Arrived:";
        //
        // label3
        //
        this.label3.AutoSize = true;
        this.label3.Location = new System.Drawing.Point(6, 123);
        this.label3.Name = "label3";
        this.label3.Size = new System.Drawing.Size(60, 13);
        this.label3.TabIndex = 2;
        this.label3.Text = "Is adopted:";
        //
        // label4
        //
        this.label4.AutoSize = true;
        this.label4.Location = new System.Drawing.Point(6, 157);
        this.label4.Name = "label4";
        this.label4.Size = new System.Drawing.Size(65, 13);
        this.label4.TabIndex = 3;
        this.label4.Text = "Adopted By:";
        //
        // groupBox2
        //
        this.groupBox2.Controls.Add(this.tb_Comment);
        this.groupBox2.Controls.Add(this.label5);
        this.groupBox2.Controls.Add(this.cb_VetCheck);
        this.groupBox2.Location = new System.Drawing.Point(252, 243);
        this.groupBox2.Name = "groupBox2";
        this.groupBox2.Size = new System.Drawing.Size(409, 157);
        this.groupBox2.TabIndex = 2;
        this.groupBox2.TabStop = false;
        this.groupBox2.Text = "Validate";
        //
        // button2
        //
        this.button2.Location = new System.Drawing.Point(553, 424);
        this.button2.Name = "button2";
        this.button2.Size = new System.Drawing.Size(107, 31);
        this.button2.TabIndex = 4;
        this.button2.Text = "Save";
        this.button2.UseVisualStyleBackColor = true;
        //
        // cb_VetCheck
        //
        this.cb_VetCheck.AutoSize = true;
        this.cb_VetCheck.Location = new System.Drawing.Point(9, 30);
        this.cb_VetCheck.Name = "cb_VetCheck";
        this.cb_VetCheck.Size = new System.Drawing.Size(76, 17);
        this.cb_VetCheck.TabIndex = 0;
        this.cb_VetCheck.Text = "Vet Check";
        this.cb_VetCheck.UseVisualStyleBackColor = true;
        //
        // label5
        //
        this.label5.AutoSize = true;
        this.label5.Location = new System.Drawing.Point(6, 75);
        this.label5.Name = "label5";
        this.label5.Size = new System.Drawing.Size(51, 13);
        this.label5.TabIndex = 1;
        this.label5.Text = "Comment";
        //
        // tb_Comment
        //
        this.tb_Comment.Location = new System.Drawing.Point(9, 91);
        this.tb_Comment.Name = "tb_Comment";
        this.tb_Comment.Size = new System.Drawing.Size(288, 20);
        this.tb_Comment.TabIndex = 2;
        //
        // tb_ID
        //
        this.tb_ID.Location = new System.Drawing.Point(81, 35);
        this.tb_ID.Name = "tb_ID";
        this.tb_ID.ReadOnly = true;
        this.tb_ID.Size = new System.Drawing.Size(66, 20);
        this.tb_ID.TabIndex = 4;
        //
        // tb_DateArrived
        //
        this.tb_DateArrived.Location = new System.Drawing.Point(81, 92);
        this.tb_DateArrived.Name = "tb_DateArrived";
        this.tb_DateArrived.ReadOnly = true;
        this.tb_DateArrived.Size = new System.Drawing.Size(66, 20);
        this.tb_DateArrived.TabIndex = 5;
        //
        // tb_IsAdopted
        //
        this.tb_IsAdopted.Location = new System.Drawing.Point(81, 120);
        this.tb_IsAdopted.Name = "tb_IsAdopted";
        this.tb_IsAdopted.ReadOnly = true;
        this.tb_IsAdopted.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
        this.tb_IsAdopted.Size = new System.Drawing.Size(66, 20);
        this.tb_IsAdopted.TabIndex = 6;
        //
        // tb_adoptedBy
        //
        this.tb_adoptedBy.Location = new System.Drawing.Point(81, 154);
        this.tb_adoptedBy.Name = "tb_adoptedBy";
        this.tb_adoptedBy.ReadOnly = true;
        this.tb_adoptedBy.Size = new System.Drawing.Size(66, 20);
        this.tb_adoptedBy.TabIndex = 7;
        //
        // groupBox3
        //
        this.groupBox3.Controls.Add(this.listBox_Cats);
        this.groupBox3.Location = new System.Drawing.Point(12, 31);
        this.groupBox3.Name = "groupBox3";
        this.groupBox3.Size = new System.Drawing.Size(175, 369);
        this.groupBox3.TabIndex = 5;
        this.groupBox3.TabStop = false;
        this.groupBox3.Text = "Cats";
        //
        // label6
        //
        this.label6.AutoSize = true;
        this.label6.Location = new System.Drawing.Point(7, 61);
        this.label6.Name = "label6";
        this.label6.Size = new System.Drawing.Size(41, 13);
        this.label6.TabIndex = 8;
        this.label6.Text = "Name: ";
        //
        // tb_Name
        //
        this.tb_Name.Location = new System.Drawing.Point(81, 61);
        this.tb_Name.Name = "tb_Name";
        this.tb_Name.ReadOnly = true;
        this.tb_Name.Size = new System.Drawing.Size(66, 20);
        this.tb_Name.TabIndex = 9;
        //
        // Form1
        //
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(721, 480);
        this.Controls.Add(this.groupBox3);
        this.Controls.Add(this.button2);
        this.Controls.Add(this.groupBox2);
        this.Controls.Add(this.groupBox1);
        this.Name = "Form1";
        this.Text = "Form1";
        this.groupBox1.ResumeLayout(false);
        this.groupBox1.PerformLayout();
        this.groupBox2.ResumeLayout(false);
        this.groupBox2.PerformLayout();
        this.groupBox3.ResumeLayout(false);
        this.ResumeLayout(false);

    }

    #endregion

    private System.Windows.Forms.ListBox listBox_Cats;
    private System.Windows.Forms.GroupBox groupBox1;
    private System.Windows.Forms.Label label1;
    private System.Windows.Forms.TextBox tb_adoptedBy;
    private System.Windows.Forms.TextBox tb_IsAdopted;
    private System.Windows.Forms.TextBox tb_DateArrived;
    private System.Windows.Forms.TextBox tb_ID;
    private System.Windows.Forms.Label label4;
    private System.Windows.Forms.Label label3;
    private System.Windows.Forms.Label label2;
    private System.Windows.Forms.GroupBox groupBox2;
    private System.Windows.Forms.TextBox tb_Comment;
    private System.Windows.Forms.Label label5;
    private System.Windows.Forms.CheckBox cb_VetCheck;
    private System.Windows.Forms.Button button2;
    private System.Windows.Forms.GroupBox groupBox3;
    private System.Windows.Forms.TextBox tb_Name;
    private System.Windows.Forms.Label label6;
}
</code>```

}

答:
Your listbox(listBox_Cats) has Cat as a Complex type so try to get the selected item by below code and see it works.</p>

```<code>Cat value = (Cat) this.listBox_Cats.SelectedItem;
</code>```

Body:
**The autopostback-fix does not work! **

I have a GUI that looks like:

I want to show the details of a cat when it's clicked on.

I used this code for it:

private void listBox_Cats_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            // Get the currently selected item in the ListBox.
            Cat cat = listBox_Cats.SelectedItem as Cat;
            if (cat != null)
            {
                tb_ID.Text = cat.ID.ToString();
                tb_Name.Text = cat.Name.ToString();
                tb_DateArrived.Text = cat.DateArrived.ToString();
                tb_IsAdopted.Text = cat.IsAdopted.ToString();
                tb_adoptedBy.Text = cat.AdoptedBy.ToString();
            }
        }

When running however, nothing seems to work. What am I doing wrong?

EDIT

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

using System.Data.SqlClient;

using IntegrationTool;

namespace IntegrationTool
{

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            SqlConnection conn = new SqlConnection("Server=.\\SQLEXPRESS;Database=CatShelter;Integrated Security=true");
            conn.Open();
            SqlCommand cmd = new SqlCommand("SELECT * FROM [dbo].[cats]", conn);
            SqlDataReader reader = cmd.ExecuteReader();

            List<Cat> cats = new List<Cat>();

            while (reader.Read())
            {
                Cat c = new Cat();
                c.ID = (int)reader["CatID"];
                c.Name = (string)reader["Name"];
                c.DateArrived = (DateTime)reader["DateArrived"];
                c.IsAdopted = (string)reader["IsAdopted"];
                c.AdoptedBy = (string)reader["AdoptedBy"];

                cats.Add(c);
            }

            foreach (Cat c in cats)
            {
                Console.WriteLine(c.Name);
            }

            reader.Close();
            conn.Close();

            if (Debugger.IsAttached)
            {
                Console.ReadLine();
            }

            listBox_Cats.DataSource = cats;
            listBox_Cats.DisplayMember = "Name";
            listBox_Cats.ValueMember = "ID";

        }

        private void listBox_Cats_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            // Get the currently selected item in the ListBox.
            Cat cat = listBox_Cats.SelectedItem as Cat;
            if (cat != null)
            {
                Console.WriteLine(cat.Name);
                tb_ID.Text = cat.ID.ToString();
                tb_Name.Text = cat.Name.ToString();
                tb_DateArrived.Text = cat.DateArrived.ToString();
                tb_IsAdopted.Text = cat.IsAdopted.ToString();
                tb_adoptedBy.Text = cat.AdoptedBy.ToString();
            }
        }
   }
}

namespace IntegrationTool

{

  partial class Form1
    {
        ///
        /// Required designer variable.
        ///
        private System.ComponentModel.IContainer components = null;

    ///
    /// Clean up any resources being used.
    ///
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Windows Form Designer generated code

    ///
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    ///
    private void InitializeComponent()
    {
        this.listBox_Cats = new System.Windows.Forms.ListBox();
        this.groupBox1 = new System.Windows.Forms.GroupBox();
        this.label1 = new System.Windows.Forms.Label();
        this.label2 = new System.Windows.Forms.Label();
        this.label3 = new System.Windows.Forms.Label();
        this.label4 = new System.Windows.Forms.Label();
        this.groupBox2 = new System.Windows.Forms.GroupBox();
        this.button2 = new System.Windows.Forms.Button();
        this.cb_VetCheck = new System.Windows.Forms.CheckBox();
        this.label5 = new System.Windows.Forms.Label();
        this.tb_Comment = new System.Windows.Forms.TextBox();
        this.tb_ID = new System.Windows.Forms.TextBox();
        this.tb_DateArrived = new System.Windows.Forms.TextBox();
        this.tb_IsAdopted = new System.Windows.Forms.TextBox();
        this.tb_adoptedBy = new System.Windows.Forms.TextBox();
        this.groupBox3 = new System.Windows.Forms.GroupBox();
        this.label6 = new System.Windows.Forms.Label();
        this.tb_Name = new System.Windows.Forms.TextBox();
        this.groupBox1.SuspendLayout();
        this.groupBox2.SuspendLayout();
        this.groupBox3.SuspendLayout();
        this.SuspendLayout();
        //
        // listBox_Cats
        //
        this.listBox_Cats.FormattingEnabled = true;
        this.listBox_Cats.Location = new System.Drawing.Point(16, 35);
        this.listBox_Cats.Name = "listBox_Cats";
        this.listBox_Cats.Size = new System.Drawing.Size(137, 316);
        this.listBox_Cats.TabIndex = 0;
        //
        // groupBox1
        //
        this.groupBox1.Controls.Add(this.tb_Name);
        this.groupBox1.Controls.Add(this.label6);
        this.groupBox1.Controls.Add(this.tb_adoptedBy);
        this.groupBox1.Controls.Add(this.tb_IsAdopted);
        this.groupBox1.Controls.Add(this.tb_DateArrived);
        this.groupBox1.Controls.Add(this.tb_ID);
        this.groupBox1.Controls.Add(this.label4);
        this.groupBox1.Controls.Add(this.label3);
        this.groupBox1.Controls.Add(this.label2);
        this.groupBox1.Controls.Add(this.label1);
        this.groupBox1.Location = new System.Drawing.Point(252, 31);
        this.groupBox1.Name = "groupBox1";
        this.groupBox1.Size = new System.Drawing.Size(409, 190);
        this.groupBox1.TabIndex = 1;
        this.groupBox1.TabStop = false;
        this.groupBox1.Text = "Details";
        //
        // label1
        //
        this.label1.AutoSize = true;
        this.label1.Location = new System.Drawing.Point(6, 35);
        this.label1.Name = "label1";
        this.label1.Size = new System.Drawing.Size(24, 13);
        this.label1.TabIndex = 0;
        this.label1.Text = "ID: ";
        //
        // label2
        //
        this.label2.AutoSize = true;
        this.label2.Location = new System.Drawing.Point(6, 95);
        this.label2.Name = "label2";
        this.label2.Size = new System.Drawing.Size(69, 13);
        this.label2.TabIndex = 1;
        this.label2.Text = "Date Arrived:";
        //
        // label3
        //
        this.label3.AutoSize = true;
        this.label3.Location = new System.Drawing.Point(6, 123);
        this.label3.Name = "label3";
        this.label3.Size = new System.Drawing.Size(60, 13);
        this.label3.TabIndex = 2;
        this.label3.Text = "Is adopted:";
        //
        // label4
        //
        this.label4.AutoSize = true;
        this.label4.Location = new System.Drawing.Point(6, 157);
        this.label4.Name = "label4";
        this.label4.Size = new System.Drawing.Size(65, 13);
        this.label4.TabIndex = 3;
        this.label4.Text = "Adopted By:";
        //
        // groupBox2
        //
        this.groupBox2.Controls.Add(this.tb_Comment);
        this.groupBox2.Controls.Add(this.label5);
        this.groupBox2.Controls.Add(this.cb_VetCheck);
        this.groupBox2.Location = new System.Drawing.Point(252, 243);
        this.groupBox2.Name = "groupBox2";
        this.groupBox2.Size = new System.Drawing.Size(409, 157);
        this.groupBox2.TabIndex = 2;
        this.groupBox2.TabStop = false;
        this.groupBox2.Text = "Validate";
        //
        // button2
        //
        this.button2.Location = new System.Drawing.Point(553, 424);
        this.button2.Name = "button2";
        this.button2.Size = new System.Drawing.Size(107, 31);
        this.button2.TabIndex = 4;
        this.button2.Text = "Save";
        this.button2.UseVisualStyleBackColor = true;
        //
        // cb_VetCheck
        //
        this.cb_VetCheck.AutoSize = true;
        this.cb_VetCheck.Location = new System.Drawing.Point(9, 30);
        this.cb_VetCheck.Name = "cb_VetCheck";
        this.cb_VetCheck.Size = new System.Drawing.Size(76, 17);
        this.cb_VetCheck.TabIndex = 0;
        this.cb_VetCheck.Text = "Vet Check";
        this.cb_VetCheck.UseVisualStyleBackColor = true;
        //
        // label5
        //
        this.label5.AutoSize = true;
        this.label5.Location = new System.Drawing.Point(6, 75);
        this.label5.Name = "label5";
        this.label5.Size = new System.Drawing.Size(51, 13);
        this.label5.TabIndex = 1;
        this.label5.Text = "Comment";
        //
        // tb_Comment
        //
        this.tb_Comment.Location = new System.Drawing.Point(9, 91);
        this.tb_Comment.Name = "tb_Comment";
        this.tb_Comment.Size = new System.Drawing.Size(288, 20);
        this.tb_Comment.TabIndex = 2;
        //
        // tb_ID
        //
        this.tb_ID.Location = new System.Drawing.Point(81, 35);
        this.tb_ID.Name = "tb_ID";
        this.tb_ID.ReadOnly = true;
        this.tb_ID.Size = new System.Drawing.Size(66, 20);
        this.tb_ID.TabIndex = 4;
        //
        // tb_DateArrived
        //
        this.tb_DateArrived.Location = new System.Drawing.Point(81, 92);
        this.tb_DateArrived.Name = "tb_DateArrived";
        this.tb_DateArrived.ReadOnly = true;
        this.tb_DateArrived.Size = new System.Drawing.Size(66, 20);
        this.tb_DateArrived.TabIndex = 5;
        //
        // tb_IsAdopted
        //
        this.tb_IsAdopted.Location = new System.Drawing.Point(81, 120);
        this.tb_IsAdopted.Name = "tb_IsAdopted";
        this.tb_IsAdopted.ReadOnly = true;
        this.tb_IsAdopted.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
        this.tb_IsAdopted.Size = new System.Drawing.Size(66, 20);
        this.tb_IsAdopted.TabIndex = 6;
        //
        // tb_adoptedBy
        //
        this.tb_adoptedBy.Location = new System.Drawing.Point(81, 154);
        this.tb_adoptedBy.Name = "tb_adoptedBy";
        this.tb_adoptedBy.ReadOnly = true;
        this.tb_adoptedBy.Size = new System.Drawing.Size(66, 20);
        this.tb_adoptedBy.TabIndex = 7;
        //
        // groupBox3
        //
        this.groupBox3.Controls.Add(this.listBox_Cats);
        this.groupBox3.Location = new System.Drawing.Point(12, 31);
        this.groupBox3.Name = "groupBox3";
        this.groupBox3.Size = new System.Drawing.Size(175, 369);
        this.groupBox3.TabIndex = 5;
        this.groupBox3.TabStop = false;
        this.groupBox3.Text = "Cats";
        //
        // label6
        //
        this.label6.AutoSize = true;
        this.label6.Location = new System.Drawing.Point(7, 61);
        this.label6.Name = "label6";
        this.label6.Size = new System.Drawing.Size(41, 13);
        this.label6.TabIndex = 8;
        this.label6.Text = "Name: ";
        //
        // tb_Name
        //
        this.tb_Name.Location = new System.Drawing.Point(81, 61);
        this.tb_Name.Name = "tb_Name";
        this.tb_Name.ReadOnly = true;
        this.tb_Name.Size = new System.Drawing.Size(66, 20);
        this.tb_Name.TabIndex = 9;
        //
        // Form1
        //
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(721, 480);
        this.Controls.Add(this.groupBox3);
        this.Controls.Add(this.button2);
        this.Controls.Add(this.groupBox2);
        this.Controls.Add(this.groupBox1);
        this.Name = "Form1";
        this.Text = "Form1";
        this.groupBox1.ResumeLayout(false);
        this.groupBox1.PerformLayout();
        this.groupBox2.ResumeLayout(false);
        this.groupBox2.PerformLayout();
        this.groupBox3.ResumeLayout(false);
        this.ResumeLayout(false);

    }

    #endregion

    private System.Windows.Forms.ListBox listBox_Cats;
    private System.Windows.Forms.GroupBox groupBox1;
    private System.Windows.Forms.Label label1;
    private System.Windows.Forms.TextBox tb_adoptedBy;
    private System.Windows.Forms.TextBox tb_IsAdopted;
    private System.Windows.Forms.TextBox tb_DateArrived;
    private System.Windows.Forms.TextBox tb_ID;
    private System.Windows.Forms.Label label4;
    private System.Windows.Forms.Label label3;
    private System.Windows.Forms.Label label2;
    private System.Windows.Forms.GroupBox groupBox2;
    private System.Windows.Forms.TextBox tb_Comment;
    private System.Windows.Forms.Label label5;
    private System.Windows.Forms.CheckBox cb_VetCheck;
    private System.Windows.Forms.Button button2;
    private System.Windows.Forms.GroupBox groupBox3;
    private System.Windows.Forms.TextBox tb_Name;
    private System.Windows.Forms.Label label6;
}

}

Body:
Your listbox(listBox_Cats) has Cat as a Complex type so try to get the selected item by below code and see it works.

Cat value = (Cat) this.listBox_Cats.SelectedItem;


来源: stackexchange

问:
Can I populate Session Variable with a query result?
Is populating PHP session variables with a query result possible - if so,

what is the proper syntax?

My code:-

```<code>session_start();
while($rows=mysql_fetch_array($result)){
   $_SESSION['userid'] = $rows['id'];
   $_SESSION['firstname'] = $rows['firstname'];
   $_SESSION['lastname'] = $rows['lastname'];
}
</code>```

I tried this code above with no positive result.

答:
if you want to get single row then update your query and simple use this code

```<code>session_start();
$rows=mysql_fetch_array($result);
$_SESSION['userid'][] = $rows['id'];
$_SESSION['firstname'][] = $rows['firstname'];
$_SESSION['lastname'][] = $rows['lastname'];
</code>```

and if you multiple data then use this code

```<code>session_start();
while($rows=mysql_fetch_array($result)){
   $_SESSION['userid'][] = $rows['id'];
    $_SESSION['firstname'][] = $rows['firstname'];
    $_SESSION['lastname'][] = $rows['lastname'];
}
</code>```

and if you want to store total row data then use this code

```<code>$rows=mysql_fetch_array($result);
$_SESSION['data'] = $rows;
</code>```

this is another method which first store your data in variable then assign to session

```<code>session_start();
$your_data='';
while($rows=mysql_fetch_array($result)){
    $user_info['userid'] = $rows['id'];
    $user_info['firstname'] = $rows['firstname'];
    $user_info['lastname'] = $rows['lastname'];
    $your_data[]=$user_info;

}
$_SESSION['your_data'] = $your_data;
</code>```

hope it will help you

ContentLicense: CC BY-SA 3.0

Body:
Is populating PHP session variables with a query result possible - if so,

what is the proper syntax?

My code:-

session_start();
while($rows=mysql_fetch_array($result)){
   $_SESSION['userid'] = $rows['id'];
   $_SESSION['firstname'] = $rows['firstname'];
   $_SESSION['lastname'] = $rows['lastname'];
}

I tried this code above with no positive result.

Body:
if you want to get single row then update your query and simple use this code

session_start();
$rows=mysql_fetch_array($result);
$_SESSION['userid'][] = $rows['id'];
$_SESSION['firstname'][] = $rows['firstname'];
$_SESSION['lastname'][] = $rows['lastname'];

and if you multiple data then use this code

session_start();
while($rows=mysql_fetch_array($result)){
   $_SESSION['userid'][] = $rows['id'];
    $_SESSION['firstname'][] = $rows['firstname'];
    $_SESSION['lastname'][] = $rows['lastname'];
}

and if you want to store total row data then use this code

$rows=mysql_fetch_array($result);
$_SESSION['data'] = $rows;

this is another method which first store your data in variable then assign to session

session_start();
$your_data='';
while($rows=mysql_fetch_array($result)){
    $user_info['userid'] = $rows['id'];
    $user_info['firstname'] = $rows['firstname'];
    $user_info['lastname'] = $rows['lastname'];
    $your_data[]=$user_info;

}
$_SESSION['your_data'] = $your_data;

hope it will help you


问:
Is there a way to restrict communication between two containers on the same pod to have improved isolation?
I have deployed two containers on a pod. One is privileged and the other is a normal user container. I want to restrict communication between the two containers so that they cannot access each other or talk to each other on local host. </p>

答:
Containers on the same Pod share the same network namespace and can reach each other on localhost. It as if the pods are on the same computer/machine/vm.

See here:
https://kubernetes.io/docs/concepts/workloads/pods/pod/#resource-sharing-and-communication

and here:
https://kubernetes.io/docs/concepts/cluster-administration/networking/


问:
Pass a layout from one activity to another
How do I pass an exactly looking RelativeLayout from one activity to another. The result shoul look something like this: Example

To explain:

I have a GridView which is populated from database using SimpleCursorAdapter and a partial layout.
Partial layout looks something like this:

```<code><RelativeLayout>
    <TextView/>
    <TextView/>
    <Button/>
    <Button/>
</RelativeLayout>
</code>```

When user clicks on a details button of an item, I woud like to pass that item's RelativeLayout to the DetailsActivity.

As I understand it cloning is not posible and inflating is not an option.

I coud pass every id, tag and text value and recreate a layout but I'm hopinbg there's an easier way.

答:
You can't pass a layout.

What you can do is

use the same layout resource (defined in xml) in both the places.

pass the data to be used in layout from one screen to other.

Body:
How do I pass an exactly looking RelativeLayout from one activity to another. The result shoul look something like this: Example

To explain:

I have a GridView which is populated from database using SimpleCursorAdapter and a partial layout.
Partial layout looks something like this:

<RelativeLayout>
    <TextView/>
    <TextView/>
    <Button/>
    <Button/>
</RelativeLayout>

When user clicks on a details button of an item, I woud like to pass that item's RelativeLayout to the DetailsActivity.

As I understand it cloning is not posible and inflating is not an option.

I coud pass every id, tag and text value and recreate a layout but I'm hopinbg there's an easier way.


问:
How to create uuid4 file names for images uploaded with Django-CKEeditor?
I want to create random uid file names for images uploaded with the django-ckeditor/uploader.

I've created utils.py in the same folder as settings.py:

```<code>import uuid

def get_name_uid():
    ext = filename.split('.')[-1]
    filename = "%s.%s" % (uuid.uuid4(), ext)
    return filename
</code>```

I would like to add this "random" file name to settings.py:

```<code>CKEDITOR_FILENAME_GENERATOR = get_name_uid()
</code>```

How can I do this? I am not sure how to get the filename that is uploaded in the editor. Should I pass the filename from settings.py to utils.py? Or is there a different way to do this?

Their documentation says the following:

```<code>``CKEDITOR_UPLOAD_PATH = "uploads/"``

When using default file system storage, images will be uploaded to "uploads" folder in your MEDIA_ROOT and urls will be created against MEDIA_URL (/media/uploads/image.jpg).

If you want be able for have control for filename generation, you have to add into settings yours custom filename generator.

```
# utils.py

def get_filename(filename):
    return filename.upper()
```

```
# settings.py

CKEDITOR_FILENAME_GENERATOR = 'utils.get_filename'
```

CKEditor has been tested with django FileSystemStorage and S3BotoStorage.
There are issues using S3Storage from django-storages.
</code>```

答:
It's basically all spelled out for you in the docs:

```<code>def get_filename(filename):
    return filename.upper()  # returns the uppercase version of filename
</code>```

So the example function get_filename gets the uploaded filename passed in and you're supposed to return the filename you want it to be. This is what we call a callback.

What the callback gets passed in as arguments is called the "callback signature" and the docs specify neatly what it gets.

So put the function in a place where it makes sense. I would choose mysite/mysite/utils.py given the structure outlined in the tutorial, under the heading "Let’s look at what startproject created:". So in the same directory as settings.py. I would name it generate_uuid4_filename and mysite/mysite/utils.py would look like this:

```<code>import uuid
import os.path

def generate_uuid4_filename(filename):
    """
    Generates a uuid4 (random) filename, keeping file extension

    :param filename: Filename passed in. In the general case, this will
                     be provided by django-ckeditor's uploader.
    :return: Randomized filename in urn format.
    :rtype: str
    """
    discard, ext = os.path.splitext(filename)
    basename = uuid.uuid4().urn
    return ''.join(basename, ext)
</code>```

Now update your settings.py:

```<code># Near the rest of the CKEditor variables
CKEDITOR_FILENAME_GENERATOR = '<app_label>.utils.generate_uuid4_filename'
</code>```

And you're done. Good luck!

Body:
I want to create random uid file names for images uploaded with the django-ckeditor/uploader.

I've created utils.py in the same folder as settings.py:

import uuid

def get_name_uid():
    ext = filename.split('.')[-1]
    filename = "%s.%s" % (uuid.uuid4(), ext)
    return filename

I would like to add this "random" file name to settings.py:

CKEDITOR_FILENAME_GENERATOR = get_name_uid()

How can I do this? I am not sure how to get the filename that is uploaded in the editor. Should I pass the filename from settings.py to utils.py? Or is there a different way to do this?

Their documentation says the following:

``CKEDITOR_UPLOAD_PATH = "uploads/"``

When using default file system storage, images will be uploaded to "uploads" folder in your MEDIA_ROOT and urls will be created against MEDIA_URL (/media/uploads/image.jpg).

If you want be able for have control for filename generation, you have to add into settings yours custom filename generator.

```
# utils.py

def get_filename(filename):
    return filename.upper()
```

```
# settings.py

CKEDITOR_FILENAME_GENERATOR = 'utils.get_filename'
```

CKEditor has been tested with django FileSystemStorage and S3BotoStorage.
There are issues using S3Storage from django-storages.

Body:
It's basically all spelled out for you in the docs:

def get_filename(filename):
    return filename.upper()  # returns the uppercase version of filename

So the example function get_filename gets the uploaded filename passed in and you're supposed to return the filename you want it to be. This is what we call a callback.

What the callback gets passed in as arguments is called the "callback signature" and the docs specify neatly what it gets.

So put the function in a place where it makes sense. I would choose mysite/mysite/utils.py given the structure outlined in the tutorial, under the heading "Let’s look at what startproject created:". So in the same directory as settings.py. I would name it generate_uuid4_filename and mysite/mysite/utils.py would look like this:

import uuid
import os.path

def generate_uuid4_filename(filename):
    """
    Generates a uuid4 (random) filename, keeping file extension

    :param filename: Filename passed in. In the general case, this will
                     be provided by django-ckeditor's uploader.
    :return: Randomized filename in urn format.
    :rtype: str
    """
    discard, ext = os.path.splitext(filename)
    basename = uuid.uuid4().urn
    return ''.join(basename, ext)

Now update your settings.py:

# Near the rest of the CKEditor variables
CKEDITOR_FILENAME_GENERATOR = '<app_label>.utils.generate_uuid4_filename'

And you're done. Good luck!


问:
C# - Send data from console application to another console application
I have an XML file read from A console application and need to send value to B console application depending on logic in the following photo:

That's what exactly needs:

Please I need your support it's so important, Thanks.

答:
You could use a WCF Service (utilizing NetNamedPipeBinding for example, if running on the same machine, NetTcpBinding if going across the network) to distribute the data to different clients.
You would need to implement a Contract with a "Subscribe" method for example where every client sends its ID so you can have a CallBack sending them the data.
Alternatively your contract could just have a method passing the ID of the client and getting the XML returned.

Here you can see a minimal implementation to get you started: WCF named pipe minimal example


问:
How to fill all rows in a column with data from other columns?
I have a dataset called 'names' as shown below. The 'expected.entry.in.this.col' column is currently empty, but below I have shown how it should look. How can I write the logic?

Basically I think I'll need to run a loop through every row and for each row, use an 'if' condition to check the format and then enter the data into 'expected.entry.in.this.col' appropriately. How would I go about doing this? (a bit unfamiliar with R syntax for these kind of tasks).

names

EDIT: row 3 is a mistake and should read williams.harry

答:
try something like this:</p>

```<code>df <- data.frame(first = c("Kevin", "Megan"), last = c("Spacey", "Fox"),
                 format = c("f.last", "F.L."))

df$new <- NA
df$new <- ifelse(df$format == "f.last",
                 tolower(paste0(substr(df$first,1,1),".",df$last)),
                 df$new)
df$new <- ifelse(df$format == "F.L.",
                 paste0(substr(df$first,1,1),".", substr(df$last,1,1)),
                 df$new)

df

  first   last format      new
1 Kevin Spacey f.last k.spacey
2 Megan    Fox   F.L.      M.F
</code>```

Body:
try something like this:

df <- data.frame(first = c("Kevin", "Megan"), last = c("Spacey", "Fox"),
                 format = c("f.last", "F.L."))

df$new <- NA
df$new <- ifelse(df$format == "f.last",
                 tolower(paste0(substr(df$first,1,1),".",df$last)),
                 df$new)
df$new <- ifelse(df$format == "F.L.",
                 paste0(substr(df$first,1,1),".", substr(df$last,1,1)),
                 df$new)

df

  first   last format      new
1 Kevin Spacey f.last k.spacey
2 Megan    Fox   F.L.      M.F


问:
Can local intranet application (built on php) query mysql database stored in offsite location?
I have a local intranet application which runs off a basic WAMP server in our offices. Every morning, one of our team members manually syncs our internal mysql db with our external mysql db (where our online enrollments occur). If a change is made during the day on the intranet application, it is not reflected on the external db until the following day.

I am wondering if it is possible to (essentially) tunnel to an external mysql connection from say a wamp or xampp server from within our offices and work in 'real-time'.

Anybody had any luck or advice?

答:
Yes

Replication enables data from one MySQL database server (the master) to be replicated to one or more MySQL database servers (the slaves). Replication is asynchronous - slaves need not to connected permanently to receive updates from the master. This means that updates can occur over long-distance connections and even over temporary or intermittent connections such as a dial-up service. Depending on the configuration, you can replicate all databases, selected databases, or even selected tables within a database.

If you use the external server directly, performance is likely to suffer. A Gigabit LAN might be a thousand times faster than your Internet connection - particularly the upload speed of an ADSL connection.

ContentLicense: CC BY-SA 2.5


问:
How to configure gulp's dependencies to prevent running 'clean' each time watch is triggered
With a simple build structure as follow (where {...} stand for non relevant callbacks):

```<code>gulp.task('clean', {...}); //task I want to run once before the first build
gulp.task('build', ['clean'], {...}); //task I want to run at each change

gulp.task('watch, ['build'], function() {
  gulp.watch('./', ['build']);
});

gulp.task('default', ['watch']);
</code>```

Each time the 'watch' is triggered, the 'clean' task is run before the 'build' task... I would like to avoid to re-run 'clean' each time.

I tried for a while to find a dependencies structure that would allow that or a tool I would have missed but I didn't find any solutions that didn't seems overly complicated.

What would be the best way to deal with this ?

答:
use 2 different tasks.</p>

```<code>gulp.task('build-with-clean', ['clean'], {...});
gulp.task('build-to-watch', {...});
gulp.task('watch', ['build-to-watch'], function() {
  gulp.watch('./', ['build-to-watch']);
});
</code>```

Body:
With a simple build structure as follow (where {...} stand for non relevant callbacks):

gulp.task('clean', {...}); //task I want to run once before the first build
gulp.task('build', ['clean'], {...}); //task I want to run at each change

gulp.task('watch, ['build'], function() {
  gulp.watch('./', ['build']);
});

gulp.task('default', ['watch']);

Each time the 'watch' is triggered, the 'clean' task is run before the 'build' task... I would like to avoid to re-run 'clean' each time.

I tried for a while to find a dependencies structure that would allow that or a tool I would have missed but I didn't find any solutions that didn't seems overly complicated.

What would be the best way to deal with this ?

Body:
use 2 different tasks.

gulp.task('build-with-clean', ['clean'], {...});
gulp.task('build-to-watch', {...});
gulp.task('watch', ['build-to-watch'], function() {
  gulp.watch('./', ['build-to-watch']);
});


问:
How do I dynamically load and display html which contains routerLink directives in Angular 2?
I have an Angular 2 component which, on some user action, loads html from a database. The html contains anchor tags with relative paths. Given that I don't want the whole application to reload when the user clicks the link, I am trying to use the routerLink directive; however, since this html is loaded dynamically, the routerLink is not processed. The html will not contain any other angular directives. What is the simplest way to achieve this? See my example below.</p>

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `<h1>Hello {{name}}</h1>
             <p><a (click)="GetTextFromDatabase()">Get data from database</a> which should contain a <a routerLink="/some-route">working link</a></p>
             <div [innerHTML]="data"></div>
             <router-outlet></router-outlet>`,
})
export class AppComponent  {
   name: string = 'Angular';
   data: string;

   private GetTextFromDatabase(): void {
      this.data = '<p>here is my paragraph containing a <a routerLink="/some-route">link</a>';
   }
}
</code>```

答:
I would just keep it simple.

If possible replace the links with  tags and use CSS to make them look like links. Rewrite them as link.

In your template use a click listener:

```<code><div [innerHTML]="data" (click)="onDataClick($event)"></div>
</code>```

In your component read the click target:

```<code>public onDataClick(event: Event) {
      if(event.target.tagName.toLowerCase() === 'span') {
          const link = event.target.getAttribute('link');
          // call the router to navigate to the new route
          console.log(link)
      }
}
</code>```

That should be enough to get the links working.

Technically, you don't really have to rewrite the tags to . The routerLink=""> would work as well since it has no href attribute to trigger a browser URL change. Just read the routerLink attribute instead of my example.

Body:
I have an Angular 2 component which, on some user action, loads html from a database. The html contains anchor tags with relative paths. Given that I don't want the whole application to reload when the user clicks the link, I am trying to use the routerLink directive; however, since this html is loaded dynamically, the routerLink is not processed. The html will not contain any other angular directives. What is the simplest way to achieve this? See my example below.

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
Hello {{name}}

Get data from database which should contain a working link

             <router-outlet></router-outlet>`,
})
export class AppComponent  {
   name: string = 'Angular';
   data: string;

   private GetTextFromDatabase(): void {
      this.data = '
here is my paragraph containing a link';
   }
}

Body:
I would just keep it simple.

If possible replace the links with <span> tags and use CSS to make them look like links. Rewrite them as <span data-link="/some-route">link</span>.

In your template use a click listener:

<div [innerHTML]="data" (click)="onDataClick($event)"></div>

In your component read the click target:

public onDataClick(event: Event) {
      if(event.target.tagName.toLowerCase() === 'span') {
          const link = event.target.getAttribute('link');
          // call the router to navigate to the new route
          console.log(link)
      }
}

That should be enough to get the links working.

Technically, you don't really have to rewrite the tags to <span>. The <a routerLink=""> would work as well since it has no href attribute to trigger a browser URL change. Just read the routerLink attribute instead of my example.


问:
readable code lines R
Is there a shortcut to add a new line into the R (RStudio) code?

I would like to avoid something like gapminder%>%filter(continent=="Asia")%>%group_by(year)%>%summarise(mean_pop=mean(pop))%>%ggplot(aes(x=year,y=mean_pop))+geom_point()+geom_line()+theme_bw()

by using

```<code>gapminder %>%
   filter(continent == "Asia") %>%
   group_by(year) %>%
   summarise(mean_pop = mean(pop)) %>%
     ggplot(aes(x = year, y = mean_pop)) +
     geom_point() +
     geom_line() +
     theme_bw()
</code>```

but without holding the space bar all the time..  and I googled now nearly half an hour and just didn't find a shortcut. Can't believe it?!
So how all are doing this?

答:
RStudio has separate windows for editing code and executing commands:

In this case, the top left is the code editor (but the layout is modifiable). Below is the console.

To edit code, create a new file or open an existing file, and edit it in the code editor. RStudio will automatically attempt to format your code as appropriate when you hit Return.

To execute code you’ve written in the code editor there are several choices. To execute just the current statement, you can hit Cmd+Return. There are more options directly above the code editor (check out the menus ‹Run› and ‹Source›).

Title: readable code lines R

Body:
Is there a shortcut to add a new line into the R (RStudio) code?

I would like to avoid something like gapminder%>%filter(continent=="Asia")%>%group_by(year)%>%summarise(mean_pop=mean(pop))%>%ggplot(aes(x=year,y=mean_pop))+geom_point()+geom_line()+theme_bw()

by using

gapminder %>%
   filter(continent == "Asia") %>%
   group_by(year) %>%
   summarise(mean_pop = mean(pop)) %>%
     ggplot(aes(x = year, y = mean_pop)) +
     geom_point() +
     geom_line() +
     theme_bw()

but without holding the space bar all the time..  and I googled now nearly half an hour and just didn't find a shortcut. Can't believe it?!
So how all are doing this?


问:
Docker: Unable to connect to container from host
I try to use docker-compose in order to run an app which consists of 2 container: akka app and postgresql.
Here is yaml file:

```<code>version: "3"
services:
  api:
    image: akka-app:latest
    ports:
        - "9000:5000"
  db:
    image: postgres-db:latest
</code>```

After the docker-compose up command I see that containers are up and running using docker ps command:

```<code>CONTAINER ID        IMAGE                                COMMAND                  CREATED             STATUS              PORTS                    NAMES
65326e5a9677        akka-app:latest                      "java -cp /..."   40 minutes ago      Up 23 seconds       0.0.0.0:9000->5000/tcp   samplecompose_api_1
1f86273c4f9a        postgres-db:latest                   "docker-ent..."   19 hours ago        Up 23 seconds       5432/tcp                 samplecompose_db_1
</code>```

But when I try to access the akka-app from the host via the GET request to 0.0.0.0:9000/status or localhost:9000/status I get back "refused to connect" error in the postman.

Extra information:

Docker version 17.06.0-ce, build 02c1d87

docker-compose version

1.14.0, build c7bdf9e MacOS Sierra 10.12.5

Network settings of the akka-app container:

```<code>"NetworkSettings": {
    "Bridge": "",
    "SandboxID": "5b5b322ffb0fb881317f8cb4e69b8fd887566b8c5b73940174aabace35d816f8",
    "HairpinMode": false,
    "LinkLocalIPv6Address": "",
    "LinkLocalIPv6PrefixLen": 0,
    "Ports": {
        "5000/tcp": [
            {
                "HostIp": "0.0.0.0",
                "HostPort": "9000"
            }
        ]
    },
    "SandboxKey": "/var/run/docker/netns/5b5b322ffb0f",
    "SecondaryIPAddresses": null,
    "SecondaryIPv6Addresses": null,
    "EndpointID": "",
    "Gateway": "",
    "GlobalIPv6Address": "",
    "GlobalIPv6PrefixLen": 0,
    "IPAddress": "",
    "IPPrefixLen": 0,
    "IPv6Gateway": "",
    "MacAddress": "",
    "Networks": {
        "pinpointcompose_default": {
            "IPAMConfig": null,
            "Links": null,
            "Aliases": [
                "api",
                "65326e5a9677"
            ],
            "NetworkID": "925c8379c6d5b334177d7d198d1d38e29983903474183bee5734df9d30ab9810",
            "EndpointID": "c7c37f545b00c6a19863315858e93a79f10b54b5675dc2cb8704d2f2f9b2bb1c",
            "Gateway": "172.18.0.1",
            "IPAddress": "172.18.0.2",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "MacAddress": "02:42:ac:12:00:02"
        }
    }
}
</code>```

UPDATE:

docker-compose output:

```<code>docker-compose up
Starting samplecompose_api_1 ...
Starting samplecompose_api_1
Starting samplecompose_db_1 ...
Starting samplecompose_api_1 ... done
Attaching to samplecompose_db_1, samplecompose_api_1
db_1   | LOG:  database system was shut down at 2017-07-06 08:54:56 UTC
db_1   | LOG:  MultiXact member wraparound protections are now enabled
api_1  | 09:04:26.030 [default-akka.actor.default-dispatcher-3] INFO akka.event.slf4j.Slf4jLogger - Slf4jLogger started
api_1  | 09:04:27.472 [default-akka.actor.default-dispatcher-4] INFO sample-service - Bound to /0.0.0.0:5000
</code>```

答:
The problem was in an old VirtualBox installed who knows when on my laptop. So while it was installed I could not access running docker containers via localhost...
You can read more about this on official docker site

After I uninstalled the VirtualBox from the laptop, then restarted the Docker app and relaunched the terminal sessions it was unreal to use localhost for access to the containers.

Instead of the localhost I used the IP which I got from the docker-machine ip default. But this is not the good way.

So ensure once again that you meet all of the requirements.

Body:
I try to use docker-compose in order to run an app which consists of 2 container: akka app and postgresql.
Here is yaml file:

version: "3"
services:
  api:
    image: akka-app:latest
    ports:
        - "9000:5000"
  db:
    image: postgres-db:latest

After the docker-compose up command I see that containers are up and running using docker ps command:

CONTAINER ID        IMAGE                                COMMAND                  CREATED             STATUS              PORTS                    NAMES
65326e5a9677        akka-app:latest                      "java -cp /..."   40 minutes ago      Up 23 seconds       0.0.0.0:9000->5000/tcp   samplecompose_api_1
1f86273c4f9a        postgres-db:latest                   "docker-ent..."   19 hours ago        Up 23 seconds       5432/tcp                 samplecompose_db_1

But when I try to access the akka-app from the host via the GET request to 0.0.0.0:9000/status or localhost:9000/status I get back "refused to connect" error in the postman.

Extra information:

Docker version 17.06.0-ce, build 02c1d87

docker-compose version

1.14.0, build c7bdf9e MacOS Sierra 10.12.5

Network settings of the akka-app container:

"NetworkSettings": {
    "Bridge": "",
    "SandboxID": "5b5b322ffb0fb881317f8cb4e69b8fd887566b8c5b73940174aabace35d816f8",
    "HairpinMode": false,
    "LinkLocalIPv6Address": "",
    "LinkLocalIPv6PrefixLen": 0,
    "Ports": {
        "5000/tcp": [
            {
                "HostIp": "0.0.0.0",
                "HostPort": "9000"
            }
        ]
    },
    "SandboxKey": "/var/run/docker/netns/5b5b322ffb0f",
    "SecondaryIPAddresses": null,
    "SecondaryIPv6Addresses": null,
    "EndpointID": "",
    "Gateway": "",
    "GlobalIPv6Address": "",
    "GlobalIPv6PrefixLen": 0,
    "IPAddress": "",
    "IPPrefixLen": 0,
    "IPv6Gateway": "",
    "MacAddress": "",
    "Networks": {
        "pinpointcompose_default": {
            "IPAMConfig": null,
            "Links": null,
            "Aliases": [
                "api",
                "65326e5a9677"
            ],
            "NetworkID": "925c8379c6d5b334177d7d198d1d38e29983903474183bee5734df9d30ab9810",
            "EndpointID": "c7c37f545b00c6a19863315858e93a79f10b54b5675dc2cb8704d2f2f9b2bb1c",
            "Gateway": "172.18.0.1",
            "IPAddress": "172.18.0.2",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "MacAddress": "02:42:ac:12:00:02"
        }
    }
}

UPDATE:

docker-compose output:

docker-compose up
Starting samplecompose_api_1 ...
Starting samplecompose_api_1
Starting samplecompose_db_1 ...
Starting samplecompose_api_1 ... done
Attaching to samplecompose_db_1, samplecompose_api_1
db_1   | LOG:  database system was shut down at 2017-07-06 08:54:56 UTC
db_1   | LOG:  MultiXact member wraparound protections are now enabled
api_1  | 09:04:26.030 [default-akka.actor.default-dispatcher-3] INFO akka.event.slf4j.Slf4jLogger - Slf4jLogger started
api_1  | 09:04:27.472 [default-akka.actor.default-dispatcher-4] INFO sample-service - Bound to /0.0.0.0:5000


问:
AJAX | Using alert(); function in the other file doesn't work
I'm working on Ajax and still learning to use it properly. I'm wondering why in one side of Ajax alert(); works but on the other side - no.

It's pretty basic code:

```<code>$('.naudoti_papildus_visiems').click(function() {
    var n;

    $.post('/ajax/naudoti_papildus_visiems.php', { status : 1, fermos_id : '<?php echo $id_kurat; ?>', gyvulio_tipas : '<?php echo $type_zagon; ?>' },
    function(data) {
        var typeclick = data.typeclick,
            typeu = data.typeu,
            stil = data.stil,
            stildell = data.stildell;

        $.noty.closeAll();
        if (n) {
            n.setText('<b>' + data.message + '</b>');
            n.setType(typeu);
        } else {
            n = noty({
                text: '<b>' + data.message + '</b>',

                type: typeu,
                dismissQueue: false,
                layout: 'top',
                theme: 'defaultTheme',
                timeout: 3000,
            });
        }
    }, 'json');
});
</code>```

"naudoti_papildus_visiems.php" content:

```<code><script>alert(9);</script>
</code>```

I've tested one thing: using alert(); function inside an Ajax, it works:

```<code>$('.naudoti_papildus_visiems').click(function() {
var n;

$.post('/ajax/naudoti_papildus_visiems.php', { status : 1, fermos_id : '<?php echo $id_kurat; ?>', gyvulio_tipas : '<?php echo $type_zagon; ?>' },
function(data) {
    var typeclick = data.typeclick,
        typeu = data.typeu,
        stil = data.stil,
        stildell = data.stildell;

    alert(9); // works

    $.noty.closeAll();
    if (n) {
        n.setText('<b>' + data.message + '</b>');
        n.setType(typeu);
    } else {
        n = noty({
            text: '<b>' + data.message + '</b>',

            type: typeu,
            dismissQueue: false,
            layout: 'top',
            theme: 'defaultTheme',
            timeout: 3000,
        });
    }
}, 'json');
});
</code>```

Chrome console doesn't show any errors. Any help would be appreciated.

loelsonk: still doesn't work. Am I doing something wrong?

```<code>    $('.naudoti_papildus_visiems').click(function() {
    var n;

$.ajax({
  url: '/ajax/naudoti_papildus_visiems.php',
  type: 'POST',
  dataType : 'json',
  data: { status : 1, fermos_id : '<?php echo $id_kurat; ?>', gyvulio_tipas : '<?php echo $type_zagon; ?>' },
  success: function(data) {
        var typeclick = data.typeclick,
            typeu = data.typeu,
            stil = data.stil,
            stildell = data.stildell;

        $.noty.closeAll();
        if (n) {
            n.setText('<b>' + data.message + '</b>');
            n.setType(typeu);
        } else {
            n = noty({
                text: '<b>' + data.message + '</b>',

                type: typeu,
                dismissQueue: false,
                layout: 'top',
                theme: 'defaultTheme',
                timeout: 3000,
            });
        }

        $('#data').html(data);
    }
});
});
</code>```

答:
If you would like to execute js code you mentioned  from your request response append it to a #temp container.

First create #temp container we append response:

```<code><div id="temp"></div>
</code>```

Instead of $.post we use $.ajax.

```<code>$.ajax({
  url: '/ajax/naudoti_papildus_visiems.php',
  type: 'POST',
  data: { status : 1, fermos_id : '<?php echo $id_kurat; ?>', gyvulio_tipas : '<?php echo $type_zagon; ?>' },
  success: function(response) {
    // Do whatever you want here

    // response contains js code to be executed
    // Now your code gets executed
    $('#temp').html(response);
  }
})
</code>```

EDIT:

Here is small working example to show you how it works:

We have two files:

file 1: index.php

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>title</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <style>
            body {
                padding-left: 250px;
            }
            #temp {
                border: 2px solid #000;
                padding: 20px;
                width: 300px;
                min-height: 200px;
            }
        </style>
  </head>
    <body>
        <div>
            <h1>Ajax</h1>
            <button id="button" type="button">Perform ajax</button>

            <div id="temp"></div>
        </div>

        <script>
            $('#button').click(function(e) {
                $.ajax({
                url: '/ajax/naudoti_papildus_visiems.php',
                type: 'POST',
                data: { status : 1, fermos_id : 888, gyvulio_tipas : 'some_type' },
                success: function(response) {
                    // Do whatever you want here

                    // response contains js code to be executed
                    // Now your code gets executed
                    $('#temp').html(response);
                }
                });
            });
        </script>
    </body>
</html>
</code>```

file 2: /ajax/naudoti_papildus_visiems.php (file is inside ajax dir)

```<code><?php

echo 'test';
echo '<script>alert(9);</script>';
</code>```

See how it works:

Body:
I'm working on Ajax and still learning to use it properly. I'm wondering why in one side of Ajax alert(); works but on the other side - no.

It's pretty basic code:

$('.naudoti_papildus_visiems').click(function() {
    var n;

    $.post('/ajax/naudoti_papildus_visiems.php', { status : 1, fermos_id : '<?php echo $id_kurat; ?>', gyvulio_tipas : '<?php echo $type_zagon; ?>' },
    function(data) {
        var typeclick = data.typeclick,
            typeu = data.typeu,
            stil = data.stil,
            stildell = data.stildell;

        $.noty.closeAll();
        if (n) {
            n.setText('' + data.message + '');
            n.setType(typeu);
        } else {
            n = noty({
                text: '' + data.message + '',

                type: typeu,
                dismissQueue: false,
                layout: 'top',
                theme: 'defaultTheme',
                timeout: 3000,
            });
        }
    }, 'json');
});

"naudoti_papildus_visiems.php" content:

I've tested one thing: using alert(); function inside an Ajax, it works:

$('.naudoti_papildus_visiems').click(function() {
var n;

$.post('/ajax/naudoti_papildus_visiems.php', { status : 1, fermos_id : '<?php echo $id_kurat; ?>', gyvulio_tipas : '<?php echo $type_zagon; ?>' },
function(data) {
    var typeclick = data.typeclick,
        typeu = data.typeu,
        stil = data.stil,
        stildell = data.stildell;

    alert(9); // works

    $.noty.closeAll();
    if (n) {
        n.setText('' + data.message + '');
        n.setType(typeu);
    } else {
        n = noty({
            text: '' + data.message + '',

            type: typeu,
            dismissQueue: false,
            layout: 'top',
            theme: 'defaultTheme',
            timeout: 3000,
        });
    }
}, 'json');
});

Chrome console doesn't show any errors. Any help would be appreciated.

loelsonk: still doesn't work. Am I doing something wrong?

    $('.naudoti_papildus_visiems').click(function() {
    var n;

$.ajax({
  url: '/ajax/naudoti_papildus_visiems.php',
  type: 'POST',
  dataType : 'json',
  data: { status : 1, fermos_id : '<?php echo $id_kurat; ?>', gyvulio_tipas : '<?php echo $type_zagon; ?>' },
  success: function(data) {
        var typeclick = data.typeclick,
            typeu = data.typeu,
            stil = data.stil,
            stildell = data.stildell;

        $.noty.closeAll();
        if (n) {
            n.setText('' + data.message + '');
            n.setType(typeu);
        } else {
            n = noty({
                text: '' + data.message + '',

                type: typeu,
                dismissQueue: false,
                layout: 'top',
                theme: 'defaultTheme',
                timeout: 3000,
            });
        }

        $('#data').html(data);
    }
});
});

Body:
If you would like to execute js code you mentioned <script>alert(9);</script> from your request response append it to a #temp container.

First create #temp container we append response:

<div id="temp"></div>

Instead of $.post we use $.ajax.

$.ajax({
  url: '/ajax/naudoti_papildus_visiems.php',
  type: 'POST',
  data: { status : 1, fermos_id : '<?php echo $id_kurat; ?>', gyvulio_tipas : '<?php echo $type_zagon; ?>' },
  success: function(response) {
    // Do whatever you want here

    // response contains js code to be executed
    // Now your code gets executed
    $('#temp').html(response);
  }
})

EDIT:

Here is small working example to show you how it works:

We have two files:

file 1: index.php

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>title</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <style>
            body {
                padding-left: 250px;
            }
            #temp {
                border: 2px solid #000;
                padding: 20px;
                width: 300px;
                min-height: 200px;
            }
        </style>
  </head>
    <body>
        <div>
            <h1>Ajax</h1>
            <button id="button" type="button">Perform ajax</button>

            <div id="temp"></div>
        </div>

        <script>
            $('#button').click(function(e) {
                $.ajax({
                url: '/ajax/naudoti_papildus_visiems.php',
                type: 'POST',
                data: { status : 1, fermos_id : 888, gyvulio_tipas : 'some_type' },
                success: function(response) {
                    // Do whatever you want here

                    // response contains js code to be executed
                    // Now your code gets executed
                    $('#temp').html(response);
                }
                });
            });
        </script>
    </body>
</html>

file 2: /ajax/naudoti_papildus_visiems.php (file is inside ajax dir)

<?php

echo 'test';
echo '<script>alert(9);</script>';

See how it works:


问:
Number of children explodes after filtering on child value
I have a model (Track) with children (Rank). That can be described (simplified) as:

```<code>class Track(models.Model):
    id = models.CharField('Unique ID', max_length=100,
    primary_key=True)
    title = models.CharField('Track title', max_length=100)
    artist = models.CharField('Artist name', max_length=100)

class Rank(models.Model):
    id = models.AutoField(primary_key=True)
    trackid = models.ForeignKey(Track, related_name='rank')
    cdate = models.DateField("Date", blank=True, null=True)
</code>```

When doing this:

```<code>track_list = Track.objects.filter(Q(artist__icontains=query) |
Q(title__icontains=query)) \
.annotate(children=Count('rank'))

for track in track_list:
    print(track.children)
</code>```

The number of children per track are all close to 100 (e.g 65,78,95) and that is correct.

But when I narrow the queryset further down by applying another filter and a needed annotation:

```<code>track_list = track_list.distinct() \
.filter(rank__cdate__year=filterquery) \
.annotate(entrydate=Min('rank__cdate')) \
.annotate(children=Count('rank'))

for track in track_list:
    print(track.children)
</code>```

The number of children explodes to several thousands per track.
Any ideas?

Body:
I have a model (Track) with children (Rank). That can be described (simplified) as:

class Track(models.Model):
    id = models.CharField('Unique ID', max_length=100,
    primary_key=True)
    title = models.CharField('Track title', max_length=100)
    artist = models.CharField('Artist name', max_length=100)

class Rank(models.Model):
    id = models.AutoField(primary_key=True)
    trackid = models.ForeignKey(Track, related_name='rank')
    cdate = models.DateField("Date", blank=True, null=True)

When doing this:

track_list = Track.objects.filter(Q(artist__icontains=query) |
Q(title__icontains=query)) \
.annotate(children=Count('rank'))

for track in track_list:
    print(track.children)

The number of children per track are all close to 100 (e.g 65,78,95) and that is correct.

But when I narrow the queryset further down by applying another filter and a needed annotation:

track_list = track_list.distinct() \
.filter(rank__cdate__year=filterquery) \
.annotate(entrydate=Min('rank__cdate')) \
.annotate(children=Count('rank'))

for track in track_list:
    print(track.children)

The number of children explodes to several thousands per track.
Any ideas?

Body: Try .annotate(children=Count('rank', distinct=True))


问:
How to extract the content of a cursor from a SQLite DB to a class?
i need to do a function on MyDBAdapter to extract a all the users from the SQLite database, and then, return a List<Friend>.

this is too munch hard for me, i am testing and trying to understand a lot of  google examples and stackoverflow posts but i can't do it

i tryed with this code but it doesn't works, CursorIndexOutOfBoundsException: Index -1 requested, with a size of 3

```<code>public List<Friend> retrieveAllUsers()
    {
        List <Friend> friends=new ArrayList<Friend>();

        Cursor result=fetchAllUsers();

        for (int i=0; i<result.getCount();i++)
        {
            //note.getString(note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
            friends.add(new Friend(result.getString(result.getColumnIndexOrThrow("email")), "","","",""));
        }

        return friends;
    }
</code>```

please can someone help me doing that function ?

i have a user (Friend) class, like this:

```<code>public class Friend {
private String email; //id de usuario
    private String password;
    private String fullName;
    private String movilephone;
    private String movileOperatingSystem;
</code>```

And also i have a SQLite database like this:

```<code>public class MyDbAdapter {

    private static final String TAG = "NotesDbAdapter";
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;
    private static final String DATABASE_NAME = "gpslocdb";
    private static final String PERMISSION_TABLE_CREATE = "CREATE TABLE permission ( fk_email1 varchar, fk_email2 varchar, validated tinyint, hour1 time default '08:00:00', hour2 time default '20:00:00', date1 date, date2 date, weekend tinyint default '0', fk_type varchar, PRIMARY KEY  (fk_email1,fk_email2))";
    private static final String USER_TABLE_CREATE = "CREATE TABLE user ( email varchar, password varchar, fullName varchar, mobilePhone varchar, mobileOperatingSystem varchar, PRIMARY KEY  (email))";

    private static final int DATABASE_VERSION = 2;

    private final Context mCtx;

    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(PERMISSION_TABLE_CREATE);
            db.execSQL(USER_TABLE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS user");
            db.execSQL("DROP TABLE IF EXISTS permission");
            onCreate(db);
        }
    }

    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     *
     * @param ctx the Context within which to work
     */
    public MyDbAdapter(Context ctx) {
        this.mCtx = ctx;
    }

    /**
     * Open the database. If it cannot be opened, try to create a new
     * instance of the database. If it cannot be created, throw an exception to
     * signal the failure
     *
     * @return this (self reference, allowing this to be chained in an
     *         initialization call)
     * @throws SQLException if the database could be neither opened or created
     */
    public MyDbAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        mDbHelper.close();
    }

    public long createUser(String email, String password, String fullName, String mobilePhone, String mobileOperatingSystem)
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put("email",email);
        initialValues.put("password",password);
        initialValues.put("fullName",fullName);
        initialValues.put("mobilePhone",mobilePhone);
        initialValues.put("mobileOperatingSystem",mobileOperatingSystem);
        return mDb.insert("user", null, initialValues);
    }

    public Cursor fetchAllUsers() {

        return mDb.query("user", new String[] {"email", "password", "fullName", "mobilePhone", "mobileOperatingSystem"}, null, null, null, null, null);
    }

    public Cursor fetchUser(String email) throws SQLException {

        Cursor mCursor = mDb.query(true, "user", new String[] {"email", "password", "fullName", "mobilePhone", "mobileOperatingSystem"}
            , "email" + "=" + email, null, null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }
}
</code>```

答:
First, you should move cursor to the first row and then (if the movoToFirst succeeded) use moveToNext</p>

```<code> Cursor result=fetchAllUsers();
    if (result.moveToFirst()) {
     do {
       friends.add(new Friend(result.getString(result.getColumnIndexOrThrow("email")), "","","",""));
     } while (result.moveToNext());
}
</code>```

Body:
i need to do a function on MyDBAdapter to extract a all the users from the SQLite database, and then, return a List<Friend>.

this is too munch hard for me, i am testing and trying to understand a lot of  google examples and stackoverflow posts but i can't do it

i tryed with this code but it doesn't works, CursorIndexOutOfBoundsException: Index -1 requested, with a size of 3

public List<Friend> retrieveAllUsers()
    {
        List <Friend> friends=new ArrayList<Friend>();

        Cursor result=fetchAllUsers();

        for (int i=0; i<result.getCount();i++)
        {
            //note.getString(note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
            friends.add(new Friend(result.getString(result.getColumnIndexOrThrow("email")), "","","",""));
        }

        return friends;
    }

please can someone help me doing that function ?

i have a user (Friend) class, like this:

public class Friend {
private String email; //id de usuario
    private String password;
    private String fullName;
    private String movilephone;
    private String movileOperatingSystem;

And also i have a SQLite database like this:

public class MyDbAdapter {

    private static final String TAG = "NotesDbAdapter";
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;
    private static final String DATABASE_NAME = "gpslocdb";
    private static final String PERMISSION_TABLE_CREATE = "CREATE TABLE permission ( fk_email1 varchar, fk_email2 varchar, validated tinyint, hour1 time default '08:00:00', hour2 time default '20:00:00', date1 date, date2 date, weekend tinyint default '0', fk_type varchar, PRIMARY KEY  (fk_email1,fk_email2))";
    private static final String USER_TABLE_CREATE = "CREATE TABLE user ( email varchar, password varchar, fullName varchar, mobilePhone varchar, mobileOperatingSystem varchar, PRIMARY KEY  (email))";

    private static final int DATABASE_VERSION = 2;

    private final Context mCtx;

    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(PERMISSION_TABLE_CREATE);
            db.execSQL(USER_TABLE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS user");
            db.execSQL("DROP TABLE IF EXISTS permission");
            onCreate(db);
        }
    }

    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     *
     * @param ctx the Context within which to work
     */
    public MyDbAdapter(Context ctx) {
        this.mCtx = ctx;
    }

    /**
     * Open the database. If it cannot be opened, try to create a new
     * instance of the database. If it cannot be created, throw an exception to
     * signal the failure
     *
     * @return this (self reference, allowing this to be chained in an
     *         initialization call)
     * @throws SQLException if the database could be neither opened or created
     */
    public MyDbAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        mDbHelper.close();
    }

    public long createUser(String email, String password, String fullName, String mobilePhone, String mobileOperatingSystem)
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put("email",email);
        initialValues.put("password",password);
        initialValues.put("fullName",fullName);
        initialValues.put("mobilePhone",mobilePhone);
        initialValues.put("mobileOperatingSystem",mobileOperatingSystem);
        return mDb.insert("user", null, initialValues);
    }

    public Cursor fetchAllUsers() {

        return mDb.query("user", new String[] {"email", "password", "fullName", "mobilePhone", "mobileOperatingSystem"}, null, null, null, null, null);
    }

    public Cursor fetchUser(String email) throws SQLException {

        Cursor mCursor = mDb.query(true, "user", new String[] {"email", "password", "fullName", "mobilePhone", "mobileOperatingSystem"}
            , "email" + "=" + email, null, null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }
}

Body:
First, you should move cursor to the first row and then (if the movoToFirst succeeded) use moveToNext

 Cursor result=fetchAllUsers();
    if (result.moveToFirst()) {
     do {
       friends.add(new Friend(result.getString(result.getColumnIndexOrThrow("email")), "","","",""));
     } while (result.moveToNext());
}


问:
Standard Values value correct in CE but null in Code
If I set the value of a field on the standard values of a base template the standard value shows up in that field in the content editor(and in Rocks), however when I reference that field by ID in code

```<code>Html.Sitecore().Field(ID, Item);
</code>```

//ED. I have a helper method that does error checking called GetField(), my mistake.
To add more clarity: this works correctly if I go into the CE and say add a character to the end of the value and press save. (overriding the standard values)

The returned value is null.

This both for new items created after the Standard Values change, and current items.

答:
I think the problem is answered here, even though it seems like a Sitecore bug regarding item fallback and fields that inherit their value from standard values:
Language Fallback not working for Fields with Standard Values (Sitecore 8.1)

The reason I'm saying that there is the solution is because I was able to solve it just that way before I even read that answer. Simply put, it seems like Sitecore does not pull standard values for fields in case of item fallback, as if I disabled item fallback the fields with standard values were not null anymore in code : (

But a probably better solution is field level fallback: if you enable field level fallback on that exact field in the template, it will pull in the standard values as well when an item fallback happens.

Body:
If I set the value of a field on the standard values of a base template the standard value shows up in that field in the content editor(and in Rocks), however when I reference that field by ID in code

Html.Sitecore().Field(ID, Item);

//ED. I have a helper method that does error checking called GetField(), my mistake.
To add more clarity: this works correctly if I go into the CE and say add a character to the end of the value and press save. (overriding the standard values)

The returned value is null.

This both for new items created after the Standard Values change, and current items.


问:
How to log to Powershell console from Workflow Job
I have a Powershell workflow. I need to log data to Console so that the progress of the workflow is clearly visible. Till now I used Log-Verbose to achieve this. When I execute this workflow with -Verbose switch, verbose logs are displayed on the console as expected.

```<code>workflow Test-Workflow
{
    Log-Verbose "Inside Test-Workflow"
}

Test-Workflow -Verbose
</code>```

Now I need to use checkpoints inside the workflow. To take advantage of checkpoints, I need to run the workflow as a Job.

```<code>Test-Workflow -Verbose -AsJob
</code>```

When I do so, I no longer see the verbose logs on the console. I know I can write to a file or write the logs as events but I would really like to write them to the console. Let me know if this is possible and how.

答:
I am sure you have discovered a solution to this by now but you can use:

```<code>Write-Output "I will print to the console"
</code>```

According to MSDN: Write-Output:

Sends the specified objects to the next command in the pipeline. If the command is the last command in the pipeline, the objects are displayed in the console.

ContentLicense: CC BY-SA 4.0

Body:
I have a Powershell workflow. I need to log data to Console so that the progress of the workflow is clearly visible. Till now I used Log-Verbose to achieve this. When I execute this workflow with -Verbose switch, verbose logs are displayed on the console as expected.

workflow Test-Workflow
{
    Log-Verbose "Inside Test-Workflow"
}

Test-Workflow -Verbose

Now I need to use checkpoints inside the workflow. To take advantage of checkpoints, I need to run the workflow as a Job.

Test-Workflow -Verbose -AsJob

When I do so, I no longer see the verbose logs on the console. I know I can write to a file or write the logs as events but I would really like to write them to the console. Let me know if this is possible and how.

Body:
I am sure you have discovered a solution to this by now but you can use:

Write-Output "I will print to the console"

According to MSDN: Write-Output:

Sends the specified objects to the next command in the pipeline. If the command is the last command in the pipeline, the objects are displayed in the console.


问:
Magento moving telephone field to to create new account page
Is there any easy way to move existing telephone field in Create new Customer Account page section

I know telephone field is present in New Address section , I don't want to create a new customer attribute ,

So far i have tried answer provided in Adding tel number field to new acount page “create account” page , but didn't helped ,

I have magneto version 1.7.0.2 ,any help would be highly appreciated .

答:
You have to follow this steps to give telephone field in registration form.

STEP 1   You have to place the following code in your custom module layout file

```<code><customer_account_create translate="label">
    <label>Customer Account Registration Form</label>
    <remove name="right"/>
    <remove name="left"/>

    <reference name="root">
        <action method="setTemplate"><template>page/1column.phtml</template></action>
    </reference>
    <reference name="content">
        <block type="customer/form_register" name="customer_form_register" template="modulename/register.phtml">
            <block type="page/html_wrapper" name="customer.form.register.fields.before" as="form_fields_before" translate="label">
                <label>Form Fields Before</label>
            </block>
        </block>
    </reference>
</customer_account_create>
</code>```

STEP 2   Create the register.phtml file in following path app/design/frontend/theme_name/default/template/modulename/register.phtml

STEP 3   Copy the register.phtml file in following path app\design\frontend\base\default\template\persistent\customer\form\register.phtml

STEP 4  relace that register.phtml file into local module path app/design/frontend/theme_name/default/template/modulename/

STEP 5  Check the following coding and inside the if condition put true or else remove the if condition.

```<code><?php if($this->getShowAddressFields()): ?>
</code>```

STEP 6 You can see the telephone field in registration form with address fields.

Body:
You have to follow this steps to give telephone field in registration form.

STEP 1   You have to place the following code in your custom module layout file

<customer_account_create translate="label">
    <label>Customer Account Registration Form</label>
    <remove name="right"/>
    <remove name="left"/>

    <reference name="root">
        <action method="setTemplate"><template>page/1column.phtml</template></action>
    </reference>
    <reference name="content">
        <block type="customer/form_register" name="customer_form_register" template="modulename/register.phtml">
            <block type="page/html_wrapper" name="customer.form.register.fields.before" as="form_fields_before" translate="label">
                <label>Form Fields Before</label>
            </block>
        </block>
    </reference>
</customer_account_create>

STEP 2   Create the register.phtml file in following path app/design/frontend/theme_name/default/template/modulename/register.phtml

STEP 3   Copy the register.phtml file in following path app\design\frontend\base\default\template\persistent\customer\form\register.phtml

STEP 4  relace that register.phtml file into local module path app/design/frontend/theme_name/default/template/modulename/

STEP 5  Check the following coding and inside the if condition put true or else remove the if condition.

<?php if($this->getShowAddressFields()): ?>

STEP 6 You can see the telephone field in registration form with address fields.


问:
Cobol technical demonstration
I'm working as a COBOL programmer - have a 6 months work experience - for a consulting firm . Today, with the rest the COBOL "department", I had a meeting with the new director of my company.

After an initial analysis made by the new team in charge, they noticed that, comparing to the other services/technologies our company has to offer - Java, C++, Objective-C, etc - COBOL was lacking "advertisement". He stated that whenever members of other teams are in-between projects they implement small demos which then can be shown to our clients whenever there is a presentation of our company. He gave examples of widgets for mobile devices in Objective-C, cool web-pages with HTML5, etc.
And noticed that there is nothing in COBOL like that. So he wants us to develop some kind of tool/app to show what our competences.

We already told him that COBOL is used under the hood, and doesn't have bells and whistles to show. Also that when hiring a COBOL programmer/analyst the most important for the client is that he shows he has "business logic" knowledge.

I know that the coding part is very important but after a two weeks introduction to the mainframe environment and to COBOL I was capable of doing my programming tasks easily. But with a 6 months experience working in a bank I find myself having to, nearly everyday, ask questions regarding "business logic" to the "gurus" just so that I don't end up changing the logic of the process when performing some maintenance task.

Can we really make something (tool/app) that shows or future clients that we have something different to offer than all the other company's which provide the same services? Or if not, is there anything that we can say to our manager so that he understands that COBOL is different from the other languages and it's purpose is not to display pretty graphics on the screen.

Thank you!

答:
COBOL gets a bad rap in large part because there is the conception that it's outdated and unable to communicate with modern systems.  A lot of people think that using COBOL "locks you in," unable to get data from other systems, push data to other systems, or call code that's written in other languages.

Potential clients would be very interested to know that, if they went with your COBOL solution, they could still share data with the rest of the world.  I think you could build some compelling demos showing COBOL applications interacting with Web APIs or with code written in C++, Objective-C, etc.  Two possibilities:

1) A simple program that submits a query to Google's search API and displays the returned results.  This will show that you can issue HTTP requests and parse the responses.

2) A program that gathers data from a custom database and passes that data to a C++ function that somehow grinds up the data and returns a result.  This will show that you can use COBOL's data handling strength and pass off to C++ or some other language the more processor-intensive calculation tasks that COBOL traditionally has not been as good at.

I think that's your biggest selling point:  that you use COBOL for its strengths, that you're able to share data with the rest of the world, and your COBOL programs can leverage other tools for specific tasks that are not COBOL's primary function.

Title: Cobol technical demonstration


问:
Why do I get a reference instead of a copy in this C# return?
I have this part of code:

```<code>MeasDataSet dset = new MeasDataSet();
MeasDataPoint point = new MeasDataPoint();
//...
MeasDataSet dset2 = new MeasDataSet(dset._path);
dset2.SaveResults();

point = dset2.GetDataPointAt(dset2.Size - 1);
point.Current = 7566;
dset2.SaveResults();
</code>```

Where MeasDataPoint and Set are just some classes containing measurement data (point a single point and set a collection of points with additional methods)

When calling SaveResults() it should save the data inside the DataSet to a file, but using the code above doesn't save the old point but instead the altered one (point.Current = 7566;).
So basically point now changes my values inside my data set instead of being a copy what i expected it to be.

GetDataPointAt (method of DatasSet):

```<code>public MeasDataPoint GetDataPointAt(int numberOfPoint)
    {
        return _dataPoints.ElementAt(numberOfPoint);
    }
</code>```

Anyone an idea why it behaves this way?

答:
Is dset._path the entire collection of MeasDataPoint objects? If so, it appears the constructor new MeasDataSet(dset._path) is simply internally storing a reference to your original dset collection of points which means it is manipulating your original collection. See Passing Parameters (C# Programming Guide).

You could extend or modify the MeasDataSet constructor to iterate over the MeasDataPoint objects to create new ones by deep copying when assigning to dset2. Here is a rough idea:

```<code>public MeasDataSet(List<MeasDataPoint> path) {
   var copiedPath = new List<MeasDataPoint>();
   foreach(var point in path) {
      copiedPath.Add(new MeasDataPoint() {
         Prop1 = point.Prop1,
         Prop2 = point.Prop2
      });
   }
   // do something with your newly created deep copy of copiedPath...
}
</code>```

Body:
I have this part of code:

MeasDataSet dset = new MeasDataSet();
MeasDataPoint point = new MeasDataPoint();
//...
MeasDataSet dset2 = new MeasDataSet(dset._path);
dset2.SaveResults();

point = dset2.GetDataPointAt(dset2.Size - 1);
point.Current = 7566;
dset2.SaveResults();

Where MeasDataPoint and Set are just some classes containing measurement data (point a single point and set a collection of points with additional methods)

When calling SaveResults() it should save the data inside the DataSet to a file, but using the code above doesn't save the old point but instead the altered one (point.Current = 7566;).
So basically point now changes my values inside my data set instead of being a copy what i expected it to be.

GetDataPointAt (method of DatasSet):

public MeasDataPoint GetDataPointAt(int numberOfPoint)
    {
        return _dataPoints.ElementAt(numberOfPoint);
    }

Anyone an idea why it behaves this way?

Body:
Is dset._path the entire collection of MeasDataPoint objects? If so, it appears the constructor new MeasDataSet(dset._path) is simply internally storing a reference to your original dset collection of points which means it is manipulating your original collection. See Passing Parameters (C# Programming Guide).

You could extend or modify the MeasDataSet constructor to iterate over the MeasDataPoint objects to create new ones by deep copying when assigning to dset2. Here is a rough idea:

public MeasDataSet(List<MeasDataPoint> path) {
   var copiedPath = new List<MeasDataPoint>();
   foreach(var point in path) {
      copiedPath.Add(new MeasDataPoint() {
         Prop1 = point.Prop1,
         Prop2 = point.Prop2
      });
   }
   // do something with your newly created deep copy of copiedPath...
}


问:
Not able to "findViewById" in Kotlin. Getting error "Type inference failed"
I am getting the following error when I try to find a RecycleView by id.

Error:-
  Type inference failed: Not enough information to infer parameter T

Code:

```<code>class FirstRecycleViewExample : AppCompatActivity() {
    val data = arrayListOf<String>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.first_recycleview)

        val recycler_view =  findViewById(R.id.recycler_view) as RecyclerView ///IN THIS LINE I AM GETTING THE ERROR

        data.add("First Data")
        data.add("Second Data")
        data.add("Third Data")
        data.add("Forth Data")
        data.add("Fifth Data")

        //creating our adapter
        val adapter = CustomRecycleAdapter(data)

        //now adding the adapter to recyclerview
        recycler_view.adapter = adapter
    }
}
</code>```

答:
You can ignore giving ids to variables in kotlin. You just need to use a plugin

Paste this in your gradle

```<code> apply plugin: 'kotlin-android-extensions'
</code>```

and then you don't need to assign ids to var, you can just do it like

```<code> recycler_view.setAdapter(youradapter);
</code>```

Body:
I am getting the following error when I try to find a RecycleView by id.

Error:-
  Type inference failed: Not enough information to infer parameter T

Code:

class FirstRecycleViewExample : AppCompatActivity() {
    val data = arrayListOf<String>()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.first_recycleview)

        val recycler_view =  findViewById(R.id.recycler_view) as RecyclerView ///IN THIS LINE I AM GETTING THE ERROR

        data.add("First Data")
        data.add("Second Data")
        data.add("Third Data")
        data.add("Forth Data")
        data.add("Fifth Data")

        //creating our adapter
        val adapter = CustomRecycleAdapter(data)

        //now adding the adapter to recyclerview
        recycler_view.adapter = adapter
    }
}

Body:
You can ignore giving ids to variables in kotlin. You just need to use a plugin

Paste this in your gradle

 apply plugin: 'kotlin-android-extensions'

and then you don't need to assign ids to var, you can just do it like

 recycler_view.setAdapter(youradapter);