问:
Issues with a button not working when SQL is being used to get data from a table
This is some code I got off the internet because I'm quite new to SQL and had no intentions of using it until I came across this login feature I wanted to add into my desktop application. Here's the code.

```<code>    SqlConnection connection = new SqlConnection(@"Data Source=JOASH;Initial Catalog=Logins;Integrated Security=True");
        SqlDataAdapter dataAdapter = new SqlDataAdapter("SELECT COUNT(*) FROM login WHERE Username='" + flatTextBox1.Text + "' AND Password='" + flatTextBox2 + "'", connection);
        DataTable dataTable = new DataTable();
        dataAdapter.Fill(dataTable);
        if (dataTable.Rows[0][0].ToString() == "1")
        {
            this.Hide();
            Dashboard dashboard_form = new Dashboard();
            dashboard_form.Show();
        }
        else
        {
            MessageBox.Show("Authentication failed!");
        }
</code>```

That is the part where the SQL stuff is taking place for the Button. Basically, on clicking a button, the code is executed. But, for some reason, when I click the button, either the code isn't executing, or it isn't working. (I'm guessing it isn't executing.) I really hope that someone can help me with this. The button just won't work.

EDIT: As requested by Nirman, here's the Form Designer code.

```<code>    namespace subTerraApplication
    {
partial class WelcomePage
{
    /// <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.formSkin1 = new FlatUI.FormSkin();
        this.flatTextBox2 = new FlatUI.FlatTextBox();
        this.flatLabel2 = new FlatUI.FlatLabel();
        this.flatTextBox1 = new FlatUI.FlatTextBox();
        this.flatLabel1 = new FlatUI.FlatLabel();
        this.flatMini1 = new FlatUI.FlatMini();
        this.flatMax1 = new FlatUI.FlatMax();
        this.flatClose1 = new FlatUI.FlatClose();
        this.flatButton1 = new FlatUI.FlatButton();
        this.formSkin1.SuspendLayout();
        this.SuspendLayout();
        //
        // formSkin1
        //
        this.formSkin1.BackColor = System.Drawing.Color.White;
        this.formSkin1.BaseColor = System.Drawing.Color.FromArgb(((int)(((byte)(60)))), ((int)(((byte)(70)))), ((int)(((byte)(73)))));
        this.formSkin1.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(53)))), ((int)(((byte)(58)))), ((int)(((byte)(60)))));
        this.formSkin1.Controls.Add(this.flatButton1);
        this.formSkin1.Controls.Add(this.flatTextBox2);
        this.formSkin1.Controls.Add(this.flatLabel2);
        this.formSkin1.Controls.Add(this.flatTextBox1);
        this.formSkin1.Controls.Add(this.flatLabel1);
        this.formSkin1.Controls.Add(this.flatMini1);
        this.formSkin1.Controls.Add(this.flatMax1);
        this.formSkin1.Controls.Add(this.flatClose1);
        this.formSkin1.Dock = System.Windows.Forms.DockStyle.Fill;
        this.formSkin1.FlatColor = System.Drawing.Color.FromArgb(((int)(((byte)(52)))), ((int)(((byte)(152)))), ((int)(((byte)(219)))));
        this.formSkin1.Font = new System.Drawing.Font("Segoe UI", 12F);
        this.formSkin1.HeaderColor = System.Drawing.Color.FromArgb(((int)(((byte)(45)))), ((int)(((byte)(47)))), ((int)(((byte)(49)))));
        this.formSkin1.HeaderMaximize = false;
        this.formSkin1.Location = new System.Drawing.Point(0, 0);
        this.formSkin1.Name = "formSkin1";
        this.formSkin1.Size = new System.Drawing.Size(256, 349);
        this.formSkin1.TabIndex = 0;
        this.formSkin1.Text = "subTerra Build 1";
        //
        // flatTextBox2
        //
        this.flatTextBox2.BackColor = System.Drawing.Color.Transparent;
        this.flatTextBox2.FocusOnHover = false;
        this.flatTextBox2.Location = new System.Drawing.Point(125, 135);
        this.flatTextBox2.MaxLength = 32767;
        this.flatTextBox2.Multiline = false;
        this.flatTextBox2.Name = "flatTextBox2";
        this.flatTextBox2.ReadOnly = false;
        this.flatTextBox2.Size = new System.Drawing.Size(109, 29);
        this.flatTextBox2.TabIndex = 10;
        this.flatTextBox2.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
        this.flatTextBox2.TextColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(192)))));
        this.flatTextBox2.UseSystemPasswordChar = true;
        //
        // flatLabel2
        //
        this.flatLabel2.AutoSize = true;
        this.flatLabel2.BackColor = System.Drawing.Color.Transparent;
        this.flatLabel2.Font = new System.Drawing.Font("Segoe UI", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
        this.flatLabel2.ForeColor = System.Drawing.Color.White;
        this.flatLabel2.Location = new System.Drawing.Point(13, 135);
        this.flatLabel2.Name = "flatLabel2";
        this.flatLabel2.Size = new System.Drawing.Size(99, 30);
        this.flatLabel2.TabIndex = 9;
        this.flatLabel2.Text = "Password";
        //
        // flatTextBox1
        //
        this.flatTextBox1.BackColor = System.Drawing.Color.Transparent;
        this.flatTextBox1.FocusOnHover = false;
        this.flatTextBox1.Location = new System.Drawing.Point(125, 81);
        this.flatTextBox1.MaxLength = 32767;
        this.flatTextBox1.Multiline = false;
        this.flatTextBox1.Name = "flatTextBox1";
        this.flatTextBox1.ReadOnly = false;
        this.flatTextBox1.Size = new System.Drawing.Size(109, 29);
        this.flatTextBox1.TabIndex = 8;
        this.flatTextBox1.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
        this.flatTextBox1.TextColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(192)))));
        this.flatTextBox1.UseSystemPasswordChar = false;
        //
        // flatLabel1
        //
        this.flatLabel1.AutoSize = true;
        this.flatLabel1.BackColor = System.Drawing.Color.Transparent;
        this.flatLabel1.Font = new System.Drawing.Font("Segoe UI", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
        this.flatLabel1.ForeColor = System.Drawing.Color.White;
        this.flatLabel1.Location = new System.Drawing.Point(13, 81);
        this.flatLabel1.Name = "flatLabel1";
        this.flatLabel1.Size = new System.Drawing.Size(106, 30);
        this.flatLabel1.TabIndex = 7;
        this.flatLabel1.Text = "Username";
        //
        // flatMini1
        //
        this.flatMini1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
        this.flatMini1.BackColor = System.Drawing.Color.White;
        this.flatMini1.BaseColor = System.Drawing.Color.FromArgb(((int)(((byte)(45)))), ((int)(((byte)(47)))), ((int)(((byte)(49)))));
        this.flatMini1.Font = new System.Drawing.Font("Marlett", 12F);
        this.flatMini1.Location = new System.Drawing.Point(189, -1);
        this.flatMini1.Name = "flatMini1";
        this.flatMini1.Size = new System.Drawing.Size(18, 18);
        this.flatMini1.TabIndex = 6;
        this.flatMini1.Text = "flatMini1";
        this.flatMini1.TextColor = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243)))));
        //
        // flatMax1
        //
        this.flatMax1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
        this.flatMax1.BackColor = System.Drawing.Color.White;
        this.flatMax1.BaseColor = System.Drawing.Color.FromArgb(((int)(((byte)(45)))), ((int)(((byte)(47)))), ((int)(((byte)(49)))));
        this.flatMax1.Font = new System.Drawing.Font("Marlett", 12F);
        this.flatMax1.Location = new System.Drawing.Point(213, -1);
        this.flatMax1.Name = "flatMax1";
        this.flatMax1.Size = new System.Drawing.Size(18, 18);
        this.flatMax1.TabIndex = 5;
        this.flatMax1.Text = "flatMax1";
        this.flatMax1.TextColor = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243)))));
        //
        // flatClose1
        //
        this.flatClose1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
        this.flatClose1.BackColor = System.Drawing.Color.White;
        this.flatClose1.BaseColor = System.Drawing.Color.FromArgb(((int)(((byte)(168)))), ((int)(((byte)(35)))), ((int)(((byte)(35)))));
        this.flatClose1.Font = new System.Drawing.Font("Marlett", 10F);
        this.flatClose1.Location = new System.Drawing.Point(237, 0);
        this.flatClose1.Name = "flatClose1";
        this.flatClose1.Size = new System.Drawing.Size(18, 18);
        this.flatClose1.TabIndex = 4;
        this.flatClose1.Text = "flatClose1";
        this.flatClose1.TextColor = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243)))));
        //
        // flatButton1
        //
        this.flatButton1.BackColor = System.Drawing.Color.Transparent;
        this.flatButton1.BaseColor = System.Drawing.Color.FromArgb(((int)(((byte)(52)))), ((int)(((byte)(152)))), ((int)(((byte)(219)))));
        this.flatButton1.Cursor = System.Windows.Forms.Cursors.Hand;
        this.flatButton1.Font = new System.Drawing.Font("Segoe UI", 12F);
        this.flatButton1.Location = new System.Drawing.Point(74, 209);
        this.flatButton1.Name = "flatButton1";
        this.flatButton1.Rounded = false;
        this.flatButton1.Size = new System.Drawing.Size(106, 32);
        this.flatButton1.TabIndex = 11;
        this.flatButton1.Text = "Login";
        this.flatButton1.TextColor = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243)))));
        //
        // WelcomePage
        //
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(256, 349);
        this.Controls.Add(this.formSkin1);
        this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
        this.Name = "WelcomePage";
        this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
        this.Text = "Form1";
        this.TransparencyKey = System.Drawing.Color.Fuchsia;
        this.formSkin1.ResumeLayout(false);
        this.formSkin1.PerformLayout();
        this.ResumeLayout(false);

    }

    #endregion

    private FlatUI.FormSkin formSkin1;
    private FlatUI.FlatMini flatMini1;
    private FlatUI.FlatMax flatMax1;
    private FlatUI.FlatClose flatClose1;
    private FlatUI.FlatTextBox flatTextBox2;
    private FlatUI.FlatLabel flatLabel2;
    private FlatUI.FlatTextBox flatTextBox1;
    private FlatUI.FlatLabel flatLabel1;
    private FlatUI.FlatButton flatButton1;
}
</code>```

}

PROBLEM HAS BEEN SOLVED! The code for the click detection was missing!

答:
Did you try setting breakpoint in if/else blocks?

And here is some considerations:
Use prepared statements and parameterized queries. Never ever create dynamic SQL based on user input, because the application becomes vulnerable to SQL injection.

Here is you rewritten code using parametrized parameters:

