Programs & Examples On #Executereader

Specified cast is not valid?

Try this:

public void LoadData()
        {
            SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Stocks;Integrated Security=True;Pooling=False");
            SqlDataAdapter sda = new SqlDataAdapter("Select * From [Stocks].[dbo].[product]", con);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            DataGridView1.Rows.Clear();

        foreach (DataRow item in dt.Rows)
        {
            int n = DataGridView1.Rows.Add();
            DataGridView1.Rows[n].Cells[0].Value = item["ProductCode"].ToString();
            DataGridView1.Rows[n].Cells[1].Value = item["Productname"].ToString();
            DataGridView1.Rows[n].Cells[2].Value = item["qty"].ToString();                
            if ((bool)item["productstatus"])
            {
                DataGridView1.Rows[n].Cells[3].Value = "Active";
            }
            else
            {
                DataGridView1.Rows[n].Cells[3].Value = "Deactive";
            }

Select query to get data from SQL Server

According to MSDN

http://msdn.microsoft.com/ru-ru/library/system.data.sqlclient.sqlcommand.executenonquery(v=vs.110).aspx

result is the number of lines affected, and since your query is select no lines are affected (i.e. inserted, deleted or updated) anyhow.

If you want to return a single row of the query, use ExecuteScalar() instead of ExecuteNonQuery():

  int result = (int) (command.ExecuteScalar());

However, if you expect many rows to be returned, ExecuteReader() is the only option:

  using (SqlDataReader reader = command.ExecuteReader()) {
    while (reader.Read()) {
      int result = reader.GetInt32(0);

      ...
    }
  }

How to refresh or show immediately in datagridview after inserting?

You can set the datagridview DataSource to null and rebind it again.

private void button1_Click(object sender, EventArgs e)
{
    myAccesscon.ConnectionString = connectionString;

    dataGridView.DataSource = null;
    dataGridView.Update();
    dataGridView.Refresh();
    OleDbCommand cmd = new OleDbCommand(sql, myAccesscon);
    myAccesscon.Open();
    cmd.CommandType = CommandType.Text;
    OleDbDataAdapter da = new OleDbDataAdapter(cmd);
    DataTable bookings = new DataTable();
    da.Fill(bookings);
    dataGridView.DataSource = bookings;
    myAccesscon.Close();
}

OPTION (RECOMPILE) is Always Faster; Why?

Necroing this question but there's an explanation that no-one seems to have considered.

STATISTICS - Statistics are not available or misleading

If all of the following are true:

  1. The columns feedid and feedDate are likely to be highly correlated (e.g. a feed id is more specific than a feed date and the date parameter is redundant information).
  2. There is no index with both columns as sequential columns.
  3. There are no manually created statistics covering both these columns.

Then sql server may be incorrectly assuming that the columns are uncorrelated, leading to lower than expected cardinality estimates for applying both restrictions and a poor execution plan being selected. The fix in this case would be to create a statistics object linking the two columns, which is not an expensive operation.

Sql connection-string for localhost server

In .Net configuration I would use something like:

"Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=..."

This information is from https://www.connectionstrings.com/sql-server-2016/

this is error ORA-12154: TNS:could not resolve the connect identifier specified?

ORA-12154: TNS:could not resolve the connect identifier specified?

In case the TNS is not defined you can also try this one:

If you are using C#.net 2010 or other version of VS and oracle 10g express edition or lower version, and you make a connection string like this:

static string constr = @"Data Source=(DESCRIPTION=
    (ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=yourhostname )(PORT=1521)))
    (CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=XE)));
    User Id=system ;Password=yourpasswrd"; 

After that you get error message ORA-12154: TNS:could not resolve the connect identifier specified then first you have to do restart your system and run your project.

And if Your windows is 64 bit then you need to install oracle 11g 32 bit and if you installed 11g 64 bit then you need to Install Oracle 11g Oracle Data Access Components (ODAC) with Oracle Developer Tools for Visual Studio version 11.2.0.1.2 or later from OTN and check it in Oracle Universal Installer Please be sure that the following are checked:

Oracle Data Provider for .NET 2.0

Oracle Providers for ASP.NET

Oracle Developer Tools for Visual Studio

Oracle Instant Client 

And then restart your Visual Studio and then run your project .... NOTE:- SYSTEM RESTART IS necessary TO SOLVE THIS TYPES OF ERROR.......

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

Try this

SqlCommand cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID=@id", con);
cmd.Parameters.AddWithValue("id", id.Text);

how to use sqltransaction in c#

You have to tell your SQLCommand objects to use the transaction:

cmd1.Transaction = transaction;

or in the constructor:

SqlCommand cmd1 = new SqlCommand("select...", connectionsql, transaction);

Make sure to have the connectionsql object open, too.

But all you are doing are SELECT statements. Transactions would benefit more when you use INSERT, UPDATE, etc type actions.

Populate data table from data reader

I looked into this as well, and after comparing the SqlDataAdapter.Fill method with the SqlDataReader.Load funcitons, I've found that the SqlDataAdapter.Fill method is more than twice as fast with the result sets I've been using

Used code:

    [TestMethod]
    public void SQLCommandVsAddaptor()
    {
        long AdapterFillLargeTableTime, readerLoadLargeTableTime, AdapterFillMediumTableTime, readerLoadMediumTableTime, AdapterFillSmallTableTime, readerLoadSmallTableTime, AdapterFillTinyTableTime, readerLoadTinyTableTime;

        string LargeTableToFill = "select top 10000 * from FooBar";
        string MediumTableToFill = "select top 1000 * from FooBar";
        string SmallTableToFill = "select top 100 * from FooBar";
        string TinyTableToFill = "select top 10 * from FooBar";

        using (SqlConnection sconn = new SqlConnection("Data Source=.;initial catalog=Foo;persist security info=True; user id=bar;password=foobar;"))
        {
            // large data set measurements
            AdapterFillLargeTableTime = MeasureExecutionTimeMethod(sconn, LargeTableToFill, ExecuteDataAdapterFillStep);
            readerLoadLargeTableTime = MeasureExecutionTimeMethod(sconn, LargeTableToFill, ExecuteSqlReaderLoadStep);
            // medium data set measurements
            AdapterFillMediumTableTime = MeasureExecutionTimeMethod(sconn, MediumTableToFill, ExecuteDataAdapterFillStep);
            readerLoadMediumTableTime = MeasureExecutionTimeMethod(sconn, MediumTableToFill, ExecuteSqlReaderLoadStep);
            // small data set measurements
            AdapterFillSmallTableTime = MeasureExecutionTimeMethod(sconn, SmallTableToFill, ExecuteDataAdapterFillStep);
            readerLoadSmallTableTime = MeasureExecutionTimeMethod(sconn, SmallTableToFill, ExecuteSqlReaderLoadStep);
            // tiny data set measurements
            AdapterFillTinyTableTime = MeasureExecutionTimeMethod(sconn, TinyTableToFill, ExecuteDataAdapterFillStep);
            readerLoadTinyTableTime = MeasureExecutionTimeMethod(sconn, TinyTableToFill, ExecuteSqlReaderLoadStep);
        }
        using (StreamWriter writer = new StreamWriter("result_sql_compare.txt"))
        {
            writer.WriteLine("10000 rows");
            writer.WriteLine("Sql Data Adapter 100 times table fill speed 10000 rows: {0} milliseconds", AdapterFillLargeTableTime);
            writer.WriteLine("Sql Data Reader 100 times table load speed 10000 rows: {0} milliseconds", readerLoadLargeTableTime);
            writer.WriteLine("1000 rows");
            writer.WriteLine("Sql Data Adapter 100 times table fill speed 1000 rows: {0} milliseconds", AdapterFillMediumTableTime);
            writer.WriteLine("Sql Data Reader 100 times table load speed 1000 rows: {0} milliseconds", readerLoadMediumTableTime);
            writer.WriteLine("100 rows");
            writer.WriteLine("Sql Data Adapter 100 times table fill speed 100 rows: {0} milliseconds", AdapterFillSmallTableTime);
            writer.WriteLine("Sql Data Reader 100 times table load speed 100 rows: {0} milliseconds", readerLoadSmallTableTime);
            writer.WriteLine("10 rows");
            writer.WriteLine("Sql Data Adapter 100 times table fill speed 10 rows: {0} milliseconds", AdapterFillTinyTableTime);
            writer.WriteLine("Sql Data Reader 100 times table load speed 10 rows: {0} milliseconds", readerLoadTinyTableTime);

        }
        Process.Start("result_sql_compare.txt");
    }

    private long MeasureExecutionTimeMethod(SqlConnection conn, string query, Action<SqlConnection, string> Method)
    {
        long time; // know C#
        // execute single read step outside measurement time, to warm up cache or whatever
        Method(conn, query);
        // start timing
        time = Environment.TickCount;
        for (int i = 0; i < 100; i++)
        {
            Method(conn, query);
        }
        // return time in milliseconds
        return Environment.TickCount - time;
    }

    private void ExecuteDataAdapterFillStep(SqlConnection conn, string query)
    {
        DataTable tab = new DataTable();
        conn.Open();
        using (SqlDataAdapter comm = new SqlDataAdapter(query, conn))
        {
            // Adapter fill table function
            comm.Fill(tab);
        }
        conn.Close();
    }

    private void ExecuteSqlReaderLoadStep(SqlConnection conn, string query)
    {
        DataTable tab = new DataTable();
        conn.Open();
        using (SqlCommand comm = new SqlCommand(query, conn))
        {
            using (SqlDataReader reader = comm.ExecuteReader())
            {
                // IDataReader Load function
                tab.Load(reader);
            }
        }
        conn.Close();
    }

Results:

10000 rows:
Sql Data Adapter 100 times table fill speed 10000 rows: 11782 milliseconds
Sql Data Reader  100 times table load speed 10000 rows: 26047 milliseconds
1000 rows:
Sql Data Adapter 100 times table fill speed 1000 rows: 984  milliseconds
Sql Data Reader  100 times table load speed 1000 rows: 2031 milliseconds
100 rows:
Sql Data Adapter 100 times table fill speed 100 rows: 125 milliseconds
Sql Data Reader  100 times table load speed 100 rows: 235 milliseconds
10 rows:
Sql Data Adapter 100 times table fill speed 10 rows: 32 milliseconds
Sql Data Reader  100 times table load speed 10 rows: 93 milliseconds

For performance issues, using the SqlDataAdapter.Fill method is far more efficient. So unless you want to shoot yourself in the foot use that. It works faster for small and large data sets.

Error "There is already an open DataReader associated with this Command which must be closed first" when using 2 distinct commands

You can get such a problem when you are two different commands on same connection - especially calling the second command in a loop. That is calling the second command for each record returned from the first command. If there are some 10,000 records returned by the first command, this issue will be more likely.

I used to avoid such a scenario by making it as a single command.. The first command returns all the required data and load it into a DataTable.

Note: MARS may be a solution - but it can be risky and many people dislike it.

Reference

  1. What does "A severe error occurred on the current command. The results, if any, should be discarded." SQL Azure error mean?
  2. Linq-To-Sql and MARS woes - A severe error occurred on the current command. The results, if any, should be discarded
  3. Complex GROUP BY on DataTable

drop down list value in asp.net

In simple way, Its not possible. Because DropdownList contain ListItem and it will be selected by default

But, you can use ValidationControl for that:

<asp:RequiredFieldValidator InitialValue="-1" ID="Req_ID" Display="Dynamic" 
ValidationGroup="g1" runat="server" ControlToValidate="ControlID"
Text="*" ErrorMessage="ErrorMessage"></asp:RequiredFieldValidator>

"Input string was not in a correct format."

The error means that the string you're trying to parse an integer from doesn't actually contain a valid integer.

It's extremely unlikely that the text boxes will contain a valid integer immediately when the form is created - which is where you're getting the integer values. It would make much more sense to update a and b in the button click events (in the same way that you are in the constructor). Also, check out the Int.TryParse method - it's much easier to use if the string might not actually contain an integer - it doesn't throw an exception so it's easier to recover from.

Fill DataTable from SQL Server database

Try with following:

public DataTable fillDataTable(string table)
    {
        string query = "SELECT * FROM dstut.dbo." +table;

        SqlConnection sqlConn = new SqlConnection(conSTR);
        sqlConn.Open();
        SqlCommand cmd = new SqlCommand(query, sqlConn);
        SqlDataAdapter da=new SqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);
        sqlConn.Close();
        return dt;
    }

Hope it is helpful.

How do I get values from a SQL database into textboxes using C#?

If you want to display single value access from database into textbox, please refer to the code below:

SqlConnection con=new SqlConnection("connection string");
SqlCommand cmd=new SqlConnection(SqlQuery,Con);
Con.Open();
TextBox1.Text=cmd.ExecuteScalar();
Con.Close();

or

SqlConnection con=new SqlConnection("connection string");
SqlCommand cmd=new SqlConnection(SqlQuery,Con);
Con.Open();
SqlDataReader dr=new SqlDataReadr();
dr=cmd.Executereader();
if(dr.read())
{
    TextBox1.Text=dr.GetValue(0).Tostring();
}
Con.Close();

Win32Exception (0x80004005): The wait operation timed out

I had the same issue. Running exec sp_updatestats did work sometimes, but not always. I decided to use the NOLOCK statement in my queries to speed up the queries. Just add NOLOCK after your FROM clause, e.g.:

SELECT clicks.entryURL, clicks.entryTime, sessions.userID
FROM sessions, clicks WITH (NOLOCK)
WHERE sessions.sessionID = clicks.sessionID AND clicks.entryTime > DATEADD(day, -1, GETDATE())

Read the full article here.

How to display data from database into textbox, and update it

Populate the text box values in the Page Init event as opposed to using the Postback.

protected void Page_Init(object sender, EventArgs e)
{
    DropDownTitle();
}

How to run multiple SQL commands in a single SQL connection?

using (var connection = new SqlConnection("Enter Your Connection String"))
    {
        connection.Open();
    
        using (var command = connection.CreateCommand())
        {
            command.CommandText = "Enter the First Command Here";
            command.ExecuteNonQuery();
    
            command.CommandText = "Enter Second Comand Here";
            command.ExecuteNonQuery();

    //Similarly You can Add Multiple
        }
    }

Insert into C# with SQLCommand

You can use dapper library:

conn2.Execute(@"INSERT INTO klant(klant_id,naam,voornaam) VALUES (@p1,@p2,@p3)", 
                new { p1 = klantId, p2 = klantNaam, p3 = klantVoornaam });

BTW Dapper is a Stack Overflow project :)

UPDATE: I believe you can't do it simpler without something like EF. Also try to use using statements when you are working with database connections. This will close connection automatically, even in case of exception. And connection will be returned to connections pool.

private readonly string _spionshopConnectionString;

private void Form1_Load(object sender, EventArgs e)
{            
    _spionshopConnectionString = ConfigurationManager
          .ConnectionStrings["connSpionshopString"].ConnectionString;
}

private void button4_Click(object sender, EventArgs e)
{
    using(var connection = new SqlConnection(_spionshopConnectionString))
    {
         connection.Execute(@"INSERT INTO klant(klant_id,naam,voornaam) 
                              VALUES (@klantId,@klantNaam,@klantVoornaam)",
                              new { 
                                      klantId = Convert.ToInt32(textBox1.Text), 
                                      klantNaam = textBox2.Text, 
                                      klantVoornaam = textBox3.Text 
                                  });
    }
}

Connecting to Oracle Database through C#?

The next approach work to me with Visual Studio 2013 Update 4 1- From Solution Explorer right click on References then select add references 2- Assemblies > Framework > System.Data.OracleClient > OK and after that you free to add using System.Data.OracleClient in your application and deal with database like you do with Sql Server database except changing the prefix from Sql to Oracle as in SqlCommand become OracleCommand for example to link to Oracle XE

OracleConnection oraConnection = new OracleConnection(@"Data Source=XE; User ID=system; Password=*myPass*");
public void Open()
{
if (oraConnection.State != ConnectionState.Open)
{
oraConnection.Open();
}
}
public void Close()
{
if (oraConnection.State == ConnectionState.Open)
{
oraConnection.Close();
}}

and to execute some command like INSERT, UPDATE, or DELETE using stored procedure we can use the following method

