text:
Q: Leverage and Influence Is it possible that an outlier is neither influential nor does it have high leverage?
Or can it happen that an observation with high leverage is not an outlier and is neither influential?

A: How do you define outlier? It generally means a data point which do not conform with the majority of the data points.  That can of course be interpreted in many ways, and just as in society, where nonconformists can be very valuable (a literary reference), and sometimes are right when the majority goes wrong, outliers in data doesn't need to be "bad". But they might need some special thought or treatment. In chemical industry outliers sometimes lead to new patents!
But your question is about leverage, which is mostly used with linear models. We could say that a high-leverage point is an outlier in $X$-space.

Or can it happen that an observation with high leverage is not an
  outlier and is neither influential?

Leverage can be calculated from only the design matrix $X$, so before any $Y$ is observed! while residuals (which would be used with any definition of outlier) obviously need $Y$. That means that, just from the mathematics, any value of the residual can go with any value of leverage. With really extreme leverage values, that design point will have so much influence in the estimation that a large residual would be rare (that is what influence means, the regression line gravitate towards the influential point.)  So a low-leverage point could have a large residual (and be considered an outlier), or a low residual while being in error (sometimes called an inlier, see Difference between Outlier and Inlier.) And a high-leverage point could have a small residual, but still being in error. So not an outlier, if that definition is based on a large residual.
You also ask if a point can have high leverage and not being influential? That question is difficult to understand, since leverage is taken to mean having high influence. So you should clarify.


text:
Q: Как избавиться от поторяющегося кода и подвисаний при работе с базой? добрые люди, проконсультируете пожалуйста джуна, написал приложение на winforms, приложение состоит из 12 форм, все формы одинаково работают , с помощью Datagridview  заносят данные в БД, автоматом отображаются в датагриде. теперь хочу узнать мнение опытных людей, насколько плохо написал код (во первых приложение медленно работает, во вторых создавал одинаковых методов на всех формах, т.к почти во всех формах одинаковые функции выполняются). пожалуйста помогите советами как можно улучшить код и насколько ужасно написал код. ниже выложил внешний вид формы и код

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Drawing.Imaging;

namespace LOCAL_PROJECT
{
public partial class mary : Form
{
    public mary()
    {
        InitializeComponent();
    }

    //CONNECTION STRING
    DataTable dt = new DataTable("mary");
    MySqlCommand command;
    MySqlConnection con = new MySqlConnection("server = 192.168.1.200; UserId = user; Password = user; database = equipment");
    MySqlDataAdapter adapter = new MySqlDataAdapter();
    int id;

    public void spisok()
    {
        con.Open();
        MySqlDataAdapter adapter = new MySqlDataAdapter(" SELECT* FROM `mary` ", con);
        DataSet dset = new DataSet();
        adapter.Fill(dset);
        dataGridView1.DataSource = dset.Tables[0];
        con.Close();
    }

    private void mary_Load(object sender, EventArgs e)
    {
        spisok();
        dataGridView1.EnableHeadersVisualStyles = false;
        dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Lime;
        dataGridView1.ColumnHeadersDefaultCellStyle.Font = new Font("Times new Roman", 13, FontStyle.Bold);
        dataGridView1.ColumnHeadersHeight = 35;
        dataGridView1.DefaultCellStyle.Font = new Font("Times new Roman", 12);
        dataGridView1.Columns[0].Width = 55;
        dataGridView1.Columns[1].Width = 210;
        dataGridView1.Columns[2].Width = 160;
        dataGridView1.Columns[3].Width = 130;
        dataGridView1.Columns[4].Width = 90;
        dataGridView1.Columns[5].Width = 78;
        dataGridView1.Columns[6].Width = 90;
        dataGridView1.Columns[7].Width = 78;
        dataGridView1.Columns[10].Width = 88;
        dataGridView1.Columns[0].HeaderCell.Value = "id";
        dataGridView1.Columns[1].HeaderCell.Value = "наименование товара";
        dataGridView1.Columns[2].HeaderCell.Value = "тип товара";
        dataGridView1.Columns[3].HeaderCell.Value = "префикс товара";
        dataGridView1.Columns[4].HeaderCell.Value = "установленная емкость оборудования";
        dataGridView1.Columns[5].HeaderCell.Value = "неиспользованная емкость оборудования";
        dataGridView1.Columns[6].HeaderCell.Value = "общий трафик интернета";
        dataGridView1.Columns[7].HeaderCell.Value = "неиспользованный трафик интернета";
        dataGridView1.Columns[8].HeaderCell.Value = "количество абонентских плат";
        dataGridView1.Columns[9].HeaderCell.Value = "количество интернет плат";
        dataGridView1.Columns[10].HeaderCell.Value = "время установки";
        dataGridView1.Columns[11].HeaderCell.Value = "Геолокация C";
        dataGridView1.Columns[12].HeaderCell.Value = "Геолокация B";
        dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

        //подсказка для Геолокации
        textBox10.Text = "C";
        textBox10.ForeColor = Color.Gray;
        textBox10.TextAlign = HorizontalAlignment.Center;
        Font myfont = new Font("Times new Roman", 14);
        textBox10.Font = myfont;

        //подсказка для Геолокации
        textBox11.Text = "B";
        textBox11.ForeColor = Color.Gray;
        textBox11.TextAlign = HorizontalAlignment.Center;
        Font myfont1 = new Font("Times new Roman", 14);
        textBox11.Font = myfont1;
    }

    private void button4_Click(object sender, EventArgs e)
    {
        Application.Exit();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        this.Hide();
        menu menuu = new menu();
        menuu.Show();
    }

    // Метод автонумерация ID
    private DataTable AutoNumberedTable(DataTable SourceTable)

    {
        DataTable ResultTable = new DataTable();
        DataColumn AutoNumberColumn = new DataColumn();
        AutoNumberColumn.ColumnName = "id";
        AutoNumberColumn.DataType = typeof(int);
        AutoNumberColumn.AutoIncrement = true;
        AutoNumberColumn.AutoIncrementSeed = 1;
        AutoNumberColumn.AutoIncrementStep = 1;
        ResultTable.Columns.Add(AutoNumberColumn);
        ResultTable.Merge(SourceTable);
        return ResultTable;
    }

    private void button5_Click(object sender, EventArgs e)
    {
        con.Open();

        string sql = "insert into mary(id, name of product, product type, product prefix, installed capacity of equipment, unused equipment capacity, total internet traffic, unused internet traffic, number of subscription fees, number of internet boards, year, geolocationC, geolocationB) Values (null, '" + textBox2.Text + "', '" + textBox1.Text + "',  '" + textBox3.Text + "', '" + textBox4.Text + "', '" + textBox5.Text + "','" + textBox6.Text + "', '" + textBox9.Text + "', '" + textBox8.Text + "', '" + textBox7.Text + "', '" + textBox12.Text + "', '" + textBox10.Text + "', '" + textBox11.Text + "' )";
        this.dataGridView1.DataSource = AutoNumberedTable(dt);
        MySqlCommand cmd = new MySqlCommand(sql, con);
        cmd.ExecuteNonQuery();
        con.Close();
        MessageBox.Show("added successfully");
        textBox2.Text = string.Empty;
        textBox1.Text = string.Empty;
        textBox3.Text = string.Empty;
        textBox4.Text = string.Empty;
        textBox5.Text = string.Empty;
        textBox6.Text = string.Empty;
        textBox7.Text = string.Empty;
        textBox8.Text = string.Empty;
        textBox9.Text = string.Empty;
        textBox10.Text = string.Empty;
        textBox11.Text = string.Empty;
        textBox12.Text = string.Empty;
        spisok();
    }