```<code>SqlDataAdapter dataAdapter = new SqlDataAdapter("SELECT COUNT(*) FROM login WHERE Username=@Username AND Password=@Password", connection);
dataAdapter.SelectCommand.Parameters.AddWithValue("@Username", flatTextBox1.Text);
dataAdapter.SelectCommand.Parameters.AddWithValue("@Password", flatTextBox2.Text);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
This is some code I got off the internet because I'm quite new to SQL and had no intentions of using it until I came across this login feature I wanted to add into my desktop application. Here's the code.

    SqlConnection connection = new SqlConnection(@"Data Source=JOASH;Initial Catalog=Logins;Integrated Security=True");
        SqlDataAdapter dataAdapter = new SqlDataAdapter("SELECT COUNT(*) FROM login WHERE Username='" + flatTextBox1.Text + "' AND Password='" + flatTextBox2 + "'", connection);
        DataTable dataTable = new DataTable();
        dataAdapter.Fill(dataTable);
        if (dataTable.Rows[0][0].ToString() == "1")
        {
            this.Hide();
            Dashboard dashboard_form = new Dashboard();
            dashboard_form.Show();
        }
        else
        {
            MessageBox.Show("Authentication failed!");
        }

That is the part where the SQL stuff is taking place for the Button. Basically, on clicking a button, the code is executed. But, for some reason, when I click the button, either the code isn't executing, or it isn't working. (I'm guessing it isn't executing.) I really hope that someone can help me with this. The button just won't work.

EDIT: As requested by Nirman, here's the Form Designer code.

    namespace subTerraApplication
    {
partial class WelcomePage
{
    ///
    /// 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.formSkin1 = new FlatUI.FormSkin();
        this.flatTextBox2 = new FlatUI.FlatTextBox();
        this.flatLabel2 = new FlatUI.FlatLabel();
        this.flatTextBox1 = new FlatUI.FlatTextBox();
        this.flatLabel1 = new FlatUI.FlatLabel();
        this.flatMini1 = new FlatUI.FlatMini();
        this.flatMax1 = new FlatUI.FlatMax();
        this.flatClose1 = new FlatUI.FlatClose();
        this.flatButton1 = new FlatUI.FlatButton();
        this.formSkin1.SuspendLayout();
        this.SuspendLayout();
        //
        // formSkin1
        //
        this.formSkin1.BackColor = System.Drawing.Color.White;
        this.formSkin1.BaseColor = System.Drawing.Color.FromArgb(((int)(((byte)(60)))), ((int)(((byte)(70)))), ((int)(((byte)(73)))));
        this.formSkin1.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(53)))), ((int)(((byte)(58)))), ((int)(((byte)(60)))));
        this.formSkin1.Controls.Add(this.flatButton1);
        this.formSkin1.Controls.Add(this.flatTextBox2);
        this.formSkin1.Controls.Add(this.flatLabel2);
        this.formSkin1.Controls.Add(this.flatTextBox1);
        this.formSkin1.Controls.Add(this.flatLabel1);
        this.formSkin1.Controls.Add(this.flatMini1);
        this.formSkin1.Controls.Add(this.flatMax1);
        this.formSkin1.Controls.Add(this.flatClose1);
        this.formSkin1.Dock = System.Windows.Forms.DockStyle.Fill;
        this.formSkin1.FlatColor = System.Drawing.Color.FromArgb(((int)(((byte)(52)))), ((int)(((byte)(152)))), ((int)(((byte)(219)))));
        this.formSkin1.Font = new System.Drawing.Font("Segoe UI", 12F);
        this.formSkin1.HeaderColor = System.Drawing.Color.FromArgb(((int)(((byte)(45)))), ((int)(((byte)(47)))), ((int)(((byte)(49)))));
        this.formSkin1.HeaderMaximize = false;
        this.formSkin1.Location = new System.Drawing.Point(0, 0);
        this.formSkin1.Name = "formSkin1";
        this.formSkin1.Size = new System.Drawing.Size(256, 349);
        this.formSkin1.TabIndex = 0;
        this.formSkin1.Text = "subTerra Build 1";
        //
        // flatTextBox2
        //
        this.flatTextBox2.BackColor = System.Drawing.Color.Transparent;
        this.flatTextBox2.FocusOnHover = false;
        this.flatTextBox2.Location = new System.Drawing.Point(125, 135);
        this.flatTextBox2.MaxLength = 32767;
        this.flatTextBox2.Multiline = false;
        this.flatTextBox2.Name = "flatTextBox2";
        this.flatTextBox2.ReadOnly = false;
        this.flatTextBox2.Size = new System.Drawing.Size(109, 29);
        this.flatTextBox2.TabIndex = 10;
        this.flatTextBox2.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
        this.flatTextBox2.TextColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(192)))));
        this.flatTextBox2.UseSystemPasswordChar = true;
        //
        // flatLabel2
        //
        this.flatLabel2.AutoSize = true;
        this.flatLabel2.BackColor = System.Drawing.Color.Transparent;
        this.flatLabel2.Font = new System.Drawing.Font("Segoe UI", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
        this.flatLabel2.ForeColor = System.Drawing.Color.White;
        this.flatLabel2.Location = new System.Drawing.Point(13, 135);
        this.flatLabel2.Name = "flatLabel2";
        this.flatLabel2.Size = new System.Drawing.Size(99, 30);
        this.flatLabel2.TabIndex = 9;
        this.flatLabel2.Text = "Password";
        //
        // flatTextBox1
        //
        this.flatTextBox1.BackColor = System.Drawing.Color.Transparent;
        this.flatTextBox1.FocusOnHover = false;
        this.flatTextBox1.Location = new System.Drawing.Point(125, 81);
        this.flatTextBox1.MaxLength = 32767;
        this.flatTextBox1.Multiline = false;
        this.flatTextBox1.Name = "flatTextBox1";
        this.flatTextBox1.ReadOnly = false;
        this.flatTextBox1.Size = new System.Drawing.Size(109, 29);
        this.flatTextBox1.TabIndex = 8;
        this.flatTextBox1.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
        this.flatTextBox1.TextColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(192)))));
        this.flatTextBox1.UseSystemPasswordChar = false;
        //
        // flatLabel1
        //
        this.flatLabel1.AutoSize = true;
        this.flatLabel1.BackColor = System.Drawing.Color.Transparent;
        this.flatLabel1.Font = new System.Drawing.Font("Segoe UI", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
        this.flatLabel1.ForeColor = System.Drawing.Color.White;
        this.flatLabel1.Location = new System.Drawing.Point(13, 81);
        this.flatLabel1.Name = "flatLabel1";
        this.flatLabel1.Size = new System.Drawing.Size(106, 30);
        this.flatLabel1.TabIndex = 7;
        this.flatLabel1.Text = "Username";
        //
        // flatMini1
        //
        this.flatMini1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
        this.flatMini1.BackColor = System.Drawing.Color.White;
        this.flatMini1.BaseColor = System.Drawing.Color.FromArgb(((int)(((byte)(45)))), ((int)(((byte)(47)))), ((int)(((byte)(49)))));
        this.flatMini1.Font = new System.Drawing.Font("Marlett", 12F);
        this.flatMini1.Location = new System.Drawing.Point(189, -1);
        this.flatMini1.Name = "flatMini1";
        this.flatMini1.Size = new System.Drawing.Size(18, 18);
        this.flatMini1.TabIndex = 6;
        this.flatMini1.Text = "flatMini1";
        this.flatMini1.TextColor = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243)))));
        //
        // flatMax1
        //
        this.flatMax1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
        this.flatMax1.BackColor = System.Drawing.Color.White;
        this.flatMax1.BaseColor = System.Drawing.Color.FromArgb(((int)(((byte)(45)))), ((int)(((byte)(47)))), ((int)(((byte)(49)))));
        this.flatMax1.Font = new System.Drawing.Font("Marlett", 12F);
        this.flatMax1.Location = new System.Drawing.Point(213, -1);
        this.flatMax1.Name = "flatMax1";
        this.flatMax1.Size = new System.Drawing.Size(18, 18);
        this.flatMax1.TabIndex = 5;
        this.flatMax1.Text = "flatMax1";
        this.flatMax1.TextColor = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243)))));
        //
        // flatClose1
        //
        this.flatClose1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
        this.flatClose1.BackColor = System.Drawing.Color.White;
        this.flatClose1.BaseColor = System.Drawing.Color.FromArgb(((int)(((byte)(168)))), ((int)(((byte)(35)))), ((int)(((byte)(35)))));
        this.flatClose1.Font = new System.Drawing.Font("Marlett", 10F);
        this.flatClose1.Location = new System.Drawing.Point(237, 0);
        this.flatClose1.Name = "flatClose1";
        this.flatClose1.Size = new System.Drawing.Size(18, 18);
        this.flatClose1.TabIndex = 4;
        this.flatClose1.Text = "flatClose1";
        this.flatClose1.TextColor = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243)))));
        //
        // flatButton1
        //
        this.flatButton1.BackColor = System.Drawing.Color.Transparent;
        this.flatButton1.BaseColor = System.Drawing.Color.FromArgb(((int)(((byte)(52)))), ((int)(((byte)(152)))), ((int)(((byte)(219)))));
        this.flatButton1.Cursor = System.Windows.Forms.Cursors.Hand;
        this.flatButton1.Font = new System.Drawing.Font("Segoe UI", 12F);
        this.flatButton1.Location = new System.Drawing.Point(74, 209);
        this.flatButton1.Name = "flatButton1";
        this.flatButton1.Rounded = false;
        this.flatButton1.Size = new System.Drawing.Size(106, 32);
        this.flatButton1.TabIndex = 11;
        this.flatButton1.Text = "Login";
        this.flatButton1.TextColor = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243)))));
        //
        // WelcomePage
        //
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(256, 349);
        this.Controls.Add(this.formSkin1);
        this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
        this.Name = "WelcomePage";
        this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
        this.Text = "Form1";
        this.TransparencyKey = System.Drawing.Color.Fuchsia;
        this.formSkin1.ResumeLayout(false);
        this.formSkin1.PerformLayout();
        this.ResumeLayout(false);

    }

    #endregion

    private FlatUI.FormSkin formSkin1;
    private FlatUI.FlatMini flatMini1;
    private FlatUI.FlatMax flatMax1;
    private FlatUI.FlatClose flatClose1;
    private FlatUI.FlatTextBox flatTextBox2;
    private FlatUI.FlatLabel flatLabel2;
    private FlatUI.FlatTextBox flatTextBox1;
    private FlatUI.FlatLabel flatLabel1;
    private FlatUI.FlatButton flatButton1;
}

}

PROBLEM HAS BEEN SOLVED! The code for the click detection was missing!

Body:
Did you try setting breakpoint in if/else blocks?

And here is some considerations:
Use prepared statements and parameterized queries. Never ever create dynamic SQL based on user input, because the application becomes vulnerable to SQL injection.

Here is you rewritten code using parametrized parameters:

SqlDataAdapter dataAdapter = new SqlDataAdapter("SELECT COUNT(*) FROM login WHERE Username=@Username AND Password=@Password", connection);
dataAdapter.SelectCommand.Parameters.AddWithValue("@Username", flatTextBox1.Text);
dataAdapter.SelectCommand.Parameters.AddWithValue("@Password", flatTextBox2.Text);


来源: stackexchange

问:
paralell_rspec with options --exclude-pattern
Trying to exclude the specs in the /home dir during the parallel run.

Tried a few things similar to the following:

parallel_rspec myproj -n 4 -o '--exclude-pattern "myproj/spec/home/*_spec.rb"'

parallel_rspec ./myproj -n 4 -o '--exclude-pattern "./myproj/spec/home/*_spec.rb"'

But it does not exclude specs in the /home dir. It runs all specs in myproj.

The following commands do exclude specs in /home dir but I need to run them in parallel:

rspec myproj --exclude-pattern "myproj/spec/home/*_spec.rb"

rspec ./myproj --exclude-pattern "./myproj/spec/home/*_spec.rb"

答:
I always used the rake task for that as advised here:

```<code>ParallelRSpec::RakeTask.new(:prspec) do |t|
  ENV['WORKERS'] = '4'
  t.rspec_opts = '--exclude-pattern "myproj/spec/home/*_spec.rb"'