public void ExecuteCMD(string storedProcedure, OracleParameter[] param)
{
OracleCommand oraCmd = new OracleCommand();
oraCmd,CommandType = CommandType.StoredProcedure;
oraCmd.CommandText = storedProcedure;
oraCmd.Connection = oraConnection;

if(param!=null)
{
oraCmd.Parameters.AddRange(param);
}
try
{
oraCmd.ExecuteNoneQuery();
}
catch (Exception)
{
MessageBox.Show("Sorry We've got Unknown Error","Connection Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}

Fill Combobox from database

To use the Combobox in the way you intend, you could pass in an object to the cmbTripName.Items.Add method.

That object should have FleetID and FleetName properties:

while (drd.Read())
{
    cmbTripName.Items.Add(new Fleet(drd["FleetID"].ToString(), drd["FleetName"].ToString()));
}
cmbTripName.ValueMember = "FleetId";
cmbTripName.DisplayMember = "FleetName";

The Fleet Class:

class Fleet
{
     public Fleet(string fleetId, string fleetName)
     {
           FleetId = fleetId;
           FleetName = fleetName
     }
     public string FleetId {get;set;}
     public string FleetName {get;set;}
}

Or, You could probably do away with the need for a Fleet class completely by using an anonymous type...

while (drd.Read())
{
    cmbTripName.Items.Add(new {FleetId = drd["FleetID"].ToString(), FleetName = drd["FleetName"].ToString()});
}
cmbTripName.ValueMember = "FleetId";
cmbTripName.DisplayMember = "FleetName";

Windows service start failure: Cannot start service from the command line or debugger

I will suggest creating a setup project for the reasons while deploying this seems the best convinience , no headaches of copying files manually. Follow the Windows service setup creation tutorial and you know how to create it. And this instance is for vb.net but it is the same for any type.

How to fill Dataset with multiple tables?

public DataSet GetDataSet()
    {
        try
        {
            DataSet dsReturn = new DataSet();
            using (SqlConnection myConnection = new SqlConnection(Core.con))
            {
                string query = "select * from table1;  select* from table2";
                SqlCommand cmd = new SqlCommand(query, myConnection);
                myConnection.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                dsReturn.Load(reader, LoadOption.PreserveChanges, new string[] { "tableOne", "tableTwo" });
                return dsReturn;
            }
        }
        catch (Exception)
        {
            throw;
        }
    }

How to refresh datagrid in WPF

Reload the datasource of your grid after the update

myGrid.ItemsSource = null;
myGrid.ItemsSource = myDataSource;

OracleCommand SQL Parameters Binding

You need to use something like this:

 OracleCommand oraCommand = new OracleCommand("SELECT fullname FROM sup_sys.user_profile
                       WHERE domain_user_name = :userName", db);

More can be found in this MSDN article: http://msdn.microsoft.com/en-us/library/system.data.oracleclient.oraclecommand.parameters%28v=vs.100%29.aspx

It is advised you use the : character instead of @ for Oracle.

Error Message: Type or namespace definition, or end-of-file expected

You have extra brackets in Hours property;

public  object Hours { get; set; }}

How to form a correct MySQL connection string?

string MyConString = "Data Source='mysql7.000webhost.com';" +
"Port=3306;" +
"Database='a455555_test';" +
"UID='a455555_me';" +
"PWD='something';";

Uploading an Excel sheet and importing the data into SQL Server database

You can use OpenXml SDK for *.xlsx files. It works very quickly. I made simple C# IDataReader implementation for this sdk. See here. Now you can easy import excel file to sql server database using SqlBulkCopy. It uses small memory because it reads by SAX(Simple API for XML) method (OpenXmlReader)

Example:

private static void DataReaderBulkCopySample()
{            
    using (var reader = new ExcelDataReader(@"test.xlsx"))
    {
        var cols = Enumerable.Range(0, reader.FieldCount).Select(i => reader.GetName(i)).ToArray();
        DataHelper.CreateTableIfNotExists(ConnectionString, TableName, cols);

        using (var bulkCopy = new SqlBulkCopy(ConnectionString))
        {
            // MSDN: When EnableStreaming is true, SqlBulkCopy reads from an IDataReader object using SequentialAccess, 
            // optimizing memory usage by using the IDataReader streaming capabilities
            bulkCopy.EnableStreaming = true;

            bulkCopy.DestinationTableName = TableName;
            foreach (var col in cols)
                bulkCopy.ColumnMappings.Add(col, col);

            bulkCopy.WriteToServer(reader);
        }
    }
}

ExecuteReader requires an open and available Connection. The connection's current state is Connecting

Sorry for only commenting in the first place, but i'm posting almost every day a similar comment since many people think that it would be smart to encapsulate ADO.NET functionality into a DB-Class(me too 10 years ago). Mostly they decide to use static/shared objects since it seems to be faster than to create a new object for any action.

That is neither a good idea in terms of peformance nor in terms of fail-safety.

Don't poach on the Connection-Pool's territory

There's a good reason why ADO.NET internally manages the underlying Connections to the DBMS in the ADO-NET Connection-Pool:

In practice, most applications use only one or a few different configurations for connections. This means that during application execution, many identical connections will be repeatedly opened and closed. To minimize the cost of opening connections, ADO.NET uses an optimization technique called connection pooling.

Connection pooling reduces the number of times that new connections must be opened. The pooler maintains ownership of the physical connection. It manages connections by keeping alive a set of active connections for each given connection configuration. Whenever a user calls Open on a connection, the pooler looks for an available connection in the pool. If a pooled connection is available, it returns it to the caller instead of opening a new connection. When the application calls Close on the connection, the pooler returns it to the pooled set of active connections instead of closing it. Once the connection is returned to the pool, it is ready to be reused on the next Open call.

So obviously there's no reason to avoid creating,opening or closing connections since actually they aren't created,opened and closed at all. This is "only" a flag for the connection pool to know when a connection can be reused or not. But it's a very important flag, because if a connection is "in use"(the connection pool assumes), a new physical connection must be openend to the DBMS what is very expensive.

So you're gaining no performance improvement but the opposite. If the maximum pool size specified (100 is the default) is reached, you would even get exceptions(too many open connections ...). So this will not only impact the performance tremendously but also be a source for nasty errors and (without using Transactions) a data-dumping-area.

If you're even using static connections you're creating a lock for every thread trying to access this object. ASP.NET is a multithreading environment by nature. So theres a great chance for these locks which causes performance issues at best. Actually sooner or later you'll get many different exceptions(like your ExecuteReader requires an open and available Connection).

Conclusion:

  • Don't reuse connections or any ADO.NET objects at all.
  • Don't make them static/shared(in VB.NET)
  • Always create, open(in case of Connections), use, close and dispose them where you need them(f.e. in a method)
  • use the using-statement to dispose and close(in case of Connections) implicitely

That's true not only for Connections(although most noticable). Every object implementing IDisposable should be disposed(simplest by using-statement), all the more in the System.Data.SqlClient namespace.

All the above speaks against a custom DB-Class which encapsulates and reuse all objects. That's the reason why i commented to trash it. That's only a problem source.


Edit: Here's a possible implementation of your retrievePromotion-method:

public Promotion retrievePromotion(int promotionID)
{
    Promotion promo = null;
    var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString;
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        var queryString = "SELECT PromotionID, PromotionTitle, PromotionURL FROM Promotion WHERE PromotionID=@PromotionID";
        using (var da = new SqlDataAdapter(queryString, connection))
        {
            // you could also use a SqlDataReader instead
            // note that a DataTable does not need to be disposed since it does not implement IDisposable
            var tblPromotion = new DataTable();
            // avoid SQL-Injection
            da.SelectCommand.Parameters.Add("@PromotionID", SqlDbType.Int);
            da.SelectCommand.Parameters["@PromotionID"].Value = promotionID;
            try
            {
                connection.Open(); // not necessarily needed in this case because DataAdapter.Fill does it otherwise 
                da.Fill(tblPromotion);
                if (tblPromotion.Rows.Count != 0)
                {
                    var promoRow = tblPromotion.Rows[0];
                    promo = new Promotion()
                    {
                        promotionID    = promotionID,
                        promotionTitle = promoRow.Field<String>("PromotionTitle"),
                        promotionUrl   = promoRow.Field<String>("PromotionURL")
                    };
                }
            }
            catch (Exception ex)
            {
                // log this exception or throw it up the StackTrace
                // we do not need a finally-block to close the connection since it will be closed implicitely in an using-statement
                throw;
            }
        }
    }
    return promo;
}

Nullable DateTime conversion

You might want to do it like this:

DateTime? lastPostDate =  (DateTime?)(reader.IsDbNull(3) ? null : reader[3]); 

The problem you are having is that the ternary operator wants a viable cast between the left and right sides. And null can't be cast to DateTime.

Note the above works because both sides of the ternary are object's. The object is explicitly cast to DateTime? which works: as long as reader[3] is in fact a date.

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated

While all the earlier responses address the issue they did not cover all cases.

Microsoft has acknowledged the issue and fixed it in 2011 for supported operating systems, so if you get the stack trace like:

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
at System.Data.SqlClient.TdsParserStateObject.ReadSniError(TdsParserStateObject stateObj, UInt32 error)
at System.Data.SqlClient.TdsParserStateObject.ReadSni(DbAsyncResult asyncResult, TdsParserStateObject stateObj)

you may need to update your .NET assemblies.

This issue occurs because of an error in the connection-retry algorithm for mirrored databases.

When the retry-algorithm is used, the data provider waits for the first read (SniReadSync) call to finish. The call is sent to the back-end computer that is running SQL Server, and the waiting time is calculated by multiplying the connection time-out value by 0.08. However, the data provider incorrectly sets a connection to a doomed state if a response is slow and if the first SniReadSync call is not completed before the waiting time expires.

See KB 2605597 for details

https://support.microsoft.com/kb/2605597

How to use OUTPUT parameter in Stored Procedure

The SQL in your SP is wrong. You probably want

Select @code = RecItemCode from Receipt where RecTransaction = @id

In your statement, you are not setting @code, you are trying to use it for the value of RecItemCode. This would explain your NullReferenceException when you try to use the output parameter, because a value is never assigned to it and you're getting a default null.

The other issue is that your SQL statement if rewritten as

Select @code = RecItemCode, RecUsername from Receipt where RecTransaction = @id

It is mixing variable assignment and data retrieval. This highlights a couple of points. If you need the data that is driving @code in addition to other parts of the data, forget the output parameter and just select the data.

Select RecItemCode, RecUsername from Receipt where RecTransaction = @id

If you just need the code, use the first SQL statement I showed you. On the offhand chance you actually need the output and the data, use two different statements

Select @code = RecItemCode from Receipt where RecTransaction = @id
Select RecItemCode, RecUsername from Receipt where RecTransaction = @id

This should assign your value to the output parameter as well as return two columns of data in a row. However, this strikes me as terribly redundant.

If you write your SP as I have shown at the very top, simply invoke cmd.ExecuteNonQuery(); and then read the output parameter value.


Another issue with your SP and code. In your SP, you have declared @code as varchar. In your code, you specify the parameter type as Int. Either change your SP or your code to make the types consistent.


Also note: If all you are doing is returning a single value, there's another way to do it that does not involve output parameters at all. You could write

 Select RecItemCode from Receipt where RecTransaction = @id

And then use object obj = cmd.ExecuteScalar(); to get the result, no need for an output parameter in the SP or in your code.

ORA-01008: not all variables bound. They are bound

I know this is an old question, but it hasn't been correctly addressed, so I'm answering it for others who may run into this problem.

By default Oracle's ODP.net binds variables by position, and treats each position as a new variable.

Treating each copy as a different variable and setting it's value multiple times is a workaround and a pain, as furman87 mentioned, and could lead to bugs, if you are trying to rewrite the query and move things around.

The correct way is to set the BindByName property of OracleCommand to true as below:

var cmd = new OracleCommand(cmdtxt, conn);
cmd.BindByName = true;

You could also create a new class to encapsulate OracleCommand setting the BindByName to true on instantiation, so you don't have to set the value each time. This is discussed in this post

Reading int values from SqlDataReader

Call ToString() instead of casting the reader result.

reader[0].ToString();
reader[1].ToString();
// etc...

And if you want to fetch specific data type values (int in your case) try the following:

reader.GetInt32(index);

What is the right way to populate a DropDownList from a database?

You could bind the DropDownList to a data source (DataTable, List, DataSet, SqlDataSource, etc).

For example, if you wanted to use a DataTable:

ddlSubject.DataSource = subjectsTable;
ddlSubject.DataTextField = "SubjectNamne";
ddlSubject.DataValueField = "SubjectID";
ddlSubject.DataBind();

EDIT - More complete example

private void LoadSubjects()
{

    DataTable subjects = new DataTable();

    using (SqlConnection con = new SqlConnection(connectionString))
    {

        try
        {
            SqlDataAdapter adapter = new SqlDataAdapter("SELECT SubjectID, SubjectName FROM Students.dbo.Subjects", con);
            adapter.Fill(subjects);

            ddlSubject.DataSource = subjects;
            ddlSubject.DataTextField = "SubjectNamne";
            ddlSubject.DataValueField = "SubjectID";
            ddlSubject.DataBind();
        }
        catch (Exception ex)
        {
            // Handle the error
        }

    }

    // Add the initial item - you can add this even if the options from the
    // db were not successfully loaded
    ddlSubject.Items.Insert(0, new ListItem("<Select Subject>", "0"));

}

To set an initial value via the markup, rather than code-behind, specify the option(s) and set the AppendDataBoundItems attribute to true:

<asp:DropDownList ID="ddlSubject" runat="server" AppendDataBoundItems="true">
    <asp:ListItem Text="<Select Subject>" Value="0" />
</asp:DropDownList>

You could then bind the DropDownList to a DataSource in the code-behind (just remember to remove:

ddlSubject.Items.Insert(0, new ListItem("<Select Subject>", "0"));

from the code-behind, or you'll have two "" items.

C# SQL Server - Passing a list to a stored procedure

Yep, make Stored proc parameter as VARCHAR(...) And then pass comma separated values to a stored procedure.

If you are using Sql Server 2008 you can leverage TVP (Table Value Parameters): SQL 2008 TVP and LINQ if structure of QueryTable more complex than array of strings otherwise it would be an overkill because requires table type to be created within SQl Server

Direct method from SQL command text to DataSet

public static string textDataSource = "Data Source=localhost;Initial Catalog=TEST_C;User ID=sa;Password=P@ssw0rd";

public static DataSet LoaderDataSet(string StrSql)      
{
    SqlConnection cnn;            
    SqlDataAdapter dad;
    DataSet dts = new DataSet();
    cnn = new SqlConnection(textDataSource);
    dad = new SqlDataAdapter(StrSql, cnn);
    try
    {
        cnn.Open();
        dad.Fill(dts);
        cnn.Close();

        return dts;
    }
    catch (Exception)
    {

        return dts;
    }
    finally
    {
        dad.Dispose();
        dts = null;
        cnn = null;
    }
}

How to check if an object is a certain type

Some more details in relation with the response from Cody Gray. As it took me some time to digest it I though it might be usefull to others.

First, some definitions:

  1. There are TypeNames, which are string representations of the type of an object, interface, etc. For example, Bar is a TypeName in Public Class Bar, or in Dim Foo as Bar. TypeNames could be seen as "labels" used in the code to tell the compiler which type definition to look for in a dictionary where all available types would be described.
  2. There are System.Type objects which contain a value. This value indicates a type; just like a String would take some text or an Int would take a number, except we are storing types instead of text or numbers. Type objects contain the type definitions, as well as its corresponding TypeName.

Second, the theory:

  1. Foo.GetType() returns a Type object which contains the type for the variable Foo. In other words, it tells you what Foo is an instance of.
  2. GetType(Bar) returns a Type object which contains the type for the TypeName Bar.
  3. In some instances, the type an object has been Cast to is different from the type an object was first instantiated from. In the following example, MyObj is an Integer cast into an Object:

    Dim MyVal As Integer = 42 Dim MyObj As Object = CType(MyVal, Object)

So, is MyObj of type Object or of type Integer? MyObj.GetType() will tell you it is an Integer.

  1. But here comes the Type Of Foo Is Bar feature, which allows you to ascertain a variable Foo is compatible with a TypeName Bar. Type Of MyObj Is Integer and Type Of MyObj Is Object will both return True. For most cases, TypeOf will indicate a variable is compatible with a TypeName if the variable is of that Type or a Type that derives from it. More info here: https://docs.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/typeof-operator#remarks

The test below illustrate quite well the behaviour and usage of each of the mentionned keywords and properties.

Public Sub TestMethod1()

    Dim MyValInt As Integer = 42
    Dim MyValDble As Double = CType(MyValInt, Double)
    Dim MyObj As Object = CType(MyValDble, Object)

    Debug.Print(MyValInt.GetType.ToString) 'Returns System.Int32
    Debug.Print(MyValDble.GetType.ToString) 'Returns System.Double
    Debug.Print(MyObj.GetType.ToString) 'Returns System.Double

    Debug.Print(MyValInt.GetType.GetType.ToString) 'Returns System.RuntimeType
    Debug.Print(MyValDble.GetType.GetType.ToString) 'Returns System.RuntimeType
    Debug.Print(MyObj.GetType.GetType.ToString) 'Returns System.RuntimeType

    Debug.Print(GetType(Integer).GetType.ToString) 'Returns System.RuntimeType
    Debug.Print(GetType(Double).GetType.ToString) 'Returns System.RuntimeType
    Debug.Print(GetType(Object).GetType.ToString) 'Returns System.RuntimeType

    Debug.Print(MyValInt.GetType = GetType(Integer)) '# Returns True
    Debug.Print(MyValInt.GetType = GetType(Double)) 'Returns False
    Debug.Print(MyValInt.GetType = GetType(Object)) 'Returns False

    Debug.Print(MyValDble.GetType = GetType(Integer)) 'Returns False
    Debug.Print(MyValDble.GetType = GetType(Double)) '# Returns True
    Debug.Print(MyValDble.GetType = GetType(Object)) 'Returns False

    Debug.Print(MyObj.GetType = GetType(Integer)) 'Returns False
    Debug.Print(MyObj.GetType = GetType(Double)) '# Returns True
    Debug.Print(MyObj.GetType = GetType(Object)) 'Returns False

    Debug.Print(TypeOf MyObj Is Integer) 'Returns False
    Debug.Print(TypeOf MyObj Is Double) '# Returns True
    Debug.Print(TypeOf MyObj Is Object) '# Returns True


End Sub

EDIT

You can also use Information.TypeName(Object) to get the TypeName of a given object. For example,

Dim Foo as Bar
Dim Result as String
Result = TypeName(Foo)
Debug.Print(Result) 'Will display "Bar"

Configuration System Failed to Initialize

Make sure that your config file (web.config if web, or app.config if windows) in your project starts as:

<?xml version="1.0"?>
<configuration>
    <configSections>
        <sectionGroup name="applicationSettings" 
                      type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >

            <section name="YourProjectName.Properties.Settings" 
                     type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" 
                     requirePermission="false" />

        </sectionGroup>
    </configSections>
</configuration>

Note that inside the configuration element, the first child must be the configSections element.

In the name property on section element, make sure you replace YourProjectName with your actual project's name.

It happened to me that I created a webservice in a class library project, then I copied (overwriting) the config file (in order to bring the endpoints configuration) to my windows app and I started to have the same problem. I had inadvertently removed configSections.

it worked for me, hope it helps

Deleting row from datatable in C#

I see a number of answers using the Remove method and others using the Delete method.

Remove (according to the docs) will immediately remove the record from the (local) table, and on Update, will not remove a missing record.

Delete in comparison changes the RowState to Deleted, and will update the server table on Update. Likewise, calling the AcceptChanges method before the Update to the server table will reset all your RowState(s) to Unchanged and nothing will flow to the server. (Still nursing my thumb after hitting this a number of times).

C# Collection was modified; enumeration operation may not execute

Any collection that you iterate over with foreach may not be modified during iteration.

So while you're running a foreach over rankings, you cannot modify its elements, add new ones or delete any.

There is already an open DataReader associated with this Command which must be closed first

Well for me it was my own bug. I was trying to run an INSERT using SqlCommand.executeReader() when I should have been using SqlCommand.ExecuteNonQuery(). It was opened and never closed, causing the error. Watch out for this oversight.

ExecuteReader: Connection property has not been initialized

You can also write this:

SqlCommand cmd=new SqlCommand ("insert into time(project,iteration) values (@project, @iteration)", conn);
cmd.Parameters.AddWithValue("@project",name1.SelectedValue);
cmd.Parameters.AddWithValue("@iteration",iteration.SelectedValue);

Exception: There is already an open DataReader associated with this Connection which must be closed first

You are trying to to an Insert (with ExecuteNonQuery()) on a SQL connection that is used by this reader already:

while (myReader.Read())

Either read all the values in a list first, close the reader and then do the insert, or use a new SQL connection.

Index (zero based) must be greater than or equal to zero

This can also happen when trying to throw an ArgumentException where you inadvertently call the ArgumentException constructor overload

public static void Dostuff(Foo bar)
{

   // this works
   throw new ArgumentException(String.Format("Could not find {0}", bar.SomeStringProperty));

   //this gives the error
   throw new ArgumentException(String.Format("Could not find {0}"), bar.SomeStringProperty);

}

How to select the last record of a table in SQL?

It is always a good practice in your table design to have an automatic row identifier, such as

 [RowID] [int] IDENTITY(1,1) NOT FOR REPLICATION NOT NULL

, then you can identify your last row by

 select * from yourTable where rowID =  @@IDENTITY 

Using Alert in Response.Write Function in ASP.NET

You ca also use Response.Write("alert('Error')");

Error: select command denied to user '<userid>'@'<ip-address>' for table '<table-name>'

This problem happened to me because I had the hibernate.default_schema set to a different database than the one in the DataSource.

Being strict on my mysql user permissions, when hibernate tried to query a table it queried the one in the hibernate.default_schema database for which the user had no permissions.

Its unfortunate that mysql does not correctly specify the database in this error message, as that would've cleared things up straight away.

Read data from SqlDataReader

string col1Value = rdr["ColumnOneName"].ToString();

or

string col1Value = rdr[0].ToString();

These are objects, so you need to either cast them or .ToString().

What is the difference between ExecuteScalar, ExecuteReader and ExecuteNonQuery?

ExecuteNonQuery

This ExecuteNonQuery method will be used only for insert, update and delete, Create, and SET statements. ExecuteNonQuery method will return number of rows effected with INSERT, DELETE or UPDATE operations.

ExecuteScalar

It’s very fast to retrieve single values from database. Execute Scalar will return single row single column value i.e. single value, on execution of SQL Query or Stored procedure using command object. ExecuteReader

Execute Reader will be used to return the set of rows, on execution of SQL Query or Stored procedure using command object. This one is forward only retrieval of records and it is used to read the table values from first to last.

how to add value to combobox item

Although this question is 5 years old I have come across a nice solution.

Use the 'DictionaryEntry' object to pair keys and values.

Set the 'DisplayMember' and 'ValueMember' properties to:

   Me.myComboBox.DisplayMember = "Key"
   Me.myComboBox.ValueMember = "Value"

To add items to the ComboBox:

   Me.myComboBox.Items.Add(New DictionaryEntry("Text to be displayed", 1))

To retreive items like this:

MsgBox(Me.myComboBox.SelectedItem.Key & " " & Me.myComboBox.SelectedItem.Value)

How to iterate through a DataTable

You can also use linq extensions for DataSets:

var imagePaths = dt.AsEnumerble().Select(r => r.Field<string>("ImagePath");
foreach(string imgPath in imagePaths)
{
    TextBox1.Text = imgPath;
}

System.Data.SqlClient.SqlException: Invalid object name 'dbo.Projects'

Delete _MigrationHistory table in (yourdatabseName > Tables > System Tables) if you already have in your database and then run below command in package manager console

PM> update-database

How to Generate Unique Public and Private Key via RSA

When you use a code like this:

using (var rsa = new RSACryptoServiceProvider(1024))
{
   // Do something with the key...
   // Encrypt, export, etc.
}

.NET (actually Windows) stores your key in a persistent key container forever. The container is randomly generated by .NET

This means:

  1. Any random RSA/DSA key you have EVER generated for the purpose of protecting data, creating custom X.509 certificate, etc. may have been exposed without your awareness in the Windows file system. Accessible by anyone who has access to your account.

  2. Your disk is being slowly filled with data. Normally not a big concern but it depends on your application (e.g. it might generates hundreds of keys every minute).

To resolve these issues:

using (var rsa = new RSACryptoServiceProvider(1024))
{
   try
   {
      // Do something with the key...
      // Encrypt, export, etc.
   }
   finally
   {
      rsa.PersistKeyInCsp = false;
   }
}

ALWAYS

How to execute a stored procedure within C# program

You mean that your code is DDL? If so, MSSQL has no difference. Above examples well shows how to invoke this. Just ensure

CommandType = CommandType.Text

Invalid attempt to read when no data is present

You have to call DataReader.Read to fetch the result:

SqlDataReader dr = cmd10.ExecuteReader();
if (dr.Read()) 
{
    // read data for first record here
}

DataReader.Read() returns a bool indicating if there are more blocks of data to read, so if you have more than 1 result, you can do:

while (dr.Read()) 
{
    // read data for each record here
}

Procedure expects parameter which was not supplied

First - why is that an EXEC? Shouldn't that just be

AS
SELECT Column_Name, ...
FROM ...
WHERE TABLE_NAME = @template

The current SP doesn't make sense? In particular, that would look for a column matching @template, not the varchar value of @template. i.e. if @template is 'Column_Name', it would search WHERE TABLE_NAME = Column_Name, which is very rare (to have table and column named the same).

Also, if you do have to use dynamic SQL, you should use EXEC sp_ExecuteSQL (keeping the values as parameters) to prevent from injection attacks (rather than concatenation of input). But it isn't necessary in this case.

Re the actual problem - it looks OK from a glance; are you sure you don't have a different copy of the SP hanging around? This is a common error...

ORA-03113: end-of-file on communication channel after long inactivity in ASP.Net app

Add Validate Connection=true to your connection string.

Look at this blog to find more about.

DETAILS: After OracleConnection.Close() the real database connection does not terminate. The connection object is put back in connection pool. The use of connection pool is implicit by ODP.NET. If you create a new connection you get one of the pool. If this connection is "yet open" the OracleConnection.Open() method does not really creates a new connection. If the real connection is broken (for any reason) you get a failure on first select, update, insert or delete.

With Validate Connection the real connection is validated in Open() method.

Design DFA accepting binary strings divisible by a number 'n'

You can build DFA using simple modular arithmetics. We can interpret w which is a string of k-ary numbers using a following rule

V[0] = 0
V[i] = (S[i-1] * k) + to_number(str[i])

V[|w|] is a number that w is representing. If modify this rule to find w mod N, the rule becomes this.

V[0] = 0
V[i] = ((S[i-1] * k) + to_number(str[i])) mod N

and each V[i] is one of a number from 0 to N-1, which corresponds to each state in DFA. We can use this as the state transition.

See an example.

k = 2, N = 5

| V | (V*2 + 0) mod 5     | (V*2 + 1) mod 5     |
+---+---------------------+---------------------+
| 0 | (0*2 + 0) mod 5 = 0 | (0*2 + 1) mod 5 = 1 |
| 1 | (1*2 + 0) mod 5 = 2 | (1*2 + 1) mod 5 = 3 |
| 2 | (2*2 + 0) mod 5 = 4 | (2*2 + 1) mod 5 = 0 |
| 3 | (3*2 + 0) mod 5 = 1 | (3*2 + 1) mod 5 = 2 |
| 4 | (4*2 + 0) mod 5 = 3 | (4*2 + 1) mod 5 = 4 |

k = 3, N = 5

| V | 0 | 1 | 2 |
+---+---+---+---+
| 0 | 0 | 1 | 2 |
| 1 | 3 | 4 | 0 |
| 2 | 1 | 2 | 3 |
| 3 | 4 | 0 | 1 |
| 4 | 2 | 3 | 4 |

Now you can see a very simple pattern. You can actually build a DFA transition just write repeating numbers from left to right, from top to bottom, from 0 to N-1.

VBA Print to PDF and Save with Automatic File Name

Hopefully this is self explanatory enough. Use the comments in the code to help understand what is happening. Pass a single cell to this function. The value of that cell will be the base file name. If the cell contains "AwesomeData" then we will try and create a file in the current users desktop called AwesomeData.pdf. If that already exists then try AwesomeData2.pdf and so on. In your code you could just replace the lines filename = Application..... with filename = GetFileName(Range("A1"))

Function GetFileName(rngNamedCell As Range) As String
    Dim strSaveDirectory As String: strSaveDirectory = ""
    Dim strFileName As String: strFileName = ""
    Dim strTestPath As String: strTestPath = ""
    Dim strFileBaseName As String: strFileBaseName = ""
    Dim strFilePath As String: strFilePath = ""
    Dim intFileCounterIndex As Integer: intFileCounterIndex = 1

    ' Get the users desktop directory.
    strSaveDirectory = Environ("USERPROFILE") & "\Desktop\"
    Debug.Print "Saving to: " & strSaveDirectory

    ' Base file name
    strFileBaseName = Trim(rngNamedCell.Value)
    Debug.Print "File Name will contain: " & strFileBaseName

    ' Loop until we find a free file number
    Do
        If intFileCounterIndex > 1 Then
            ' Build test path base on current counter exists.
            strTestPath = strSaveDirectory & strFileBaseName & Trim(Str(intFileCounterIndex)) & ".pdf"
        Else
            ' Build test path base just on base name to see if it exists.
            strTestPath = strSaveDirectory & strFileBaseName & ".pdf"
        End If

        If (Dir(strTestPath) = "") Then
            ' This file path does not currently exist. Use that.
            strFileName = strTestPath
        Else
            ' Increase the counter as we have not found a free file yet.
            intFileCounterIndex = intFileCounterIndex + 1
        End If

    Loop Until strFileName <> ""

    ' Found useable filename
    Debug.Print "Free file name: " & strFileName
    GetFileName = strFileName

End Function

The debug lines will help you figure out what is happening if you need to step through the code. Remove them as you see fit. I went a little crazy with the variables but it was to make this as clear as possible.

In Action

My cell O1 contained the string "FileName" without the quotes. Used this sub to call my function and it saved a file.

Sub Testing()
    Dim filename As String: filename = GetFileName(Range("o1"))

    ActiveWorkbook.Worksheets("Sheet1").Range("A1:N24").ExportAsFixedFormat Type:=xlTypePDF, _
                                              filename:=filename, _
                                              Quality:=xlQualityStandard, _
                                              IncludeDocProperties:=True, _
                                              IgnorePrintAreas:=False, _
                                              OpenAfterPublish:=False
End Sub

Where is your code located in reference to everything else? Perhaps you need to make a module if you have not already and move your existing code into there.

Why do I get PLS-00302: component must be declared when it exists?

You can get that error if you have an object with the same name as the schema. For example:

create sequence s2;

begin
  s2.a;
end;
/

ORA-06550: line 2, column 6:
PLS-00302: component 'A' must be declared
ORA-06550: line 2, column 3:
PL/SQL: Statement ignored

When you refer to S2.MY_FUNC2 the object name is being resolved so it doesn't try to evaluate S2 as a schema name. When you just call it as MY_FUNC2 there is no confusion, so it works.

The documentation explains name resolution. The first piece of the qualified object name - S2 here - is evaluated as an object on the current schema before it is evaluated as a different schema.

It might not be a sequence; other objects can cause the same error. You can check for the existence of objects with the same name by querying the data dictionary.

select owner, object_type, object_name
from all_objects
where object_name = 'S2';

Why are empty catch blocks a bad idea?

This goes hand-in-hand with, "Don't use exceptions to control program flow.", and, "Only use exceptions for exceptional circumstances." If these are done, then exceptions should only be occurring when there's a problem. And if there's a problem, you don't want to fail silently. In the rare anomalies where it's not necessary to handle the problem you should at least log the exception, just in case the anomaly becomes no longer an anomaly. The only thing worse than failing is failing silently.

Elegant way to create empty pandas DataFrame with NaN of type float

Hope this can help!

 pd.DataFrame(np.nan, index = np.arange(<num_rows>), columns = ['A'])

get enum name from enum value

This is my take on it:

public enum LoginState { 
    LOGGED_IN(1), LOGGED_OUT(0), IN_TRANSACTION(-1);

    private int code;

    LoginState(int code) {
        this.code = code;
    }

    public int getCode() {
        return code;
    }

    public static LoginState getLoginStateFromCode(int code){
        for(LoginState e : LoginState.values()){
            if(code == e.code) return e;
        }
        return LoginState.LOGGED_OUT; //or null
    }
};

And I have used it with System Preferences in Android like so:

LoginState getLoginState(int i) {
    return LoginState.getLoginStateFromCode(
                prefs().getInt(SPK_IS_LOGIN, LoginState.LOGGED_OUT.getCode())
            );
}

public static void setLoginState(LoginState newLoginState) {
    editor().putInt(SPK_IS_LOGIN, newLoginState.getCode());
    editor().commit();
}

where pref and editor are SharedPreferences and a SharedPreferences.Editor

Decompile .smali files on an APK

No, APK Manager decompiles the .dex file into .smali and binary .xml to human readable xml.

The sequence (based on APK Manager 4.9) is 22 to select the package, and then 9 to decompile it. If you press 1 instead of 9, then you will just unpack it (useful only if you want to exchange .png images).

There is no tool available to decompile back to .java files and most probably it won't be any. There is an alternative, which is using dex2jar to transform the dex file in to a .class file, and then use a jar decompiler (such as the free jd-gui) to plain text java. The process is far from optimal, though, and it won't generate working code, but it's decent enough to be able to read it.

dex2jar: https://github.com/pxb1988/dex2jar

jd-gui: http://jd.benow.ca/

Edit: I knew there was somewhere here in SO a question with very similar answers... decompiling DEX into Java sourcecode

embedding image in html email

  1. You need 3 boundaries for inline images to be fully compliant.

  2. Everything goes inside the multipart/mixed.

  3. Then use the multipart/related to contain your multipart/alternative and your image attachment headers.

  4. Lastly, include your downloadable attachments inside the last boundary of multipart/mixed.

What is the difference between a strongly typed language and a statically typed language?

Strongly typed means that there are restrictions between conversions between types.

Statically typed means that the types are not dynamic - you can not change the type of a variable once it has been created.

Excel VBA: AutoFill Multiple Cells with Formulas

The approach you're looking for is FillDown. Another way so you don't have to kick your head off every time is to store formulas in an array of strings. Combining them gives you a powerful method of inputting formulas by the multitude. Code follows:

Sub FillDown()

    Dim strFormulas(1 To 3) As Variant

    With ThisWorkbook.Sheets("Sheet1")
        strFormulas(1) = "=SUM(A2:B2)"
        strFormulas(2) = "=PRODUCT(A2:B2)"
        strFormulas(3) = "=A2/B2"

        .Range("C2:E2").Formula = strFormulas
        .Range("C2:E11").FillDown
    End With

End Sub

Screenshots:

Result as of line: .Range("C2:E2").Formula = strFormulas:

enter image description here

Result as of line: .Range("C2:E11").FillDown:

enter image description here

Of course, you can make it dynamic by storing the last row into a variable and turning it to something like .Range("C2:E" & LRow).FillDown, much like what you did.

Hope this helps!

Stop a gif animation onload, on mouseover start the activation

No, you can't control the animation of the images.

You would need two versions of each image, one that is animated, and one that's not. On hover you can easily change from one image to another.

Example:

$(function(){
  $('img').each(function(e){
    var src = $(e).attr('src');
    $(e).hover(function(){
      $(this).attr('src', src.replace('.gif', '_anim.gif'));
    }, function(){
      $(this).attr('src', src);
    });
  });
});

Update:

Time goes by, and possibilities change. As kritzikatzi pointed out, having two versions of the image is not the only option, you can apparently use a canvas element to create a copy of the first frame of the animation. Note that this doesn't work in all browsers, IE 8 for example doesn't support the canvas element.

How to define optional methods in Swift protocol?

if you want to do it in pure swift the best way is to provide a default implementation particullary if you return a Swift type like for example struct with Swift types

example :

struct magicDatas {
    var damagePoints : Int?
    var manaPoints : Int?
}

protocol magicCastDelegate {
    func castFire() -> magicDatas
    func castIce() -> magicDatas
}

extension magicCastDelegate {
    func castFire() -> magicDatas {
        return magicDatas()
    }

    func castIce() -> magicDatas {
        return magicDatas()
    }
}

then you can implement protocol without defines every func

How can I calculate an md5 checksum of a directory?

I want to add that if you are trying to do this for files/directories in a git repository to track if they have changed, then this is the best approach:

git log -1 --format=format:%H --full-diff <file_or_dir_name>

And if it's not a git-directory/repo, then answer by @ire_and_curses is probably the best bet:

tar c <dir_name> | md5sum

However, please note that tar command will change the output hash if you run it in a different OS and stuff. If you want to be immune to that, this is the best approach, even though it doesn't look very elegant on first sight:

find <dir_name> -type f -print0 | sort -z | xargs -0 md5sum | md5sum | awk '{ print $1 }'

Alternate output format for psql

you can use the zenity to displays the query output as html table.

  • first implement bash script with following code:

    cat > '/tmp/sql.op'; zenity --text-info --html --filename='/tmp/sql.op';

    save it like mypager.sh

  • Then export the environment variable PAGER by set full path of the script as value.

    for example:- export PAGER='/path/mypager.sh'

  • Then login to the psql program then execute the command \H

  • And finally execute any query,the tabled output will displayed in the zenity in html table format.

Python decorators in classes

What you're wanting to do isn't possible. Take, for instance, whether or not the code below looks valid:

class Test(object):

    def _decorator(self, foo):
        foo()

    def bar(self):
        pass
    bar = self._decorator(bar)

It, of course, isn't valid since self isn't defined at that point. The same goes for Test as it won't be defined until the class itself is defined (which its in the process of). I'm showing you this code snippet because this is what your decorator snippet transforms into.

So, as you can see, accessing the instance in a decorator like that isn't really possible since decorators are applied during the definition of whatever function/method they are attached to and not during instantiation.

If you need class-level access, try this:

class Test(object):

    @classmethod
    def _decorator(cls, foo):
        foo()

    def bar(self):
        pass
Test.bar = Test._decorator(Test.bar)

How to disable a particular checkstyle rule for a particular line of code?

I had difficulty with the answers above, potentially because I set the checkStyle warnings to be errors. What did work was SuppressionFilter: http://checkstyle.sourceforge.net/config_filters.html#SuppressionFilter

The drawback of this is that the line range is stored in a separate suppresssions.xml file, so an unfamiliar developer may not immediately make the connection.

iOS 7's blurred overlay effect using CSS?

You made me want to try, so I did, check out the example here:

http://codepen.io/Edo_B/pen/cLbrt

Using:

  1. HW Accelerated CSS filters
  2. JS for class assigning and arrow key events
  3. Images CSS Clip property

that's it.

I also believe this could be done dynamically for any screen if using canvas to copy the current dom and blurring it.

Deserialize a JSON array in C#

[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("Age")]
public int required { get; set; }
[JsonProperty("Location")]
public string type { get; set; }

and Remove a "{"..,

strFieldString = strFieldString.Remove(0, strFieldString.IndexOf('{'));

DeserializeObject..,

   optionsItem objActualField = JsonConvert.DeserializeObject<optionsItem(strFieldString);

How can I sort generic list DESC and ASC?

Very simple way to sort List with int values in Descending order:

li.Sort((a,b)=> b-a);

Hope that this helps!

Where does the @Transactional annotation belong?

Transactional Annotations should be placed around all operations that are inseparable.

For example, your call is "change password". That consists of two operations

  1. Change the password.
  2. Audit the change.
  3. Email the client that the password has changed.

So in the above, if the audit fails, then should the password change also fail? If so, then the transaction should be around 1 and 2 (so at the service layer). If the email fails (probably should have some kind of fail safe on this so it won't fail) then should it roll back the change password and the audit?

These are the kind of questions you need to be asking when deciding where to put the @Transactional.

Node.js: Python not found exception due to node-sass and node-gyp

My machine is Windows 10, I've faced similar problems while tried to compile SASS using node-sass package. My node version is v10.16.3 and npm version is 6.9.0

The way that I resolved the problem:

  1. At first delete package-lock.json file and node_modules/ folder.
  2. Open Windows PowerShell as Administrator.
  3. Run the command npm i -g node-sass.
  4. After that, go to the project folder and run npm install
  5. And finally, run the SASS compiling script, in my case, it is npm run build:css

And it works!!

How should I do integer division in Perl?

Eg 9 / 4 = 2.25

int(9) / int(4) = 2

9 / 4 - remainder / deniminator = 2

9 /4 - 9 % 4 / 4 = 2

How to test my servlet using JUnit

Use Selenium for webbased unit tests. There's a Firefox plugin called Selenium IDE which can record actions on the webpage and export to JUnit testcases which uses Selenium RC to run the test server.

Formatting a Date String in React Native

The beauty of the React Native is that it supports lots of JS libraries like Moment.js. Using moment.js would be a better/easier way to handle date/time instead coding from scratch

just run this in the terminal (yarn add moment also works if using React's built-in package manager):

npm install moment --save

And in your React Native js page:

import Moment from 'moment';

render(){
    Moment.locale('en');
    var dt = '2016-05-02T00:00:00';
    return(<View> {Moment(dt).format('d MMM')} </View>) //basically you can do all sorts of the formatting and others
}

You may check the moment.js official docs here https://momentjs.com/docs/

How do I put an image into my picturebox using ImageLocation?

if you provide a bad path or a broken link, if the compiler cannot find the image, the picture box would display an X icon on its body.

PictureBox picture = new PictureBox
        {
            Name = "pictureBox",
            Size = new Size(100, 50),
            Location = new Point(14, 17),
            Image = Image.FromFile(@"c:\Images\test.jpg"),
            SizeMode = PictureBoxSizeMode.CenterImage
        };
p.Controls.Add(picture);

OR

PictureBox picture = new PictureBox
        {
            Name = "pictureBox",
            Size = new Size(100, 50),
            Location = new Point(14, 17),
            ImageLocation = @"c:\Images\test.jpg",
            SizeMode = PictureBoxSizeMode.CenterImage
        };
p.Controls.Add(picture);

i'm not sure where you put images in your folder structure but you can find the path as bellow

 picture.ImageLocation = Path.Combine(System.Windows.Forms.Application.StartupPath, "Resources\Images\1.jpg");

How to print multiple variable lines in Java

You can create Class Person with fields firstName and lastName and define method toString(). Here I created a util method which returns String presentation of a Person object.

This is a sample

Main

public class Main {

    public static void main(String[] args) {
        Person person = generatePerson();
        String personStr = personToString(person);
        System.out.println(personStr);
    }

    private static Person generatePerson() {
        String firstName = "firstName";//generateFirstName();
        String lastName = "lastName";//generateLastName;
        return new Person(firstName, lastName);
    }

    /*
     You can even put this method into a separate util class.
    */
    private static String personToString(Person person) {
        return person.getFirstName() + "\n" + person.getLastName();
    }
}

Person

public class Person {

    private String firstName;
    private String lastName;

    //getters, setters, constructors.
}

I prefer a separate util method to toString(), because toString() is used for debug. https://stackoverflow.com/a/3615741/4587961

I had experience writing programs with many outputs: HTML UI, excel or txt file, console. They may need different object presentation, so I created a util class which builds a String depending on the output.

How to remove "rows" with a NA value?

dat <- data.frame(x1 = c(1,2,3, NA, 5), x2 = c(100, NA, 300, 400, 500))

na.omit(dat)
  x1  x2
1  1 100
3  3 300
5  5 500

Unable to find the requested .Net Framework Data Provider in Visual Studio 2010 Professional

i had the same problem in visual studio 2019 and it resolved by searching in the searchbar inside visual studio: manage NuGet packages > oracle.ManagedDataAccess (first result) install it. and then it should works!

Vertically align text within a div

Try this:

HTML

<div><span>Text</span></div>

CSS

div {
    height: 100px;
}

span {
    height: 100px;
    display: table-cell;
    vertical-align: middle;
}

Parsing a JSON array using Json.Net

You can get at the data values like this:

string json = @"
[ 
    { ""General"" : ""At this time we do not have any frequent support requests."" },
    { ""Support"" : ""For support inquires, please see our support page."" }
]";

JArray a = JArray.Parse(json);

foreach (JObject o in a.Children<JObject>())
{
    foreach (JProperty p in o.Properties())
    {
        string name = p.Name;
        string value = (string)p.Value;
        Console.WriteLine(name + " -- " + value);
    }
}

Fiddle: https://dotnetfiddle.net/uox4Vt

How to display loading message when an iFrame is loading?

I have followed the following approach

First, add sibling div

$('<div class="loading"></div>').insertBefore("#Iframe");

and then when the iframe completed loading

$("#Iframe").load(function(){
   $(this).siblings(".loading-fetching-content").remove(); 
  });

How to write to files using utl_file in oracle

Here is a robust function for using UTL_File.putline that includes the necessary error handling. It also handles headers, footers and a few other exceptional cases.

PROCEDURE usp_OUTPUT_ToFileAscii(p_Path IN VARCHAR2, p_FileName IN VARCHAR2, p_Input IN refCursor, p_Header in VARCHAR2, p_Footer IN VARCHAR2, p_WriteMode VARCHAR2) IS

              vLine VARCHAR2(30000);
              vFile UTL_FILE.file_type; 
              vExists boolean;
              vLength number;
              vBlockSize number;
    BEGIN

        UTL_FILE.fgetattr(p_path, p_FileName, vExists, vLength, vBlockSize);

                 FETCH p_Input INTO vLine;
         IF p_input%ROWCOUNT > 0
         THEN
            IF vExists THEN
               vFile := UTL_FILE.FOPEN_NCHAR(p_Path, p_FileName, p_WriteMode);
            ELSE
               --even if the append flag is passed if the file doesn't exist open it with W.
                vFile := UTL_FILE.FOPEN(p_Path, p_FileName, 'W');
            END IF;
            --GET HANDLE TO FILE
            IF p_Header IS NOT NULL THEN 
              UTL_FILE.PUT_LINE(vFile, p_Header);
            END IF;
            UTL_FILE.PUT_LINE(vFile, vLine);
            DBMS_OUTPUT.PUT_LINE('Record count > 0');

             --LOOP THROUGH CURSOR VAR
             LOOP
                FETCH p_Input INTO vLine;

                EXIT WHEN p_Input%NOTFOUND;

                UTL_FILE.PUT_LINE(vFile, vLine);

             END LOOP;


             IF p_Footer IS NOT NULL THEN 
                UTL_FILE.PUT_LINE(vFile, p_Footer);
             END IF;

             CLOSE p_Input;
             UTL_FILE.FCLOSE(vFile);
        ELSE
          DBMS_OUTPUT.PUT_LINE('Record count = 0');

        END IF; 


    EXCEPTION
       WHEN UTL_FILE.INVALID_PATH THEN 
           DBMS_OUTPUT.PUT_LINE ('invalid_path'); 
           DBMS_OUTPUT.PUT_LINE(SQLERRM);
           RAISE;

       WHEN UTL_FILE.INVALID_MODE THEN 
           DBMS_OUTPUT.PUT_LINE ('invalid_mode'); 
           DBMS_OUTPUT.PUT_LINE(SQLERRM);
           RAISE;

       WHEN UTL_FILE.INVALID_FILEHANDLE THEN 
           DBMS_OUTPUT.PUT_LINE ('invalid_filehandle'); 
           DBMS_OUTPUT.PUT_LINE(SQLERRM);
           RAISE;

       WHEN UTL_FILE.INVALID_OPERATION THEN 
           DBMS_OUTPUT.PUT_LINE ('invalid_operation'); 
           DBMS_OUTPUT.PUT_LINE(SQLERRM);
           RAISE;

       WHEN UTL_FILE.READ_ERROR THEN  
           DBMS_OUTPUT.PUT_LINE ('read_error');
           DBMS_OUTPUT.PUT_LINE(SQLERRM);
           RAISE;

       WHEN UTL_FILE.WRITE_ERROR THEN 
          DBMS_OUTPUT.PUT_LINE ('write_error'); 
          DBMS_OUTPUT.PUT_LINE(SQLERRM);
           RAISE;

       WHEN UTL_FILE.INTERNAL_ERROR THEN 
          DBMS_OUTPUT.PUT_LINE ('internal_error'); 
          DBMS_OUTPUT.PUT_LINE(SQLERRM);
          RAISE;            
       WHEN OTHERS THEN
          DBMS_OUTPUT.PUT_LINE ('other write error'); 
          DBMS_OUTPUT.PUT_LINE(SQLERRM);
          RAISE;
    END;

How can I convert a string with dot and comma into a float in Python

s =  "123,456.908"
print float(s.replace(',', ''))

How to write a confusion matrix in Python?

Here is a simple implementation that handles an unequal number of classes in the predicted and actual labels (see examples 3 and 4). I hope this helps!

For folks just learning this, here's a quick review. The labels for the columns indicate the predicted class, and the labels for the rows indicate the correct class. In example 1, we have [3 1] on the top row. Again, rows indicate truth, so this means that the correct label is "0" and there are 4 examples with ground truth label of "0". Columns indicate predictions, so we have 3/4 of the samples correctly labeled as "0", but 1/4 was incorrectly labeled as a "1".

def confusion_matrix(actual, predicted):
    classes       = np.unique(np.concatenate((actual,predicted)))
    confusion_mtx = np.empty((len(classes),len(classes)),dtype=np.int)
    for i,a in enumerate(classes):
        for j,p in enumerate(classes):
            confusion_mtx[i,j] = np.where((actual==a)*(predicted==p))[0].shape[0]
    return confusion_mtx

Example 1:

actual    = np.array([1,1,1,1,0,0,0,0])
predicted = np.array([1,1,1,1,0,0,0,1])
confusion_matrix(actual,predicted)

   0  1
0  3  1
1  0  4

Example 2:

actual    = np.array(["a","a","a","a","b","b","b","b"])
predicted = np.array(["a","a","a","a","b","b","b","a"])
confusion_matrix(actual,predicted)

   0  1
0  4  0
1  1  3

Example 3:

actual    = np.array(["a","a","a","a","b","b","b","b"])
predicted = np.array(["a","a","a","a","b","b","b","z"]) # <-- notice the 3rd class, "z"
confusion_matrix(actual,predicted)

   0  1  2
0  4  0  0
1  0  3  1
2  0  0  0

Example 4:

actual    = np.array(["a","a","a","x","x","b","b","b"]) # <-- notice the 4th class, "x"
predicted = np.array(["a","a","a","a","b","b","b","z"])
confusion_matrix(actual,predicted)

   0  1  2  3
0  3  0  0  0
1  0  2  0  1
2  1  1  0  0
3  0  0  0  0

Declaring functions in JSP?

You need to enclose that in <%! %> as follows:

<%!

public String getQuarter(int i){
String quarter;
switch(i){
        case 1: quarter = "Winter";
        break;

        case 2: quarter = "Spring";
        break;

        case 3: quarter = "Summer I";
        break;

        case 4: quarter = "Summer II";
        break;

        case 5: quarter = "Fall";
        break;

        default: quarter = "ERROR";
}

return quarter;
}

%>

You can then invoke the function within scriptlets or expressions:

<%
     out.print(getQuarter(4));
%>

or

<%= getQuarter(17) %>

What is a non-capturing group in regular expressions?

I think I would give you the answer. Don't use capture variables without checking that the match succeeded.

The capture variables, $1, etc, are not valid unless the match succeeded, and they're not cleared, either.

#!/usr/bin/perl  
use warnings;
use strict;   
$_ = "bronto saurus burger";
if (/(?:bronto)? saurus (steak|burger)/)
{
    print "Fred wants a  $1";
}
else
{
    print "Fred dont wants a $1 $2";
}

In the above example, to avoid capturing bronto in $1, (?:) is used.

If the pattern is matched , then $1 is captured as next grouped pattern.

So, the output will be as below:

Fred wants a burger

It is Useful if you don't want the matches to be saved.

Why did my Git repo enter a detached HEAD state?

It can easily happen if you try to undo changes you've made by re-checking-out files and not quite getting the syntax right.

You can look at the output of git log - you could paste the tail of the log here since the last successful commit, and we could all see what you did. Or you could paste-bin it and ask nicely in #git on freenode IRC.

Rails 4: List of available datatypes

You might also find it useful to know generally what these data types are used for:

There's also references used to create associations. But, I'm not sure this is an actual data type.

New Rails 4 datatypes available in PostgreSQL:

  • :hstore - storing key/value pairs within a single value (learn more about this new data type)
  • :array - an arrangement of numbers or strings in a particular row (learn more about it and see examples)
  • :cidr_address - used for IPv4 or IPv6 host addresses
  • :inet_address - used for IPv4 or IPv6 host addresses, same as cidr_address but it also accepts values with nonzero bits to the right of the netmask
  • :mac_address - used for MAC host addresses

Learn more about the address datatypes here and here.

Also, here's the official guide on migrations: http://edgeguides.rubyonrails.org/migrations.html

Concatenate string with field value in MySQL

Have you tried using the concat() function?

ON tableTwo.query = concat('category_id=',tableOne.category_id)

Use of 'prototype' vs. 'this' in JavaScript?

Prototype is the template of the class; which applies to all future instances of it. Whereas this is the particular instance of the object.

How to download Visual Studio Community Edition 2015 (not 2017)

You can use these links to download Visual Studio 2015

Community Edition:

And for anyone in the future who might be looking for the other editions here are the links for them as well:

Professional Edition:

Enterprise Edition:

Short circuit Array.forEach like calling break

If you want to keep your forEach syntax, this is a way to keep it efficient (although not as good as a regular for loop). Check immediately for a variable that knows if you want to break out of the loop.

This example uses a anonymous function for creating a function scope around the forEach which you need to store the done information.

_x000D_
_x000D_
(function(){_x000D_
    var element = document.getElementById('printed-result');_x000D_
    var done = false;_x000D_
    [1,2,3,4].forEach(function(item){_x000D_
        if(done){ return; }_x000D_
        var text = document.createTextNode(item);_x000D_
        element.appendChild(text);_x000D_
        if (item === 2){_x000D_
          done = true;_x000D_
          return;_x000D_
        }_x000D_
    });_x000D_
})();
_x000D_
<div id="printed-result"></div>
_x000D_
_x000D_
_x000D_

My two cents.

Select multiple images from android gallery

A lot of these answers have similarities but are all missing the most important part which is in onActivityResult, check if data.getClipData is null before checking data.getData

The code to call the file chooser:

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*"); //allows any image file type. Change * to specific extension to limit it
//**The following line is the important one!
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURES); //SELECT_PICTURES is simply a global int used to check the calling intent in onActivityResult

The code to get all of the images selected:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == SELECT_PICTURES) {
        if(resultCode == Activity.RESULT_OK) {
            if(data.getClipData() != null) {
                int count = data.getClipData().getItemCount(); //evaluate the count before the for loop --- otherwise, the count is evaluated every loop.
                for(int i = 0; i < count; i++)  
                    Uri imageUri = data.getClipData().getItemAt(i).getUri();
                    //do something with the image (save it to some directory or whatever you need to do with it here) 
                }
            } else if(data.getData() != null) {
                String imagePath = data.getData().getPath();
                //do something with the image (save it to some directory or whatever you need to do with it here)
            }
        }
    }
}

Note that Android's chooser has Photos and Gallery available on some devices. Photos allows multiple images to be selected. Gallery allows just one at a time.

Install apps silently, with granted INSTALL_PACKAGES permission

An 3rd party application cannot install an Android App sliently. However, a 3rd party application can ask the Android OS to install a application.

So you should define this:

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file:///sdcard/app.apk", "application/vnd.android.package-archive");
startActivity(intent);

You can also try to install it as a system app to grant the permission and ignore this define. (Root Required)

You can run the following command on your 3rd party app to install an app on the rooted device.

The code is:

private void installApk(String filename) {
File file = new File(filename); 
if(file.exists()){
    try {   
        final String command = "pm install -r " + file.getAbsolutePath();
        Process proc = Runtime.getRuntime().exec(new String[] { "su", "-c", command });
        proc.waitFor();
    } catch (Exception e) {
        e.printStackTrace();
    }
 }
}

I hope that this answer is helpful for you.

Allowed memory size of X bytes exhausted

PHP's config can be set in multiple places:

  1. master system php.ini (usually in /etc somewhere)
  2. somewhere in Apache's configuration (httpd.conf or a per-site .conf file, via php_value)
  3. CLI & CGI can have a different php.ini (use the command php -i | grep memory_limit to check the CLI conf)
  4. local .htaccess files (also php_value)
  5. in-script (via ini_set())

In PHPinfo's output, the "Master" value is the compiled-in default value, and the "Local" value is what's actually in effect. It can be either unchanged from the default, or overridden in any of the above locations.

Also note that PHP generally has different .ini files for command-line and webserver-based operation. Checking phpinfo() from the command line will report different values than if you'd run it in a web-based script.

Easiest way to ignore blank lines when reading a file in Python

Why are you all going the hard way?

with open("myfile") as myfile:
    nonempty = filter(str.rstrip, myfile)

Convert nonempty into a list if you have the urge to do so, although I highly suggest keeping nonempty a generator as it is in Python 3.x

In Python 2.x you may use itertools.ifilter to do your bidding instead.

Boolean checking in the 'if' condition

This is more readable and good practice too.

if(!status){
//do sth
}else{
//do sth
}

Sending GET request with Authentication headers using restTemplate

Here's a super-simple example with basic authentication, headers, and exception handling...

private HttpHeaders createHttpHeaders(String user, String password)
{
    String notEncoded = user + ":" + password;
    String encodedAuth = "Basic " + Base64.getEncoder().encodeToString(notEncoded.getBytes());
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.add("Authorization", encodedAuth);
    return headers;
}

private void doYourThing() 
{
    String theUrl = "http://blah.blah.com:8080/rest/api/blah";
    RestTemplate restTemplate = new RestTemplate();
    try {
        HttpHeaders headers = createHttpHeaders("fred","1234");
        HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
        ResponseEntity<String> response = restTemplate.exchange(theUrl, HttpMethod.GET, entity, String.class);
        System.out.println("Result - status ("+ response.getStatusCode() + ") has body: " + response.hasBody());
    }
    catch (Exception eek) {
        System.out.println("** Exception: "+ eek.getMessage());
    }
}

What's the difference between ngOnInit and ngAfterViewInit of Angular2?

ngOnInit() is called after ngOnChanges() was called the first time. ngOnChanges() is called every time inputs are updated by change detection.

ngAfterViewInit() is called after the view is initially rendered. This is why @ViewChild() depends on it. You can't access view members before they are rendered.

Command Prompt Error 'C:\Program' is not recognized as an internal or external command, operable program or batch file

Go to Start and search for cmd. Right click on it, properties then set the Target path in quotes. This worked fine for me.

Facebook Android Generate Key Hash

If you are releasing, use the keystore you used to export your app with and not the debug.keystore.

Warning: Failed propType: Invalid prop `component` supplied to `Route`

In some cases, such as routing with a component that's wrapped with redux-form, replacing the Route component argument on this JSX element:

<Route path="speaker" component={Speaker}/>

With the Route render argument like the following, will fix issue:

<Route path="speaker" render={props => <Speaker {...props} />} />

Storing Images in DB - Yea or Nay?

I'm in charge of some applications that manage many TB of images. We've found that storing file paths in the database to be best.

There are a couple of issues:

  • database storage is usually more expensive than file system storage
  • you can super-accelerate file system access with standard off the shelf products
    • for example, many web servers use the operating system's sendfile() system call to asynchronously send a file directly from the file system to the network interface. Images stored in a database don't benefit from this optimization.
  • things like web servers, etc, need no special coding or processing to access images in the file system
  • databases win out where transactional integrity between the image and metadata are important.
    • it is more complex to manage integrity between db metadata and file system data
    • it is difficult (within the context of a web application) to guarantee data has been flushed to disk on the filesystem

What's the advantage of a Java enum versus a class with public static final fields?

There are many good answers here, but none mentiones that there are highly optimized implementations of the Collection API classes/interfaces specifically for enums:

These enum specific classes only accept Enum instances (the EnumMap only accept Enums only as keys), and whenever possible, they revert to compact representation and bit manipulation in their implementation.

What does this mean?

If our Enum type has no more that 64 elements (most of real-life Enum examples will qualify for this), the implementations store the elements in a single long value, each Enum instance in question will be associated with a bit of this 64-bit long long. Adding an element to an EnumSet is simply just setting the proper bit to 1, removing it is just setting that bit to 0. Testing if an element is in the Set is just one bitmask test! Now you gotta love Enums for this!

Determining 32 vs 64 bit in C++

That won't work on Windows for a start. Longs and ints are both 32 bits whether you're compiling for 32 bit or 64 bit windows. I would think checking if the size of a pointer is 8 bytes is probably a more reliable route.

changing visibility using javascript

Use display instead of visibility. display: none for invisible and no setting for visible.

Key Listeners in python?

I was searching for a simple solution without window focus. Jayk's answer, pynput, works perfect for me. Here is the example how I use it.

from pynput import keyboard

def on_press(key):
    if key == keyboard.Key.esc:
        return False  # stop listener
    try:
        k = key.char  # single-char keys
    except:
        k = key.name  # other keys
    if k in ['1', '2', 'left', 'right']:  # keys of interest
        # self.keys.append(k)  # store it in global-like variable
        print('Key pressed: ' + k)
        return False  # stop listener; remove this if want more keys

listener = keyboard.Listener(on_press=on_press)
listener.start()  # start to listen on a separate thread
listener.join()  # remove if main thread is polling self.keys

Parsing a YAML file in Python, and accessing the data?

Since PyYAML's yaml.load() function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:

import yaml
with open('tree.yaml', 'r') as f:
    doc = yaml.load(f)

To access branch1 text you would use:

txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"

because, in your YAML document, the value of the branch1 key is under the treeroot key.

String.equals() with multiple conditions (and one action on result)

Possibilities:

  • Use String.equals():

    if (some_string.equals("john") ||
        some_string.equals("mary") ||
        some_string.equals("peter"))
    {
    }
    
  • Use a regular expression:

    if (some_string.matches("john|mary|peter"))
    {
    }
    
  • Store a list of strings to be matched against in a Collection and search the collection:

    Set<String> names = new HashSet<String>();
    names.add("john");
    names.add("mary");
    names.add("peter");
    
    if (names.contains(some_string))
    {
    }
    

GridLayout and Row/Column Span Woe

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <GridLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:columnCount="8"
        android:rowCount="7" >

        <TextView
            android:layout_width="50dip"
            android:layout_height="50dip"
            android:layout_columnSpan="2"
            android:layout_rowSpan="2"
            android:background="#a30000"
            android:gravity="center"
            android:text="1"
            android:textColor="@android:color/white"
            android:textSize="20dip" />

        <TextView
            android:layout_width="50dip"
            android:layout_height="25dip"
            android:layout_columnSpan="2"
            android:layout_rowSpan="1"
            android:background="#0c00a3"
            android:gravity="center"
            android:text="2"
            android:textColor="@android:color/white"
            android:textSize="20dip" />

        <TextView
            android:layout_width="25dip"
            android:layout_height="100dip"
            android:layout_columnSpan="1"
            android:layout_rowSpan="4"
            android:background="#00a313"
            android:gravity="center"
            android:text="3"
            android:textColor="@android:color/white"
            android:textSize="20dip" />

        <TextView
            android:layout_width="75dip"
            android:layout_height="50dip"
            android:layout_columnSpan="3"
            android:layout_rowSpan="2"
            android:background="#a29100"
            android:gravity="center"
            android:text="4"
            android:textColor="@android:color/white"
            android:textSize="20dip" />

        <TextView
            android:layout_width="75dip"
            android:layout_height="25dip"
            android:layout_columnSpan="3"
            android:layout_rowSpan="1"
            android:background="#a500ab"
            android:gravity="center"
            android:text="5"
            android:textColor="@android:color/white"
            android:textSize="20dip" />

        <TextView
            android:layout_width="50dip"
            android:layout_height="25dip"
            android:layout_columnSpan="2"
            android:layout_rowSpan="1"
            android:background="#00a9ab"
            android:gravity="center"
            android:text="6"
            android:textColor="@android:color/white"
            android:textSize="20dip" />
    </GridLayout>

</RelativeLayout>

ScreenShot

Python if-else short-hand

Try this:

x = a > b and 10 or 11

This is a sample of execution:

>>> a,b=5,7
>>> x = a > b and 10 or 11
>>> print x
11

What difference between the DATE, TIME, DATETIME, and TIMESTAMP Types

I have a slightly different perspective on the difference between a DATETIME and a TIMESTAMP. A DATETIME stores a literal value of a date and time with no reference to any particular timezone. So, I can set a DATETIME column to a value such as '2019-01-16 12:15:00' to indicate precisely when my last birthday occurred. Was this Eastern Standard Time? Pacific Standard Time? Who knows? Where the current session time zone of the server comes into play occurs when you set a DATETIME column to some value such as NOW(). The value stored will be the current date and time using the current session time zone in effect. But once a DATETIME column has been set, it will display the same regardless of what the current session time zone is.

A TIMESTAMP column on the other hand takes the '2019-01-16 12:15:00' value you are setting into it and interprets it in the current session time zone to compute an internal representation relative to 1/1/1970 00:00:00 UTC. When the column is displayed, it will be converted back for display based on whatever the current session time zone is. It's a useful fiction to think of a TIMESTAMP as taking the value you are setting and converting it from the current session time zone to UTC for storing and then converting it back to the current session time zone for displaying.

If my server is in San Francisco but I am running an event in New York that starts on 9/1/1029 at 20:00, I would use a TIMESTAMP column for holding the start time, set the session time zone to 'America/New York' and set the start time to '2009-09-01 20:00:00'. If I want to know whether the event has occurred or not, regardless of the current session time zone setting I can compare the start time with NOW(). Of course, for displaying in a meaningful way to a perspective customer, I would need to set the correct session time zone. If I did not need to do time comparisons, then I would probably be better off just using a DATETIME column, which will display correctly (with an implied EST time zone) regardless of what the current session time zone is.

TIMESTAMP LIMITATION

The TIMESTAMP type has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC and so it may not usable for your particular application. In that case you will have to use a DATETIME type. You will, of course, always have to be concerned that the current session time zone is set properly whenever you are using this type with date functions such as NOW().

How to add buttons like refresh and search in ToolBar in Android?

OK, I got the icons because I wrote in menu.xml android:showAsAction="ifRoom" instead of app:showAsAction="ifRoom" since i am using v7 library.

However the title is coming at center of extended toolbar. How to make it appear at the top?

Can't open file 'svn/repo/db/txn-current-lock': Permission denied

I just had this problem

  1. Having multiple user using the same repo caused the problem
  2. Logout evey other user using the repo

Hope this helps

video as site background? HTML 5

First, your HTML markup looks like this:

<video id="awesome_video" src="first_video.mp4" autoplay />

Second, your JavaScript code will look like this:

<script type="text/javascript">
  var index = 1,
      playlist = ['first_video.mp4', 'second_video.mp4', 'third_video.mp4'],
      video = document.getElementById('awesome_video');

  video.addEventListener('ended', rotate_video, false);

  function rotate_video() {
    video.setAttribute('src', playlist[index]);
    video.load();
    index++;
    if (index >= playlist.length) { index = 0; }
  }
</script>

And last but not least, your CSS:

#awesome_video { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }

This will create a video element on your page that starts playing the first video right away, then iterates through the playlist defined by the JavaScript variable. Your mileage with the CSS may vary depending on the CSS for the rest of the site, but 100% width/height should do it on a basic page.

Attach Authorization header for all axios requests

Sometimes you get a case where some of the requests made with axios are pointed to endpoints that do not accept authorization headers. Thus, alternative way to set authorization header only on allowed domain is as in the example below. Place the following function in any file that gets executed each time React application runs such as in routes file.

export default () => {
    axios.interceptors.request.use(function (requestConfig) {
        if (requestConfig.url.indexOf(<ALLOWED_DOMAIN>) > -1) {
            const token = localStorage.token;
            requestConfig.headers['Authorization'] = `Bearer ${token}`;
        }

        return requestConfig;
    }, function (error) {
        return Promise.reject(error);
    });

}

how to get the host url using javascript from the current page

To get the hostname: location.hostname

But your example is looking for the scheme as well, so location.origin appears to do what you want in Chrome, but gets not mention in the Mozdev docs. You can construct it with

location.protocol + '//' + location.hostname

If you want the port number as well (for when it isn't 80) then:

location.protocol + '//' + location.host

Where can I download the jar for org.apache.http package?

At the Maven repo, there are samples to add the dependency in maven, sbt, gradle, etc.

https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore/4.4.11

ie for Maven, you just create a project, for example

mvn archetype:generate -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4

then look at the pom.xml, then at the library at the dependencies xml element:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpcore</artifactId>
    <version>4.4.11</version>
</dependency>

For sbt do something like

sbt new scala/hello-world.g8

then edit the build.sbt to add the library

libraryDependencies += "org.apache.httpcomponents" % "httpcore" % "4.4.11"

How to SELECT WHERE NOT EXIST using LINQ?

The outcome sql will be different but the result should be the same:

var shifts = Shifts.Where(s => !EmployeeShifts.Where(es => es.ShiftID == s.ShiftID).Any());

Error Code: 1062. Duplicate entry '1' for key 'PRIMARY'

When I get this kind of error I had to update the data type by a notch. For Example, if I have it as "tiny int" change it to "small int" ~ Nita

How to embed a video into GitHub README.md?

I strongly recommend placing the video in a project website created with GitHub Pages instead of the readme, like described in VonC's answer; it will be a lot better than any of these ideas. But if you need a quick fix just like I needed, here are some suggestions.

Use a gif

See aloisdg's answer, result is awesome, gifs are rendered on github's readme ;)

Use a video player picture

You could trick the user into thinking the video is on the readme page with a picture. It sounds like an ad trick, it's not perfect, but it works and it's funny ;).

Example:

[![Watch the video](https://i.imgur.com/vKb2F1B.png)](https://youtu.be/vt5fpE0bzSY)

Result:

Watch the video

Use youtube's preview picture

You can also use the picture generated by youtube for your video.

For youtube urls in the form of:

https://www.youtube.com/watch?v=<VIDEO ID>
https://youtu.be/<VIDEO URL>

The preview urls are in the form of:

https://img.youtube.com/vi/<VIDEO ID>/maxresdefault.jpg
https://img.youtube.com/vi/<VIDEO ID>/hqdefault.jpg

Example:

[![Watch the video](https://img.youtube.com/vi/T-D1KVIuvjA/maxresdefault.jpg)](https://youtu.be/T-D1KVIuvjA)

Result:

Watch the video

Use asciinema

If your use case is something that runs in a terminal, asciinema lets you record a terminal session and has nice markdown embedding.

Hit share button and copy the markdown snippet.

Example:

[![asciicast](https://asciinema.org/a/113463.png)](https://asciinema.org/a/113463)

Result:

asciicast

How to allow access outside localhost

Using ng serve --host 0.0.0.0 will allow you to connect to the ng serve using your ip instead of localhost.

EDIT

In newer versions of the cli, you have to provide your local ip address instead

EDIT 2

In newer versions of the cli (I think v5 and up) you can use 0.0.0.0 as the ip again to host it for anyone on your network to talk to.

Convert JSON String to JSON Object c#

This works

    string str = "{ 'context_name': { 'lower_bound': 'value', 'pper_bound': 'value', 'values': [ 'value1', 'valueN' ] } }";
    JavaScriptSerializer j = new JavaScriptSerializer();
    object a = j.Deserialize(str, typeof(object));

Update Git branches from master

You have basically two options:

  1. You merge. That is actually quite simple, and a perfectly local operation:

    git checkout b1
    git merge master
    # repeat for b2 and b3
    

    This leaves the history exactly as it happened: You forked from master, you made changes to all branches, and finally you incorporated the changes from master into all three branches.

    git can handle this situation really well, it is designed for merges happening in all directions, at the same time. You can trust it be able to get all threads together correctly. It simply does not care whether branch b1 merges master, or master merges b1, the merge commit looks all the same to git. The only difference is, which branch ends up pointing to this merge commit.

  2. You rebase. People with an SVN, or similar background find this more intuitive. The commands are analogue to the merge case:

    git checkout b1
    git rebase master
    # repeat for b2 and b3
    

    People like this approach because it retains a linear history in all branches. However, this linear history is a lie, and you should be aware that it is. Consider this commit graph:

    A --- B --- C --- D <-- master
     \
      \-- E --- F --- G <-- b1
    

    The merge results in the true history:

    A --- B --- C --- D <-- master
     \                 \
      \-- E --- F --- G +-- H <-- b1
    

    The rebase, however, gives you this history:

    A --- B --- C --- D <-- master
                       \
                        \-- E' --- F' --- G' <-- b1
    

    The point is, that the commits E', F', and G' never truly existed, and have likely never been tested. They may not even compile. It is actually quite easy to create nonsensical commits via a rebase, especially when the changes in master are important to the development in b1.

    The consequence of this may be, that you can't distinguish which of the three commits E, F, and G actually introduced a regression, diminishing the value of git bisect.

    I am not saying that you shouldn't use git rebase. It has its uses. But whenever you do use it, you need to be aware of the fact that you are lying about history. And you should at least compile test the new commits.

How to use RANK() in SQL Server

SELECT contendernum,totals, RANK() OVER (ORDER BY totals ASC) AS xRank FROM
(
SELECT ContenderNum ,SUM(Criteria1+Criteria2+Criteria3+Criteria4) AS totals
FROM dbo.Cat1GroupImpersonation
 GROUP BY ContenderNum
) AS a

Unable to run Java GUI programs with Ubuntu

Check your X Window environment variables using the "env" command.

How can I check if a Perl module is installed on my system from the command line?

Bravo for @user80168's solution (I'm still counting \'s !) but to avoid all the escaping involved with aliases and shells:

%~/ cat ~/bin/perlmod
perl -le'eval qq{require $ARGV[0]; } 
    ? print ( "Found $ARGV[0] Version: ", eval "$ARGV[0]->VERSION" ) 
    : print "Not installed" ' $1

works reasonably well.

Here might be the simplest and most "modern" approach, using Module::Runtime:

perl -MModule::Runtime=use_module -E '
     say "$ARGV[0] ", use_module($ARGV[0])->VERSION' DBI

This will give a useful error if the module is not installed.

Using -MModule::Runtime requires it to be installed (it is not a core module).

ReferenceError: variable is not defined

Variables are available only in the scope you defined them. If you define a variable inside a function, you won't be able to access it outside of it.

Define variable with var outside the function (and of course before it) and then assign 10 to it inside function:

var value;
$(function() {
  value = "10";
});
console.log(value); // 10

Note that you shouldn't omit the first line in this code (var value;), because otherwise you are assigning value to undefined variable. This is bad coding practice and will not work in strict mode. Defining a variable (var variable;) and assigning value to a variable (variable = value;) are two different things. You can't assign value to variable that you haven't defined.

It might be irrelevant here, but $(function() {}) is a shortcut for $(document).ready(function() {}), which executes a function as soon as document is loaded. If you want to execute something immediately, you don't need it, otherwise beware that if you run it before DOM has loaded, value will be undefined until it has loaded, so console.log(value); placed right after $(function() {}) will return undefined. In other words, it would execute in following order:

var value;
console.log(value);
value = "10";

See also:

How do I adb pull ALL files of a folder present in SD Card

Please try with just giving the path from where you want to pull the files I just got the files from sdcard like

adb pull sdcard/

do NOT give * like to broaden the search or to filter out. ex: adb pull sdcard/*.txt --> this is invalid.

just give adb pull sdcard/

What does the 'static' keyword do in a class?

Can also think of static members not having a "this" pointer. They are shared among all instances.

Reading rows from a CSV file in Python

Example:

import pandas as pd

data = pd.read_csv('data.csv')

# read row line by line
for d in data.values:
  # read column by index
  print(d[2])

Open a folder using Process.Start

You should use one of the System.Diagnostics.Process.Start() overloads. It's quite simple!

If you don't place the filename of the process you want to run (explorer.exe), the system will recognize it as a valid folder path and try to attach it to the already running Explorer process. In this case, if the folder is already open, Explorer will do nothing.

If you place the filename of the process (as you did), the system will try to run a new instance of the process, passing the second string as a parameter. If the string is a valid folder, it is opened on the newly created process, if not, the new process will do nothing.

I don't know how invalid folder paths are treated by the process in any case. Using System.IO.Directory.Exists() should be enough to ensure that.

How to change the status bar background color and text color on iOS 7?

While handling the background color of status bar in iOS 7, there are 2 cases

Case 1: View with Navigation Bar

In this case use the following code in your viewDidLoad method

 UIApplication *app = [UIApplication sharedApplication];
 CGFloat statusBarHeight = app.statusBarFrame.size.height;

 UIView *statusBarView = [[UIView alloc] initWithFrame:CGRectMake(0, -statusBarHeight, [UIScreen mainScreen].bounds.size.width, statusBarHeight)];
 statusBarView.backgroundColor = [UIColor yellowColor];
 [self.navigationController.navigationBar addSubview:statusBarView];

Case 2: View without Navigation Bar

In this case use the following code in your viewDidLoad method

 UIApplication *app = [UIApplication sharedApplication];
 CGFloat statusBarHeight = app.statusBarFrame.size.height;

 UIView *statusBarView =  [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, statusBarHeight)];
 statusBarView.backgroundColor  =  [UIColor yellowColor];
 [self.view addSubview:statusBarView];

Source link http://code-ios.blogspot.in/2014/08/how-to-change-background-color-of.html

_DEBUG vs NDEBUG

Is NDEBUG standard?

Yes it is a standard macro with the semantic "Not Debug" for C89, C99, C++98, C++2003, C++2011, C++2014 standards. There are no _DEBUG macros in the standards.

C++2003 standard send the reader at "page 326" at "17.4.2.1 Headers" to standard C.

That NDEBUG is similar as This is the same as the Standard C library.

In C89 (C programmers called this standard as standard C) in "4.2 DIAGNOSTICS" section it was said

http://port70.net/~nsz/c/c89/c89-draft.html

If NDEBUG is defined as a macro name at the point in the source file where is included, the assert macro is defined simply as

     #define assert(ignore) ((void)0)

If look at the meaning of _DEBUG macros in Visual Studio https://msdn.microsoft.com/en-us/library/b0084kay.aspx then it will be seen, that this macro is automatically defined by your ?hoice of language runtime library version.

What are the uses of the exec command in shell scripts?

The exec built-in command mirrors functions in the kernel, there are a family of them based on execve, which is usually called from C.

exec replaces the current program in the current process, without forking a new process. It is not something you would use in every script you write, but it comes in handy on occasion. Here are some scenarios I have used it;

  1. We want the user to run a specific application program without access to the shell. We could change the sign-in program in /etc/passwd, but maybe we want environment setting to be used from start-up files. So, in (say) .profile, the last statement says something like:

     exec appln-program
    

    so now there is no shell to go back to. Even if appln-program crashes, the end-user cannot get to a shell, because it is not there - the exec replaced it.

  2. We want to use a different shell to the one in /etc/passwd. Stupid as it may seem, some sites do not allow users to alter their sign-in shell. One site I know had everyone start with csh, and everyone just put into their .login (csh start-up file) a call to ksh. While that worked, it left a stray csh process running, and the logout was two stage which could get confusing. So we changed it to exec ksh which just replaced the c-shell program with the korn shell, and made everything simpler (there are other issues with this, such as the fact that the ksh is not a login-shell).

  3. Just to save processes. If we call prog1 -> prog2 -> prog3 -> prog4 etc. and never go back, then make each call an exec. It saves resources (not much, admittedly, unless repeated) and makes shutdown simplier.

You have obviously seen exec used somewhere, perhaps if you showed the code that's bugging you we could justify its use.

Edit: I realised that my answer above is incomplete. There are two uses of exec in shells like ksh and bash - used for opening file descriptors. Here are some examples:

exec 3< thisfile          # open "thisfile" for reading on file descriptor 3
exec 4> thatfile          # open "thatfile" for writing on file descriptor 4
exec 8<> tother           # open "tother" for reading and writing on fd 8
exec 6>> other            # open "other" for appending on file descriptor 6
exec 5<&0                 # copy read file descriptor 0 onto file descriptor 5
exec 7>&4                 # copy write file descriptor 4 onto 7
exec 3<&-                 # close the read file descriptor 3
exec 6>&-                 # close the write file descriptor 6

Note that spacing is very important here. If you place a space between the fd number and the redirection symbol then exec reverts to the original meaning:

  exec 3 < thisfile       # oops, overwrite the current program with command "3"

There are several ways you can use these, on ksh use read -u or print -u, on bash, for example:

read <&3
echo stuff >&4

How to rename a table in SQL Server?

Table Name

sp_rename 'db_name.old_table_name', 'new_table_name'

Column

sp_rename 'db_name.old_table_name.name' 'userName', 'COLUMN'

Index

sp_rename 'db_name.old_table_name.id', 'product_ID', 'INDEX'

also available for statics and datatypes

How to clear gradle cache?

In android studio open View > Tool Windows > Terminal and execute the following commands

On Windows:

gradlew cleanBuildCache

On Mac or Linux:

./gradlew cleanBuildCache

if you want to disable the cache from your project add this into the gradle build properties

(Warning: this may slow your PC performance if there is no cache than same time will consume after every time during the run app)

android.enableBuildCache=false

UIView's frame, bounds, center, origin, when to use what?

The properties center, bounds and frame are interlocked: changing one will update the others, so use them however you want. For example, instead of modifying the x/y params of frame to recenter a view, just update the center property.

How can I get the Google cache age of any URL or web page?

You can use this site: https://cachedviews.com/ . Cache View or Cached Pages of Any Website - Google Cached Pages of Any Website

How to add leading zeros for for-loop in shell?

Use the following syntax:

$ for i in {01..05}; do echo "$i"; done
01
02
03
04
05

Disclaimer: Leading zeros only work in >=bash-4.

If you want to use printf, nothing prevents you from putting its result in a variable for further use:

$ foo=$(printf "%02d" 5)
$ echo "${foo}"
05

Date Comparison using Java

Date#equals() and Date#after()

If there is a possibility that the hour and minute fields are != 0, you'd have to set them to 0.

I can't forget to mention that using java.util.Date is considered a bad practice, and most of its methods are deprecated. Use java.util.Calendar or JodaTime, if possible.

Setting std=c99 flag in GCC

How about alias gcc99= gcc -std=c99?

ORA-01861: literal does not match format string

A simple view like this was giving me the ORA-01861 error when executed from Entity Framework:

create view myview as 
select * from x where x.initialDate >= '01FEB2021'

Just did something like this to fix it:

create view myview as 
select * from x where x.initialDate >= TO_DATE('2021-02-01', 'YYYY-MM-DD')

I think the problem is EF date configuration is not the same as Oracle's.

How to validate inputs dynamically created using ng-repeat, ng-show (angular)

If your using ng-repeat $index works like this

  name="QTY{{$index}}"

and

   <td>
       <input ng-model="r.QTY" class="span1" name="QTY{{$index}}" ng-            
        pattern="/^[\d]*\.?[\d]*$/" required/>
        <span class="alert-error" ng-show="form['QTY' + $index].$error.pattern">
        <strong>Requires a number.</strong></span>
        <span class="alert-error" ng-show="form['QTY' + $index].$error.required">
       <strong>*Required</strong></span>
    </td>

we have to show the ng-show in ng-pattern

   <span class="alert-error" ng-show="form['QTY' + $index].$error.pattern">
   <span class="alert-error" ng-show="form['QTY' + $index].$error.required">

python requests get cookies

Alternatively, you can use requests.Session and observe cookies before and after a request:

>>> import requests
>>> session = requests.Session()
>>> print(session.cookies.get_dict())
{}
>>> response = session.get('http://google.com')
>>> print(session.cookies.get_dict())
{'PREF': 'ID=5514c728c9215a9a:FF=0:TM=1406958091:LM=1406958091:S=KfAG0U9jYhrB0XNf', 'NID': '67=TVMYiq2wLMNvJi5SiaONeIQVNqxSc2RAwVrCnuYgTQYAHIZAGESHHPL0xsyM9EMpluLDQgaj3db_V37NjvshV-eoQdA8u43M8UwHMqZdL-S2gjho8j0-Fe1XuH5wYr9v'}

How to style an asp.net menu with CSS

I remember the StaticSelectedStyle-CssClass attribute used to work in ASP.NET 2.0. And in .NET 4.0 if you change the Menu control's RenderingMode attribute "Table" (thus making it render the menu as s and sub-s like it did back '05) it will at least write your specified StaticSelectedStyle-CssClass into the proper html element.

That may be enough for you page to work like you want. However my work-around for the selected menu item in ASP 4.0 (when leaving RenderingMode to its default), is to mimic the control's generated "selected" CSS class but give mine the "!important" CSS declaration so my styles take precedence where needed.

For instance by default the Menu control renders an "li" element and child "a" for each menu item and the selected menu item's "a" element will contain class="selected" (among other control generated CSS class names including "static" if its a static menu item), therefore I add my own selector to the page (or in a separate stylesheet file) for "static" and "selected" "a" tags like so:

a.selected.static
{
background-color: #f5f5f5 !important;
border-top: Red 1px solid !important;
border-left: Red 1px solid !important;
border-right: Red 1px solid !important;
} 

HttpServletRequest - Get query string parameters, no form data

As the other answers state there is no way getting query string parameters using servlet api.

So, I think the best way to get query parameters is parsing the query string yourself. ( It is more complicated iterating over parameters and checking if query string contains the parameter)

I wrote below code to get query string parameters. Using apache StringUtils and ArrayUtils which supports CSV separated query param values as well.

Example: username=james&username=smith&password=pwd1,pwd2 will return

password : [pwd1, pwd2] (length = 2)

username : [james, smith] (length = 2)

public static Map<String, String[]> getQueryParameters(HttpServletRequest request) throws UnsupportedEncodingException {
    Map<String, String[]> queryParameters = new HashMap<>();
    String queryString = request.getQueryString();
    if (StringUtils.isNotEmpty(queryString)) {
        queryString = URLDecoder.decode(queryString, StandardCharsets.UTF_8.toString());
        String[] parameters = queryString.split("&");
        for (String parameter : parameters) {
            String[] keyValuePair = parameter.split("=");
            String[] values = queryParameters.get(keyValuePair[0]);
            //length is one if no value is available.
            values = keyValuePair.length == 1 ? ArrayUtils.add(values, "") :
                    ArrayUtils.addAll(values, keyValuePair[1].split(",")); //handles CSV separated query param values.
            queryParameters.put(keyValuePair[0], values);
        }
    }
    return queryParameters;
}

Get div's offsetTop positions in React

I do realize that the author asks question in relation to a class-based component, however I think it's worth mentioning that as of React 16.8.0 (February 6, 2019) you can take advantage of hooks in function-based components.

Example code:

import { useRef } from 'react'

function Component() {
  const inputRef = useRef()

  return (
    <input ref={inputRef} />
    <div
      onScroll={() => {
        const { offsetTop } = inputRef.current
        ...
      }}
    >
  )
}

XPath query to get nth instance of an element

This is a FAQ:

//somexpression[$N]

means "Find every node selected by //somexpression that is the $Nth child of its parent".

What you want is:

(//input[@id="search_query"])[2]

Remember: The [] operator has higher precedence (priority) than the // abbreviation.

LISTAGG in Oracle to return distinct values

Has anyone thought of using a PARTITION BY clause? It worked for me in this query to get a list of application services and the access.

SELECT DISTINCT T.APP_SVC_ID, 
       LISTAGG(RTRIM(T.ACCESS_MODE), ',') WITHIN GROUP(ORDER BY T.ACCESS_MODE) OVER(PARTITION BY T.APP_SVC_ID) AS ACCESS_MODE 
  FROM APP_SVC_ACCESS_CNTL T 
 GROUP BY T.ACCESS_MODE, T.APP_SVC_ID

I had to cut out my where clause for NDA, but you get the idea.

How to show math equations in general github's markdown(not github's blog)

But github show nothing for the math symbols! please help me, thanks!

GitHub markdown parsing is performed by the SunDown (ex libUpSkirt) library.

The motto of the library is "Standards compliant, fast, secure markdown processing library in C". The important word being "secure" there, considering your question :).

Indeed, allowing javascript to be executed would be a bit off of the MarkDown standard text-to-HTML contract.

Moreover, everything that looks like a HTML tag is either escaped or stripped out.

Tell me how to show math symbols in general github markdown.

Your best bet would be to find a website similar to yuml.me which can generate on-the-fly images from by parsing the provided URL querystring.

Update

I've found some sites providing users with such service: codedogs.com (no longer seems to support embedding) or iTex2Img. You may want to try them out. Of course, others may exist and some Google-fu will help you find them.

given the following markdown syntax

![equation](http://www.sciweavers.org/tex2img.php?eq=1%2Bsin%28mc%5E2%29&bc=White&fc=Black&im=jpg&fs=12&ff=arev&edit=)

it will display the following image

equation http://www.sciweavers.org/tex2img.php?eq=1%2Bsin%28mc%5E2%29&bc=White&fc=Black&im=jpg&fs=12&ff=arev&edit=

Note: In order for the image to be properly displayed, you'll have to ensure the querystring part of the url is percent encoded. You can easily find online tools to help you with that task, such as www.url-encode-decode.com

How can I check if a URL exists via PHP?

kind of an old thread, but.. i do this:

$file = 'http://www.google.com';
$file_headers = @get_headers($file);
if ($file_headers) {
    $exists = true;
} else {
    $exists = false;
}

How do I "Add Existing Item" an entire directory structure in Visual Studio?

At last, Visual Studio 2017 allows the user to import an entire directory with a single click. Visual Studio 2017 has a new functionality "Open Folder" that allows opening the entire folder, even without the need to save it as solution. The source code can be imported using the following methods.

  1. Menu File ? Open ? *Folder (Ctrl + Shift + O)
  2. devenv.exe <source folder>

It even supports building and debugging CMake projects.

Bring your C++ codebase to Visual Studio with “Open Folder”

Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error

I had the same problem building VS 2013 Project with Visual Studio 2017 IDE. The solution was to set the right "Platformtoolset v120 (Visual Studio 2013). Therefor there must be the Windows SDK 8.1 installed. If you want to use Platformtoolset v141 (Visual Studio 2017) there must be Windows SDK 10. The Platformtoolset can be chosen inside the properties dialog of the project: General -> Platformtoolset

Make footer stick to bottom of page correctly

I would like to share how I solved mine using Javascript function that is called on page load. This solution positions the footer at the bottom of the screen when the height of the page content is less than the height of the screen.

_x000D_
_x000D_
function fix_layout(){_x000D_
  //increase content div length by uncommenting below line_x000D_
  //expandContent();_x000D_
  _x000D_
    var wraph = document.getElementById('wrapper').offsetHeight;_x000D_
    if(wraph<window.innerHeight){ //if content is less than screenheight_x000D_
        var headh   = document.getElementById('header').offsetHeight;_x000D_
        var conth   = document.getElementById('content').offsetHeight;_x000D_
        var footh   = document.getElementById('footer').offsetHeight;_x000D_
        //var foottop = window.innerHeight - (headh + conth + footh);_x000D_
        var foottop = window.innerHeight - (footh);_x000D_
        $("#footer").css({top:foottop+'px'});_x000D_
    }_x000D_
}_x000D_
_x000D_
function expandContent(){_x000D_
  $('#content').append('<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed at ante. Mauris eleifend, quam a vulputate dictum, massa quam dapibus leo, eget vulputate orci purus ut lorem. In fringilla mi in ligula. Pellentesque aliquam quam vel dolor. Nunc adipiscing. Sed quam odio, tempus ac, aliquam molestie, varius ac, tellus. Vestibulum ut nulla aliquam risus rutrum interdum. Pellentesque lorem. Curabitur sit amet erat quis risus feugiat viverra. Pellentesque augue justo, sagittis et, lacinia at, venenatis non, arcu. Nunc nec libero. In cursus dictum risus. Etiam tristique nisl a nulla. Ut a orci. Curabitur dolor nunc, egestas at, accumsan at, malesuada nec, magna.</p>'+_x000D_
_x000D_
'<p>Nulla facilisi. Nunc volutpat. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Ut sit amet orci vel mauris blandit vehicula. Nullam quis enim. Integer dignissim viverra velit. Curabitur in odio. In hac habitasse platea dictumst. Ut consequat, tellus eu volutpat varius, justo orci elementum dolor, sed imperdiet nulla tellus ut diam. Vestibulum ipsum ante, malesuada quis, tempus ac, placerat sit amet, elit.</p>'+_x000D_
_x000D_
'<p>Sed eget turpis a pede tempor malesuada. Vivamus quis mi at leo pulvinar hendrerit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Pellentesque aliquet lacus vitae pede. Nullam mollis dolor ac nisi. Phasellus sit amet urna. Praesent pellentesque sapien sed lacus. Donec lacinia odio in odio. In sit amet elit. Maecenas gravida interdum urna. Integer pretium, arcu vitae imperdiet facilisis, elit tellus tempor nisi, vel feugiat ante velit sit amet mauris. Vivamus arcu. Integer pharetra magna ac lacus. Aliquam vitae sapien in nibh vehicula auctor. Suspendisse leo mauris, pulvinar sed, tempor et, consequat ac, lacus. Proin velit. Nulla semper lobortis mauris. Duis urna erat, ornare et, imperdiet eu, suscipit sit amet, massa. Nulla nulla nisi, pellentesque at, egestas quis, fringilla eu, diam.</p>'+_x000D_
_x000D_
'<p>Donec semper, sem nec tristique tempus, justo neque commodo nisl, ut gravida sem tellus suscipit nunc. Aliquam erat volutpat. Ut tincidunt pretium elit. Aliquam pulvinar. Nulla cursus. Suspendisse potenti. Etiam condimentum hendrerit felis. Duis iaculis aliquam enim. Donec dignissim augue vitae orci. Curabitur luctus felis a metus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In varius neque at enim. Suspendisse massa nulla, viverra in, bibendum vitae, tempor quis, lorem.</p>'+_x000D_
_x000D_
'<p>Donec dapibus orci sit amet elit. Maecenas rutrum ultrices lectus. Aliquam suscipit, lacus a iaculis adipiscing, eros orci pellentesque nisl, non pharetra dolor urna nec dolor. Integer cursus dolor vel magna. Integer ultrices feugiat sem. Proin nec nibh. Duis eu dui quis nunc sagittis lobortis. Fusce pharetra, enim ut sodales luctus, lectus arcu rhoncus purus, in fringilla augue elit vel lacus. In hac habitasse platea dictumst. Aliquam erat volutpat. Fusce iaculis elit id tellus. Ut accumsan malesuada turpis. Suspendisse potenti. Vestibulum lacus augue, lobortis mattis, laoreet in, varius at, nisi. Nunc gravida. Phasellus faucibus. In hac habitasse platea dictumst. Integer tempor lacus eget lectus. Praesent fringilla augue fringilla dui.</p>');_x000D_
}
_x000D_
/*sample CSS*/_x000D_
body{ background: black; margin: 0; }_x000D_
#header{ background: grey; }_x000D_
#content{background: yellow; }_x000D_
#footer{ background: red; position: absolute; }_x000D_
_x000D_
#header, #content, #footer{ display: inline-block; width: 100vw; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<body onload="fix_layout()">_x000D_
        <div id="wrapper">_x000D_
            <div id="header" class="navbar navbar-inverse navbar-fixed-top" role="navigation">_x000D_
                [some header elements here]_x000D_
            </div>_x000D_
            <div id="content" class="container">_x000D_
              [some content elements here]_x000D_
              _x000D_
              _x000D_
            </div>_x000D_
            <div id="footer" class="footer">_x000D_
                [some footer elements here]_x000D_
            </div>_x000D_
        </div>_x000D_
    </body>
_x000D_
_x000D_
_x000D_

Hope that helps.

If else in stored procedure sql server

Thank you all for your answers but I figured out how to do it and the final procedure looks like that :

Create Procedure sp_ADD_RESPONSABLE_EXTRANET_CLIENT
(
@ParLngId int output
)
as
Begin
if not exists (Select ParLngId from T_Param where ParStrIndex = 'RES' and ParStrP2 = 'Web')
    Begin
            INSERT INTO T_Param values('RES','¤ExtranetClient', 'ECli', 'Web', 1, 1, Null, Null, 'non', 'ExtranetClient', 'ExtranetClient', 25032, Null, '[email protected]', 'Extranet-Client', Null, 27, Null, Null, Null, Null, Null, Null, Null, Null, 1, Null, Null, 0 )
            SET @ParLngId = @@IDENTITY
    End
Else
    Begin
            SET @ParLngId = (Select top 1 ParLngId from T_Param where ParStrNom = 'Extranet Client')
            Return @ParLngId
    End   
End

So the thing that I found out and which made it works is:

if not exists

It allows us to use a boolean instead of Null or 0 or a number resulted of count()

Can't open and lock privilege tables: Table 'mysql.user' doesn't exist

in laragon delete all internal data files from "C:\laragon\data\mysql" and restart it, that worked for me

"Undefined reference to" template class constructor

You will have to define the functions inside your header file.
You cannot separate definition of template functions in to the source file and declarations in to header file.

When a template is used in a way that triggers its intstantation, a compiler needs to see that particular templates definition. This is the reason templates are often defined in the header file in which they are declared.

Reference:
C++03 standard, § 14.7.2.4:

The definition of a non-exported function template, a non-exported member function template, or a non-exported member function or static data member of a class template shall be present in every translation unit in which it is explicitly instantiated.

EDIT:
To clarify the discussion on the comments:
Technically, there are three ways to get around this linking problem:

  • To move the definition to the .h file
  • Add explicit instantiations in the .cpp file.
  • #include the .cpp file defining the template at the .cpp file using the template.

Each of them have their pros and cons,

Moving the defintions to header files may increase the code size(modern day compilers can avoid this) but will increase the compilation time for sure.

Using the explicit instantiation approach is moving back on to traditional macro like approach.Another disadvantage is that it is necessary to know which template types are needed by the program. For a simple program this is easy but for complicated program this becomes difficult to determine in advance.

While including cpp files is confusing at the same time shares the problems of both above approaches.

I find first method the easiest to follow and implement and hence advocte using it.

Chrome - ERR_CACHE_MISS

This is an issue distinct to Chrome, but there are two paths you can take to fix it.

I noticed the error once I added this specific header to my PHP script.

header('Content-Type: application/json');

The error appears to be related to PHP sessions when sending response headers. So according to chromium bug report 424599, this was fixed and you can just update to a newer version of Chrome. But if for some reason you can't or don't want to update, the workaround would be to remove these response headers from your PHP script if possible (that's what I did because it wasn't required).

release Selenium chromedriver.exe from memory

There is another way which is working only for windows, but now it is deprecated. it works for previous selenium releases (it works on 3.11.0 version).

import org.openqa.selenium.os.WindowsUtils;

 WindowsUtils.killByName("chromedriver.exe") // any process name you want

Going through a text file line by line in C

So many problems in so few lines. I probably forget some:

  • argv[0] is the program name, not the first argument;
  • if you want to read in a variable, you have to allocate its memory
  • one never loops on feof, one loops on an IO function until it fails, feof then serves to determinate the reason of failure,
  • sscanf is there to parse a line, if you want to parse a file, use fscanf,
  • "%s" will stop at the first space as a format for the ?scanf family
  • to read a line, the standard function is fgets,
  • returning 1 from main means failure

So

#include <stdio.h>

int main(int argc, char* argv[])
{
    char const* const fileName = argv[1]; /* should check that argc > 1 */
    FILE* file = fopen(fileName, "r"); /* should check the result */
    char line[256];

    while (fgets(line, sizeof(line), file)) {
        /* note that fgets don't strip the terminating \n, checking its
           presence would allow to handle lines longer that sizeof(line) */
        printf("%s", line); 
    }
    /* may check feof here to make a difference between eof and io failure -- network
       timeout for instance */

    fclose(file);

    return 0;
}

Inserting the iframe into react component

With ES6 you can now do it like this

Example Codepen URl to load

const iframe = '<iframe height="265" style="width: 100%;" scrolling="no" title="fx." src="//codepen.io/ycw/embed/JqwbQw/?height=265&theme-id=0&default-tab=js,result" frameborder="no" allowtransparency="true" allowfullscreen="true">See the Pen <a href="https://codepen.io/ycw/pen/JqwbQw/">fx.</a> by ycw(<a href="https://codepen.io/ycw">@ycw</a>) on <a href="https://codepen.io">CodePen</a>.</iframe>'; 

A function component to load Iframe

function Iframe(props) {
  return (<div dangerouslySetInnerHTML={ {__html:  props.iframe?props.iframe:""}} />);
}

Usage:

import React from "react";
import ReactDOM from "react-dom";
function App() {
  return (
    <div className="App">
      <h1>Iframe Demo</h1>
      <Iframe iframe={iframe} />,
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Edit on CodeSandbox:

https://codesandbox.io/s/react-iframe-demo-g3vst

How to install gem from GitHub source?

You can also use rdp/specific_install gem:

gem install specific_install
gem specific_install https://github.com/capistrano/drupal-deploy.git

Export specific rows from a PostgreSQL table as INSERT SQL script

I tried to write a procedure doing that, based on @PhilHibbs codes, on a different way. Please have a look and test.

 CREATE OR REPLACE FUNCTION dump(IN p_schema text, IN p_table text, IN p_where text)
   RETURNS setof text AS
 $BODY$
 DECLARE
     dumpquery_0 text;
     dumpquery_1 text;
     selquery text;
     selvalue text;
     valrec record;
     colrec record;
 BEGIN

     -- ------ --
     -- GLOBAL --
     --   build base INSERT
     --   build SELECT array[ ... ]
     dumpquery_0 := 'INSERT INTO ' ||  quote_ident(p_schema) || '.' || quote_ident(p_table) || '(';
     selquery    := 'SELECT array[';

     <<label0>>
     FOR colrec IN SELECT table_schema, table_name, column_name, data_type
                   FROM information_schema.columns
                   WHERE table_name = p_table and table_schema = p_schema
                   ORDER BY ordinal_position
     LOOP
         dumpquery_0 := dumpquery_0 || quote_ident(colrec.column_name) || ',';
         selquery    := selquery    || 'CAST(' || quote_ident(colrec.column_name) || ' AS TEXT),';
     END LOOP label0;

     dumpquery_0 := substring(dumpquery_0 ,1,length(dumpquery_0)-1) || ')';
     dumpquery_0 := dumpquery_0 || ' VALUES (';
     selquery    := substring(selquery    ,1,length(selquery)-1)    || '] AS MYARRAY';
     selquery    := selquery    || ' FROM ' ||quote_ident(p_schema)||'.'||quote_ident(p_table);
     selquery    := selquery    || ' WHERE '||p_where;
     -- GLOBAL --
     -- ------ --

     -- ----------- --
     -- SELECT LOOP --
     --   execute SELECT built and loop on each row
     <<label1>>
     FOR valrec IN  EXECUTE  selquery
     LOOP
         dumpquery_1 := '';
         IF not found THEN
             EXIT ;
         END IF;

         -- ----------- --
         -- LOOP ARRAY (EACH FIELDS) --
         <<label2>>
         FOREACH selvalue in ARRAY valrec.MYARRAY
         LOOP
             IF selvalue IS NULL
             THEN selvalue := 'NULL';
             ELSE selvalue := quote_literal(selvalue);
             END IF;
             dumpquery_1 := dumpquery_1 || selvalue || ',';
         END LOOP label2;
         dumpquery_1 := substring(dumpquery_1 ,1,length(dumpquery_1)-1) || ');';
         -- LOOP ARRAY (EACH FIELD) --
         -- ----------- --

         -- debug: RETURN NEXT dumpquery_0 || dumpquery_1 || ' --' || selquery;
         -- debug: RETURN NEXT selquery;
         RETURN NEXT dumpquery_0 || dumpquery_1;

     END LOOP label1 ;
     -- SELECT LOOP --
     -- ----------- --

 RETURN ;
 END
 $BODY$
   LANGUAGE plpgsql VOLATILE;

And then :

-- for a range
SELECT dump('public', 'my_table','my_id between 123456 and 123459'); 
-- for the entire table
SELECT dump('public', 'my_table','true');

tested on my postgres 9.1, with a table with mixed field datatype (text, double, int,timestamp without time zone, etc).

That's why the CAST in TEXT type is needed. My test run correctly for about 9M lines, looks like it fail just before 18 minutes of running.

ps : I found an equivalent for mysql on the WEB.

What is a user agent stylesheet?

What are the target browsers? Different browsers set different default CSS rules. Try including a CSS reset, such as the meyerweb CSS reset or normalize.css, to remove those defaults. Google "CSS reset vs normalize" to see the differences.

Index inside map() function

Using Ramda:

import {addIndex, map} from 'ramda';

const list = [ 'h', 'e', 'l', 'l', 'o'];
const mapIndexed = addIndex(map);
mapIndexed((currElement, index) => {
  console.log("The current iteration is: " + index);
  console.log("The current element is: " + currElement);
  console.log("\n");
  return 'X';
}, list);

Submit form without page reloading

I've found what I think is an easier way. If you put an Iframe in the page, you can redirect the exit of the action there and make it show up. You can do nothing, of course. In that case, you can set the iframe display to none.

<iframe name="votar" style="display:none;"></iframe>
<form action="tip.php" method="post" target="votar">
    <input type="submit" value="Skicka Tips">
    <input type="hidden" name="ad_id" value="2">            
</form>

How to create multiple class objects with a loop in python?

Using a dictionary for unique names without a name list:

class MyClass:
    def __init__(self, name):
        self.name = name
        self.pretty_print_name()

    def pretty_print_name(self):
    print("This object's name is {}.".format(self.name))

my_objects = {}
for i in range(1,11):
    name = 'obj_{}'.format(i)
    my_objects[name] = my_objects.get(name, MyClass(name = name))

Output:

"This object's name is obj_1."
"This object's name is obj_2."
"This object's name is obj_3."
"This object's name is obj_4."
"This object's name is obj_5."
"This object's name is obj_6."
"This object's name is obj_7."
"This object's name is obj_8."
"This object's name is obj_9."
"This object's name is obj_10."

How to resolve "local edit, incoming delete upon update" message

I just got this same issue and I found that

$ svn revert foo bar

solved the problem.

svn resolve did not work for me:

$ svn st
!  +  C foo
      >   local edit, incoming delete upon update
!  +  C bar
      >   local edit, incoming delete upon update

$ svn resolve --accept working
svn: Try 'svn help' for more info
svn: Not enough arguments provided

$ svn resolve --accept working .

$ svn st
!  +  C foo
      >   local edit, incoming delete upon update
!  +  C bar
      >   local edit, incoming delete upon update

$ svn resolve --accept working foo
Resolved conflicted state of 'foo'

$ svn st
!  +    foo
!  +  C bar
      >   local edit, incoming delete upon update

java.net.ConnectException: Connection refused

I had the same problem, but running the Server before running the Client fixed it.

Displaying all table names in php from MySQL database

SHOW TABLES

will show all the tables in your db. If you want to filter the names you use LIKE and wildcard %

SHOW TABLES FROM my_database LIKE '%user%'

will give you all tables that's name include 'user', for example

users
user_pictures
mac_users

etc.

Sum across multiple columns with dplyr

dplyr >= 1.0.0 using across

sum up each row using rowSums (rowwise works for any aggreation, but is slower)

df %>%
   replace(is.na(.), 0) %>%
   mutate(sum = rowSums(across(where(is.numeric))))

sum down each column

df %>%
   summarise(across(everything(), ~ sum(., is.na(.), 0)))

dplyr < 1.0.0

sum up each row

df %>%
   replace(is.na(.), 0) %>%
   mutate(sum = rowSums(.[1:5]))

sum down each column using superseeded summarise_all:

df %>%
   replace(is.na(.), 0) %>%
   summarise_all(funs(sum))

Configuring IntelliJ IDEA for unit testing with JUnit

One way of doing this is to do add junit.jar to your $CLASSPATH as an external dependency.

adding junit intellij

So to do that, go to project structure, and then add JUnit as one of the libraries as shown in the gif.

In the 'Choose Modules' prompt choose only the modules that you'd need JUnit for.

How to align an indented line in a span that wraps into multiple lines?

display:block;

then you've got a block element and the margin is added to all lines.

While it's true that a span is semantically not a block element, there are cases where you don't have control of the pages DOM. This answer is inteded for those.

class method generates "TypeError: ... got multiple values for keyword argument ..."

I want to add one more answer :

It happens when you try to pass positional parameter with wrong position order along with keyword argument in calling function.

there is difference between parameter and argument you can read in detail about here Arguments and Parameter in python

def hello(a,b=1, *args):
   print(a, b, *args)


hello(1, 2, 3, 4,a=12)

since we have three parameters :

a is positional parameter

b=1 is keyword and default parameter

*args is variable length parameter

so we first assign a as positional parameter , means we have to provide value to positional argument in its position order, here order matter. but we are passing argument 1 at the place of a in calling function and then we are also providing value to a , treating as keyword argument. now a have two values :

one is positional value: a=1

second is keyworded value which is a=12

Solution

We have to change hello(1, 2, 3, 4,a=12) to hello(1, 2, 3, 4,12) so now a will get only one positional value which is 1 and b will get value 2 and rest of values will get *args (variable length parameter)

additional information

if we want that *args should get 2,3,4 and a should get 1 and b should get 12

then we can do like this
def hello(a,*args,b=1): pass hello(1, 2, 3, 4,b=12)

Something more :

def hello(a,*c,b=1,**kwargs):
    print(b)
    print(c)
    print(a)
    print(kwargs)

hello(1,2,1,2,8,9,c=12)

output :

1

(2, 1, 2, 8, 9)

1

{'c': 12}

Getting index value on razor foreach

Very Simple:

     @{
         int i = 0;
         foreach (var item in Model)
         {
          <tr>
          <td>@(i = i + 1)</td>`
          </tr>
         }
      }`

Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1

Check your code for errors in my case i had an error in Kernel.php. First solve errors if any Than run composer require ....(package you wish)

If REST applications are supposed to be stateless, how do you manage sessions?

You have to manage client session on the client side. This means that you have to send authentication data with every request, and you probably, but not necessary have an in-memory cache on the server, which pairs auth data to user information like identity, permissions, etc...

This REST statelessness constraint is very important. Without applying this constraint, your server side application won't scale well, because maintaining every single client session will be its Achilles' heel.

How do I revert all local changes in Git managed project to previous state?

Try this for revert all changes uncommited in local branch

$ git reset --hard HEAD

But if you see a error like this:

fatal: Unable to create '/directory/for/your/project/.git/index.lock': File exists.

You can navigate to '.git' folder then delete index.lock file:

$ cd /directory/for/your/project/.git/
$ rm index.lock

Finaly, run again the command:

$ git reset --hard HEAD

How to get a value of an element by name instead of ID

you can also use the class name.

$(".yourclass").val();

How to add a line to a multiline TextBox?

The "Lines" property of a TextBox is an array of strings. By definition, you cannot add elements to an existing string[], like you can to a List<string>. There is simply no method available for the purpose. You must instead create a new string[] based on the current Lines reference, and assign it to Lines.

Using a little Linq (.NET 3.5 or later):

textBox1.Lines = textBox.Lines.Concat(new[]{"Some Text"}).ToArray();

This code is fine for adding one new line at a time based on user interaction, but for initializing a textbox with a few dozen new lines, it will perform very poorly. If you're setting the initial value of a TextBox, I would either set the Text property directly using a StringBuilder (as other answers have mentioned), or if you're set on manipulating the Lines property, use a List to compile the collection of values and then convert it to an array to assign to Lines:

var myLines = new List<string>();

myLines.Add("brown");
myLines.Add("brwn");
myLines.Add("brn");
myLines.Add("brow");
myLines.Add("br");
myLines.Add("brw");
...

textBox1.Lines = myLines.ToArray();

Even then, because the Lines array is a calculated property, this involves a lot of unnecessary conversion behind the scenes.

Initial size for the ArrayList

If you want to add the elements with index, you could instead use an array.

    String [] test = new String[length];
    test[0] = "add";

Get filename and path from URI from mediastore

I do this with a one liner:

val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, uri)

Which in the onActivityResult looks like:

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE_IMAGE_PICKER ) {
        data?.data?.let { imgUri: Uri ->
            val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, imgUri)
        }
    }
}

View/edit ID3 data for MP3 files

TagLib Sharp is pretty popular.

As a side note, if you wanted to take a quick and dirty peek at doing it yourself.. here is a C# snippet I found to read an mp3's tag info.

class MusicID3Tag

{

    public byte[] TAGID = new byte[3];      //  3
    public byte[] Title = new byte[30];     //  30
    public byte[] Artist = new byte[30];    //  30 
    public byte[] Album = new byte[30];     //  30 
    public byte[] Year = new byte[4];       //  4 
    public byte[] Comment = new byte[30];   //  30 
    public byte[] Genre = new byte[1];      //  1

}

string filePath = @"C:\Documents and Settings\All Users\Documents\My Music\Sample Music\041105.mp3";

        using (FileStream fs = File.OpenRead(filePath))
        {
            if (fs.Length >= 128)
            {
                MusicID3Tag tag = new MusicID3Tag();
                fs.Seek(-128, SeekOrigin.End);
                fs.Read(tag.TAGID, 0, tag.TAGID.Length);
                fs.Read(tag.Title, 0, tag.Title.Length);
                fs.Read(tag.Artist, 0, tag.Artist.Length);
                fs.Read(tag.Album, 0, tag.Album.Length);
                fs.Read(tag.Year, 0, tag.Year.Length);
                fs.Read(tag.Comment, 0, tag.Comment.Length);
                fs.Read(tag.Genre, 0, tag.Genre.Length);
                string theTAGID = Encoding.Default.GetString(tag.TAGID);

                if (theTAGID.Equals("TAG"))
                {
                    string Title = Encoding.Default.GetString(tag.Title);
                    string Artist = Encoding.Default.GetString(tag.Artist);
                    string Album = Encoding.Default.GetString(tag.Album);
                    string Year = Encoding.Default.GetString(tag.Year);
                    string Comment = Encoding.Default.GetString(tag.Comment);
                    string Genre = Encoding.Default.GetString(tag.Genre);

                    Console.WriteLine(Title);
                    Console.WriteLine(Artist);
                    Console.WriteLine(Album);
                    Console.WriteLine(Year);
                    Console.WriteLine(Comment);
                    Console.WriteLine(Genre);
                    Console.WriteLine();
                }
            }
        }

How to convert C# nullable int to int

I am working on C# 9 and .NET 5, example

foo is nullable int, I need get int value of foo

var foo = (context as AccountTransfer).TransferSide;
int value2 = 0;
if (foo != null)
{
    value2 = foo.Value;
}

See more at https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/nullable-value-types#examination-of-an-instance-of-a-nullable-value-type

Append data to a POST NSURLRequest

All the changes to the NSMutableURLRequest must be made before calling NSURLConnection.

I see this problem as I copy and paste the code above and run TCPMon and see the request is GET instead of the expected POST.

NSURL *aUrl = [NSURL URLWithString:@"http://www.apple.com/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aUrl
                                     cachePolicy:NSURLRequestUseProtocolCachePolicy
                                 timeoutInterval:60.0];


[request setHTTPMethod:@"POST"];
NSString *postString = @"company=Locassa&quality=AWESOME!";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request 
                                                         delegate:self];

How do I change select2 box height

Seems the stylesheet selectors have changed over time. I'm using select2-4.0.2 and the correct selector to set the box height is currently:

.select2-container--default .select2-results > .select2-results__options {
    max-height: 200px
}

How to read a config file using python

In order to use my example,Your file "abc.txt" needs to look like:

[your-config]
path1 = "D:\test1\first"
path2 = "D:\test2\second"
path3 = "D:\test2\third"

Then in your software you can use the config parser:

import ConfigParser

and then in you code:

 configParser = ConfigParser.RawConfigParser()   
 configFilePath = r'c:\abc.txt'
 configParser.read(configFilePath)

Use case:

self.path = configParser.get('your-config', 'path1')

*Edit (@human.js)

in python 3, ConfigParser is renamed to configparser (as described here)

Label python data points on plot

How about print (x, y) at once.

from matplotlib import pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54

plt.plot(A,B)
for xy in zip(A, B):                                       # <--
    ax.annotate('(%s, %s)' % xy, xy=xy, textcoords='data') # <--

plt.grid()
plt.show()

enter image description here

Finding diff between current and last version

You can do it this way too:

Compare with the previous commit

git diff --name-status HEAD~1..HEAD

Compare with the current and previous two commits

git diff --name-status HEAD~2..HEAD

Communication between tabs or windows

Another method that people should consider using is Shared Workers. I know it's a cutting edge concept, but you can create a relay on a Shared Worker that is MUCH faster than localstorage, and doesn't require a relationship between the parent/child window, as long as you're on the same origin.

See my answer here for some discussion I made about this.

Have a variable in images path in Sass?

Have you tried the Interpolation syntax?

background: url(#{$get-path-to-assets}/site/background.jpg) repeat-x fixed 0 0;

What is the best way to implement a "timer"?

Reference ServiceBase to your class and put the below code in the OnStartevent:

Constants.TimeIntervalValue = 1 (hour)..Ideally you should set this value in config file.

StartSendingMails = function name you want to run in the application.

 protected override void OnStart(string[] args)
        {
            // It tells in what interval the service will run each time.
            Int32 timeInterval = Int32.Parse(Constants.TimeIntervalValue) * 60 * 60 * 1000;
            base.OnStart(args);
            TimerCallback timerDelegate = new TimerCallback(StartSendingMails);
            serviceTimer = new Timer(timerDelegate, null, 0, Convert.ToInt32(timeInterval));
        }

Cache an HTTP 'Get' service response in AngularJS?

An easier way to do this in the current stable version (1.0.6) requires a lot less code.

After setting up your module add a factory:

var app = angular.module('myApp', []);
// Configure routes and controllers and views associated with them.
app.config(function ($routeProvider) {
    // route setups
});
app.factory('MyCache', function ($cacheFactory) {
    return $cacheFactory('myCache');
});

Now you can pass this into your controller:

app.controller('MyController', function ($scope, $http, MyCache) {
    $http.get('fileInThisCase.json', { cache: MyCache }).success(function (data) {
        // stuff with results
    });
});

One downside is that the key names are also setup automatically, which could make clearing them tricky. Hopefully they'll add in some way to get key names.

Create a day-of-week column in a Pandas dataframe using Python

Just in case if .dt doesn't work for you. Trying .DatetimeIndex might help. Hope the code and our test result here help you fix it. Regards,

import pandas as pd
import datetime

df = pd.DataFrame({'Date':['2015-01-01','2015-01-02','2015-01-03'],'Number':[1,2,3]})

df['Day'] = pd.DatetimeIndex(df['Date']).day_name() # week day name
df.head()

enter image description here

Python != operation vs "is not"

None is a singleton, therefore identity comparison will always work, whereas an object can fake the equality comparison via .__eq__().

How to define a default value for "input type=text" without using attribute 'value'?

You can set the value property using client script after the element is created:

<input type="text" id="fee" />

<script type="text/javascript>
document.getElementById('fee').value = '1000';
</script>

How to empty ("truncate") a file on linux that already exists and is protected in someway?

You can also use function truncate

$truncate -s0 yourfile

if permission denied, use sudo

$sudo truncate -s0 yourfile

Help/Manual: man truncate

tested on ubuntu Linux

Does Eclipse have line-wrap

The Eclipse Word-Wrap plugin works for any type of file for me.

Css height in percent not working

You can achieve that by using positioning.

Try

position: absolute;

to get the 100% height.

RSA Public Key format

Reference Decoder of CRL,CRT,CSR,NEW CSR,PRIVATE KEY, PUBLIC KEY,RSA,RSA Public Key Parser

RSA Public Key

-----BEGIN RSA PUBLIC KEY-----
-----END RSA PUBLIC KEY-----

Encrypted Private Key

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
-----END RSA PRIVATE KEY-----

CRL

-----BEGIN X509 CRL-----
-----END X509 CRL-----

CRT

-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----

CSR

-----BEGIN CERTIFICATE REQUEST-----
-----END CERTIFICATE REQUEST-----

NEW CSR

-----BEGIN NEW CERTIFICATE REQUEST-----
-----END NEW CERTIFICATE REQUEST-----

PEM

-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----

PKCS7

-----BEGIN PKCS7-----
-----END PKCS7-----

PRIVATE KEY

-----BEGIN PRIVATE KEY-----
-----END PRIVATE KEY-----

DSA KEY

-----BEGIN DSA PRIVATE KEY-----
-----END DSA PRIVATE KEY-----

Elliptic Curve

-----BEGIN EC PRIVATE KEY-----
-----END EC PRIVATE KEY-----

PGP Private Key

-----BEGIN PGP PRIVATE KEY BLOCK-----
-----END PGP PRIVATE KEY BLOCK-----

PGP Public Key

-----BEGIN PGP PUBLIC KEY BLOCK-----
-----END PGP PUBLIC KEY BLOCK-----

Installing Python 2.7 on Windows 8

Easiest way is to open CMD or powershell as administrator and type

set PATH=%PATH%;C:\Python27

Batch file to copy files from one folder to another folder

You may want to take a look at XCopy or RoboCopy which are pretty comprehensive solutions for nearly all file copy operations on Windows.

Powershell remoting with ip-address as target

On your machine* run 'Set-Item WSMan:\localhost\Client\TrustedHosts -Value "$ipaddress"

*Machine from where you are running PSSession

BehaviorSubject vs Observable?

An observable allows you to subscribe only whereas a subject allows you to both publish and subscribe.

So a subject allows your services to be used as both a publisher and a subscriber.

As of now, I'm not so good at Observable so I'll share only an example of Subject.

Let's understand better with an Angular CLI example. Run the below commands:

npm install -g @angular/cli

ng new angular2-subject

cd angular2-subject

ng serve

Replace the content of app.component.html with:

<div *ngIf="message">
  {{message}}
</div>

<app-home>
</app-home>

Run the command ng g c components/home to generate the home component. Replace the content of home.component.html with:

<input type="text" placeholder="Enter message" #message>
<button type="button" (click)="setMessage(message)" >Send message</button>

#message is the local variable here. Add a property message: string; to the app.component.ts's class.

Run this command ng g s service/message. This will generate a service at src\app\service\message.service.ts. Provide this service to the app.

Import Subject into MessageService. Add a subject too. The final code shall look like this:

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class MessageService {

  public message = new Subject<string>();

  setMessage(value: string) {
    this.message.next(value); //it is publishing this value to all the subscribers that have already subscribed to this message
  }
}

Now, inject this service in home.component.ts and pass an instance of it to the constructor. Do this for app.component.ts too. Use this service instance for passing the value of #message to the service function setMessage:

import { Component } from '@angular/core';
import { MessageService } from '../../service/message.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent {

  constructor(public messageService:MessageService) { }

  setMessage(event) {
    console.log(event.value);
    this.messageService.setMessage(event.value);
  }
}

Inside app.component.ts, subscribe and unsubscribe (to prevent memory leaks) to the Subject:

import { Component, OnDestroy } from '@angular/core';
import { MessageService } from './service/message.service';
import { Subscription } from 'rxjs/Subscription';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {

  message: string;
  subscription: Subscription;

  constructor(public messageService: MessageService) { }

  ngOnInit() {
    this.subscription = this.messageService.message.subscribe(
      (message) => {
        this.message = message;
      }
    );
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

That's it.

Now, any value entered inside #message of home.component.html shall be printed to {{message}} inside app.component.html

How many characters can you store with 1 byte?

2^8 = 256 Characters. A character in binary is a series of 8 ( 0 or 1).

   |----------------------------------------------------------|
   |                                                          |
   | Type    | Storage |  Minimum Value    | Maximum Value    |
   |         | (Bytes) | (Signed/Unsigned) | (Signed/Unsigned)|
   |         |         |                   |                  |
   |---------|---------|-------------------|------------------|
   |         |         |                   |                  |
   |         |         |                   |                  |
   | TINYINT |  1      |      -128 - 0     |  127 - 255       |
   |         |         |                   |                  |
   |----------------------------------------------------------|

Java says FileNotFoundException but file exists

There are a number situation where a FileNotFoundException may be thrown at runtime.

  1. The named file does not exist. This could be for a number of reasons including:

    • The pathname is simply wrong
    • The pathname looks correct but is actually wrong because it contains non-printing characters (or homoglyphs) that you did not notice
    • The pathname is relative, and it doesn't resolve correctly relative to the actual current directory of the running application. This typically happens because the application's current directory is not what you are expecting or assuming.
    • The path to the file is is broken; e.g. a directory name of the path is incorrect, a symbolic link on the path is broken, or there is a permission problem with one of the path components.
  2. The named file is actually a directory.

  3. The named file cannot be opened for reading for some reason.

The good news that, the problem will inevitably be one of the above. It is just a matter of working out which. Here are some things that you can try:

  • Calling file.exists() will tell you if any file system object exists with the given name / pathname.
  • Calling file.isDirectory() will test if it is a directory.
  • Calling file.canRead() will test if it is a readable file.
  • This line will tell you what the current directory is:

    System.out.println(new File(".").getAbsolutePath());
    
  • This line will print out the pathname in a way that makes it easier to spot things like unexpected leading or trainiong whitespace:

    System.out.println("The path is '" + path + "'");
    

    Look for unexpected spaces, line breaks, etc in the output.


It turns out that your example code has a compilation error.

I ran your code without taking care of the complaint from Netbeans, only to get the following exception message:

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown

If you change your code to the following, it will fix that problem.

public static void main(String[] args) throws FileNotFoundException {    
    File file = new File("scores.dat");
    System.out.println(file.exists());
    Scanner scan = new Scanner(file);
}

Explanation: the Scanner(File) constructor is declared as throwing the FileNotFoundException exception. (It happens the scanner it cannot open the file.) Now FileNotFoundException is a checked exception. That means that a method in which the exception may be thrown must either catch the exception or declare it in the throws clause. The above fix takes the latter approach.

How to change facet labels?

Change the underlying factor level names with something like:

# Using the Iris data
> i <- iris
> levels(i$Species)
[1] "setosa"     "versicolor" "virginica" 
> levels(i$Species) <- c("S", "Ve", "Vi")
> ggplot(i, aes(Petal.Length)) + stat_bin() + facet_grid(Species ~ .)

How to execute UNION without sorting? (SQL)

Try this:

  SELECT DISTINCT * FROM (

      SELECT  column1, column2 FROM Table1
      UNION ALL
      SELECT  column1, column2 FROM Table2
      UNION ALL
      SELECT  column1, column2 FROM Table3

  ) X ORDER BY Column1

What is the --save option for npm install?

Update as of npm 5:

As of npm 5.0.0, installed modules are added as a dependency by default, so the --save option is no longer needed. The other save options still exist and are listed in the documentation for npm install.


Original answer:

It won't do anything if you don't have a package.json file. Start by running npm init to create one. Then calls to npm install --save or npm install --save-dev or npm install --save-optional will update the package.json to list your dependencies.

How do you do dynamic / dependent drop downs in Google Sheets?

You can start with a google sheet set up with a main page and drop down source page like shown below.

You can set up the first column drop down through the normal Data > Validations menu prompts.

Main Page

Main Page with the drop down for the first column already populated.

Drop Down Source Page

Source page for all of the sub-categories needed

After that, you need to set up a script with the name onEdit. (If you don't use that name, the getActiveRange() will do nothing but return cell A1)

And use the code provided here:

function onEdit() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = SpreadsheetApp.getActiveSheet();
  var myRange = SpreadsheetApp.getActiveRange();
  var dvSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Categories");
  var option = new Array();
  var startCol = 0;

  if(sheet.getName() == "Front Page" && myRange.getColumn() == 1 && myRange.getRow() > 1){
    if(myRange.getValue() == "Category 1"){
      startCol = 1;
    } else if(myRange.getValue() == "Category 2"){
      startCol = 2;
    } else if(myRange.getValue() == "Category 3"){
      startCol = 3;
    } else if(myRange.getValue() == "Category 4"){
      startCol = 4;
    } else {
      startCol = 10
    }

  if(startCol > 0 && startCol < 10){
    option = dvSheet.getSheetValues(3,startCol,10,1);
    var dv = SpreadsheetApp.newDataValidation();
    dv.setAllowInvalid(false);  
    //dv.setHelpText("Some help text here");
    dv.requireValueInList(option, true);
    sheet.getRange(myRange.getRow(),myRange.getColumn() + 1).setDataValidation(dv.build());
   }

  if(startCol == 10){
    sheet.getRange(myRange.getRow(),myRange.getColumn() + 1).clearDataValidations();
  } 
  }
}

After that, set up a trigger in the script editor screen by going to Edit > Current Project Triggers. This will bring up a window to have you select various drop downs to eventually end up at this:

Trigger set up

You should be good to go after that!

Adding images or videos to iPhone Simulator

I just stumbled upon how to bulk upload images on the iOS Simulator. (I've only confirmed it on 6.1.)

  1. Backup the folder:

    ~/Library/Application Support/iPhone Simulator/6.1/Media
    
  2. Copy all your images into the folder:

    ~/Library/Application Support/iPhone Simulator/6.1/Media/DCIM/100APPLE
    
  3. Move or delete the folder:

    ~/Library/Application Support/iPhone Simulator/6.1/Media/PhotoData
    
  4. Restart iOS Simulator

  5. Open the Photos app

The simulator will restore all the images from the 100APPLE folder!

ASP.Net Download file to client browser

Just a slight addition to the above solution if you are having problem with downloaded file's name...

Response.AddHeader("Content-Disposition", "attachment; filename=\"" + file.Name + "\"");

This will return the exact file name even if it contains spaces or other characters.

laravel select where and where condition

$this->where('email', $email)->where('password', $password) 

is returning a Builder object which you could use to append more where filters etc.

To get the result you need:

$userRecord = $this->where('email', $email)->where('password', $password)->first();

Make A List Item Clickable (HTML/CSS)

How about putting all content inside link?

<li><a href="#" onClick="..." ... >Backpack <img ... /></a></li>

Seems like the most natural thing to try.

Batch files: List all files in a directory with relative paths

This answer will not work correctly with root paths containing equal signs (=). (Thanks @dbenham for pointing that out.)


EDITED: Fixed the issue with paths containing !, again spotted by @dbenham (thanks!).

Alternatively to calculating the length and extracting substrings you could use a different approach:

  • store the root path;

  • clear the root path from the file paths.

Here's my attempt (which worked for me):

@ECHO OFF
SETLOCAL DisableDelayedExpansion
SET "r=%__CD__%"
FOR /R . %%F IN (*) DO (
  SET "p=%%F"
  SETLOCAL EnableDelayedExpansion
  ECHO(!p:%r%=!
  ENDLOCAL
)

The r variable is assigned with the current directory. Unless the current directory is the root directory of a disk drive, it will not end with \, which we amend by appending the character. (No longer the case, as the script now reads the __CD__ variable, whose value always ends with \ (thanks @jeb!), instead of CD.)

In the loop, we store the current file path into a variable. Then we output the variable, stripping the root path along the way.

How do I get indices of N maximum values in a NumPy array?

This code works for a numpy 2D matrix array:

mat = np.array([[1, 3], [2, 5]]) # numpy matrix
 
n = 2  # n
n_largest_mat = np.sort(mat, axis=None)[-n:] # n_largest 
tf_n_largest = np.zeros((2,2), dtype=bool) # all false matrix
for x in n_largest_mat: 
  tf_n_largest = (tf_n_largest) | (mat == x) # true-false  

n_largest_elems = mat[tf_n_largest] # true-false indexing 

This produces a true-false n_largest matrix indexing that also works to extract n_largest elements from a matrix array

Setting UILabel text to bold

Use attributed string:

// Define attributes
let labelFont = UIFont(name: "HelveticaNeue-Bold", size: 18)
let attributes :Dictionary = [NSFontAttributeName : labelFont]

// Create attributed string
var attrString = NSAttributedString(string: "Foo", attributes:attributes)
label.attributedText = attrString

You need to define attributes.

Using attributed string you can mix colors, sizes, fonts etc within one text

How do I configure Notepad++ to use spaces instead of tabs?

Go to the Preferences menu command under menu Settings, and select Language Menu/Tab Settings, depending on your version. Earlier versions use Tab Settings. Later versions use Language. Click the Replace with space check box. Set the size to 4.

Enter image description here

See documentation: http://docs.notepad-plus-plus.org/index.php/Built-in_Languages#Tab_settings

Java Enum Methods - return opposite direction enum

Yes we do it all the time. You return a static instance rather than a new Object

 static Direction getOppositeDirection(Direction d){
       Direction result = null;
       if (d != null){
           int newCode = -d.getCode();
           for (Direction direction : Direction.values()){
               if (d.getCode() == newCode){
                   result = direction;
               }
           }
       }
       return result;
 }

Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?

install cors module of expressjs. you can follow these steps >

Installation

npm install cors

Simple Usage (Enable All CORS Requests)

var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());

for more details go to https://github.com/expressjs/cors

Rails: Why "sudo" command is not recognized?

That you are running Windows. Read:

http://en.wikipedia.org/wiki/Sudo

It basically allows you to execute an application with elevated privileges. If you want to achieve a similar effect under Windows, open an administrative prompt and execute your command from there. Under Vista, this is easily done by opening the shortcut while holding Ctrl+Shift at the same time.

That being said, it might very well be possible that your account already has sufficient privileges, depending on how your OS is setup, and the Windows version used.

How to create new folder?

You can create a folder with os.makedirs()
and use os.path.exists() to see if it already exists:

newpath = r'C:\Program Files\arbitrary' 
if not os.path.exists(newpath):
    os.makedirs(newpath)

If you're trying to make an installer: Windows Installer does a lot of work for you.

Flutter Circle Design

More efficient way

I suggest you to draw a circle with CustomPainter. It's very easy and way more efficient than creating a bunch of widgets/masks:

Flutter draw circle

/// Draws a circle if placed into a square widget.
class CirclePainter extends CustomPainter {
  final _paint = Paint()
    ..color = Colors.red
    ..strokeWidth = 2
    // Use [PaintingStyle.fill] if you want the circle to be filled.
    ..style = PaintingStyle.stroke;

  @override
  void paint(Canvas canvas, Size size) {
    canvas.drawOval(
      Rect.fromLTWH(0, 0, size.width, size.height),
      _paint,
    );
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => false;
}

Usage:

  Widget _buildCircle(BuildContext context) {
    return SizedBox(
      width: 20,
      height: 20,
      child: CustomPaint(
        painter: CirclePainter(),
      ),
    );
  }

Bold words in a string of strings.xml in Android

Strings.xml

<string name="my_text"><Data><![CDATA[<b>Your text</b>]]></Data></string>

To set

textView.setText(Html.fromHtml(getString(R.string.activity_completed_text)));

Removing leading zeroes from a field in a SQL statement

select substring(ColumnName, patindex('%[^0]%',ColumnName), 10)

CSS On hover show another element

You can use axe selectors for this.

There are two approaches:

1. Immediate Parent axe Selector (<)

#a:hover < #content + #b

This axe style rule will select #b, which is the immediate sibling of #content, which is the immediate parent of #a which has a :hover state.

_x000D_
_x000D_
div {
display: inline-block;
margin: 30px;
font-weight: bold;
}

#content {
width: 160px;
height: 160px;
background-color: rgb(255, 0, 0);
}

#a, #b {
width: 100px;
height: 100px;
line-height: 100px;
text-align: center;
}

#a {
color: rgb(255, 0, 0);
background-color: rgb(255, 255, 0);
cursor: pointer;
}

#b {
display: none;
color: rgb(255, 255, 255);
background-color: rgb(0, 0, 255);
}

#a:hover < #content + #b {
display: inline-block;
}
_x000D_
<div id="content">
<div id="a">Hover me</div>
</div>

<div id="b">Show me</div>

<script src="https://rouninmedia.github.io/axe/axe.js"></script>
_x000D_
_x000D_
_x000D_


2. Remote Element axe Selector (\)

#a:hover \ #b

This axe style rule will select #b, which is present in the same document as #a which has a :hover state.

_x000D_
_x000D_
div {
display: inline-block;
margin: 30px;
font-weight: bold;
}

#content {
width: 160px;
height: 160px;
background-color: rgb(255, 0, 0);
}

#a, #b {
width: 100px;
height: 100px;
line-height: 100px;
text-align: center;
}

#a {
color: rgb(255, 0, 0);
background-color: rgb(255, 255, 0);
cursor: pointer;
}

#b {
display: none;
color: rgb(255, 255, 255);
background-color: rgb(0, 0, 255);
}

#a:hover \ #b {
display: inline-block;
}
_x000D_
<div id="content">
<div id="a">Hover me</div>
</div>