    // Метод делете
    private void delete(int id)
    {
        string sql = "DELETE FROM mary WHERE id=" + id + "";
        command = new MySqlCommand(sql, con);

        //OPEN CON, EXECUTE DELETE, CLOSE CON

        try
        {
            con.Open();
            adapter = new MySqlDataAdapter(command);
            adapter.DeleteCommand = con.CreateCommand();
            adapter.DeleteCommand.CommandText = sql;

            // PROMT FOR CONFIRMATION

            if (command.ExecuteNonQuery() > 0)
            {
                MessageBox.Show("Deleted");
            }

            con.Close();

            spisok();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    //Delete button
    private void button3_Click(object sender, EventArgs e)
    {
        string selected = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
        int tb = Convert.ToInt32(selected);
        delete(tb);
    }

    //UPDATE PROSESS
    private void update(int id)
    {
        string sql = "UPDATE mary SET name of product='" + textBox2.Text + "', product type='" + textBox1.Text + "', product prefix='" + textBox3.Text + "', installed capacity of equipment='" + textBox4.Text + "', unused equipment capacity='" + textBox5.Text + "', total internet traffic='" + textBox6.Text + "', unused internet traffic='" + textBox9.Text + "', number of subscription fees='" + textBox8.Text + "', number of internet boards='" + textBox7.Text + "', year='" + textBox12.Text + "', geolocationC='" + textBox10.Text + "', geolocationC='" + textBox11.Text + "'";
        command = new MySqlCommand(sql, con);

        //OPEN CON, EXECUTE DELETE, CLOSE CON

        try
        {
            con.Open();
            adapter = new MySqlDataAdapter(command);
            adapter.UpdateCommand = con.CreateCommand();
            adapter.UpdateCommand.CommandText = sql;
            // PROMT FOR CONFIRMATION

            if (adapter.UpdateCommand.ExecuteNonQuery() > 0)
            {
                MessageBox.Show("Successfully UPDATED!");
            }

            con.Close();

            spisok();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
            con.Close();
        }
    }

    private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
    {
        id = Convert.ToInt32(dataGridView1.CurrentRow.Cells[0].Value.ToString());

        textBox2.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString();
        textBox1.Text = dataGridView1.CurrentRow.Cells[2].Value.ToString();
        textBox3.Text = dataGridView1.CurrentRow.Cells[3].Value.ToString();
        textBox4.Text = dataGridView1.CurrentRow.Cells[4].Value.ToString();
        textBox5.Text = dataGridView1.CurrentRow.Cells[5].Value.ToString();
        textBox6.Text = dataGridView1.CurrentRow.Cells[6].Value.ToString();
        textBox9.Text = dataGridView1.CurrentRow.Cells[7].Value.ToString();
        textBox8.Text = dataGridView1.CurrentRow.Cells[8].Value.ToString();
        textBox7.Text = dataGridView1.CurrentRow.Cells[9].Value.ToString();
        textBox12.Text = dataGridView1.CurrentRow.Cells[10].Value.ToString();
        textBox10.Text = dataGridView1.CurrentRow.Cells[11].Value.ToString();
        textBox11.Text = dataGridView1.CurrentRow.Cells[12].Value.ToString();
    }

    private void textBox13_TextChanged(object sender, EventArgs e)
    {
        con.Open();
        string query = "Select * From mary where name of product like '%" + textBox13.Text + "%' OR product type like '%" + textBox13.Text + "%' OR product prefix like '%" + textBox13.Text + "%' OR installed capacity of equipment like '%" + textBox13.Text + "%' OR unused equipment capacity like '%" + textBox13.Text + "%' OR total internet traffic like '%" + textBox13.Text + "%' OR unused internet traffic like '%" + textBox13.Text + "%' OR number of subscription fees like '%" + textBox13.Text + "%' OR number of internet boards like '%" + textBox13.Text + "%' OR year like '%" + textBox13.Text + "%' OR geolocationC like '%" + textBox13.Text + "%' OR geolocationC like '%" + textBox13.Text + "%' OR geolocationB like '%" + textBox13.Text + "%'";
        DataSet dset = new DataSet();
        MySqlDataAdapter adapter = new MySqlDataAdapter(query, con);
        MySqlCommandBuilder builder = new MySqlCommandBuilder(adapter);
        adapter.Fill(dset);
        dataGridView1.DataSource = dset.Tables[0];
        con.Close();
    }

    private void button6_Click(object sender, EventArgs e)
    {
        try
        {
            con.Open();
            command = new MySqlCommand("update mary SET name of product='" + textBox2.Text + "', product type='" + textBox1.Text + "', product prefix='" + textBox3.Text + "', installed capacity of equipment='" + textBox4.Text + "', unused equipment capacity='" + textBox5.Text + "', total internet traffic='" + textBox6.Text + "', unused internet traffic='" + textBox9.Text + "', number of subscription fees='" + textBox8.Text + "', number of internet boards='" + textBox7.Text + "', year='" + textBox12.Text + "', geolocationC='" + textBox10.Text + "', geolocationC='" + textBox11.Text + "' WHERE tb='" + tertip + "'", con);
            command.ExecuteNonQuery();
            MessageBox.Show("updated!");
            con.Close();
            spisok();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}

}
вторая форма так же выглядит только меняется таблица базы данных
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Drawing.Imaging;

namespace LOCAL_PROJECT
{
public partial class city : Form
{
    public city()
    {
        InitializeComponent();
    }

    //CONNECTION STRING
    DataTable dt = new DataTable("city");
    MySqlCommand command;
    MySqlConnection con = new MySqlConnection("server = 192.168.1.200; UserId = user; Password = user; database = equipment");
    MySqlDataAdapter adapter = new MySqlDataAdapter();
    int id;

    public void spisok()
    {
        con.Open();
        MySqlDataAdapter adapter = new MySqlDataAdapter(" SELECT* FROM `city` ", con);
        DataSet dset = new DataSet();
        adapter.Fill(dset);
        dataGridView1.DataSource = dset.Tables[0];
        con.Close();
    }

    private void city_Load(object sender, EventArgs e)
    {
        spisok();
        dataGridView1.EnableHeadersVisualStyles = false;
        dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Lime;
        dataGridView1.ColumnHeadersDefaultCellStyle.Font = new Font("Times new Roman", 13, FontStyle.Bold);
        dataGridView1.ColumnHeadersHeight = 35;
        dataGridView1.DefaultCellStyle.Font = new Font("Times new Roman", 12);
        dataGridView1.Columns[0].Width = 55;
        dataGridView1.Columns[1].Width = 210;
        dataGridView1.Columns[2].Width = 160;
        dataGridView1.Columns[3].Width = 130;
        dataGridView1.Columns[4].Width = 90;
        dataGridView1.Columns[5].Width = 78;
        dataGridView1.Columns[6].Width = 90;
        dataGridView1.Columns[7].Width = 78;
        dataGridView1.Columns[10].Width = 88;
        dataGridView1.Columns[0].HeaderCell.Value = "id";
        dataGridView1.Columns[1].HeaderCell.Value = "наименование товара";
        dataGridView1.Columns[2].HeaderCell.Value = "тип товара";
        dataGridView1.Columns[3].HeaderCell.Value = "префикс товара";
        dataGridView1.Columns[4].HeaderCell.Value = "установленная емкость оборудования";
        dataGridView1.Columns[5].HeaderCell.Value = "неиспользованная емкость оборудования";
        dataGridView1.Columns[6].HeaderCell.Value = "общий трафик интернета";
        dataGridView1.Columns[7].HeaderCell.Value = "неиспользованный трафик интернета";
        dataGridView1.Columns[8].HeaderCell.Value = "количество абонентских плат";
        dataGridView1.Columns[9].HeaderCell.Value = "количество интернет плат";
        dataGridView1.Columns[10].HeaderCell.Value = "время установки";
        dataGridView1.Columns[11].HeaderCell.Value = "Геолокация C";
        dataGridView1.Columns[12].HeaderCell.Value = "Геолокация B";
        dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

        //подсказка для Геолокации
        textBox10.Text = "C";
        textBox10.ForeColor = Color.Gray;
        textBox10.TextAlign = HorizontalAlignment.Center;
        Font myfont = new Font("Times new Roman", 14);
        textBox10.Font = myfont;

        //подсказка для Геолокации
        textBox11.Text = "B";
        textBox11.ForeColor = Color.Gray;
        textBox11.TextAlign = HorizontalAlignment.Center;
        Font myfont1 = new Font("Times new Roman", 14);
        textBox11.Font = myfont1;
    }

    private void button4_Click(object sender, EventArgs e)
    {
        Application.Exit();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        this.Hide();
        menu menuu = new menu();
        menuu.Show();
    }

    // Метод автонумерация ID
    private DataTable AutoNumberedTable(DataTable SourceTable)

    {
        DataTable ResultTable = new DataTable();
        DataColumn AutoNumberColumn = new DataColumn();
        AutoNumberColumn.ColumnName = "id";
        AutoNumberColumn.DataType = typeof(int);
        AutoNumberColumn.AutoIncrement = true;
        AutoNumberColumn.AutoIncrementSeed = 1;
        AutoNumberColumn.AutoIncrementStep = 1;
        ResultTable.Columns.Add(AutoNumberColumn);
        ResultTable.Merge(SourceTable);
        return ResultTable;
    }

    private void button5_Click(object sender, EventArgs e)
    {
        con.Open();

        string sql = "insert into city(id, name of product, product type, product prefix, installed capacity of equipment, unused equipment capacity, total internet traffic, unused internet traffic, number of subscription fees, number of internet boards, year, geolocationC, geolocationB) Values (null, '" + textBox2.Text + "', '" + textBox1.Text + "',  '" + textBox3.Text + "', '" + textBox4.Text + "', '" + textBox5.Text + "','" + textBox6.Text + "', '" + textBox9.Text + "', '" + textBox8.Text + "', '" + textBox7.Text + "', '" + textBox12.Text + "', '" + textBox10.Text + "', '" + textBox11.Text + "' )";
        this.dataGridView1.DataSource = AutoNumberedTable(dt);
        MySqlCommand cmd = new MySqlCommand(sql, con);
        cmd.ExecuteNonQuery();
        con.Close();
        MessageBox.Show("added successfully");
        textBox2.Text = string.Empty;
        textBox1.Text = string.Empty;
        textBox3.Text = string.Empty;
        textBox4.Text = string.Empty;
        textBox5.Text = string.Empty;
        textBox6.Text = string.Empty;
        textBox7.Text = string.Empty;
        textBox8.Text = string.Empty;
        textBox9.Text = string.Empty;
        textBox10.Text = string.Empty;
        textBox11.Text = string.Empty;
        textBox12.Text = string.Empty;
        spisok();
    }

    // Метод делете
    private void delete(int id)
    {
        string sql = "DELETE FROM city WHERE id=" + id + "";
        command = new MySqlCommand(sql, con);

        //OPEN CON, EXECUTE DELETE, CLOSE CON

        try
        {
            con.Open();
            adapter = new MySqlDataAdapter(command);
            adapter.DeleteCommand = con.CreateCommand();
            adapter.DeleteCommand.CommandText = sql;

            // PROMT FOR CONFIRMATION

            if (command.ExecuteNonQuery() > 0)
            {
                MessageBox.Show("Deleted");
            }

            con.Close();

            spisok();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    //Delete button
    private void button3_Click(object sender, EventArgs e)
    {
        string selected = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
        int tb = Convert.ToInt32(selected);
        delete(tb);
    }

    //UPDATE PROSESS
    private void update(int id)
    {
        string sql = "UPDATE city SET name of product='" + textBox2.Text + "', product type='" + textBox1.Text + "', product prefix='" + textBox3.Text + "', installed capacity of equipment='" + textBox4.Text + "', unused equipment capacity='" + textBox5.Text + "', total internet traffic='" + textBox6.Text + "', unused internet traffic='" + textBox9.Text + "', number of subscription fees='" + textBox8.Text + "', number of internet boards='" + textBox7.Text + "', year='" + textBox12.Text + "', geolocationC='" + textBox10.Text + "', geolocationC='" + textBox11.Text + "'";
        command = new MySqlCommand(sql, con);

        //OPEN CON, EXECUTE DELETE, CLOSE CON

        try
        {
            con.Open();
            adapter = new MySqlDataAdapter(command);
            adapter.UpdateCommand = con.CreateCommand();
            adapter.UpdateCommand.CommandText = sql;
            // PROMT FOR CONFIRMATION

            if (adapter.UpdateCommand.ExecuteNonQuery() > 0)
            {
                MessageBox.Show("Successfully UPDATED!");
            }

            con.Close();

            spisok();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
            con.Close();
        }
    }

    private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
    {
        id = Convert.ToInt32(dataGridView1.CurrentRow.Cells[0].Value.ToString());

        textBox2.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString();
        textBox1.Text = dataGridView1.CurrentRow.Cells[2].Value.ToString();
        textBox3.Text = dataGridView1.CurrentRow.Cells[3].Value.ToString();
        textBox4.Text = dataGridView1.CurrentRow.Cells[4].Value.ToString();
        textBox5.Text = dataGridView1.CurrentRow.Cells[5].Value.ToString();
        textBox6.Text = dataGridView1.CurrentRow.Cells[6].Value.ToString();
        textBox9.Text = dataGridView1.CurrentRow.Cells[7].Value.ToString();
        textBox8.Text = dataGridView1.CurrentRow.Cells[8].Value.ToString();
        textBox7.Text = dataGridView1.CurrentRow.Cells[9].Value.ToString();
        textBox12.Text = dataGridView1.CurrentRow.Cells[10].Value.ToString();
        textBox10.Text = dataGridView1.CurrentRow.Cells[11].Value.ToString();
        textBox11.Text = dataGridView1.CurrentRow.Cells[12].Value.ToString();
    }

    private void textBox13_TextChanged(object sender, EventArgs e)
    {
        con.Open();
        string query = "Select * From city where name of product like '%" + textBox13.Text + "%' OR product type like '%" + textBox13.Text + "%' OR product prefix like '%" + textBox13.Text + "%' OR installed capacity of equipment like '%" + textBox13.Text + "%' OR unused equipment capacity like '%" + textBox13.Text + "%' OR total internet traffic like '%" + textBox13.Text + "%' OR unused internet traffic like '%" + textBox13.Text + "%' OR number of subscription fees like '%" + textBox13.Text + "%' OR number of internet boards like '%" + textBox13.Text + "%' OR year like '%" + textBox13.Text + "%' OR geolocationC like '%" + textBox13.Text + "%' OR geolocationC like '%" + textBox13.Text + "%' OR geolocationB like '%" + textBox13.Text + "%'";
        DataSet dset = new DataSet();
        MySqlDataAdapter adapter = new MySqlDataAdapter(query, con);
        MySqlCommandBuilder builder = new MySqlCommandBuilder(adapter);
        adapter.Fill(dset);
        dataGridView1.DataSource = dset.Tables[0];
        con.Close();
    }

    private void button6_Click(object sender, EventArgs e)
    {
        try
        {
            con.Open();
            command = new MySqlCommand("update city SET name of product='" + textBox2.Text + "', product type='" + textBox1.Text + "', product prefix='" + textBox3.Text + "', installed capacity of equipment='" + textBox4.Text + "', unused equipment capacity='" + textBox5.Text + "', total internet traffic='" + textBox6.Text + "', unused internet traffic='" + textBox9.Text + "', number of subscription fees='" + textBox8.Text + "', number of internet boards='" + textBox7.Text + "', year='" + textBox12.Text + "', geolocationC='" + textBox10.Text + "', geolocationC='" + textBox11.Text + "' WHERE tb='" + tertip + "'", con);
            command.ExecuteNonQuery();
            MessageBox.Show("updated!");
            con.Close();
            spisok();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
}

}

A: Здесь много работы, чтобы привести этот код в порядок. Начните с выноса повторяющегося кода в отдельный класс.
Например у вас есть 2 формы
public partial class Form1 : Form
{
    const string connectionString = "server = 192.168.1.200; UserId = user; Password = user; database = equipment";

    public Form1()
    {
        InitializeComponent();
    }

    private Method()
    {
        //...
    }

    private void button1_click(object sender, EventArgs e)
    {
        Method();
    }
}

public partial class Form2 : Form
{
    const string connectionString = "server = 192.168.1.200; UserId = user; Password = user; database = equipment";

    public Form2()
    {
        InitializeComponent();
    }

    private Method()
    {
        //...
    }

    private void button1_click(object sender, EventArgs e)
    {
        Method();
    }
}

И есть главная форма, например такая
public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();
    }

    private void button1_click(object sender, EventArgs e)
    {
        var form = new Form1();
        form.Show();
    }

    private void button2_click(object sender, EventArgs e)
    {
        var form = new Form2();
        form.Show();
    }
}

Тогда вы можете вынести одинаковые методы в один класс
public class DatabaseConnector
{
    const string connectionString = "server = 192.168.1.200; UserId = user; Password = user; database = equipment";

    public Method()
    {
        //...
    }
}

В главной форме создать его экземпляр и передать его формам
public partial class MainForm : Form
{
    private readonly DatabaseConnector dbConnector = new DatabaseConnector();

    public MainForm()
    {
        InitializeComponent();
    }

    private void button1_click(object sender, EventArgs e)
    {
        var form = new Form1(dbConnector);
        form.Show();
    }

    private void button2_click(object sender, EventArgs e)
    {
        var form = new Form2(dbConnector);
        form.Show();
    }
}

В формах его принять и использовать
public partial class Form1 : Form
{
    private readonly DatabaseConnector dbConnector;

    public Form1(DatabaseConnector dbConnector)
    {
        this.dbConnector = dbConnector;
        InitializeComponent();
    }

    private void button1_click(object sender, EventArgs e)
    {
        dbConnector.Method();
    }
}

public partial class Form2 : Form
{
    private readonly DatabaseConnector dbConnector;

    public Form2(DatabaseConnector dbConnector)
    {
        this.dbConnector = dbConnector;
        InitializeComponent();
    }

    private void button1_click(object sender, EventArgs e)
    {
        dbConnector.Method();
    }
}

Таким образом код повторяться не будет.

На вопрос "почему тормозит" - потому что вы используете один и тот же поток выполнения кода для работы с базой и интерфейса. Пока приложение работает с базой, оно не может работать с интерфейсом, обновлять его, и подвисает.
Еще вы постоянно открываете и закрываете подключение к базе. Попробуйте держать одно единственное подключение открытым и закрывать его например только когда приложение закрывается. Можно для этого подписаться на событие Form.Closing у главного окна.
Для исправления ситуации нужно использовать асинхронные методы работы с базой, либо выносить работу с базой в другой поток. То есть использовать многопоточность. Но начните именно с приведения кода в порядок, потому что сейчас если дорабатывать код, придется делать это в 12 местах одновременно, легко ошибиться при внесении правок.

redpajama_set_name: RedPajamaStackExchange


text:
Q: General notions of "basis" in algebra/model theory Free groups, free abelian groups, and vector spaces all have a notion of 'basis': a subset $B$ of the structure such that everything in the structure can be written uniquely as a finite combination of elements of $B$.

*

*What is the most general (model theoretic) structure for which it makes sense to think about a basis?

*Do all of these structures have theorems along the lines of "if $S$ is a structure with a basis and $T$ is a substructure, then $T$ must also have a basis"? This certainly is true for free (abelian) groups and vector spaces.

A: The notion of basis can be generalized in multiple ways. The way it seems like you're thinking of - a basis for a structure $A$ is a subset $S\subseteq A$ such that every element of $A$ can be expressed uniquely (in some sense) as a term using parameters from $S$ - is more a notion of universal algebra than of model theory: Look into free algebras.
In this reading of the question, the answer to (2) is no. For example, consider the free monoid on one generator. This is isomorphic to $\langle \mathbb{N}, 0, +\rangle$, and $\{1\}$ is a basis. Now consider the submonoid with domain $\mathbb{N}\setminus \{1\}$. This submonoid is generated by $2$ and $3$, and it's not hard to see that any generating set must contain $2$ and $3$. But no generating set is a basis, since $6$ can be written as $2+2+2$ or as $3+3$.
Another way to generalize is the abstract notion of a matroid. Matroids also get involved in model theory, though model theorists tend to call their matroids "pregeometries". There are various natural closure operators that you can associate to models of a complete first-order theory $T$, the most prominent being algebraic closure, acl. Under certain conditions, these closure operators will satisfy the matroid axioms, giving rise to notions of basis and dimension for models of $T$. For example, in a strongly minimal theory, acl gives a pregeometry - in the theory of $k$-vector spaces, acl is Span and the dimension is linear dimension, while in the theory of algebraically closed fields, $\text{acl}(X)$ is the algebraic closure of the field generated by $X$ and the dimension is transcendence degree.
In the model-theoretic situation, sometimes the existence of a nice pregeometry is guaranteed by elementary properties of the theory (for example, the property of being strongly minimal), and then an elementary substructure of a structure with a basis will still have a basis (since it shares the pregeometry).


text:
Q: Is the last button in a form automatically the submit button in react? I'm noticing some strange behavior with forms in react. I'm using a button with a handleSubmit function for the onClick attribute, but it is not technically a submit button for the form. Nevertheless, parts of the handleSubmit function are not working even when they are exactly the same lines of code from other functions. I believe the form is submitting on click of the button, but I have not designated this button as a submit button for the form. It's just a button.
<button
    class="button is-dark"
    onClick={(e) => handleSubmit(e, listItem.album.albumid, document.getElementById('scoreNum'+ listItem.index).value, listItem.index)}
    disabled={setDisabledInputs()}
>
    Submit
</button>

This function works fine:
const onClear = (item) => {
    document.getElementById('scoreNum' + item).removeAttribute("value")
    document.getElementById('scoreRange' + item).value = document.getElementById('scoreRange' + item).defaultValue
}

When I use one of the same lines of code in the handleSubmit function, it doesn't work, and the page refreshes as if the form has been submitted unless I use event.preventDefault():
const handleSubmit = (event, albumid, rating, item) => {
    document.getElementById('scoreNum' + item).removeAttribute("value") //why doesn't this work
}

I would expect the handleSubmit function to just do the code I wrote and nothing else.

A: Yes, if you have one button in a form element, this automatically becomes the submit button, unless it is given a different type attribute.
Also, i wouldn't name the eventHandler on the button as onSubmit, as you don't submit the button, you submit the form. This may cause confusion as you are not handling a submit event, you are handling a click event.
What you should declare in the callback function is e.PreventDefault() calling the PreventDefault method stops the page from trying to complete the submit event and thus stops the page refreshing.


text:
Q: Azure AD Graph API: Unable to use StartsWith under Any function I would like to ask on how to apply StartsWith in Any function when querying in Azure AD Graph Explorer.
Based on the documentation, below is the sample when querying multi-valued properties.
https://graph.windows.net/contoso.com/users?$filter=signInNames/any(x:x/value eq 'joe@example.com')&api-version=1.6

However, the sample uses "eq" which means it is doing an Exact match.
Is it possible if we can perform StartsWith in this scenario?
I already check this tutorial but I got the error as shown below.
Getting all SignNames with "test"
https://graph.windows.net/myorganization/users?$filter=signInNames/any(x:x.startswith(x,'test'))

Error:
"value": "An unknown function with name 'x.startswith' was found. This may also be a key lookup on a navigation property, which is not allowed."

A: GET https://graph.windows.net/myorganization/users?$filter=signInNames/any(c:startswith(c/value, 'test'))

Unfortunately, it will show an error: value only supports equals-match. PrefixMatch is not supported.

please use below query for signinnames in Azure Ad graph
https://graph.windows.net/myorganization/users?$filter=signInNames/any(c:c/value eq '***')


text:
Q: check list with AsyncTask I have problem when i get the list from server i want to check it, if it's any object there or not.
if there are object , appears in my layout text : there is no object after few seconds it's disappears
 and show my list.
i want just if there is object will appear in my layout directly.
               private class RetrieveTask extends AsyncTask> {
    @Override
    protected List<branch> doInBackground(String... params) {

        manager = new SessionManager(getActivity().getApplicationContext());
        manager.checkLogin();
        HashMap<String, String> user = manager.getUserID();
        String uid = user.get(SessionManager.KEY_uid);
       // Intent intent= getActivity().getIntent(); // gets the previously created intent
        //String type18 = intent.getStringExtra("key28");
        String strUrl =

        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            URL url = new URL(strUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            InputStream stream = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(stream));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            String finalJson = buffer.toString();

            JSONObject parentObject = new JSONObject(finalJson);
            JSONArray parentArray = parentObject.getJSONArray("markers");

            ////////////////////////////////////////
            List<branch> bList = new ArrayList<>();

            Gson gson = new Gson();
            for (int i = 0; i < parentArray.length(); i++) {
                JSONObject finalObject = parentArray.getJSONObject(i);

                /////////market object
                market mr = new market(Integer.valueOf(finalObject.getString("id")), finalObject.getString("mName")
                        , finalObject.getString("pic"));

                /////////location object
                location lo = new location(Float.valueOf(finalObject.getString("lat")), Float.valueOf(finalObject.getString("lng"))
                        , finalObject.getString("area"), finalObject.getString("city"));

                /////////(branch object) inside it (market object)
                branch it = new branch(Integer.valueOf(finalObject.getString("bid")), Integer.valueOf(finalObject.getString("phone"))
                        , finalObject.getString("ser"), Integer.valueOf(finalObject.getString("dis")), Integer.valueOf(finalObject.getString("brNo"))
                        , Float.valueOf(finalObject.getString("rating")), mr, lo,true);

                /*//////////add marker
                LatLng latlng = new LatLng(Double.valueOf(finalObject.getString("lat")), Double.valueOf(finalObject.getString("lng")));
                addMarker(latlng, Integer.valueOf(finalObject.getString("bid")));*/

                // adding the branch object in the list
                bList.add(it);
            }
            return bList;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;

    }

here the postExcute
    @Override
    protected void onPostExecute(final List<branch> result) {
        super.onPostExecute(result);

        if (result != null) {

            final itemAdapter adapter = new itemAdapter(getActivity().getApplicationContext(), R.layout.row_favmarkets, result);
            lv.setAdapter(adapter);

        }
    }

}

this is my layout xml
  <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="4dp"
android:paddingLeft="4dp"
android:paddingRight="4dp"
android:paddingTop="4dp"
tools:context="com.gmplatform.gmp.favouriteitem">
<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView28"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="40dp"
        android:layout_marginTop="250dp"
        android:text="There is no Markets in your Favourite List.."
        android:textSize="24sp"
        android:visibility="gone" />
</LinearLayout>

<ListView
    android:id="@+id/l20"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:horizontalSpacing="3dp"
    android:numColumns="3"
    android:verticalSpacing="0dp" />
<Button
    android:text="Button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/button6"
    android:layout_marginLeft="400dp" />

A: Suggested changes which will at first show nothing when the request is executed. Once completed, if the list is empty it'll show "There is no Markets in your Favourite List..", otherwise the list will show.
Part Layout XML:
<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/linearLayout28">

    <TextView
        android:id="@+id/textView28"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="40dp"
        android:layout_marginTop="250dp"
        android:text="There is no Markets in your Favourite List.."
        android:textSize="24sp"
        android:visibility="gone" />
</LinearLayout>

Initialize linearLayout28:
LinearLayout linearLayout28 = findViewById(R.id.linearLayout28);

And changes for the AsyncTask:
private class RetrieveTask extends AsyncTask<Void, Void, List<branch>> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        lv.setVisibility(View.GONE);
        linearLayout28.setVisibility(View.GONE);
    }

    @Override
    protected List<branch> doInBackground(String... params) {
        //Keep as your code
        ...
    }

    @Override
    protected void onPostExecute(final List<branch> result) {
        super.onPostExecute(result);

        if (result != null && result.size() != 0) {
            final itemAdapter adapter = new itemAdapter(
                getActivity().getApplicationContext(),
                R.layout.row_favmarkets, result);
            lv.setAdapter(adapter);
            lv.setVisibility(View.VISIBLE);
            linearLayout28.setVisibility(View.GONE);
        } else {
            lv.setVisibility(View.GONE);
            linearLayout28.setVisibility(View.VISIBLE);
        }
    }
}

A: You are basically on the solution but you should not update the user interface from your AsyncTask. Create an interface and implement it on the Activity. Let the activity to update the data on the UI when data is ready or show a message error.
As an example, define the interface in your AsyncTask like:
private TaskCallback listener = null;

public interface TaskCallback {
    void OnTaskCompleted ();
}

public void setListener (TaskCallback listener) {
    this.listener = listener;
}

When your task was completed:
@Override
public void onPostExecute (Void v) {
    if (listener != null) {
        listener.OnTaskCompleted ();
    }
}

You can add parameters to your callback base on your needs.
At your Activity level:
public class YourActivity extends Activity implements YourTask.TaskCallback {

//  When you execute your task add the reference to the listener
YourTask task = new YourTask (YourActivity.this);
        task.setListener (YourActivity.this);
        task.execute ();

@Override
public void OnTaskCompleted () {
    //  Update your screen or show an error message
}

}


text:
Q: Is there any way to get logic app name from workflow_Id? I have a logic app subscribed to event grid topic. I just want to indentify the logic app name from endpoint URL . Is there any way to identify ?
I tried to get it from logs analytics workspace using below query , but I am not getting any record in result. Any help appreciated. Thanks.
AzureDiagnostics
| where workflowId_s == "xxxxxxxxxxxxxxxxxxxxxxxx"

A: I think you can query like this, with Azure CLI you could use an Azure Resource Graph query.
az graph query -q "where type == 'microsoft.logic/workflows' and properties.accessEndpoint endswith 'xxxxxxxxxxxxxxxxxxxxxxxx'"


text:
Q: React componentDidMount "Parsing error: Missing semicolon" "Parsing error: Missing semicolon".

SyntaxError: client\src\App.js: Missing semicolon (15:21)

This error is showing on componentDidMount() line.
and the full code is given below.
import React, { Component } from "react";
import AppNavBar from "./components/AppNavbar";
import ShoppingList from "./components/ShoppingList";
import ItemModal from "./components/ItemModal";
import { Container } from "reactstrap";

import { Provider } from "react-redux";
import store from "./store";
import { loadUser } from "./actions/authActions";

import "bootstrap/dist/css/bootstrap.min.css";
import "./App.css";

function App() {
  componentDidMount() {
    store.dispatch(loadUser());
  }
  return (
    <Provider store={store}>
      <div className="App">
        <AppNavBar />
        <Container>
          <ItemModal />
          <ShoppingList />
        </Container>
      </div>
    </Provider>
  );
}

export default App;

A: Import useEffect:
import { useEffect } from "react";

... and replace:
componentDidMount() {
  store.dispatch(loadUser());
}

with:
useEffect(() => {
  store.dispatch(loadUser());
}, []);


text:
Q: Can Fuse ESB receive message from TIBCO rendezvous? I wanted to know the different methods Fuse ESB can read a message from the TIBCO rendezvous channel.
Regards,
Arun Lakhotia

A: Fuse ESB supports messaging using JMS (its a Java Messaging Specification). TIBCO supports JMS as well, and therefore you can integrate Fuse ESB with Tibco (using JMS).


text:
Q: From operational data store to warehouse I have 3 ODS, so in order to create DWH, do I need a DWH for each ODSs, or the DWH select the tables from any of the ODSs?

A: The design of a DWH is based on your reporting requirements. The number and locations of any data sources is entirely irrelevant.
Also, please can you explain what you mean by the phrase "the DWH select Dim table for any of the ODSs"? It doesn't make much sense to me


text:
Q: How to quit a pygtk application after last window is closed/destroyed Is there a way I can tell gtk to automatically call gtk.main_quit() when the last open window of the application is closed/destroyed?
If there is no direct feature offering this functionality, I could think of the following:
In the window's destroy method: get a list of open windows in the process, if its empty quit. Is there a way to get such a list?
The obvious solution would be to keep manually track of all open windows, but I would want to avoid this if possible.

A: the destroy signal of the main window must be connected to gtk main_quit :
window.connect("destroy", gtk.main_quit)

A: Use the method gtk.main_level() to get the current nesting level of the main loop. The nesting level is increased by calling the gtk.main() function and reduced by calling the gtk.main_quit() function


text:
Q: Generic passing of interface and class implementing interface I'm trying to create a method that through generics tries to pass an interface and a class.
It should look something like this, but this does not build:
public static void Register<TInterface, TClass>()
  where TClass     : TInterface
  where TInterface : interface // <- doesn't compile
{
   ...
}

Is there any way to get this to work. The idea is to build a wrapper around an ioc container.

A: You cannot do it the way you want.
The closest you will be able to achieve is by limiting TClass to inherit/implement the TInterface, but TInterface can also be a class (and TClass can also be an interface. Perhaps its worth noting that class does not mean class but any reference type. It can also be an interface)
public static void Register<TInterface, TClass>()
  where TClass     : class, TInterface
  where TInterface : class
{

}


text:
Q: How to get gzippo with newer version of node when also needing express. I am following this tutorial for deploying an yeoman app with heroku. I am running into a problem with npm install gzippo express --save because gzippo is asking for a lower version of node, but express is asking for a higher one. There is no overlap. Error:
gzippo@0.2.0: wanted: {"node":">= 0.5 < 0.9"} (current: {"node":"0.10.35","npm":"1.4.28"}) whereas I get the same thing but >10.0 for express. Is there a way to resolve this issue?

A: From https://github.com/tomgco/gzippo
Deprecated Please use https://github.com/expressjs/compression instead


text:
Q: Proxy server can not send response back to client I am creating a proxy server using Java while my client and server both are  written in NodeJS. As client can send multiple request, so I am creating thread for each client request to proxy server. Now when I get response back from server (an integer value), I want to send the same data back to the client from my proxy server. But my proxy server is unable to do so.
Client expects a response within 100ms. So I have set connect and read time out  property. If I do not receive response within this time then, I want to respond to the client with integer 0.
SocketServer.java
private int portNo;
private ServerSocket serverSocket = null;

public SocketServer(int portNo) {
    this.portNo = portNo;
    try {
        serverSocket = new ServerSocket(this.portNo);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public void runServer() {
    while(true) {
        try {
            Socket clientSocket = serverSocket.accept();
            new Thread(new Task(clientSocket)).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public static void main(String args[]) {
    SocketServer socketServer = new SocketServer(3000);
    socketServer.runServer();
}

Task.java
public class Task implements Runnable {

    Socket socket = null;

    public Task(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            String dataFromClient = in.readLine(); // this is the url from client
            String partOfLink = dataFromClient.substring(5, 9);

            URL url = new URL("http://localhost:3001/" + partOfLink);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setDoOutput(true);
            conn.setConnectTimeout(80);
            conn.setReadTimeout(80);

            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                out.write(line);
            }

        } catch (IOException e) {
            //e.printStackTrace();
            try {
                BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                out.write(0);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
}

A: The specific issue that you're hitting right now is probably that the client receives the zero and says "this isn't a complete HTTP reply and I'm expecting a complete HTTP reply, so more data must be coming", so it waits for more data
Since the client only speaks HTTP and you are not sending HTTP to the client in the timeout case, why would you expect it to work?
You are actually not doing this even in the success case! You have attached an HTTP decoder to the outbound connection and are relaying the decoded output to the client. But the client expects raw HTTP.
There are lots of ways this can bite you. Say the proxied response headers indicate chunked encoding. You either need to modify those headers or send the data to the client with chunked encoding too because your code to receive the proxy response decodes chunked encoding. Where is the code for this?
You need to correctly handle HTTP connection persistence. You need to detect whether the client supports it and whether the proxied reply is compatible with it to know how to handle the client connection after you proxy the reply. Should you close it? Should you try to receive another reply on the same connection? It depends on several factors -- where is the code to make this decision correctly?
There are lots of other issues with your code too. You should look at code for existing HTTP proxies that work and understand how they work. There are a large number of issues you must get right for a real HTTP proxy to work and you haven't addressed them.
There are some possible hacks that might get this approach to seem to work enough that you may be able to pass it off as done. But if this is an important application that has to be reliable, this is the wrong approach. HTTP proxies are big, complicated things. This code is not one.
Look at finding the simplest code for a working real HTTP proxy that you can use. Read the HTTP specification and look closely at the requirements for proxies. This is a minefield and you really should start with an HTTP proxy that's known to work and modify it as you need.


text:
Q: Расположение в шапке в линию

.header {
  background: rgba(18, 93, 175, 0.0);
  position: relative;
  width: 100%;
  height: 315px;
  padding: 10px 0;
  margin-bottom: 5px;
}

.logo {
  font-family: "A_La_Russ", sans-serif;
  src: url('../A_La_Russ.ttf');
  background: rgba(128, 74, 19, 0.8);
  height: 275px;
  margin-left: 60px;
  margin-right: 60px;
  width: 1223px;
}

.logotip {
  width: 335px;
  height: 275px;
  background: url('../images/logo.png')no-repeat;
  background-size: 100% 100%;
  float: left;
}

.logo p {
  color: #ffb015;
  margin: 0 auto;
  font-size: 80px;
  text-shadow: #ea690b 1px 1px 0, #ea690b -1px -1px 0, #ea690b -1px 1px 0, #ea690b 1px -1px 0;
}

.up p {
  padding-left: 351px;
}

.centr p {
  padding-left: 390px;
}

.down p {
  padding-left: 485px;
}

.grup {
  width: 300px;
  height: 275px;
}

Храм

Воскресения

Словущего

нужно div class"grup" расположить в одну линию с остальными.

A: Пытаюсь Ванговать ...

.header {
  background: rgba(18, 93, 175, 0.0);
  position: relative;
  width: 100%;
  height: 315px;
  padding: 10px 0;
  margin-bottom: 5px;
  display:flex;
  align-items:center;
  justify-content:space-between;
}

.logo {
  font-family: "A_La_Russ", sans-serif;
  src: url('../A_La_Russ.ttf');
  background: rgba(128, 74, 19, 0.8);
}

.logotip {
  background: url('../images/logo.png')no-repeat;
  background-size: 100% 100%;
}

.logo p {
  color: #ffb015;
  margin: 0 auto;
  font-size: 80px;
  text-shadow: #ea690b 1px 1px 0, #ea690b -1px -1px 0, #ea690b -1px 1px 0, #ea690b 1px -1px 0;
}

img{
  display:block;
  width:200px;
}

Храм

Воскресения

Словущего

group


text:
Q: Automate Chi-square across columns I would like to use Chi-square for testing set of data. How to do it, using loop for or sapply.
This is a set of sample data:
n<-40
set.seed(1)
data <- data.frame(v1.1=sample(c('0','1'),n,replace=T),v1.2=sample(c('0','1'),n,replace=T),v1.3=sample(c('0','1'),n,replace=T),v1.4=sample(c('0','1'),n,replace=T),v1.5=sample(c('0','1'),n,replace=T),m1=sample(c('1','2'),n,replace=T))

I would like to test all variables named v1.x with variable m1. That's all.
I want to avoid such a situtation:
chisq.test(table(data$v1.1,data$m1))
chisq.test(table(data$v1.2,data$m1))
chisq.test(table(data$v1.3,data$m1))
chisq.test(table(data$v1.4,data$m1))
chisq.test(table(data$v1.5,data$m1))

I found this topic, but for me and for now it's too difficult.

A: You can just use lapply to loop through the variables.
myTests <- lapply(data[-length(data)], function(x) chisq.test(table(x, data$m1)))

This returns a named list, with the changin variable as the name of each list item.
names(myTests)
[1] "v1.1" "v1.2" "v1.3" "v1.4" "v1.5"

Then access each with myTests[[1]] or myTests[["v1.1"]]. These return
    Pearson's Chi-squared test with Yates' continuity correction

data:  table(x, data$m1)
X-squared = 0, df = 1, p-value = 1

Then, to pull out components from the individual tests, use names(myTests[[1]] and str(myTests[[1]]) to inspect the contents. myTests[[1]]$p.value, for example, will pull out the p.value from the first test and unlist(sapply(myTests, "[", "p.value")) will return a named vector with p-values from all of the tests.


text:
Q: If $F_X(z)>F_Y(z)$ for all $z$, then $P[X0$. If $F_X(z)>F_Y(z)$ for all $z$, then $P[X<Y]>0$.
$$P[X\leq{}z] > P[Y\leq{}z]\Rightarrow{} P[X<z] > P[Y<z] \rightarrow{} (1)$$
By (1)
$$P[X<z] > P[Y<z]$$
$$P[X-Y<z] > P[Y-Y<z]$$
$$P[X-Y<{}0] > P[0<0]$$
$$P[X-Y<0] > 0$$
$$P[X<Y] > 0$$
I have two question
Is correct say that $P[0<0]=0$??? and is correct (1)??
Thanks for your help :D

A: I think it might be of some value for you to look up the concept of stochastic dominance. http://en.wikipedia.org/wiki/Stochastic_dominance
Try and picture the two Cumulative Distribution Functions simultaneously. To say that one CDF stochastically dominates another is to say that
In terms of the cumulative distribution functions of RVs, Y dominating X means that $F_Y(z) \le F_X(z) \forall z,$ with strict inequality at some $z$. This might seem backward at first, but think about what the CDF evaluated at some $z$ is saying. Specifically:
$F_Y(z)=P(Y<z)$
If that probability is smaller than
$F_X(z)=P(X<z)$
then at some point we must have $P(X<Y)>0$
Try to draw two CDFs on paper with one of them "always at least as high" as the other one. The $z$ here represents where you can draw a vertical line through both CDFs simultaneously. One of those cumulative curves will have more area to the left of your line at $z$ than the other one.
Think about what that means for the underlying distributions of $X$ and $Y$.
Hope that helps.


text:
Q: How to substitute two columns with a condition in pandas? I have a Pandas DataFrame that has products, actions, quantity and price. If the action is "SELL", I need to consider the price 0 for the product and also invert the quantity.
What I've tried:
import pandas as pd

def my_function(df):
    kwargs = {
        "quantity": lambda x: -x["quantity"] if "SELL" in str(x["action"]) else x["quantity"],
        "price (usd)": lambda x: 0 if "SELL" in str(x["action"]) else x["price (usd)"],
    }
    return df.assign(**kwargs)

input_df = pd.DataFrame({"product": ["APPLE", "APPLE", "BANANA"],
                         "action": ["  SELL  ", "  BUY  ", "  SELL  "],
                         "quantity": [1, 2, 3],
                         "price (usd)": [3, 5, 8],
                         })

result_df = my_function(input_df)

expected_df = pd.DataFrame({"product": ["APPLE", "APPLE", "BANANA"],
                            "action": ["  SELL  ", "  BUY  ", "  SELL  "],
                            "quantity": [-1, 2, -3],
                            "price (usd)": [0, 5, 0],
                            })

Somehow the conditions in my lambda expressions always return True and I also think that might be a simpler way to do it. Any ideas?

A: We can do
s=input_df.action.str.contains('SELL')
input_df.quantity*=s.map({True:-1,False:1})
input_df["price (usd)"]*=~s
input_df
  product    action  quantity  price (usd)
0   APPLE    SELL          -1            0
1   APPLE     BUY           2            5
2  BANANA    SELL          -3            0

In function
def my(x):
...     s=x.action.str.contains('SELL')
...     x.quantity*=s.map({True:-1,False:1})
...     x["price (usd)"]*=~s
...     return (x)

out=my(input_df)
out
  product    action  quantity  price (usd)
0   APPLE    SELL          -1            0
1   APPLE     BUY           2            5
2  BANANA    SELL          -3            0

A: The below code fixes it. I got the desired output.
def my_function(df):
    kwargs = {
        "quantity": df.apply(lambda x: -x["quantity"] if "SELL" in str(x["action"]) else x["quantity"], axis = 1),
        "price (usd)": df.apply(lambda x: 0 if "SELL" in str(x["action"]) else x["price (usd)"], axis = 1),
    }
    return df.assign(**kwargs)


text:
Q: Initialize static const data members of a class into a class Suppose we have this at a header file:
class A
{
private:
     static const double x;
public:
    A(double given_x);
};

class B
{
private:
    static const double x;
    class A;
public:
     B(double x_given);
};

And we need to initialize the static const data member of class A during initialization.
I thought that passing the variable x_given with initializer list from the constructor of B class to A class would be ok, but I'm apparently wrong.
How can this be done?
Also, both classes might need to have the same datamember.
Edit #1:
I need to declare a const variable so as to ensure that it is not changed anywhere in the class member functions.
But this value is given at construction time.

A: A static member has static storage duration, so it doesn't wait until an object is created before it is initialized. When you have a const static member of integral type, you can initialise it right there and then in the class definition. However, since yours is of type double, you need to define it in a single translation unit (such as in your A class's implementation file):
const double A::x = 48151623.42;


text:
Q: Razor Pages textarea input just grows and grows when other input validations fail validation I'm using asp.net core and razor pages. I have a simple form page with several textboxes and then 1 textarea. If my model object variable that is linked to the textarea passes validation , but say 1 of the other textboxes fails validation then after the Page returns the value in my textarea grows based on the previous value. so for example if the textarea contained "abc,xyz" then what happens after the Page returns from a failed validation from another regular textbox on the page, then the textarea grows to "abc,xyzabc,xyz"
all i have is a simple textarea
<textarea class="form-control" asp-for="MyObject.EmailsList" rows="3" placeholder="Multiple addresses need to be seperated by a semi-colon ;"></textarea>

I debugged and validated that MyObject.EmailsList only contains "abc,xyz" every time the page returns due to some other textbox validation failing. so i'm scratching my head as to why this textarea is not clearing itself and loading in the value properly??

A: When you have an input box validation error, you want to double the given value on your textarea, you can refer to this demo:
Model:
[Required]
        [BindProperty]
        public string name { get; set; }
        [BindProperty]
        public myObject MyObject { get; set; } = new myObject { EmailsList="xyz"};
        public  class myObject
        {
            public  string  EmailsList { get; set; }
        }

View:
<form id="myform" method="post">

        <input asp-for="name" class="form-control" />

    <textarea class="form-control" asp-for="MyObject.EmailsList" rows="3" placeholder="Multiple addresses need to be seperated by a semi-colon ;"></textarea>
</form>
<button onclick="Test()">click me!</button>

@section Scripts{

}

Request:


text:
Q: MediaRecorder record audio in a loop I'm developing a sound recognition system. I'm using a tensorflow model developed on python to convert MFCC values to labels. I'm using the MediaRecorder class to record the audio, and I'm doing it in a loop so I can be constantly getting microphone audio and then getting the label from the model. Here is the recording loop:
temp = 0;
    while (true) {
        audioPath = getApplicationContext().getFilesDir().getAbsolutePath();
        audioPath += "/Recording" + temp + ".3gp";

        audioFile = new File(audioPath);
        mediaRecorder = new MediaRecorder();
        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        mediaRecorder.setOutputFile(audioPath);
        try {
            mediaRecorder.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mediaRecorder.start();
        sleep(2000);
        if (!isRunning) {
            mediaRecorder.stop();
            return;
        }
        try {
            int amplitude = mediaRecorder.getMaxAmplitude();
            Log.d("volume", Integer.toString(amplitude));
            //finished = false;
            avgVolumeTask task = new avgVolumeTask();
            task.execute(amplitude);
        } catch (Exception e) {
            Log.d("Exception in startMediaRecorder()", e.toString());
        }
        mediaRecorder.stop();
        mediaRecorder.release();

        soundRecognition task2 = new soundRecognition();
        task2.execute();
        audioFile.delete();
        temp++;
    }

This is the soundRecognition method:
private class soundRecognition extends AsyncTask<Integer, Integer, Long> {
    @Override
    protected Long doInBackground(Integer... level) {
        float[] mfccValues = null;
        Interpreter tflite = null;
        float[][] labelProbArray = null;
        try {
            mfccValues = computeMFCC();
            labelList = loadLabelList();
            labelProbArray = new float[1][labelList.size()];
            tflite = new Interpreter(loadModel());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (UnsupportedAudioFileException e) {
            e.printStackTrace();
        }
        tflite.run(mfccValues, labelProbArray);

        for (int i = 0; i < labelProbArray[0].length; i++) {
            float value = labelProbArray[0][i];
            //if (i == 1f){
                //Log.d("Output at " + Integer.toString(i) + ": ", Float.toString(value));
                //doAlert(i);
            //}
        }

        return null;
    }
}

The computeMFCC method is this:
public float[] computeMFCC() throws IOException, UnsupportedAudioFileException {

    FileInputStream in2 = new FileInputStream(audioPath);
    int i;
    // InputStream to byte array
    byte[] buf = IOUtils.toByteArray(in2);
    in2.close();
    i = Integer.MAX_VALUE;

    // byte array to short array
    short[] shortArr = new short[buf.length / 2];
    ByteBuffer.wrap(buf).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().get(shortArr);

    int count = 0;
    while (count <= shortArr.length) {                    // Still have data to process.
        for (int n = 0; n < nSubframePerBuf; n++) {            // Process audio signal in ArrayList and shift by one subframe each time
            int k = 0;
            for (i = (n * frameShift); i < (n + 1) * frameShift; i++) {
                subx[k] = shortArr[i];
                k++;
            }
            subframeList.add(subx);                            // Add the current subframe to the subframe list. Later, a number of
        }
        count++;
    }
    // Need at least nSubframePerMfccFrame to get one analysis frame
    x = extractOneFrameFromList(nSubframePerMfccFrame);

    MFCC mfcc = new MFCC(samplePerFrm, 16000, numMfcc);
    double[] mfccVals = mfcc.doMFCC(x);
    float[] floatArray = new float[mfccVals.length];
    for (i = 0 ; i < mfccVals.length; i++)
    {
        floatArray[i] = (float) mfccVals[i];
    }
    return floatArray;
}

And the doMFCC method is from a downloaded java file here:
https://github.com/enmwmak/ScreamDetector/blob/master/src/edu/polyu/mfcc/MFCC.java
The issue I'm having is that after a few iterations, I run into the problem that the file doesnt get created, and then get a null error passing the results from the input stream to the tensorflow model.
Possible Issues
One reason could be where the file is stored. I've been trying to send the file to local storage because I was worried that all the devices wouldnt have external storage.
Another reason could be that i'm not calling the sound recognition in the right spot. I waited will after the mediaRecorder is stopped to make sure that the file is written with the mic audio, but when I review the contents of the fileInputStream, it appears to not be working, and in each loop the file is always the same.
Any help would be much appreciated.

A: It may be tricky to  have a sleep(2000) inside while loop.
It may be better to check millis and break until 2000 ms has lapsed.


text:
Q: SlidingTabLayout and ViewPager: how to load the current fragment and not the adjacent one at the same time? I am trying to implement a sliding tab layout that and each fragment should only load when the tab is selected instead i get the adjacent fragment loading, I have tried setOffScreenPageLimit(1) as my code shows but still the adjacent fragment gets loaded any assistance please ???
private SlidingTabLayout tabLayout;
private ViewPager viewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    viewPager = (ViewPager) findViewById(R.id.viewpager);
    viewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
    viewPager.setOffscreenPageLimit(1);
    tabLayout = (SlidingTabLayout) findViewById(R.id.tabs);
    if (tabLayout != null) {
        tabLayout.setViewPager(viewPager);
        tabLayout.setDistributeEvenly(true);
        tabLayout.setSelectedIndicatorColors(R.color.md_amber_600);
    }

A: I can see you have used setOffScreenPageLimit as 1. It means you are loading only 1 extra screen at a time using viewPager, when actually you want to load nothing. It is not possible to set 0 value for setOffScreenPageLimit this method, actually you can set it but it will not work.
So, it is not possible to achieve this using view pager. If you still want to perform such a functionality, you can use FrameLayout and switch between the fragments based on tab selection.
Below is the tab selection code sample:
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            switchToTab(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {
        }
    });


text:
Q: destroy $_SESSION after clicking 'Cancel' button I would like to destroy $_SESSION['userList'] after cliking 'Cancel' button. However, the $_SESSION['userList'] is destroied when page load.
Below is my code:
Cancel

Really appreciate for any help.

A: You cannot execute PHP (server-side) in your javascript (client-side). You need to issue an HTTP request to invoke PHP. You can do that using AJAX.

A: JAVASCRIPT
$.ajax({
    type: "POST",
    url: "phppage.php",
    data: "action=unsetsession",
    success: function(msg){
        alert(msg);
        if(msg == "success"){
            //cleared session
        }else{
            //failed
        }
    },
    error: function(msg){
        alert('Error: cannot load page.');
    }
});

PHP
if($_POST['action'] == "unsetsession"){
    unset($_SESSION['userList']);
    echo "success";
}

A: You can not execute php code in the client side like you try in your example. If you want to to destroy session withou reload then you must use ajax request.

A: You better use jquery for this
Cancel

And create a new cancel.php which will be like this -
<?php
unset($_SESSION['userList']);
?>

A: You can't call PHP from JS like this. You'll need to do a call back to the server.

A: Use submit button for Cancel (You can use CSS to make it look the away you want)
//HTML
<form method="post" >
<input type="button" value="Cancel" name="cancel" id="cancel" />
</form>

//PHP
if(isset($_POST['cancel'))
{
  unset($_SESSION['userList']);
}


text:
Q: Terminating app due to uncaught exception 'NSUnknownKeyException'- initWithNibName
Possible Duplicate:
this class is not key value coding-compliant for the key

CODE
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
   return self;
}

OUTPUT
2012-11-20 15:23:55.035 ReaderDeployment[5152:11f03] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<Signature 0x7aa9de0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key drawSign.'
*** First throw call stack:
(0x1b94022 0x155dcd6 0x1b93ee1 0x3b2022 0x323f6b 0x323edb 0x33ed50 0xa4f878 0xa4f8b3 0x1b95dea 0x1aff7f1 0x88326e 0x7291fc 0x729779 0x72999b 0x7329bc 0x72d818 0x949565 0x730857 0x7309bc 0x61bb 0x1b95e99 0x66514e 0x6650e6 0x70bade 0x70bfa7 0x70b266 0x68a3c0 0x68a5e6 0x670dc4 0x664634 0x1a7eef5 0x1b68195 0x1accff2 0x1acb8da 0x1acad84 0x1acac9b 0x1a7d7d8 0x1a7d88a 0x662626 0x2bed 0x2b65)
terminate called throwing an exception

I am unable to understand the exception and the reason for the exception.Hence I am unable to eradicate the issue. Please help in understanding the exception and  solution.

A: Open the xib file in the interface builder. On the rightmost view open connections panel ( disk with an arrow) there will probably be an exclamation mark on the connection called "drawSign". Either remove or reconnect it

A: check the class name with xib , It is caused by the your ReaderDeployment class or xib are not available in the project so just check it and give the right name..
for more details see this may you can get idea from this..
this-class-is-not-key-value-coding-compliant-for-the-key

A: I agree with paras joshi. Just check the class names again. Changing to the correct class names should resolve the problem. Or try reassigning the classes.


text:
Q: Actionscript 2.0 gotoAndPlay without buttons I'm having a weird problem with Flash working in AS2 where a gotoAndPlay script is not working so well for me...
I have a scene with a movie clip.
Inside my movie clip I have a stop on the first frame, and at frame 2 and 100 there are two different animations.
I'll begin with saying that I managed to go around the goto problem with a play action, so through the main scene at a specific keyframe I gave my movie clip this action:
onClipEvent (enterFrame) {
    play();
}

So the movie clip started to play the animation on its 2nd frame and everything was cool.
But what if I wanted to play the one starting at 100? so I did this:
onClipEvent (enterFrame) {
    gotoAndPlay(100);
}

And obviously, for some reason, the movie clip did not go to 100 and play.
I do not want to use any button commands to make it work! I want the movie clip to start playing when told to from my root scene, at a certain frame within it.
Any suggestions?
Thanks, Guy

A: onClipEvent(enterFrame) will create a listener that will be called in every frame after you set it up like that (even after you called stop(), your "play()" code will be called 24 or something times per second!). You don't want that. If you only want to execute "gotoAndPlay(100)" once, just write it there. No reason for lines 1 and 3.


text:
Q: Transform feature space to make points linearly separable? I am trying to figure out an appropriate transformation of the x1 and x2 features such that one can make this linearly separable while keeping the dimensions of the feature space below 3 so that we can visualize it. I have tried various transformations such as ReLU, tanh, squaring, etc, but to no success. Any guidance?
features


text:
Q: Android get view position inside horizontal scroll view I want to get the position of Image View on Image Click listener which is added inside horizontal Scroll View dynamically using for loop. And that position want to set the View pager current item in another Activity.
I'm trying this method:
int numpos = imageView.getId();
Log.e("numpos "," = "+ numpos);

Every view position is getting -1.
Here is my code:
   private void prepareTextViewsForHistory(){
      HorizontalScrollView parent=(HorizontalScrollView)findViewById(R.id.horizontal_scroll_view_id_01);
      LinearLayout layout=new LinearLayout(this);
      layout.setOrientation(LinearLayout.HORIZONTAL);
      parent.addView(layout);
      for (int i=DEFAULT_HISTORY_MAX - 1; i >= 0; i--)
 {
        final ImageView imageView=new ImageView (this);
         imageView.setTag(i);
         imageView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v)
                        {
                            Log.e("imageView ", " Click ");
                            int numpos = imageView.getId();
                            Log.e("numpos "," = "+ numpos);

                            String item_ActivityId =  all_Post.getStrActivityId();

                            Toast.makeText(getBaseContext(), String.valueOf(v.getId()), Toast.LENGTH_SHORT).show();
                            Log.e(" Image ID = "," = "+String.valueOf(v.getId()));
                            Intent intent = new Intent(getContext(),SimpleImageActivity.class);
                            //intent.putExtras(extras);
                            intent.putExtra("activity_id",item_ActivityId);
                            startActivity(intent);
                        }
                    });
        layout.addView(textView);
      }
    }

A: you can do this by setting a Tag while creating a view
in your loop where you have created your view just add this line :
 yourView.setTag("your incremental variable");
 yourView.setOnClickListener(this);

and in onclick(View v) you can get that position by
v.getTag().toString()

A: You are using imageView.setTag(i); for setting tag, use v.getTag().toString() inside onClick(View v ) method.


text:
Q: Help with Integrals (and conditional expectations) of the Beta distribution: Integrate[e^(az) z^a (1-z)^b, {z, 0, 1}] I have a Beta distribution, and am interested in calculating expectations and conditional expectations.  The domain on the distribution is $z \in [0,1]$ Ignoring constants of proportionality, the expectation of an exponential function is:
$Assumptions = z >= 0 && z <= 1 && a > 0 && b > 0 && c > 0 && d > 0 && d < 1;

Print["*******Different parameters, {a,b}"];
Integrate[Exp[c z]  z^(a - 1) (1 - z)^(b - 1), {z, 0, 1}]

Print["********Symmetric parameter, a"];
Integrate[Exp[c z]  z^(a - 1) (1 - z)^(b - 1) /. {b -> a}, {z, 0, 1}]

The output from this is:
Gamma[a] Gamma[b] Hypergeometric1F1Regularized[a, a + b, c]
(-c)^(1/2 - a) E^(c/2) Sqrt[\[Pi]]  BesselI[-(1/2) + a, -(c/2)] Gamma[a]

These are solid.  The problem I am having is when calculating conditional expectations, which is effectively integration over a subset of the domain.  Again ignoring constants of proportionality,
Print["********Truncated Integral on [d, 1], symmetric for simplicity"];
Integrate[Exp[c z]  z^(a - 1) (1 - z)^(b - 1) /. {b -> a}, {z, d, 1}]

This is unable to solve it.  Any idea on this? Are there any tricks in mathematica, in math that I am missing?


text:
Q: How to send ping packets using jabber-net library I am developing a xmpp client application. I need to send ping iq packets to the xmpp server to make sure the server is still alive. How can i send it thru jabber-net library ?
thanks

A: Read FAQ_Packets and XEP-0199.  Set NS to urn:xmpp:ping.  Something like:
namespace your.protocol
{
  public class PingQuery : Element
  {
    public const string PING_NS  = "urn:xmpp:ping";

    // used when creating elements to send
    public PingQuery(XmlDocument doc) : base("ping", PING_NS, doc)
    {}

    // used to create elements for inbound protocol
    public PingQuery(string prefix, XmlQualifiedName qname, XmlDocument doc)
        : base(prefix, qname, doc)
    {}
  }

  public class Factory : jabber.protocol.IPacketTypes
  {
    private static QnameType[] s_qnt = new QnameType[]
    {
      new QnameType("ping", PingQuery.PING_NS, typeof(your.protocol.PingQuery))
    };
    QnameType[] IPacketTypes.Types { get { return s_qnt; } }
  }
}

Then use something like:
private void jabberClient_OnStreamInit(object sender, ElementStream stream)
{
  stream.AddFactory(new your.protocol.Factory());
}

to hook in your factory.  Then use IQTracker as usual to send the request and get notified of the response.


text:
Q: NameError when doing a basic input I have a super basic question, but I'm just starting to learn python. My script:
print('What is your name?')
person = input("Enter name: ")
print("Hello ", person)

is returning an error: NameError: name 'Bob' is not defined.
I have basically just copied and pasted what was from the tutorial at this point, but it still doesn't work unless I put the name in quotation marks. What am I doing wrong?

A: Your code should work perfectly fine in Python 3. However, in Py2 it will throw a NameError as there are differences between input() and raw_input(). Essentially, input() in Python 2 is the same as eval(raw_input(""Enter name: ")), meaning that it will attempt to run the inputed code as Python.
In Python 3, raw_input() is no more, and input() operates the way you are expecting it to here: Print a line, accept input, and assign it in string format to a variable.

A: You simply are not using Python 3. In Python 2, input() works differently; see this excerpt from the docs.

Equivalent to eval(raw_input(prompt)).

So, when you type Bob without quotation marks, you are basically saying eval(Bob). With quotes it is eval("Bob"). raw_input() does not exist in Python 3, so it will not be defined if you are running with Python 3.
Make sure that you are running your file with Python 3:

*

*Type which python and which python3 to make sure you have both.

*Run python and python3 and see which versions you are running when the python shell opens.

*You can check the version of Python which is running your code by doing import sys; print(sys.version).

*Run your code via python3 yourfile.py.

*As J.F. Sebastian notes, you should add #!/usr/bin/env python3 to the very first line of your file. Chances are, you either wrote #! /usr/bin/env python which on OS X is 2.7.x (I think it's 2.7.2, and I think python is a symlink to the python27 binary) and are running your file just by typing its name, or you are running it through python.


text:
Q: For/While loops triangle in Python not working Working on my 2nd triangle but it is not giving me the result needed using the while nested loop and I should have the following output.
Using for loop:
0
01
012
0123
01234
012345

Using while loops:
     5
    45
   345
  2345
 12345
012345

Code:
print('Using for loop')
print()
M = 6 #constant
cnt = 1

for i in range(0,M):
    for j in range(0,cnt):
        if(j<M):
            print(j,'',end='')
        else:
            print('',end='')
    cnt+=1
    print()
print()
print('Using While loop')
print()
cnt = 6

while(cnt != -1):
    for j in range(0,cnt-1):
        if(j<cnt+1):
            print(j,'',end='')
        else:
            print(j)
    cnt -=1
    print()
print()

my current results are..
Using for loop
0
01
012
0123
01234
012345

Using while loop
012345
01234
0123
012
01
0

A: you have lot of syntax error use this
print('Using for loop')
print()
M = 6 #constant
cnt = 1

for i in range(0,M):
    for j in range(0,cnt):
        if(j<M):
            print(j,'',end='')
    cnt+=1
    print()
print('\nUsing While loop\n')
cnt = 0

while(cnt != M):
    for j in range(0,M-(cnt+1)):
        print(' ','',end='')
    for j in range(0,cnt+1):
        print(M-(cnt+1-j),'',end='')
    cnt +=1
    print()
print()

A: Your logic is wrong. Also you have many syntax errors. Use this:
print('Using While loop')
print()
cnt = 6
v = cnt
while(cnt != -1):
    print(' ' * cnt, end='')
    for j in range(cnt, v):
        if j < cnt+1:
            print(j, end='')
        else:
            print(j, end='')
    cnt -=1
    print()

Output:
Using While loop

     5
    45
   345
  2345
 12345
012345

A: Here is a while-loop solution without any for-loop:
print('Using While loop')
print()
cnt = 6
v = cnt
while(cnt != -1):
    j = cnt
    print(' ' * cnt, end='')
    while(j < v):
        print(j, end='')
        j += 1

    cnt -=1
    print()


text:
Q: Local System Account in Windows Server 2008 Have the security persmission or anything else changed for the Local System Account in Windows Server 2008 versus Windows Server 2003?  We have a service, that logs on as the Local System Account, that creates folders on the server (same server as the service is installed).  It works perfectly when installed on Windows Server 2003 however when installed in Windows Server 2008 the folders do not get created.  It appears as if the Local System Account does not have persmission to create the folders.  Any insight that anyone can provide is greatly appreciated.
Thanks,
Scott

A: My immediate thought would be User Account Control
http://en.wikipedia.org/wiki/User_Account_Control
Depending on the use of the machine, it may be worthwhile turning it off and in other cases not so much. It's a bit of a controversial subject :)
Try disabling this through the Control Panel -> users and see if this helps :)

A: You can add your system account to the local machine's administrators group and it's not set by default in Windows 2008.


text:
Q: Is there an opposite of 'eq' in Lisp? I am comparing the first value of two lists, with two outcomes, they are either equal or unequal. My first IF statement is:
(if (eq (car L1) (car L2)))

Is there an opposite of 'eq' that can I  use?
Like...
(if (not eq (car L1) (car L2)))

Any help would be much appreciated!

A: This should work:
(not (eq (car L1) (car L2))


text:
Q: How to render component regardless of the props change I hope the title makes sense but this React lifecycle method is quite confusing by the nature.
I can't re-render the new component because of the previous prop changes. (props.error is NOT undefined)
Explanation

*

*Once error is occured in componentDidMount, props.error becomes 'STRING'

*First time, it goBack() and works fine.

*Second time but when we open this component again, because props.error is STRING(not undefined), it doesn't render and go back,

HOW do I make it render the component?
  static getDerivedStateFromProps(props: Props, state: State): State | null {
    const {
      error,
    } = props;

    // Once error is occured in componentDidMount, props.error is not undefined.
    // First time, it works and go back to the previous page.
    // But when we open this component again, it doesn't render and go back, because props.error is NOT undefined.
    // componentDidMount still gets triggered to fetch, but it gets triggers AFTER this
    if (error) {
      goBack(); //// I MUST call this (This hide or unmount the current component)
    }
    ...
  }
  componentDidMount() {
     fetch() // this causes an error and update props.error (from undefined to 'STRING')
  }

A: Clear the error state of a parent component, when you call goBack


text: Q: How to remove dot in numbers by pandas I have a column with about 5000 indexes. In each row, there is numeric value. However, for some rows the numbers contain decimal points, meaning that it contains dots. For example, 1000 is expressed like 1.000. How would i fix this with pandas?


text:
Q: Deploy Angular 7 Server Git gostaria de poder mandar um deploy em Angular 7 para um servidor DigitalOcean, através dos comandos git
A arquitetura do meu projeto está organizado desta maneira (pastas)
Meu-projeto
  .git
  dist
     deploy-meu-projeto
  e2e
  node_modules
  src
  ...

Eu gostaria de mandar para o servidor, apenas o deploy de meu projeto, apenas a produção, através do comando git


text:
Q: IIS Express: Either a required impersonation level was not provided, or the provided impersonation level is invalid. (0x80070542) I am experiencing a weird issue while testing an Asp.Net Webforms application with Windows authentication & IIS Express.
Here is the context information:
OS:
OS Name Microsoft Windows Server 2016 Standard
Version 10.0.14393 Build 14393

Visual Studio 2019:
Microsoft Visual Studio Enterprise 2019
Version 16.4.6
VisualStudio.16.Release/16.4.6+29905.134
Microsoft .NET Framework
Version 4.8.03761

Application: Asp.net WebForms, MVC 5, Web Api 2.0 application with Windows authentication.I use Chrome & FireFox to test the app and IIS Express 10.
I have two windows accounts let's call them Account1 and Account2 under a domain called SomeDomain which is the main domain. Both accounts have Local Administrator privileges on this VM. UAC is enabled on this VM. I do not run Visual Studio as administrator.
When I do development I am logged in as Account1 I don't have any issue with this account. However, when I log in in the application under Account2 (when I am prompted by the browser that is) I get past the default page but then I click on some other pages and I get prompted for password again. Sometimes one page might work and second time I access that page I am prompted for password! Extremely weird. I have to say I never ever had such a problem on previous development VMs, with Windows Server 2012 and Visual Studio 2017.
Now, I started to investigate to see what's going on.
First of all, Account2 has read access to the application directory. I double checked that using the Effective Access feature in Windows -> Security dialog.
I checked the IIS Express log file and here is the error:
<EventData>
  <Data Name="ContextId">{8000002A-0001-FA00-B63F-84710C7967BB}</Data>
  <Data Name="ModuleName">IIS Web Core</Data>
  <Data Name="Notification">2</Data>
  <Data Name="HttpStatus">500</Data>
  <Data Name="HttpReason">Internal Server Error</Data>
  <Data Name="HttpSubStatus">0</Data>
  <Data Name="ErrorCode">2147943746</Data>
  <Data Name="ConfigExceptionInfo"></Data>
 </EventData>
 <RenderingInfo Culture="en-US">
  <Opcode>MODULE_SET_RESPONSE_ERROR_STATUS</Opcode>
  <Keywords>
   <Keyword>RequestNotifications</Keyword>
  </Keywords>
  <freb:Description Data="Notification">AUTHENTICATE_REQUEST</freb:Description>
  <freb:Description Data="ErrorCode">Either a required impersonation level was not provided, or the provided impersonation level is invalid.
 (0x80070542)</freb:Description>
 </RenderingInfo>

A search on the web shows that these errors have been plaguing developers for a very long time. But now, 2020?

A: It turns out that the issue occurred because I was not running VS Studio 2019 as administrator. Once I set that I don't have any issues anymore.


text:
Q: dockerhub build fails requirements.txt not found I am building a Docker image for some python packages, for which I using requirements.txt to install all python packages by pip.
I have all Dockerfile, requirements.txt, and related python scripts in the subfolder of my GitHub repo.
-> Main repo
---> folder
    --> some python scripts
    --> docker_folder
       --> Dockerfile
       --> requirements.txt
---> some files
---> some files

I have built the image locally which works fine but while configuring autobuild in Docker Hub it throws an error by stating that requirements.txt not found but it found Dockerfile. I have changed the Dockerfile location in the build setting on Docker Hub by:folder/docker_folder/Dockerfile.
I think the main problem lies in the Build configuration setting. Any help? Thanks.
logfile from Dockerhub built:
Cloning into '.'...
Warning: Permanently added the RSA host key for IP address '140.82.114.3' to the list of known hosts.
Reset branch 'master'
Your branch is up-to-date with 'origin/master'.
KernelVersion: 4.4.0-1060-aws
Components: [{u'Version': u'19.03.8', u'Name': u'Engine', u'Details': {u'KernelVersion': u'4.4.0-1060-aws', u'Os': u'linux', u'BuildTime': u'2020-03-11T01:24:30.000000000+00:00', u'ApiVersion': u'1.40', u'MinAPIVersion': u'1.12', u'GitCommit': u'afacb8b7f0', u'Arch': u'amd64', u'Experimental': u'false', u'GoVersion': u'go1.12.17'}}, {u'Version': u'1.2.13', u'Name': u'containerd', u'Details': {u'GitCommit': u'7ad184331fa3e55e52b890ea95e65ba581ae3429'}}, {u'Version': u'1.0.0-rc10', u'Name': u'runc', u'Details': {u'GitCommit': u'dc9208a3303feef5b3839f4323d9beb36df0a9dd'}}, {u'Version': u'0.18.0', u'Name': u'docker-init', u'Details': {u'GitCommit': u'fec3683'}}]
Arch: amd64
BuildTime: 2020-03-11T01:24:30.000000000+00:00
ApiVersion: 1.40
Platform: {u'Name': u'Docker Engine - Community'}
Version: 19.03.8
MinAPIVersion: 1.12
GitCommit: afacb8b7f0
Os: linux
GoVersion: go1.12.17
Starting build of index.docker.io/darsh3/python_drl:latest...
Step 1/5 : FROM python:3.8
---> 8f6adb7689b5
Step 2/5 : WORKDIR ${PWD}/..
---> Running in 516d190b493f
Removing intermediate container 516d190b493f
---> e948c6e6f641
Step 3/5 : COPY requirements.txt ./
COPY failed: stat /var/lib/docker/tmp/docker-builder968608568/requirements.txt: no such file or directory

A: Please use COPY command like below. Error occurs because you might be building image using . context
COPY folder/docker_folder/requirements.txt ./

A: With the directory structure you show, if you run
docker build -f folder/docker_folder/Dockerfile "Main repo"

then the source of all COPY commands is relative to the "Main repo" directory.
FROM python:3.8
WORKDIR /app
# Needs to COPY from the directory relative to the `docker build`
# context directory argument
COPY folder/docker_folder/requirements.txt .
RUN pip install -r requirements.txt

You might consider moving the requirements.txt file up to the top level of your repository or perhaps the directory containing the Python scripts, since it's a standard Python packaging file and not Docker-specific.  If the only Docker-specific thing you have is the Dockerfile then putting it in the top-level directory is fairly common as well.
# If the Dockerfile is in the named directory, no -f option is needed
docker build "Main repo/folder"

# If the file is in the named directory, just use its name without a path
COPY requirements.txt .


text:
Q: Why can't I see datetime fields in rails_admin show view? I'm adding a new model to rails_admin.  The list page displays datetime fields correctly, even without any configuration.  But the detail (show) page for a given object does not display datetimes. How do I configure rails_admin to show datetime fields on the show page?
Model file: alert_recording.rb:
class AlertRecording < ActiveRecord::Base
  attr_accessible :user_id, :admin_id, :message, :sent_at, :acknowledged_at, :created_at, :updated_at
end

Rails_admin initializer file:
...
config.included_models = [
  AlertRecording
]

...

config.model AlertRecording do
  field :sent_at, :datetime
  field :acknowledged_at, :datetime
  field :message
  field :user
  field :admin
  field :created_at, :datetime
  field :updated_at, :datetime
  list do; end
  show do; end
end

What's the correct way to configure the datetime fields so I see them on the show view?

A: These fields are hidden by default as you can see here:
https://github.com/sferik/rails_admin/blob/ead1775c48754d6a99c25e4d74494a60aee9b4d1/lib/rails_admin/config.rb#L277
You can overwrite this setting on your config initializer, just open the file config/initializers/rails_admin.rb and add this line to it:
config.default_hidden_fields = []
or something like this:
config.default_hidden_fields = [:id, :my_super_top_secret_field]
That way you doesn't need to do a config to every model in your app ;)
BUT!!! This will show these fields in edit action, so it's a good idea to hide id, created_at and updated_at in this case.
To do this you can assign a hash on this setting, like so:
config.default_hidden_fields = {
  show: [],
  edit: [:id, :created_at, :updated_at]
}

And voilà, you have what you want. ;)

A: What you have in there for sent_at and acknowledged_at should work. Make sure the records you are trying to "show" have dates present for these fields.
For created_at and updated_at, try this:
config.model AlertRecording do
  field :created_at
  configure :created_at do
    show
  end
  field :updated_at, :datetime
  configure :updated_at do
    show
  end
end


text:
Q: jquery/js closest().attr() returns undefined I've only recently started learning JS, jQuery, HTML and CSS. Right now I'm trying to make my page, when a category class is clicked, animate and then redirecting to the link of the clicked item.
I've looked around a lot and got the .closest(selector).attr('href') thing or the parent thing. I tried both, and I just keep getting undefined for linkto
HTML:

        Programs

JS:
$('.category').click(function() {
  $('.mainCon').animate({
    right: '100px',
    opacity: '0',
  }, 500, function() {
    var linkto = $(this).closest('a').attr('href');
    location.href= linkto;
  })
  return false;
});

Any idea why linkto always returns undefined? The linked html file(programs.html) is in the same directory as the page where I'm going to be coming from so I really don't know what's wrong.

A: Yours is invalid HTML. li can only be child of ul,
Use
$('.category').click(function() {
    var self = $(this); //Cache this in a variable
    self.closest('.mainCon').animate({
        right: '100px',
        opacity: '0',
    }, 500, function() {
        var linkto = self.closest('a').attr('href');
        location.href= linkto;
    })
    return false;
});

OR
$('.category').click(function() {
    var self = $(this);
    self.closest('.mainCon').animate({
        right: '100px',
        opacity: '0',
    }, 500, function() {
        var linkto = $(this).find('a').attr('href');
        location.href= linkto;
    })
    return false;
})

A: Inside the animate callback this is the mainCon element. .closest() is used to find an ancestor element, but in your case you need to find a descendant element so use .find()
$('.category').click(function() {
    $('.mainCon').animate({
        right: '100px',
        opacity: '0',
    }, 500, function() {
        var linkto = $(this).find('a').attr('href');
        location.href= linkto;
    })
    return false;
});

Note: Your html is invalid, li can't be a child of anchor element

A: you can simply use
var linkto = $(this).children('a').attr('href');

instead of
var linkto = $(this).closest('a').attr('href');

A: $('.mainCon'). (this) object and $('.category') (this) object are different, When you use $(this) under
$('.mainCon').animate()

that means you are in
 not

<!DOCTYPE html>

                            Programs

A: You can use .find() also.
var link = $(this).find('a').attr('href')