end
</code>```

and run it as:

```<code>bundle exec rake prspec
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I always used the rake task for that as advised here:

ParallelRSpec::RakeTask.new(:prspec) do |t|
  ENV['WORKERS'] = '4'
  t.rspec_opts = '--exclude-pattern "myproj/spec/home/*_spec.rb"'
end

and run it as:

bundle exec rake prspec


问:
Return an Array of Indexes for Matching Values in a Primary Array
I have an array with multiple duplicates.  I'm trying to write code that will produce a second array that contains the indexes of all of the elements in the first array that equal a look up value.

For example, I have this array:

```<code>1
1
1
2
2
2
2
2
3
3
4
5
6
6
7
</code>```

I want a second array that will return the indexes of the number 6.

This is the code that I have right now.

```<code>Sub test()
Dim look_up As Integer
Dim id_ar As Variant
Dim index_ar As Variant

look_up = 6
id_ar = Range("A1:A16").Value
index_ar = Application.Match(id_ar, look_up, True)

End Sub
</code>```

I want this to result in an array like this:

```<code>13
14
</code>```

But it just returns a bunch of '#N/A's

答:
Some extremely simple code may help you better than brief and concise approaches.

Definitions : arrOut is your desired output, rngLookup is where your number 6 and any others reside. rngDB is where you want to search for the indexes of the lookup values.

```<code>Option Explicit

Sub dupes()
Dim rngLookup, rngDB As Range
Dim i, j As Variant
Dim arrOut As New Collection

Set rngLookup = Worksheets("Sheet1").Range("B1")
Set rngDB = Worksheets("Sheet1").Range("A1:A14")

Dim counter As Integer
counter = 0

For Each i In rngLookup

    For Each j In rngDB
        counter = counter + 1
        If j.Value = i.Value Then
            arrOut.Add Item:=CInt(counter)
        Else
        End If
    Next j
Next i

End Sub
</code>```

Body:
I have an array with multiple duplicates.  I'm trying to write code that will produce a second array that contains the indexes of all of the elements in the first array that equal a look up value.

For example, I have this array:

1
1
1
2
2
2
2
2
3
3
4
5
6
6
7

I want a second array that will return the indexes of the number 6.

This is the code that I have right now.

Sub test()
Dim look_up As Integer
Dim id_ar As Variant
Dim index_ar As Variant

look_up = 6
id_ar = Range("A1:A16").Value
index_ar = Application.Match(id_ar, look_up, True)

End Sub

I want this to result in an array like this:

13
14

But it just returns a bunch of '#N/A's

Body:
Some extremely simple code may help you better than brief and concise approaches.

Definitions : arrOut is your desired output, rngLookup is where your number 6 and any others reside. rngDB is where you want to search for the indexes of the lookup values.

Option Explicit

Sub dupes()
Dim rngLookup, rngDB As Range
Dim i, j As Variant
Dim arrOut As New Collection

Set rngLookup = Worksheets("Sheet1").Range("B1")
Set rngDB = Worksheets("Sheet1").Range("A1:A14")

Dim counter As Integer
counter = 0

For Each i In rngLookup

    For Each j In rngDB
        counter = counter + 1
        If j.Value = i.Value Then
            arrOut.Add Item:=CInt(counter)
        Else
        End If
    Next j
Next i

End Sub


问:
Domain Driven Design, Domain objects, attitude about Setters
Been watching some Greg Young videos lately and I'm trying to understand why there is a negative attitude towards Setters on Domain objects. I thought Domain objects were supposed to be "heavy" with logic in DDD. Are there any good examples online of the bad example and then they way to correct it? Any examples or explanations are good. Does this only apply to Events stored in a CQRS manner or does this apply to all of DDD?</p>

答:
Setters doesnt carry any semantic information.

e.g.

```<code>blogpost.PublishDate = DateTime.Now;
</code>```

Does that mean that the post has been published?
Or just that the publish date have been set?

Consider:

```<code>blogpost.Publish();
</code>```

This clearly shows the intention that the blogpost should be published.

Also, setters may break the object invariants.
For example if we have a "Triangle" entity, the invariant should be that the sum of all angles should be 180 degrees.

```<code>Assert.AreEqual (t.A + t.B + t.C ,180);
</code>```

Now if we have setters, we can easily break the invariants:

```<code>t.A = 0;
t.B = 0;
t.C = 0;
</code>```

So we have a triangle where the sum of all angles are 0...
Is that really a Triangle? I'd say no.

Replacing setters with methods could force us to maintain invariants:

```<code>t.SetAngles(0,0,0); //should fail
</code>```

Such call should throw an exception telling you that this causes an invalid state for your entity.

So you get semantics and invariants with methods instead of setters.

ContentLicense: CC BY-SA 2.5

Body:
Setters doesnt carry any semantic information.

e.g.

blogpost.PublishDate = DateTime.Now;

Does that mean that the post has been published?
Or just that the publish date have been set?

Consider:

blogpost.Publish();

This clearly shows the intention that the blogpost should be published.

Also, setters may break the object invariants.
For example if we have a "Triangle" entity, the invariant should be that the sum of all angles should be 180 degrees.

Assert.AreEqual (t.A + t.B + t.C ,180);

Now if we have setters, we can easily break the invariants:

t.A = 0;
t.B = 0;
t.C = 0;

So we have a triangle where the sum of all angles are 0...
Is that really a Triangle? I'd say no.

Replacing setters with methods could force us to maintain invariants:

t.SetAngles(0,0,0); //should fail

Such call should throw an exception telling you that this causes an invalid state for your entity.

So you get semantics and invariants with methods instead of setters.


问:
Maintaining list items positions on device rotation in an android fragment
In a fragment I am trying to save the scroll state of the RecyclerView list, but somehow it is not saving the state. As it is a fragment, I am overriding the onSaveInstanceState() and onActivityCreated() methods to save the scroll position. Even tried implementing in onViewStateRestored() method. I saw related some posts on saving the scroll state but it ain't working. Kindly let me know where am I failing. Below is my code:</p>

```<code>public class RecipeListFragment extends Fragment
    implements RecipeListContract.View {
@BindView(R.id.recipe_list_recycler_view)
RecyclerView mRecipeListRecyclerView;
@BindView(R.id.recipe_list_progress_bar)
ProgressBar mRecipeListProgressBar;

@BindInt(R.integer.grid_column_count)
int mGridColumnCount;
@BindString(R.string.recipe_list_sync_completed)
String mRecipeListSyncCompleted;
@BindString(R.string.recipe_list_connection_error)
String mRecipeListConnectionError;

GridLayoutManager gridLayoutManager;
Parcelable savedRecyclerLayoutState;

Unbinder unbinder;

private static final String SAVED_LAYOUT_MANAGER
        = "com.learnwithme.buildapps.bakingapp.ui.recipelist.fragment";

private RecipeListContract.Presenter mRecipeListPresenter;
private RecipeListAdapter mRecipeListAdapter;

public RecipeListFragment() { }

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup
container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_recipe_list, container,
false);
unbinder = ButterKnife.bind(this, view);

mRecipeListAdapter = new RecipeListAdapter(
            getContext(),
            new ArrayList<>(0),
            recipeId -> mRecipeListPresenter.loadRecipeDetails(recipeId)
);
mRecipeListAdapter.setHasStableIds(true);

    gridLayoutManager = new GridLayoutManager(getContext(),
mGridColumnCount);
    mRecipeListRecyclerView.setLayoutManager(gridLayoutManager);
    mRecipeListRecyclerView.setHasFixedSize(true);
    mRecipeListRecyclerView.setAdapter(mRecipeListAdapter);

    return view;
}

@Override
public void onPause() {
    super.onPause();
    mRecipeListPresenter.unsubscribe();
}

@Override
public void onResume() {
    super.onResume();
    mRecipeListPresenter.subscribe();
}

@Override
public void onSaveInstanceState() { }

@Override
public void onSaveInstanceState(Bundle bundle) {
    super.onSaveInstanceState(bundle);
    if(bundle != null) {
        bundle.putParcelable(SAVED_LAYOUT_MANAGER,
                mRecipeListRecyclerView
                    .getLayoutManager()
                    .onSaveInstanceState());
        Timber.d("instance state=>",
mRecipeListRecyclerView.getLayoutManager().onSaveInstanceState());
    }
}

@Override
public void onViewStateRestored(@Nullable Bundle bundle) {
    super.onViewStateRestored(bundle);
    if(bundle != null) {
        savedRecyclerLayoutState =
bundle.getParcelable(SAVED_LAYOUT_MANAGER);
        Timber.d("onViewStateRestored savedRecyclerLayoutState=>",
savedRecyclerLayoutState);
        mRecipeListRecyclerView
                .getLayoutManager()
                .onRestoreInstanceState(savedRecyclerLayoutState);
    }
}

@Override
public void onActivityCreated(@Nullable Bundle bundle) {
    super.onActivityCreated(bundle);
    if(bundle != null) {
        savedRecyclerLayoutState =
bundle.getParcelable(SAVED_LAYOUT_MANAGER);
        Timber.d("onViewStateRestored savedRecyclerLayoutState=>",
                savedRecyclerLayoutState);
        mRecipeListRecyclerView
                .getLayoutManager()
                .onRestoreInstanceState(savedRecyclerLayoutState);
    }
}

@Override
public void onDestroyView() {
    super.onDestroyView();
    unbinder.unbind();
}

public static RecipeListFragment newInstance() {
    return new RecipeListFragment();
}

@Override
public void setPresenter(RecipeListContract.Presenter recipeListPresenter) {
    this.mRecipeListPresenter = recipeListPresenter;
}

@Override
public void showRecipeList(List<Recipe> recipeList) {
    mRecipeListAdapter.refreshRecipes(recipeList);
}

@Override
public void loadProgressBar(boolean show) {
    setViewVisibility(mRecipeListRecyclerView, !show);
    setViewVisibility(mRecipeListProgressBar, show);
}

@Override
public void displayCompletedMessage() {
    Toast.makeText(getContext(), mRecipeListSyncCompleted,
Toast.LENGTH_SHORT).show();
}

@Override
public void displayErrorMessage() {
    Toast.makeText(getContext(), mRecipeListConnectionError,
Toast.LENGTH_SHORT).show();
}

@Override
public void displayRecipeDetails(int recipeId) {
    startActivity(RecipeDetailsActivity.prepareIntent(getContext(),
recipeId));
}

private void setViewVisibility(View view, boolean visible) {
    if (visible) {
        view.setVisibility(View.VISIBLE);
    } else {
        view.setVisibility(View.INVISIBLE);
    }
}
}
</code>```