<div id="b">Show me</div>

<script src="https://rouninmedia.github.io/axe/axe.js"></script>
_x000D_
_x000D_
_x000D_

Update records in table from CTE

You don't need a CTE for this

UPDATE PEDI_InvoiceDetail
SET
    DocTotal = v.DocTotal
FROM
     PEDI_InvoiceDetail
inner join 
(
   SELECT InvoiceNumber, SUM(Sale + VAT) AS DocTotal
   FROM PEDI_InvoiceDetail
   GROUP BY InvoiceNumber
) v
   ON PEDI_InvoiceDetail.InvoiceNumber = v.InvoiceNumber

MySQL Query - Records between Today and Last 30 Days

You need to apply DATE_FORMAT in the SELECT clause, not the WHERE clause:

SELECT  DATE_FORMAT(create_date, '%m/%d/%Y')
FROM    mytable
WHERE   create_date BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE()

Also note that CURDATE() returns only the DATE portion of the date, so if you store create_date as a DATETIME with the time portion filled, this query will not select the today's records.

In this case, you'll need to use NOW instead:

SELECT  DATE_FORMAT(create_date, '%m/%d/%Y')
FROM    mytable
WHERE   create_date BETWEEN NOW() - INTERVAL 30 DAY AND NOW()

How to open a new tab in GNOME Terminal from command line?