答:
I have resolved the issue myself. The problem was to save the scroll position of the device in onSaveInstanceState() and restoring the same in onViewRestored() method.

```<code>private Parcelable mRecipeListParcelable;
private int mScrollPosition = -1;

@Override
public void onSaveInstanceState(Bundle bundle) {
    super.onSaveInstanceState(bundle);
    int scrollPosition = ((GridLayoutManager)
    mRecipeListRecyclerView.getLayoutManager())
            .findFirstCompletelyVisibleItemPosition();
    mRecipeListParcelable = gridLayoutManager.onSaveInstanceState();
    bundle.putParcelable(KEY_LAYOUT, mRecipeListParcelable);
    bundle.putInt(POSITION, scrollPosition);
}

@Override
public void onViewStateRestored(@Nullable Bundle bundle) {
    super.onViewStateRestored(bundle);
    if(bundle != null) {
        mRecipeListParcelable = bundle.getParcelable(KEY_LAYOUT);
        mScrollPosition = bundle.getInt(POSITION);
    }
}
</code>```

Also, in the loadProgress() method I had to set the scrollToPosition() with the scroll position saved.

```<code>@Override
public void loadProgressBar(boolean show) {
    setViewVisibility(mRecipeListRecyclerView, !show);
    setViewVisibility(mRecipeListProgressBar, show);
    mRecipeListRecyclerView.scrollToPosition(mScrollPosition);
}
</code>```

Also, one more thing to remember is that no need to restore anything in onResume() method as the presenter callbacks would get called and the view is reset anyway.

Body:
In a fragment I am trying to save the scroll state of the RecyclerView list, but somehow it is not saving the state. As it is a fragment, I am overriding the onSaveInstanceState() and onActivityCreated() methods to save the scroll position. Even tried implementing in onViewStateRestored() method. I saw related some posts on saving the scroll state but it ain't working. Kindly let me know where am I failing. Below is my code:

public class RecipeListFragment extends Fragment
    implements RecipeListContract.View {
@BindView(R.id.recipe_list_recycler_view)
RecyclerView mRecipeListRecyclerView;
@BindView(R.id.recipe_list_progress_bar)
ProgressBar mRecipeListProgressBar;

@BindInt(R.integer.grid_column_count)
int mGridColumnCount;
@BindString(R.string.recipe_list_sync_completed)
String mRecipeListSyncCompleted;
@BindString(R.string.recipe_list_connection_error)
String mRecipeListConnectionError;

GridLayoutManager gridLayoutManager;
Parcelable savedRecyclerLayoutState;

Unbinder unbinder;

private static final String SAVED_LAYOUT_MANAGER
        = "com.learnwithme.buildapps.bakingapp.ui.recipelist.fragment";

private RecipeListContract.Presenter mRecipeListPresenter;
private RecipeListAdapter mRecipeListAdapter;

public RecipeListFragment() { }

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup
container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_recipe_list, container,
false);
unbinder = ButterKnife.bind(this, view);

mRecipeListAdapter = new RecipeListAdapter(
            getContext(),
            new ArrayList<>(0),
            recipeId -> mRecipeListPresenter.loadRecipeDetails(recipeId)
);
mRecipeListAdapter.setHasStableIds(true);

    gridLayoutManager = new GridLayoutManager(getContext(),
mGridColumnCount);
    mRecipeListRecyclerView.setLayoutManager(gridLayoutManager);
    mRecipeListRecyclerView.setHasFixedSize(true);
    mRecipeListRecyclerView.setAdapter(mRecipeListAdapter);

    return view;
}

@Override
public void onPause() {
    super.onPause();
    mRecipeListPresenter.unsubscribe();
}

@Override
public void onResume() {
    super.onResume();
    mRecipeListPresenter.subscribe();
}

@Override
public void onSaveInstanceState() { }

@Override
public void onSaveInstanceState(Bundle bundle) {
    super.onSaveInstanceState(bundle);
    if(bundle != null) {
        bundle.putParcelable(SAVED_LAYOUT_MANAGER,
                mRecipeListRecyclerView
                    .getLayoutManager()
                    .onSaveInstanceState());
        Timber.d("instance state=>",
mRecipeListRecyclerView.getLayoutManager().onSaveInstanceState());
    }
}

@Override
public void onViewStateRestored(@Nullable Bundle bundle) {
    super.onViewStateRestored(bundle);
    if(bundle != null) {
        savedRecyclerLayoutState =
bundle.getParcelable(SAVED_LAYOUT_MANAGER);
        Timber.d("onViewStateRestored savedRecyclerLayoutState=>",
savedRecyclerLayoutState);
        mRecipeListRecyclerView
                .getLayoutManager()
                .onRestoreInstanceState(savedRecyclerLayoutState);
    }
}

@Override
public void onActivityCreated(@Nullable Bundle bundle) {
    super.onActivityCreated(bundle);
    if(bundle != null) {
        savedRecyclerLayoutState =
bundle.getParcelable(SAVED_LAYOUT_MANAGER);
        Timber.d("onViewStateRestored savedRecyclerLayoutState=>",
                savedRecyclerLayoutState);
        mRecipeListRecyclerView
                .getLayoutManager()
                .onRestoreInstanceState(savedRecyclerLayoutState);
    }
}

@Override
public void onDestroyView() {
    super.onDestroyView();
    unbinder.unbind();
}

public static RecipeListFragment newInstance() {
    return new RecipeListFragment();
}

@Override
public void setPresenter(RecipeListContract.Presenter recipeListPresenter) {
    this.mRecipeListPresenter = recipeListPresenter;
}

@Override
public void showRecipeList(List<Recipe> recipeList) {
    mRecipeListAdapter.refreshRecipes(recipeList);
}

@Override
public void loadProgressBar(boolean show) {
    setViewVisibility(mRecipeListRecyclerView, !show);
    setViewVisibility(mRecipeListProgressBar, show);
}

@Override
public void displayCompletedMessage() {
    Toast.makeText(getContext(), mRecipeListSyncCompleted,
Toast.LENGTH_SHORT).show();
}

@Override
public void displayErrorMessage() {
    Toast.makeText(getContext(), mRecipeListConnectionError,
Toast.LENGTH_SHORT).show();
}

@Override
public void displayRecipeDetails(int recipeId) {
    startActivity(RecipeDetailsActivity.prepareIntent(getContext(),
recipeId));
}

private void setViewVisibility(View view, boolean visible) {
    if (visible) {
        view.setVisibility(View.VISIBLE);
    } else {
        view.setVisibility(View.INVISIBLE);
    }
}
}

Body:
I have resolved the issue myself. The problem was to save the scroll position of the device in onSaveInstanceState() and restoring the same in onViewRestored() method.

private Parcelable mRecipeListParcelable;
private int mScrollPosition = -1;

@Override
public void onSaveInstanceState(Bundle bundle) {
    super.onSaveInstanceState(bundle);
    int scrollPosition = ((GridLayoutManager)
    mRecipeListRecyclerView.getLayoutManager())
            .findFirstCompletelyVisibleItemPosition();
    mRecipeListParcelable = gridLayoutManager.onSaveInstanceState();
    bundle.putParcelable(KEY_LAYOUT, mRecipeListParcelable);
    bundle.putInt(POSITION, scrollPosition);
}

@Override
public void onViewStateRestored(@Nullable Bundle bundle) {
    super.onViewStateRestored(bundle);
    if(bundle != null) {
        mRecipeListParcelable = bundle.getParcelable(KEY_LAYOUT);
        mScrollPosition = bundle.getInt(POSITION);
    }
}

Also, in the loadProgress() method I had to set the scrollToPosition() with the scroll position saved.

@Override
public void loadProgressBar(boolean show) {
    setViewVisibility(mRecipeListRecyclerView, !show);
    setViewVisibility(mRecipeListProgressBar, show);
    mRecipeListRecyclerView.scrollToPosition(mScrollPosition);
}

Also, one more thing to remember is that no need to restore anything in onResume() method as the presenter callbacks would get called and the view is reset anyway.


问:
Running macros one after another in Microsoft Word
I have 3 macros, and I want to have them executed in a very precise order. My code is currently as below:

```<code>Sub MasterFindAndReplace()
    Call BulkFindTermsWithCase
    Call BulkFindTerms
    Call BulkFindReplace
End Sub
</code>```

With this code, will the macros run successively, or will they run simultaneously?

If this code will result in all macro executed at the same time/in random order, is there any way I can make it runs like so: BulkFindTermsWithCase -> BulkFindTerms -> Call BulkFindReplace

答: Can't be done natively with VBA. VBA is built in a single-threaded apartment. The only way to get multiple threads is to build a DLL in something other than VBA that has a COM interface and call it from VBA. Of course, if you do have multiple processor cores in your computer (which is commonplace nowadays), your program can use threads to take advantage of additional cores to perform your processing, and you will see a speedup, because you are throwing more horsepower at your computing problem. If you don't use threads at all, your program will only utilize a single processor core, which is fine if that's all you need. </p>

Body:
I have 3 macros, and I want to have them executed in a very precise order. My code is currently as below:

Sub MasterFindAndReplace()
    Call BulkFindTermsWithCase
    Call BulkFindTerms
    Call BulkFindReplace
End Sub

With this code, will the macros run successively, or will they run simultaneously?

If this code will result in all macro executed at the same time/in random order, is there any way I can make it runs like so: BulkFindTermsWithCase -> BulkFindTerms -> Call BulkFindReplace


问:
Automatically passing own type to function call
I'd like to pass a value when calling a function but want to omit to actually add it as a parameter.

To be more precise I'd like to write a logger that also prints which class called the logging function but don't want to always pass a "this" as a parameter.

Example code:

```<code>class static Logger{
    public static void LogMsg(string msg, object objectCalling){
         Print(objectCalling.GetType().Name + ": " + msg);
    }
    private void Print(string msg){
        // print it
    }
}

class SomeClass{
    private void WriteTestLog() {
        Logger.LogMsg("Testing!");
    }
}
</code>```

This should then create an output like: "SomeClass: Testing!"

I am not sure how to tackle this maybe I am just missing sth.

答:
If you really wish to extract the caller's type you can play with the stack trace:

```<code>[MethodImpl(MethodImplOptions.NoInlining)]
public static void LogMsg(string msg)
{
     var caller = new StackTrace().GetFrames()[1].GetMethod();
     Console.WriteLine($"{caller.DeclaringType}.{caller.Name}: {msg}");
}
</code>```

But keep in mind that extracting the caller from the stack trace is a very expensive operation. Besides despite of the NoInlining it is not guaranteed that in an optimized build the caller itself is not inlined. I do not recommend to use it in a release build or if performance matters.

Body:
I'd like to pass a value when calling a function but want to omit to actually add it as a parameter.

To be more precise I'd like to write a logger that also prints which class called the logging function but don't want to always pass a "this" as a parameter.

Example code:

class static Logger{
    public static void LogMsg(string msg, object objectCalling){
         Print(objectCalling.GetType().Name + ": " + msg);
    }
    private void Print(string msg){
        // print it
    }
}

class SomeClass{
    private void WriteTestLog() {
        Logger.LogMsg("Testing!");
    }
}

This should then create an output like: "SomeClass: Testing!"

I am not sure how to tackle this maybe I am just missing sth.

Body:
If you really wish to extract the caller's type you can play with the stack trace:

[MethodImpl(MethodImplOptions.NoInlining)]
public static void LogMsg(string msg)
{
     var caller = new StackTrace().GetFrames()[1].GetMethod();
     Console.WriteLine($"{caller.DeclaringType}.{caller.Name}: {msg}");
}

But keep in mind that extracting the caller from the stack trace is a very expensive operation. Besides despite of the NoInlining it is not guaranteed that in an optimized build the caller itself is not inlined. I do not recommend to use it in a release build or if performance matters.


问:
Delegate on subView
I have 4 UIViewController namely vcA, vcB, vcC and vcD. Now, vcB has a tableView with two rows. And vcB is subViewed on vcA with one half side like iPad's setting screen. Till here, its working fine, but i required if I click on vcB's tableView's first cell, then vcC should be subViewed on other half side, similarly by selecting vcB's tableview's second cell vcD should be subViewed and vcC should remove.

Here is my screen:

Suppose u select "Select Country", the other vcC's view should subviewd & similary by selecting "Notification" vcD should be subViewed and vcC should remove. , and don't worry about frame, i will set that. And assume that the parent view is vcA here.

Here, I tried with delegate but on subViews delegate is not working I think, it can be Possible through NSNotificationCenter but is there any other way to do that ?

Thanks Any help will be appreciated.

Updated

Following way I'm using for get the result. But I know its not the correct way, and also not happening what i'm looking for.

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        print(indexPath.section)
        print(indexPath.row)
        if UIDevice.Display.typeIsLike == UIDevice.DisplayType.ipad {

            let iPadVc = iPadSettingViewController()

            if indexPath.section == 0 && indexPath.row == 0 {

                var sliderVC: SettingsViewController! = nil

                sliderVC = self.storyboard?.instantiateViewController(withIdentifier: "SettingsViewController") as! SettingsViewController

                sliderVC.view.frame = CGRect(x:0, y: 64, width: CGFloat((iPadVc.view.frame.size.width)/2.4), height: CGFloat(iPadVc.view.frame.size.height-64))
                iPadVc.view?.addSubview(sliderVC.view)

            }
            else if indexPath.section == 0 && indexPath.row == 2 {

                var countryVC : CountryViewController! = nil

                countryVC = self.storyboard?.instantiateViewController(withIdentifier: "CountryViewController") as! CountryViewController

                countryVC.view.frame = CGRect(x:CGFloat((iPadVc.view.frame.size.width)/2.4), y: 64, width: CGFloat((iPadVc.view.frame.size.width) - (iPadVc.view.frame.size.width)/2.4), height: CGFloat(iPadVc.view.frame.size.height-64))

                iPadVc.view?.addSubview(countryVC.view)

            }

        }
}
</code>```

答:
You allocated 'iPadVc' and without presenting you are trying to add the countryVC view.it's wrong.  You just allocated the vc but the vc view will be nil at the time of you are adding.

My suggestion : Pass the vcA object reference to vcB while adding a vcB.view to vcA.view

```<code>class vcA: UIViewController {

   func loadSlideVC() {
     viewcontrollerB = //Initialize the vcB
     viewControllerB.containerVC = self
     //Add the view to vaA
   }
}

class vcB: UIViewController {
  weak var containerVC: vcA?

  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  if UIDevice.Display.typeIsLike == UIDevice.DisplayType.ipad {
     if indexPath.section == 0 && indexPath.row == 0 {

        var sliderVC: SettingsViewController! = nil
        sliderVC = self.storyboard?.instantiateViewController(withIdentifier: "SettingsViewController") as! SettingsViewController
        containerVC?.view?.addSubview(sliderVC.view)
     }
    }
  }

}
</code>```

Title: Delegate on subView

Body:
I have 4 UIViewController namely vcA, vcB, vcC and vcD. Now, vcB has a tableView with two rows. And vcB is subViewed on vcA with one half side like iPad's setting screen. Till here, its working fine, but i required if I click on vcB's tableView's first cell, then vcC should be subViewed on other half side, similarly by selecting vcB's tableview's second cell vcD should be subViewed and vcC should remove.

Here is my screen:

Suppose u select "Select Country", the other vcC's view should subviewd & similary by selecting "Notification" vcD should be subViewed and vcC should remove. , and don't worry about frame, i will set that. And assume that the parent view is vcA here.

Here, I tried with delegate but on subViews delegate is not working I think, it can be Possible through NSNotificationCenter but is there any other way to do that ?

Thanks Any help will be appreciated.

Updated

Following way I'm using for get the result. But I know its not the correct way, and also not happening what i'm looking for.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        print(indexPath.section)
        print(indexPath.row)
        if UIDevice.Display.typeIsLike == UIDevice.DisplayType.ipad {

            let iPadVc = iPadSettingViewController()

            if indexPath.section == 0 && indexPath.row == 0 {

                var sliderVC: SettingsViewController! = nil

                sliderVC = self.storyboard?.instantiateViewController(withIdentifier: "SettingsViewController") as! SettingsViewController

                sliderVC.view.frame = CGRect(x:0, y: 64, width: CGFloat((iPadVc.view.frame.size.width)/2.4), height: CGFloat(iPadVc.view.frame.size.height-64))
                iPadVc.view?.addSubview(sliderVC.view)

            }
            else if indexPath.section == 0 && indexPath.row == 2 {

                var countryVC : CountryViewController! = nil

                countryVC = self.storyboard?.instantiateViewController(withIdentifier: "CountryViewController") as! CountryViewController

                countryVC.view.frame = CGRect(x:CGFloat((iPadVc.view.frame.size.width)/2.4), y: 64, width: CGFloat((iPadVc.view.frame.size.width) - (iPadVc.view.frame.size.width)/2.4), height: CGFloat(iPadVc.view.frame.size.height-64))

                iPadVc.view?.addSubview(countryVC.view)

            }

        }
}

Body:
You allocated 'iPadVc' and without presenting you are trying to add the countryVC view.it's wrong.  You just allocated the vc but the vc view will be nil at the time of you are adding.

My suggestion : Pass the vcA object reference to vcB while adding a vcB.view to vcA.view

class vcA: UIViewController {

   func loadSlideVC() {
     viewcontrollerB = //Initialize the vcB
     viewControllerB.containerVC = self
     //Add the view to vaA
   }
}

class vcB: UIViewController {
  weak var containerVC: vcA?

  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  if UIDevice.Display.typeIsLike == UIDevice.DisplayType.ipad {
     if indexPath.section == 0 && indexPath.row == 0 {

        var sliderVC: SettingsViewController! = nil
        sliderVC = self.storyboard?.instantiateViewController(withIdentifier: "SettingsViewController") as! SettingsViewController
        containerVC?.view?.addSubview(sliderVC.view)
     }
    }
  }

}


问:
How to design templates for clustered nifi
Do we need to think about underlying cluster while designing nifi templates?

Here is my simple flow

```<code>+-----------------+                         +---------------+                       +-----------------+
|                 |                         |               |                       |                 |
|  READ FROM      |                         |  MERGE        |                       |   PUT HDFS      |
|  KAFKA          |                         |  FILES        |                       |                 |
|                 +-----------------------> |               +---------------------> |                 |
|                 |                         |               |                       |                 |
|                 |                         |               |                       |                 |
|                 |                         |               |                       |                 |
+-----------------+                         +---------------+                       +-----------------+
</code>```

I have 3 nodes cluster.. When system is running I check "cluster" menu and see only master node is utilizing sources, other cluster nodes seems idle... The question is in such a cluster should I design template according to cluster or nifi should do the load balancing.

I saw one of my colleagues created remote processors for each node on cluster and put a load balancer in front of these within template, is it required? (like below)

```<code>                                                                   +------------------+
                                                                   |                  |                 +-------------+
                                                                   | REMOTE PROCESS   |                 |  input port |
                                                            +----> | GROUP FOR        |                 |    (rpg)    |
                                                            |      | NODE 1           |                 +-------------+
                                                            |      |                  |                        |
                                                            |      |                  |                        |
                                                            |      +------------------+                        v
+-----------------+               +-----------------+       RPG
|                 |               |                 |       |                                           +--------------+
|  READ FROM      |               |                 |       |                                           |              |
|  KAFKA          |               | LOAD BALANCER   |       |       +------------------+                | MERGE FILES  |
|                 +-------------> |                 +-------------> |                  |                |              |
|                 |               |                 |       |       |  REMOTE PROCESS  |                |              |
|                 |               |                 |       |       |  GROUP FOR       |                |              |
|                 |               |                 |       |       |  NODE 2          |                |              |
+-----------------+               +-----------------+       RPG     |                  |                +--------------+
                                                            |       +------------------+                       |
                                                            |                                                  |
                                                            |                                                  v
                                                            |
                                                            |       +-------------------+               +---------------+
                                                            |       |                   |               |               |
                                                            |       |   REMOTE PROCESS  |               | PUT HDFS      |
                                                            +-----> |   GROUP FOR       |               |               |
                                                                    |   NODE 3          |               |               |
                                                                    |                   |               |               |
                                                                    |                   |               |               |
                                                                    +-------------------+               +---------------+