For anyone seeking a solution that does not use the command line: ctrl+shift+t

How to properly set the 100% DIV height to match document/window height?

why don't you use width: 100% and height: 100%.

Matplotlib-Animation "No MovieWriters Available"

Had the same problem....managed to get it to work after a little while.

Thing to do is follow instructions on installing FFmpeg - which is (at least on windows) a bundle of executables you need to set a path to in your environment variables

http://www.wikihow.com/Install-FFmpeg-on-Windows

Download from ffmpeg.org

Hope this helps someone - even after a while after the question - good luck

Specify the from user when sending email using the mail command

You can specify any extra header you may need with -a

$mail -s "Some random subject" -a "From: [email protected]" [email protected]

How to disable Google asking permission to regularly check installed apps on my phone?

On Android prior to 4.2, go to Google Settings, tap Verify apps and uncheck the option Verify apps.

On Android 4.2+, uncheck the option Settings > Security > Verify apps and/or Settings > Developer options > Verify apps over USB.

Using pickle.dump - TypeError: must be str, not bytes

The output file needs to be opened in binary mode:

f = open('varstor.txt','w')

needs to be:

f = open('varstor.txt','wb')

Attempted to read or write protected memory

Microsoft also released a hotfix (July 2nd, 2007) to prevent the error "Attempted to read or write protected memory" that has been plaguing the .NET 2.0 platform for some time now. Look at http://support.microsoft.com/kb/923028 - not sure if it applies to you, but thought you might like to check it out.