</code>```

And what is the use-case for load-balancer except remote clusters, can I use load-balancer to split traffic into several processors to speedup the operation?

答:
Apache NiFi does not do any automatic load balancing or moving of data, so it is up to you to design the data flow in a way that utilizes your cluster. How to do this will depend on the data flow and how the data is being brought into the cluster.

I wrote this article once to try and summarize the approaches:

https://community.hortonworks.com/articles/16120/how-do-i-distribute-data-across-a-nifi-cluster.html

In you case with Kafka, you should be able to have the flow run as shown in your first picture (without remote process groups). This is because Kafka is a data source that will allow each node to consume different data.

If ConsumeKafka appears to be running on only one node, there could be a couple of reasons for this...

First, make sure ConsumeKafka is not scheduled for primary node only.

Second, figure out how many partitions you have for your Kafka topic. The Kafka client (used by NiFi) will assign 1 consumer to 1 partition, so if you have only 1 partition then you can only ever have 1 NiFi node consuming from it. Here is an article to further describe this behavior:

http://bryanbende.com/development/2016/09/15/apache-nifi-and-apache-kafka

Body:
Do we need to think about underlying cluster while designing nifi templates?

Here is my simple flow

+-----------------+                         +---------------+                       +-----------------+
|                 |                         |               |                       |                 |
|  READ FROM      |                         |  MERGE        |                       |   PUT HDFS      |
|  KAFKA          |                         |  FILES        |                       |                 |
|                 +-----------------------> |               +---------------------> |                 |
|                 |                         |               |                       |                 |
|                 |                         |               |                       |                 |
|                 |                         |               |                       |                 |
+-----------------+                         +---------------+                       +-----------------+

I have 3 nodes cluster.. When system is running I check "cluster" menu and see only master node is utilizing sources, other cluster nodes seems idle... The question is in such a cluster should I design template according to cluster or nifi should do the load balancing.

I saw one of my colleagues created remote processors for each node on cluster and put a load balancer in front of these within template, is it required? (like below)

                                                                   +------------------+
                                                                   |                  |                 +-------------+
                                                                   | REMOTE PROCESS   |                 |  input port |
                                                            +----> | GROUP FOR        |                 |    (rpg)    |
                                                            |      | NODE 1           |                 +-------------+
                                                            |      |                  |                        |
                                                            |      |                  |                        |
                                                            |      +------------------+                        v
+-----------------+               +-----------------+       RPG
|                 |               |                 |       |                                           +--------------+
|  READ FROM      |               |                 |       |                                           |              |
|  KAFKA          |               | LOAD BALANCER   |       |       +------------------+                | MERGE FILES  |
|                 +-------------> |                 +-------------> |                  |                |              |
|                 |               |                 |       |       |  REMOTE PROCESS  |                |              |
|                 |               |                 |       |       |  GROUP FOR       |                |              |
|                 |               |                 |       |       |  NODE 2          |                |              |
+-----------------+               +-----------------+       RPG     |                  |                +--------------+
                                                            |       +------------------+                       |
                                                            |                                                  |
                                                            |                                                  v
                                                            |
                                                            |       +-------------------+               +---------------+
                                                            |       |                   |               |               |
                                                            |       |   REMOTE PROCESS  |               | PUT HDFS      |
                                                            +-----> |   GROUP FOR       |               |               |
                                                                    |   NODE 3          |               |               |
                                                                    |                   |               |               |
                                                                    |                   |               |               |
                                                                    +-------------------+               +---------------+

And what is the use-case for load-balancer except remote clusters, can I use load-balancer to split traffic into several processors to speedup the operation?


问:
statically/dynamically typed vs static/dynamic binding
everyone what is the difference between those 4 terms, can You give please examples?</p>

答:
Static and dynamic are jargon words that refer to the point in time at which some programming element is resolved.  Static indicates that resolution takes place at the time a program is constructed.  Dynamic indicates that resolution takes place at the time a program is run.

Static and Dynamic Typing

Typing refers to changes in program structure that are due to the differences between data values: integers, characters, floating point numbers, strings, objects and so on.  These differences can have many effects, for example:

memory layout (e.g. 4 bytes for an int, 8 bytes for a double, more for an object)

instructions executed (e.g. primitive operations to add small integers, library calls to add large ones)

program flow (simple subroutine calling conventions versus hash-dispatch for multi-methods)

Static typing means that the executable form of a program generated at build time will vary depending upon the types of data values found in the program.  Dynamic typing means that the generated code will always be the same, irrespective of type -- any differences in execution will be determined at run-time.

Note that few real systems are either purely one or the other, it is just a question of which is the preferred strategy.

Static and Dynamic Binding

Binding refers to the association of names in program text to the storage locations to which they refer.  In static binding, this association is predetermined at build time.  With dynamic binding, this association is not determined until run-time.

Truly static binding is almost extinct.  Earlier assemblers and FORTRAN, for example, would completely precompute the exact memory location of all variables and subroutine locations.  This situation did not last long, with the introduction of stack and heap allocation for variables and dynamically-loaded libraries for subroutines.

So one must take some liberty with the definitions.  It is the spirit of the concept that counts here: statically bound programs precompute as much as possible about storage layout as is practical in a modern virtual memory, garbage collected, separately compiled application.  Dynamically bound programs wait as late as possible.

An example might help.  If I attempt to invoke a method MyClass.foo(), a static-binding system will verify at build time that there is a class called MyClass and that class has a method called foo.  A dynamic-binding system will wait until run-time to see whether either exists.

Contrasts

The main strength of static strategies is that the program translator is much more aware of the programmer's intent.  This makes it easier to:

catch many common errors early, during the build phase

build refactoring tools

incur a significant amount of the computational cost required to determine the executable form of the program only once, at build time

The main strength of dynamic strategies is that they are much easier to implement, meaning that:

a working dynamic environment can be created at a fraction of the cost of a static one

it is easier to add language features that might be very challenging to check statically

it is easier to handle situations that require self-modifying code


问:
SQL count using multiple join
I have three tables related to each other in the following way:

host (has multiple sessions)

session (has multiple processes)

processes

The table structure is as follows:

host table - id, name

session table - id, host_id, name

process table - id, session_id, name

What I am trying to achieve is the count of the number of sessions and the count of the number of processes on each host. To achieve this I tried the following query, but the output is wrong.

```<code>select host.id,
       count(sessions.id) as "session count",
       count(process.id) as "process count"
from host as host
     left outer join sessions as sessions on host.id = sessions.host_id
     left outer join process as process on sessions.id = process.session_id
group by host.id;
</code>```

Here's the SQLFiddle to the schema.

As per the data in the fiddle, the output should be:

```<code>id | session count | process count
----------------------------------
1  |     2         |   3
2  |     1         |   2
3  |     1         |   2
4  |     2         |   3
</code>```

But what I get is:

```<code>id | session count | process count
----------------------------------
1  |     3         |   3
2  |     2         |   2
3  |     2         |   2
4  |     3         |   3
</code>```

What can be the correct query to get the desired output?

答:
Distinct;</p>

```<code>select host.id,
       count(distinct sessions.id) as "session count",
       count(distinct process.id) as "process count"
from host as host
     left outer join sessions as sessions on host.id = sessions.host_id
     left outer join process as process on sessions.id = process.session_id
group by host.id;
</code>```

Title: SQL count using multiple join

Body:
I have three tables related to each other in the following way:

host (has multiple sessions)

session (has multiple processes)

processes

The table structure is as follows:

host table - id, name

session table - id, host_id, name

process table - id, session_id, name

What I am trying to achieve is the count of the number of sessions and the count of the number of processes on each host. To achieve this I tried the following query, but the output is wrong.

select host.id,
       count(sessions.id) as "session count",
       count(process.id) as "process count"
from host as host
     left outer join sessions as sessions on host.id = sessions.host_id
     left outer join process as process on sessions.id = process.session_id
group by host.id;

Here's the SQLFiddle to the schema.

As per the data in the fiddle, the output should be:

id | session count | process count
----------------------------------
1  |     2         |   3
2  |     1         |   2
3  |     1         |   2
4  |     2         |   3

But what I get is:

id | session count | process count
----------------------------------
1  |     3         |   3
2  |     2         |   2
3  |     2         |   2
4  |     3         |   3

What can be the correct query to get the desired output?

Body:
Distinct;

select host.id,
       count(distinct sessions.id) as "session count",
       count(distinct process.id) as "process count"
from host as host
     left outer join sessions as sessions on host.id = sessions.host_id
     left outer join process as process on sessions.id = process.session_id
group by host.id;


问:
Is it possible to view the console for a URL loaded into a React Native WebView?
I have a simple website that loads a URL into a WebView.

The website I load then loads another external website which in one instance is generating an error. I need to see what JavaScript errors are being generated by this website.

I've tried using the Debugger but this just seems to debug the WebView itself rather than what's inside it.

Is it possible to debug/view the console for the website that is inside the WebView?

答: It seems the only way to do this is the connect the debugger to Safari and then you can see the console in Safari as if you were debugging a normal mobile site.</p>


问:
How to declare a function as a variable in Kotlin
So I am trying to create a listener in Kotlin. I just want to pass a method that will be executed latter in my code. Like this:

```<code>override fun setButtonClickListener(listener: (text: String) -> Unit) {
    this.listener = listener
}
</code>```

But, when I declare my listener, I must declare it like this:

```<code>private var listener : (text: String) -> Unit = null!!
</code>```

Otherwise my AS will complain. But this !! in a null object seams so weird. How should I declare this listener??

Thanks!

答:
there many ways to declare a function as a variable in kotlin.

you can using lateinit properties to initializing the property in later, for example:

```<code>private lateinit var listener : (text: String) -> Unit
</code>```

OR make the listener nullable, but  you must call it with safe-call: listener?.handle(...) in this way:

```<code>private var listener : ((text: String) -> Unit)? = null
</code>```

OR declare it with a empty lambda to avoiding NPException, for example:

```<code>private var listener : (String) -> Unit = {}
</code>```

OR declare a private function, and then you can reference it by function reference expression, for example:

```<code>private var listener = this::handle