Corrupted Access .accdb file: "Unrecognized Database Format"

Try to create a new database and import every table, query etc into this new database. With this import Access recreates all the objects from scratch. If there is some sort of corruption in an object, it should be solved.

If you're Lucky only the corrupted item(s) will be lost, if any.

Why do we check up to the square root of a prime number to determine if it is prime?

If a number n is not a prime, it can be factored into two factors a and b:

n = a * b

Now a and b can't be both greater than the square root of n, since then the product a * b would be greater than sqrt(n) * sqrt(n) = n. So in any factorization of n, at least one of the factors must be smaller than the square root of n, and if we can't find any factors less than or equal to the square root, n must be a prime.

Convert a list to a string in C#

The direct answer to your question is String.Join as others have mentioned.

However, if you need some manipulations, you can use Aggregate:

List<string> employees = new List<string>();
employees.Add("e1");
employees.Add("e2");
employees.Add("e3");

string employeesString = "'" + employees.Aggregate((x, y) => x + "','" + y) + "'";
Console.WriteLine(employeesString);
Console.ReadLine();

MVC Redirect to View from jQuery with parameters

If your click handler is successfully called then this should work:

$('#results').on('click', '.item', function () {
            var NestId = $(this).data('id');
            var url = "/Artists/Details?NestId=" + NestId; 
            window.location.href = url; 
        })

EDIT: In this particular case given that the action method parameter is a string which is nullable, then if NestId == null, won't cause any exception at all, given that the ModelBinder won't complain about it.

An "and" operator for an "if" statement in Bash

Quote:

The "-a" operator also doesn't work:

if [ $STATUS -ne 200 ] -a [[ "$STRING" != "$VALUE" ]]

For a more elaborate explanation: [ and ] are not Bash reserved words. The if keyword introduces a conditional to be evaluated by a job (the conditional is true if the job's return value is 0 or false otherwise).

For trivial tests, there is the test program (man test).

As some find lines like if test -f filename; then foo bar; fi, etc. annoying, on most systems you find a program called [ which is in fact only a symlink to the test program. When test is called as [, you have to add ] as the last positional argument.

So if test -f filename is basically the same (in terms of processes spawned) as if [ -f filename ]. In both cases the test program will be started, and both processes should behave identically.

Here's your mistake: if [ $STATUS -ne 200 ] -a [[ "$STRING" != "$VALUE" ]] will parse to if + some job, the job being everything except the if itself. The job is only a simple command (Bash speak for something which results in a single process), which means the first word ([) is the command and the rest its positional arguments. There are remaining arguments after the first ].

Also not, [[ is indeed a Bash keyword, but in this case it's only parsed as a normal command argument, because it's not at the front of the command.

Set Matplotlib colorbar size to match graph

You can do this easily with a matplotlib AxisDivider.

The example from the linked page also works without using subplots:

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np

plt.figure()
ax = plt.gca()
im = ax.imshow(np.arange(100).reshape((10,10)))

# create an axes on the right side of ax. The width of cax will be 5%
# of ax and the padding between cax and ax will be fixed at 0.05 inch.
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)

plt.colorbar(im, cax=cax)

enter image description here

HTML image bottom alignment inside DIV container

Flexboxes can accomplish this by using align-items: flex-end; with display: flex; or display: inline-flex;

div#imageContainer {
    height: 160px;  
    align-items: flex-end;
    display: flex;

    /* This is the default value, so you only need to explicitly set it if it's already being set to something else elsewhere. */
    /*flex-direction: row;*/
}

JSFiddle example

CSS-Tricks has a good guide for flexboxes

Given a starting and ending indices, how can I copy part of a string in C?

Just use memcpy.

If the destination isn't big enough, strncpy won't null terminate. if the destination is huge compared to the source, strncpy just fills the destination with nulls after the string. strncpy is pointless, and unsuitable for copying strings.

strncpy is like memcpy except it fills the destination with nulls once it sees one in the source. It's absolutely useless for string operations. It's for fixed with 0 padded records.

Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state

The other answers in my case did not work. I had to restart windows before I could debug the application again.

Google Maps JS API v3 - Simple Multiple Marker Example

Here is a nearly complete example javascript function that will allow multiple markers defined in a JSONObject.

It will only display the markers that are with in the bounds of the map.

This is important so you are not doing extra work.

You can also set a limit to the markers so you are not showing an extreme amount of markers (if there is a possibility of a thing in your usage);

it will also not display markers if the center of the map has not changed more than 500 meters.
This is important because if a user clicks on the marker and accidentally drags the map while doing so you don't want the map to reload the markers.

I attached this function to the idle event listener for the map so markers will show only when the map is idle and will redisplay the markers after a different event.

In action screen shot there is a little change in the screen shot showing more content in the infowindow. enter image description here pasted from pastbin.com

_x000D_
_x000D_
<script src="//pastebin.com/embed_js/uWAbRxfg"></script>
_x000D_
_x000D_
_x000D_