private fun handle(text:String) = TODO()
</code>```

Note: when you declare a function variable, the parameter name is optional, for example:

```<code>private var listener : (text:String) -> Unit = TODO()
//                      |--- parameter name is omitted
private var listener : (String) -> Unit = TODO()
</code>```

Body:
So I am trying to create a listener in Kotlin. I just want to pass a method that will be executed latter in my code. Like this:

override fun setButtonClickListener(listener: (text: String) -> Unit) {
    this.listener = listener
}

But, when I declare my listener, I must declare it like this:

private var listener : (text: String) -> Unit = null!!

Otherwise my AS will complain. But this !! in a null object seams so weird. How should I declare this listener??

Thanks!

Body:
there many ways to declare a function as a variable in kotlin.

you can using lateinit properties to initializing the property in later, for example:

private lateinit var listener : (text: String) -> Unit

OR make the listener nullable, but  you must call it with safe-call: listener?.handle(...) in this way:

private var listener : ((text: String) -> Unit)? = null

OR declare it with a empty lambda to avoiding NPException, for example:

private var listener : (String) -> Unit = {}

OR declare a private function, and then you can reference it by function reference expression, for example:

private var listener = this::handle

private fun handle(text:String) = TODO()

Note: when you declare a function variable, the parameter name is optional, for example:

private var listener : (text:String) -> Unit = TODO()
//                      |--- parameter name is omitted
private var listener : (String) -> Unit = TODO()


问:
DWH not a Star-Schema not a Snow flake not a E-R
I m aware aboud litterature/Theorie  for datawarehouse-architecture and how should be design.
The Bill-Imon E-R 3NF or the Kimball Star-Schema/Snow - flake Schema.

The problem come when i currently work in a DWH and it have no either any of these Schema, it is composed for 3 big Fact Tables around each of them are a lot of dimension Tables.(2 of 3 big Tables are conected)

So what kind of Schema its that ?

Thanks in Advance , Enrique

答: This is called a galaxy schema.</p>

Body: This is called a galaxy schema.


问:
jQuery highlighting clicked list item
When I clicked on list item it is highlighting only one. If list item has sub list then the total sub list is also highlighting but only one list should be highlight.

CSS

```<code>.active {
  background: #f00;
}
</code>```

HTML

```<code><ul id="orgCat">
  <li class="list-group-item active">Cras justo odio</li>
  <li class="list-group-item">Dapibus ac facilisis in</li>
  <li class="list-group-item">Morbi leo risus
    <ul>
    <li>abc</li>
    <li>sdf</li>
    <li>oupu
      <ul>
      <li>progf</li>
      <li>ghfhg</li>
      </ul>
    </li>
    </ul>
  </li>
  <li class="list-group-item">Porta ac consectetur ac</li>
  <li class="list-group-item">Vestibulum at eros</li>
  <li class="list-group-item">Cras justo odio</li>
  <li class="list-group-item">Dapibus ac facilisis in</li>
  <li class="list-group-item">Morbi leo risus</li>
  <li class="list-group-item">Porta ac consectetur ac</li>
  <li class="list-group-item">Vestibulum at eros</li>
</ul>
</code>```

JQUERY

```<code>$('#orgCat li').click(function(e) {
    e.preventDefault()

    $that = $(this);

    $that.parent().find('li').removeClass('active');
    $that.addClass('active');
  });
</code>```

Demo

答:
If i understand you correctly, you want something more like this:

```<code>$(function(){
  $(document).on('click', 'li', function(e) {
    var $me = $(e.originalEvent.target);
    e.preventDefault();
    $('li.active').removeClass('active');
    $me.addClass('active');
    $('#out').text($me.text());
  });
});
</code>```

see fiddle

Title: jQuery highlighting clicked list item

Body:
When I clicked on list item it is highlighting only one. If list item has sub list then the total sub list is also highlighting but only one list should be highlight.

CSS

.active {
  background: #f00;
}

HTML

Cras justo odio

Dapibus ac facilisis in

Morbi leo risus

abc

sdf

oupu

progf

ghfhg

Porta ac consectetur ac

Vestibulum at eros

Cras justo odio

Dapibus ac facilisis in

Morbi leo risus

Porta ac consectetur ac

Vestibulum at eros

JQUERY

$('#orgCat li').click(function(e) {
    e.preventDefault()

    $that = $(this);

    $that.parent().find('li').removeClass('active');
    $that.addClass('active');
  });

Demo

Body:
If i understand you correctly, you want something more like this:

$(function(){
  $(document).on('click', 'li', function(e) {
    var $me = $(e.originalEvent.target);
    e.preventDefault();
    $('li.active').removeClass('active');
    $me.addClass('active');
    $('#out').text($me.text());
  });
});

see fiddle


问:
Use jQuery to scroll to the bottom of a div with lots of text
I have a div with a scrollbar on the right when there is a lot of text in it. I tried to use this code to scroll to the bottom of a div when the page loads, but I am not having much luck. How can it be achieved?

Style:

```<code>div.messageScrollArea{
    width: 100%;
    max-height: 300px;
    overflow: auto;
}
</code>```

JavaScript code:

```<code>$(document).ready(function () {
    var objDiv = $('.messageScrollArea');
    if (objDiv.length > 0){
        objDiv[0].scrollTop = objDiv[0].scrollHeight;
    }
});
</code>```

答:
Make a jQuery function more flexible.

```<code>$.fn.scrollDown=function(){
    let el=$(this)
    el.scrollTop(el[0].scrollHeight)
}

$('div').scrollDown()
</code>```

https://jsfiddle.net/Thielicious/82ar7db2/

Body:
I have a div with a scrollbar on the right when there is a lot of text in it. I tried to use this code to scroll to the bottom of a div when the page loads, but I am not having much luck. How can it be achieved?

Style:

div.messageScrollArea{
    width: 100%;
    max-height: 300px;
    overflow: auto;
}

JavaScript code:

$(document).ready(function () {
    var objDiv = $('.messageScrollArea');
    if (objDiv.length > 0){
        objDiv[0].scrollTop = objDiv[0].scrollHeight;
    }
});

Body:
Make a jQuery function more flexible.

$.fn.scrollDown=function(){
    let el=$(this)
    el.scrollTop(el[0].scrollHeight)
}

$('div').scrollDown()

https://jsfiddle.net/Thielicious/82ar7db2/


问:
Trying to Compile 64-bit DLL with mingw-w64
I've been trying to compile a 64-bit version of an Ada dll using mingw-w64 for use in a C++ program.

It appears to be working, in that it compiles without error and will load into 64-bit programs and I can get the address of the interface functions with GetProcAddress.

However, when trying to call these functions, they break in unusual places with access violation errors. Looking into the pointers, it looks like they're all 0x00000000########, meaning, none of them have any bits outside the usual 32-bit addressing set.

Looking into the ads files generated by gnatbind, I also find:

```<code>  type Version_32 is mod 2 ** 32;
   u00001 : constant Version_32 := 16#65712768#;
</code>```

This seems to indicate, to me, that even though it's compiling parts of the dll in 64-bit (enough to fool the compiler and program into believing the dll is 64-bit enough to load it), the underlying implementation is still coming out as 32-bit. I'm guessing that's what's causing the access violation errors, accessing 32-bit memory addresses when the program's expecting 64-bit addressing.

How can I get mingw-w64 to actually compile AND bind a dll in 64-bit properly?

答:
Ensure you call DLL adainit and adafinal. Or else you need to use gnatbind -a key. In GPR it looks like:

```<code>   package Binder is
      for Default_Switches ("Ada") use
        ("-a");         -- call adainit from DllMain
   end Binder;
</code>```

Try using MinGW64 from MSYS2. Some people state that it's best free toolchain for Win64. TDM-GCC doesn't have libgnarl built dynamically or something like this.

Body:
I've been trying to compile a 64-bit version of an Ada dll using mingw-w64 for use in a C++ program.

It appears to be working, in that it compiles without error and will load into 64-bit programs and I can get the address of the interface functions with GetProcAddress.

However, when trying to call these functions, they break in unusual places with access violation errors. Looking into the pointers, it looks like they're all 0x00000000########, meaning, none of them have any bits outside the usual 32-bit addressing set.

Looking into the ads files generated by gnatbind, I also find:

  type Version_32 is mod 2 ** 32;
   u00001 : constant Version_32 := 16#65712768#;

This seems to indicate, to me, that even though it's compiling parts of the dll in 64-bit (enough to fool the compiler and program into believing the dll is 64-bit enough to load it), the underlying implementation is still coming out as 32-bit. I'm guessing that's what's causing the access violation errors, accessing 32-bit memory addresses when the program's expecting 64-bit addressing.

How can I get mingw-w64 to actually compile AND bind a dll in 64-bit properly?

Body:
Ensure you call DLL adainit and adafinal. Or else you need to use gnatbind -a key. In GPR it looks like:

   package Binder is
      for Default_Switches ("Ada") use
        ("-a");         -- call adainit from DllMain
   end Binder;

Try using MinGW64 from MSYS2. Some people state that it's best free toolchain for Win64. TDM-GCC doesn't have libgnarl built dynamically or something like this.


问:
Is a local PHP include() file cached?
After doing some research i'm struggling to find a definitive answer on how and if a PHP include() file is cached.

The closest i've found is here but it doesn't quite make sense to me.

I have several methods that use other methods from different files and I want to avoid placing include()'s just at the top of the file but i'm not sure how this might affect performance.

Any help is appreciated.

答:
PHP is an interpreted language. The default PHP runtime compiles PHP sourcecode to an intermediate representation called PHP bytecode which is then executed. A bytecode cache stores this compiled representation of PHP sourcecode in shared memory. This eliminates the need to load and compile sourcecode on each request which leads to a significant increase in performance (up to 70% more requests per second).

The basic idea, when executing a PHP script is in two steps:

First: the PHP code, written in plain-text, is compiled to opcodes

Then: those opcodes are executed.
When you have one PHP script, as long as it is not modified, the opcodes will always be the same ; so, doing the compilation phase each time that script is to be executed is kind of a waste of CPU-time.

To prevent that redundant-compilation, there are some opcode caching mechanism that you can use.

Once the PHP script has been compiled to opcodes, those will be kept in RAM -- and directly used from memory the next time the script is to be executed ; preventing the compilation from being done again and again.

Read more

https://blog.graphiq.com/500x-faster-caching-than-redis-memcache-apc-in-php-hhvm-dcd26e8447ad#.tsokdw9d4

https://github.com/TerryE/opcache/wiki/The-Zend-Engine-and-opcode-caching#opcode-caching-with-opcache

https://juokaz.com/blog/from-php-to-machine-code

Title: Is a local PHP include() file cached?


问:
ios / CoreML - The input type is MultiArray when keras model is converted to CoreML
I am trying to train a keras model and convert it to coreML model using keras 1.2.2 and TensorFlow backend. This is for a classification task. The input to CoreML is being shown as MultiArray. I need this to be Image <BGR, 32, 32> or something like CVPixelBuffer. I tried adding image_input_names='data' as mentioned here. Also my input shape is (height, width, depth) which I believe is what is required.

Kindly help fix this issue. I used cifar10 dataset and the following code (Reference):

```<code>from keras.datasets import cifar10
from keras.models import Model
from keras.layers import Input, Convolution2D, MaxPooling2D, Dense, Dropout, Flatten
from keras.utils import np_utils
import numpy as np
import coremltools

np.random.seed(1234)

batch_size = 32
num_epochs = 1

kernel_size = 3
pool_size = 2
conv_depth_1 = 32
conv_depth_2 = 64
drop_prob_1 = 0.25
drop_prob_2 = 0.5
hidden_size = 512

(X_train, y_train), (X_test, y_test) = cifar10.load_data()
num_train, height, width, depth = X_train.shape
num_test = X_test.shape[0]
num_classes = 10

X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= np.max(X_train)
X_test /= np.max(X_test)

y_train = np_utils.to_categorical(y_train, num_classes)
y_test = np_utils.to_categorical(y_test, num_classes)

data = Input(shape=(height, width, depth))
conv_1 = Convolution2D(conv_depth_1, (kernel_size, kernel_size), padding='same', activation='relu')(data)
conv_2 = Convolution2D(conv_depth_1, (kernel_size, kernel_size), padding='same', activation='relu')(conv_1)
pool_1 = MaxPooling2D(pool_size=(pool_size, pool_size))(conv_2)
drop_1 = Dropout(drop_prob_1)(pool_1)

conv_3 = Convolution2D(conv_depth_2, (kernel_size, kernel_size), padding='same', activation='relu')(drop_1)
conv_4 = Convolution2D(conv_depth_2, (kernel_size, kernel_size), padding='same', activation='relu')(conv_3)
pool_2 = MaxPooling2D(pool_size=(pool_size, pool_size))(conv_4)
drop_2 = Dropout(drop_prob_1)(pool_2)

flat = Flatten()(drop_2)
hidden = Dense(hidden_size, activation='relu')(flat)
drop_3 = Dropout(drop_prob_2)(hidden)
out = Dense(num_classes, activation='softmax')(drop_3)

model = Model(inputs=data, outputs=out)

model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

model.fit(X_train, y_train,
          batch_size=batch_size, epochs=num_epochs,
          verbose=1, validation_split=0.1)
loss, accuracy = model.evaluate(X_test, y_test, verbose=1)
print ("\nTest Loss: {loss} and Test Accuracy: {acc}\n".format(loss = loss, acc = accuracy))
coreml_model = coremltools.converters.keras.convert(model, input_names='data', image_input_names='data')
coreml_model.save('my_model.mlmodel')
</code>```

答:
I've just checked this with Keras 2 and the input of your model is Image<RGB,32,32>, not MultiArray. Maybe this depends on the Keras version.

If you need it to be BGR, add is_bgr=True to the coremltools.converters.keras.convert() call.

Here is the documentation for this converter.

Body:
I am trying to train a keras model and convert it to coreML model using keras 1.2.2 and TensorFlow backend. This is for a classification task. The input to CoreML is being shown as MultiArray. I need this to be Image <BGR, 32, 32> or something like CVPixelBuffer. I tried adding image_input_names='data' as mentioned here. Also my input shape is (height, width, depth) which I believe is what is required.

Kindly help fix this issue. I used cifar10 dataset and the following code (Reference):

from keras.datasets import cifar10
from keras.models import Model
from keras.layers import Input, Convolution2D, MaxPooling2D, Dense, Dropout, Flatten
from keras.utils import np_utils
import numpy as np
import coremltools

np.random.seed(1234)

batch_size = 32
num_epochs = 1

kernel_size = 3
pool_size = 2
conv_depth_1 = 32
conv_depth_2 = 64
drop_prob_1 = 0.25
drop_prob_2 = 0.5
hidden_size = 512

(X_train, y_train), (X_test, y_test) = cifar10.load_data()
num_train, height, width, depth = X_train.shape
num_test = X_test.shape[0]
num_classes = 10

X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= np.max(X_train)
X_test /= np.max(X_test)

y_train = np_utils.to_categorical(y_train, num_classes)
y_test = np_utils.to_categorical(y_test, num_classes)

data = Input(shape=(height, width, depth))
conv_1 = Convolution2D(conv_depth_1, (kernel_size, kernel_size), padding='same', activation='relu')(data)
conv_2 = Convolution2D(conv_depth_1, (kernel_size, kernel_size), padding='same', activation='relu')(conv_1)
pool_1 = MaxPooling2D(pool_size=(pool_size, pool_size))(conv_2)
drop_1 = Dropout(drop_prob_1)(pool_1)

conv_3 = Convolution2D(conv_depth_2, (kernel_size, kernel_size), padding='same', activation='relu')(drop_1)
conv_4 = Convolution2D(conv_depth_2, (kernel_size, kernel_size), padding='same', activation='relu')(conv_3)
pool_2 = MaxPooling2D(pool_size=(pool_size, pool_size))(conv_4)
drop_2 = Dropout(drop_prob_1)(pool_2)

flat = Flatten()(drop_2)
hidden = Dense(hidden_size, activation='relu')(flat)
drop_3 = Dropout(drop_prob_2)(hidden)
out = Dense(num_classes, activation='softmax')(drop_3)

model = Model(inputs=data, outputs=out)

model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])

model.fit(X_train, y_train,
          batch_size=batch_size, epochs=num_epochs,
          verbose=1, validation_split=0.1)
loss, accuracy = model.evaluate(X_test, y_test, verbose=1)
print ("\nTest Loss: {loss} and Test Accuracy: {acc}\n".format(loss = loss, acc = accuracy))
coreml_model = coremltools.converters.keras.convert(model, input_names='data', image_input_names='data')
coreml_model.save('my_model.mlmodel')


问:
how can i make an interface in php to add data csv file
hey...i need to create a html+php+javascript interface

where i got three text area  and i want::::

that if i'll enter some data into text area and pressing submit button,,then it'll enter that textarea's data into a csv file..

pls some one help....

答:
$fp = fopen('file.csv', 'w');
fputcsv($fp, $_GET['TextArea']);
fclose($fp);

?>


问:
Basic Python looping and appending
Write a program that takes a list and prints a message for each element in the list, based on that element's data type.

Your program input will always be a list. For each item in the list, test its data type. If the item is a string, concatenate it onto a new string. If it is a number, add it to a running sum. At the end of your program print the string, the number and an analysis of what the array contains. If it contains only one type, print that type, otherwise, print 'mixed'.

So the above is what I am trying to accomplish. And I am extremely new to all this so sorry if I don't make sense at times. Right now I am just trying to set up running through my list and appending any str to string list, and any int to my num list. Ive tried tons of ways and read documentation, and tried to search for help but I am either misreading stuff or just searching the wrong stuff. any help would be greatly appreciated.

```<code>stuff = ['magical unicorns',19,'hello',98.98,'world']

string = []
num = []

for i in range(len(stuff)):
    if isinstance(i,str):
        string.append(value,i)
    if isinstance(i,int):
        num.append(i)

print (string)
print (num)
</code>```

答:
Think about python for loops as foreach loops in other languages. So we want to iterate over each item in the stuff list.
We then want to make running totals of the strings and numbers.
Here is a simple loop which accomplishes this :)</p>

```<code>from numbers import Number
stuff = ['magical unicorns',19,'hello',98.98,'world']

running_string = ''
running_total = 0

for item in stuff:
    if isinstance(item, basestring):
        running_string += item
    if isinstance(item, Number):
        running_total += item

print running_total
print running_string
if running_string and running_total:
    print 'mixed'
elif running_string:
    print 'string'
elif running_total:
    print 'int'
else:
    print 'empty'
</code>```

Title: Basic Python looping and appending

Body:
Write a program that takes a list and prints a message for each element in the list, based on that element's data type.

Your program input will always be a list. For each item in the list, test its data type. If the item is a string, concatenate it onto a new string. If it is a number, add it to a running sum. At the end of your program print the string, the number and an analysis of what the array contains. If it contains only one type, print that type, otherwise, print 'mixed'.

So the above is what I am trying to accomplish. And I am extremely new to all this so sorry if I don't make sense at times. Right now I am just trying to set up running through my list and appending any str to string list, and any int to my num list. Ive tried tons of ways and read documentation, and tried to search for help but I am either misreading stuff or just searching the wrong stuff. any help would be greatly appreciated.

stuff = ['magical unicorns',19,'hello',98.98,'world']

string = []
num = []

for i in range(len(stuff)):
    if isinstance(i,str):
        string.append(value,i)
    if isinstance(i,int):
        num.append(i)

print (string)
print (num)

Body:
Think about python for loops as foreach loops in other languages. So we want to iterate over each item in the stuff list.
We then want to make running totals of the strings and numbers.
Here is a simple loop which accomplishes this :)

from numbers import Number
stuff = ['magical unicorns',19,'hello',98.98,'world']

running_string = ''
running_total = 0

for item in stuff:
    if isinstance(item, basestring):
        running_string += item
    if isinstance(item, Number):
        running_total += item

print running_total
print running_string
if running_string and running_total:
    print 'mixed'
elif running_string:
    print 'string'
elif running_total:
    print 'int'
else:
    print 'empty'


问:
How can I ignore accented characters when string matching in SPARQL
I have no idea to how to compare different labels without taking accents into account.

The next query doesn't return the place because "Ibáñez" has accents in Spanish DBpedia, but it has different accents in my data source.

```<code>PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos#>

SELECT DISTINCT ?iri

WHERE {

  ?iri rdfs:label ?label .
  ?label  bif:contains  "'Blasco Ibañez'" .

  ?iri ?location ?city .
  FILTER (?location = <http://dbpedia.org/ontology/location> ||  <http://dbpedia.org/ontology/wikiPageWikiLink>) .
  ?city bif:contains "valencia"

} LIMIT 100
</code>```

Is there a way to not to take account of the accents?

答:
The issue is the current configuration of the Spanish DBpedia endpoint.  (You may find the query I used to check their configuration interesting.)

Their virtuoso.ini must be adjusted to include --

```<code>[I18N]
XAnyNormalization=3
</code>```

-- as described in the documentation of the INI file, and as further discussed in the article about "normalization of UNICODE3 accented chars in free-text index and queries", as cited in comments by @StanislavKralin.

(Note -- as of this writing, there's a typo in the doc; the section about "WideFileNames = 1/2/3/0" should say it's about "XAnyNormalization = 1/2/3/0")

Body:
I have no idea to how to compare different labels without taking accents into account.

The next query doesn't return the place because "Ibáñez" has accents in Spanish DBpedia, but it has different accents in my data source.

PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX geo: <http://www.w3.org/2003/01/geo/wgs84_pos#>

SELECT DISTINCT ?iri

WHERE {

  ?iri rdfs:label ?label .
  ?label  bif:contains  "'Blasco Ibañez'" .

  ?iri ?location ?city .
  FILTER (?location = <http://dbpedia.org/ontology/location> ||  <http://dbpedia.org/ontology/wikiPageWikiLink>) .
  ?city bif:contains "valencia"

} LIMIT 100

Is there a way to not to take account of the accents?

Body:
The issue is the current configuration of the Spanish DBpedia endpoint.  (You may find the query I used to check their configuration interesting.)

Their virtuoso.ini must be adjusted to include --

[I18N]
XAnyNormalization=3

-- as described in the documentation of the INI file, and as further discussed in the article about "normalization of UNICODE3 accented chars in free-text index and queries", as cited in comments by @StanislavKralin.

(Note -- as of this writing, there's a typo in the doc; the section about "WideFileNames = 1/2/3/0" should say it's about "XAnyNormalization = 1/2/3/0")