Programs & Examples On #Oledbconnection

C# Inserting Data from a form into an access Database

 private void Add_Click(object sender, EventArgs e) {
 OleDbConnection con = new OleDbConnection(@ "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\HP\Desktop\DS Project.mdb");
 OleDbCommand cmd = con.CreateCommand();
 con.Open();
 cmd.CommandText = "Insert into DSPro (Playlist) values('" + textBox1.Text + "')";
 cmd.ExecuteNonQuery();
 MessageBox.Show("Record Submitted", "Congrats");
 con.Close();
} 

how to refresh my datagridview after I add new data

If you using formview or something similar you can databind the gridview on the iteminserted event of the formview too. Like below

protected void FormView1_ItemInserted(object sender, FormViewInsertedEventArgs e)
    {
        GridView1.DataBind();
    }

You can do this on the data source iteminserted too.

How to connect access database in c#

Try this code,

public void ConnectToAccess()
{
    System.Data.OleDb.OleDbConnection conn = new 
        System.Data.OleDb.OleDbConnection();
    // TODO: Modify the connection string and include any
    // additional required properties for your database.
    conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
        @"Data source= C:\Documents and Settings\username\" +
        @"My Documents\AccessFile.mdb";
    try
    {
        conn.Open();
        // Insert code to process data.
    }
        catch (Exception ex)
    {
        MessageBox.Show("Failed to connect to data source");
    }
    finally
    {
        conn.Close();
    }
}

http://msdn.microsoft.com/en-us/library/5ybdbtte(v=vs.71).aspx

Cannot implicitly convert type 'int?' to 'int'.

this is because the return type of your method is int and OrdersPerHour is int? (nullable) , you can solve this by returning its value like below:

return OrdersPerHour.Value

also check if its not null to avoid exception like as below:

if(OrdersPerHour != null)
{

    return OrdersPerHour.Value;

}
else
{

  return 0; // depends on your choice

}

but in this case you will have to return some other value in the else part or after the if part otherwise compiler will flag an error that not all paths of code return value.

Import Excel to Datagridview

Since you have not replied to my comment above, I am posting a solution for both.

You are missing ' in Extended Properties

For Excel 2003 try this (TRIED AND TESTED)

    private void button1_Click(object sender, EventArgs e)
    {
        String name = "Items";
        String constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
                        "C:\\Sample.xls" + 
                        ";Extended Properties='Excel 8.0;HDR=YES;';";

        OleDbConnection con = new OleDbConnection(constr);
        OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
        con.Open();

        OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
        DataTable data = new DataTable();
        sda.Fill(data);
        grid_items.DataSource = data;
    }

BTW, I stopped working with Jet longtime ago. I use ACE now.

    private void button1_Click(object sender, EventArgs e)
    {
        String name = "Items";
        String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
                        "C:\\Sample.xls" + 
                        ";Extended Properties='Excel 8.0;HDR=YES;';";

        OleDbConnection con = new OleDbConnection(constr);
        OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
        con.Open();

        OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
        DataTable data = new DataTable();
        sda.Fill(data);
        grid_items.DataSource = data;
    }

enter image description here

For Excel 2007+

    private void button1_Click(object sender, EventArgs e)
    {
        String name = "Items";
        String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
                        "C:\\Sample.xlsx" + 
                        ";Extended Properties='Excel 12.0 XML;HDR=YES;';";

        OleDbConnection con = new OleDbConnection(constr);
        OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
        con.Open();

        OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
        DataTable data = new DataTable();
        sda.Fill(data);
        grid_items.DataSource = data;
    }

Where/how can I download (and install) the Microsoft.Jet.OLEDB.4.0 for Windows 8, 64 bit?

Make sure to target x86 on your project in Visual Studio. This should fix your trouble.

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

Try Using

string filename = Path.GetFileName(FileUploadControl.FileName);

Then Save the file at specified location using:

FileUploadControl.PostedFile.SaveAs(strpath + filename);

DataRow: Select cell value by a given column name

Which version of .NET are you using? Since .NET 3.5, there's an assembly System.Data.DataSetExtensions, which contains various useful extensions for dataTables, dataRows and the like.

You can try using

row.Field<type>("fieldName");

if that doesn't work, you can do this:

DataTable table = new DataTable();
var myColumn = table.Columns.Cast<DataColumn>().SingleOrDefault(col => col.ColumnName == "myColumnName");
if (myColumn != null)
{
    // just some roww
    var tableRow = table.AsEnumerable().First();
    var myData = tableRow.Field<string>(myColumn);
    // or if above does not work
    myData = tableRow.Field<string>(table.Columns.IndexOf(myColumn));
}

DataAdapter.Fill(Dataset)

You need to do this:

OleDbConnection connection = new OleDbConnection(
    "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Inventar.accdb");
DataSet DS = new DataSet();
connection.Open();

string query = 
    @"SELECT tbl_Computer.*,  tbl_Besitzer.*
    FROM tbl_Computer 
    INNER JOIN tbl_Besitzer ON tbl_Computer.FK_Benutzer = tbl_Besitzer.ID 
    WHERE (((tbl_Besitzer.Vorname)='ma'))";
OleDbDataAdapter DBAdapter = new OleDbDataAdapter();
DBAdapter.SelectCommand = new OleDbCommand(query, connection); 
DBAdapter.Fill(DS);

By the way, what is this DataSet1? This should be "DataSet".

Using Excel OleDb to get sheet names IN SHEET ORDER

I have created the below function using the information provided in the answer from @kraeppy (https://stackoverflow.com/a/19930386/2617732). This requires the .net framework v4.5 to be used and requires a reference to System.IO.Compression. This only works for xlsx files and not for the older xls files.

    using System.IO.Compression;
    using System.Xml;
    using System.Xml.Linq;

    static IEnumerable<string> GetWorksheetNamesOrdered(string fileName)
    {
        //open the excel file
        using (FileStream data = new FileStream(fileName, FileMode.Open))
        {
            //unzip
            ZipArchive archive = new ZipArchive(data);

            //select the correct file from the archive
            ZipArchiveEntry appxmlFile = archive.Entries.SingleOrDefault(e => e.FullName == "docProps/app.xml");

            //read the xml
            XDocument xdoc = XDocument.Load(appxmlFile.Open());

            //find the titles element
            XElement titlesElement = xdoc.Descendants().Where(e => e.Name.LocalName == "TitlesOfParts").Single();

            //extract the worksheet names
            return titlesElement
                .Elements().Where(e => e.Name.LocalName == "vector").Single()
                .Elements().Where(e => e.Name.LocalName == "lpstr")
                .Select(e => e.Value);
        }
    }

Microsoft.ACE.OLEDB.12.0 provider is not registered

I am assuming that if you are running a 64 bit system with a 32 bit database and trying to run a 64 bit console, the following packages need to be installed on the machine.

  1. Install the Microsoft Access Database Engine 2010 x86 Redistributable, this installation is available at: http://www.microsoft.com/download/en/details.aspx?id=13255 .
  2. Data Connectivity Components of Office 2007, this installation is available at: http://www.microsoft.com/download/en/confirmation.aspx?id=23734 .
  3. Microsoft Access Database Engine 2010 x64 Redistributable. You will need to download the package locally and run it with a passive flag. You can download the installation here: http://www.microsoft.com/en-us/download/details.aspx?id=13255 Installing using the command prompt with the '/passive' flag. In the command prompt run the following command: 'AccessDatabaseEngine_x64.exe /passive'

Note: The order seems to matter - so if you have anything installed already, uninstall and follow the steps above.

Format SQL in SQL Server Management Studio

There is a special trick I discovered by accident.

  1. Select the query you wish to format.
  2. Ctrl+Shift+Q (This will open your query in the query designer)
  3. Then just go OK Voila! Query designer will format your query for you. Caveat is that you can only do this for statements and not procedural code, but its better than nothing.

Nested JSON objects - do I have to use arrays for everything?

You have too many redundant nested arrays inside your jSON data, but it is possible to retrieve the information. Though like others have said you might want to clean it up.

use each() wrap within another each() until the last array.

for result.data[0].stuff[0].onetype[0] in jQuery you could do the following:

`

$.each(data.result.data, function(index0, v) {
    $.each(v, function (index1, w) {
        $.each(w, function (index2, x) {
            alert(x.id);
        });
    });

});

`

Export P7b file with all the certificate chain into CER file

If you add -chain to your command line, it will export any chained certificates.

http://www.openssl.org/docs/apps/pkcs12.html

What are -moz- and -webkit-?

These are the vendor-prefixed properties offered by the relevant rendering engines (-webkit for Chrome, Safari; -moz for Firefox, -o for Opera, -ms for Internet Explorer). Typically they're used to implement new, or proprietary CSS features, prior to final clarification/definition by the W3.

This allows properties to be set specific to each individual browser/rendering engine in order for inconsistencies between implementations to be safely accounted for. The prefixes will, over time, be removed (at least in theory) as the unprefixed, the final version, of the property is implemented in that browser.

To that end it's usually considered good practice to specify the vendor-prefixed version first and then the non-prefixed version, in order that the non-prefixed property will override the vendor-prefixed property-settings once it's implemented; for example:

.elementClass {
    -moz-border-radius: 2em;
    -ms-border-radius: 2em;
    -o-border-radius: 2em;
    -webkit-border-radius: 2em;
    border-radius: 2em;
}

Specifically, to address the CSS in your question, the lines you quote:

-webkit-column-count: 3;
-webkit-column-gap: 10px;
-webkit-column-fill: auto;
-moz-column-count: 3;
-moz-column-gap: 10px;
-moz-column-fill: auto;

Specify the column-count, column-gap and column-fill properties for Webkit browsers and Firefox.

References:

window.onbeforeunload and window.onunload is not working in Firefox, Safari, Opera?

I was able to get it to work in IE and FF with jQuery's:

$(window).bind('beforeunload', function(){

});

instead of: unload, onunload, or onbeforeunload

Adding the "Clear" Button to an iPhone UITextField

this don't work, do like me:

swift:

customTextField.clearButtonMode = UITextField.ViewMode.Always

customTextField.clearsOnBeginEditing = true;

func textFieldShouldClear(textField: UITextField) -> Bool {
    return true
}

Getting the current date in SQL Server?

As you are using SQL Server 2008, go with Martin's answer.

If you find yourself needing to do it in SQL Server 2005 where you don't have access to the Date column type, I'd use:

SELECT DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)

SQLFiddle

Access a global variable in a PHP function

You can do one of the following:

<?php
    $data = 'My data';

    function menugen() {
        global $data;
        echo "[" . $data . "]";
    }

    menugen();

Or

<?php
    $data = 'My data';

    function menugen() {
        echo "[" . $GLOBALS['data'] . "]";
    }

    menugen();

That being said, overuse of globals can lead to some poor code. It is usually better to pass in what you need. For example, instead of referencing a global database object you should pass in a handle to the database and act upon that. This is called dependency injection. It makes your life a lot easier when you implement automated testing (which you should).

How do I list one filename per output line in Linux?

Easy, as long as your filenames don't include newlines:

find . -maxdepth 1

If you're piping this into another command, you should probably prefer to separate your filenames by null bytes, rather than newlines, since null bytes cannot occur in a filename (but newlines may):

find . -maxdepth 1 -print0

Printing that on a terminal will probably display as one line, because null bytes are not normally printed. Some programs may need a specific option to handle null-delimited input, such as sort's -z. Your own script similarly would need to account for this.

How can I reverse the order of lines in a file?

For cross OS (i.e. OSX, Linux) solution that may use tac inside a shell script use homebrew as others have mentioned above, then just alias tac like so:

Install lib

For MacOS

brew install coreutils

For linux debian

sudo apt-get update
sudo apt-get install coreutils 

Then add alias

echo "alias tac='gtac'" >> ~/.bash_aliases (or wherever you load aliases)
source ~/.bash_aliases
tac myfile.txt

how to change listen port from default 7001 to something different?

I solved the issue by Changing the port no. in adrs-instances.xml file:

\JDEV_USER_HOME\system11.1.1.3.37.56.60\o.j2ee\adrs-instances.xml

Passing a String by Reference in Java?

For someone who are more curious

class Testt {
    static void Display(String s , String varname){
        System.out.println(varname + " variable data = "+ s + " :: address hashmap =  " + s.hashCode());
    }

    static void changeto(String s , String t){
        System.out.println("entered function");
        Display(s , "s");
        s = t ;
        Display(s,"s");
        System.out.println("exiting function");
    }

    public static void main(String args[]){
        String s =  "hi" ;
        Display(s,"s");
        changeto(s,"bye");
        Display(s,"s");
    }
}

Now by running this above code you can see how address hashcodes change with String variable s . a new object is allocated to variable s in function changeto when s is changed

What is the difference between class and instance methods?

Adding to above answers

Class method will work on class, we will use this for general purpose where like +stringWithFormat, size of class and most importantly for init etc

NSString *str = [NSString stringWithFormat:@"%.02f%%",someFloat]; 

Instance Method will work on an instance of a class not on a class like we are having two persons and we want to get know the balance of each separately here we need to use instance method. Because it won't return general response. e.g. like determine the count of NSSArray etc.

[johnson getAccountBalance];
[ankit getAccountBalance];

How does delete[] know it's an array?

ONE OF THE approaches for compilers is to allocate a little more memory and store count of elements in the head element.

Example how it could be done: Here

int* i = new int[4];

compiler will allocate sizeof(int)*5 bytes.

int *temp = malloc(sizeof(int)*5)

Will store 4 in first sizeof(int) bytes

*temp = 4;

and set i

i = temp + 1;

So i points to array of 4 elements, not 5.

And

delete[] i;

will be processed following way

int *temp = i - 1;
int numbers_of_element = *temp; // = 4
... call destructor for numbers_of_element elements if needed
... that are stored in temp + 1, temp + 2, ... temp + 4
free (temp)

Psexec "run as (remote) admin"

Simply add a -h after adding your credentials using a -u -p, and it will run with elevated privileges.

Amazon AWS Filezilla transfer permission denied

In my case, after 30 minutes changing permissions, got into account that the XLSX file I was trying to transfer was still open in Excel.

How do you enable mod_rewrite on any OS?

In order to use mod_rewrite you can type the following command in the terminal:

 $ su

 $ passwd **********

 # a2enmod rewrite

Restart apache2 after

 # service apache2 restart

 # /etc/init.d/apache2 restart

or

 # service apache2 restart

Generating a random hex color code with PHP

Web-safe colors are no longer necessary (nor a valid concept, even) as even mobile devices have 16+ bit colour these days.

See Wikipedia for more info.

In other words, use any colour from #000000 to #FFFFFF.

edit: Dear downvoters. Check the edit history for the question first.

How to format strings using printf() to get equal length in the output

printf allows formatting with width specifiers. For example,

printf( "%-30s %s\n", "Starting initialization...", "Ok." );

You would use a negative width specifier to indicate left-justification because the default is to use right-justification.

Is Eclipse the best IDE for Java?

Don't forget that Eclipse Platform was started by IBM. There are few platforms out there.

  • IBM Websphere Application Developer (WSAD) and/or Rational Application Developer (RAD) which is a Eclipse-type IDE from IBM (actually, that's Eclipse with IBM specialized libraries/plugins).
  • MyEclipse (never used it but it's another Eclipse-type IDE)
  • Sun Microsystem's NetBeans. It's too Java-centric as it's designed to create applications purely in java (NetBeans runs in Java).
  • IntelliJ (to name but a few)
  • Oracle JDeveloper (I never really liked the directory structure layout JDeveloper creates).

The advantage with Eclipse is that it can be customized to your development pleasure, plugins can be written for Eclipse to conform to your needs (e.g. The Eclipse "Easy Explorer" plugin for browsing the directory of your source in Windows Explorer). Eclipse allows you to also incorporate other languages/SDK's, such as C++, Silverlight projects, Android Projects for development. You can also easily manage resources in Eclipse.

In my experience NetBeans are resource intensive. Oracle JDeveloper and IntelliJ aren't free though. Oh yes, If you have issues or bugs with Eclipse, Eclipse has the ability to restart and submit the crash to Eclipse servers.

How do I debug Windows services in Visual Studio?

Debug a Windows Service over http (tested with VS 2015 Update 3 and .Net FW 4.6)

Firstly, you have to create a Console Project within your VS Solution(Add -> New Project -> Console Application).

Within the new project, create a class "ConsoleHost" with that code:

class ConsoleHost : IDisposable
{
    public static Uri BaseAddress = new Uri(http://localhost:8161/MyService/mex);
    private ServiceHost host;

    public void Start(Uri baseAddress)
    {
        if (host != null) return;

        host = new ServiceHost(typeof(MyService), baseAddress ?? BaseAddress);

        //binding
        var binding = new BasicHttpBinding()
        {
            Name = "MyService",
            MessageEncoding = WSMessageEncoding.Text,
            TextEncoding = Encoding.UTF8,
            MaxBufferPoolSize = 2147483647,
            MaxBufferSize = 2147483647,
            MaxReceivedMessageSize = 2147483647
        };

        host.Description.Endpoints.Clear();
        host.AddServiceEndpoint(typeof(IMyService), binding, baseAddress ?? BaseAddress);

        // Enable metadata publishing.
        var smb = new ServiceMetadataBehavior
        {
            HttpGetEnabled = true,
            MetadataExporter = { PolicyVersion = PolicyVersion.Policy15 },
        };

        host.Description.Behaviors.Add(smb);

        var defaultBehaviour = host.Description.Behaviors.OfType<ServiceDebugBehavior>().FirstOrDefault();
        if (defaultBehaviour != null)
        {
            defaultBehaviour.IncludeExceptionDetailInFaults = true;
        }

        host.Open();
    }

    public void Stop()
    {
        if (host == null)
            return;

        host.Close();
        host = null;
    }

    public void Dispose()
    {
        this.Stop();
    }
}

And this is the code for the Program.cs class:

public static class Program
{
    [STAThread]
    public static void Main(string[] args)
    {
        var baseAddress = new Uri(http://localhost:8161/MyService);
        var host = new ConsoleHost();
        host.Start(null);
        Console.WriteLine("The service is ready at {0}", baseAddress);
        Console.WriteLine("Press <Enter> to stop the service.");
        Console.ReadLine();
        host.Stop();
    }
}

Configurations such as connectionstrings should be copied in the App.config file of the Console project.

To sturt up the console, righ-click on Console project and click Debug -> Start new instance.

Missing `server' JVM (Java\jre7\bin\server\jvm.dll.)

To Fix The "Missing "server" JVM at C:\Program Files\Java\jre7\bin\server\jvm­­.dll, please install or use the JRE or JDK that contains these missing components.

Follow these steps:

Go to oracle.com and install Java JRE7 (Check if Java 6 is not installed already)

After that, go to C:/Program files/java/jre7/bin

Here, create an folder called Server

Now go into the C:/Program files/java/jre7/bin/client folder

Copy all the data in this folder into the new C:/Program files/java/jre7/bin/Server folder

How to get the selected item from ListView?

myList.setOnItemClickListener(new OnItemClickListener() {
  public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
      MyClass selItem = (MyClass) adapter.getItem(position);
   }
}

Oracle DateTime in Where Clause?

This is because a DATE column in Oracle also contains a time part. The result of the to_date() function is a date with the time set to 00:00:00 and thus it probably doesn't match any rows in the table.

You should use:

SELECT EMP_NAME, DEPT
FROM EMPLOYEE
WHERE trunc(TIME_CREATED) = TO_DATE('26/JAN/2011','dd/mon/yyyy')

Customize UITableView header section

Swift 4.2

In Swift 4.2 the name of table is a little changed.

    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: 18))
        let label = UILabel(frame: CGRect(x: 10, y: 5, width: tableView.frame.size.width, height: 18))
        label.font = UIFont.systemFont(ofSize: 14)
        label.text = list.objectAtIndex(section) as! String
        view.addSubview(label)
        view.backgroundColor = UIColor.gray // Set your background color

        return view
    }

Android Studio SDK location

For Mac/OSX the default location is /Users/<username>/Library/Android/sdk.

Do standard windows .ini files allow comments?

Windows INI API support for:

  • Line comments: yes, using semi-colon ;
  • Trailing comments: No

The authoritative source is the Windows API function that reads values out of INI files

GetPrivateProfileString

Retrieves a string from the specified section in an initialization file.

The reason "full line comments" work is because the requested value does not exist. For example, when parsing the following ini file contents:

[Application]
UseLiveData=1
;coke=zero
pepsi=diet   ;gag
#stackoverflow=splotchy

Reading the values:

  • UseLiveData: 1
  • coke: not present
  • ;coke: not present
  • pepsi: diet ;gag
  • stackoverflow: not present
  • #stackoverflow: splotchy

Update: I used to think that the number sign (#) was a pseudo line-comment character. The reason using leading # works to hide stackoverflow is because the name stackoverflow no longer exists. And it turns out that semi-colon (;) is a line-comment.

But there is no support for trailing comments.

Converting a POSTMAN request to Curl

enter image description here

You can see the button "Code" in the attached screenshot, press it and you can get your code in many different languages including PHP cURL

enter image description here

Jquery Validate custom error message location

JQUERY FORM VALIDATION CUSTOM ERROR MESSAGE

Demo & example

_x000D_
_x000D_
$(document).ready(function(){_x000D_
  $("#registration").validate({_x000D_
    // Specify validation rules_x000D_
    rules: {_x000D_
      firstname: "required",_x000D_
      lastname: "required",_x000D_
      email: {_x000D_
        required: true,_x000D_
        email: true_x000D_
      },      _x000D_
      phone: {_x000D_
        required: true,_x000D_
        digits: true,_x000D_
        minlength: 10,_x000D_
        maxlength: 10,_x000D_
      },_x000D_
      password: {_x000D_
        required: true,_x000D_
        minlength: 5,_x000D_
      }_x000D_
    },_x000D_
    messages: {_x000D_
      firstname: {_x000D_
      required: "Please enter first name",_x000D_
     },      _x000D_
     lastname: {_x000D_
      required: "Please enter last name",_x000D_
     },     _x000D_
     phone: {_x000D_
      required: "Please enter phone number",_x000D_
      digits: "Please enter valid phone number",_x000D_
      minlength: "Phone number field accept only 10 digits",_x000D_
      maxlength: "Phone number field accept only 10 digits",_x000D_
     },     _x000D_
     email: {_x000D_
      required: "Please enter email address",_x000D_
      email: "Please enter a valid email address.",_x000D_
     },_x000D_
    },_x000D_
  _x000D_
  });_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>jQuery Form Validation Using validator()</title>_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> _x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>_x000D_
<style>_x000D_
  .error{_x000D_
    color: red;_x000D_
  }_x000D_
  label,_x000D_
  input,_x000D_
  button {_x000D_
    border: 0;_x000D_
    margin-bottom: 3px;_x000D_
    display: block;_x000D_
    width: 100%;_x000D_
  }_x000D_
 .common_box_body {_x000D_
    padding: 15px;_x000D_
    border: 12px solid #28BAA2;_x000D_
    border-color: #28BAA2;_x000D_
    border-radius: 15px;_x000D_
    margin-top: 10px;_x000D_
    background: #d4edda;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
<div class="common_box_body test">_x000D_
  <h2>Registration</h2>_x000D_
  <form action="#" name="registration" id="registration">_x000D_
 _x000D_
    <label for="firstname">First Name</label>_x000D_
    <input type="text" name="firstname" id="firstname" placeholder="John"><br>_x000D_
 _x000D_
    <label for="lastname">Last Name</label>_x000D_
    <input type="text" name="lastname" id="lastname" placeholder="Doe"><br>_x000D_
 _x000D_
    <label for="phone">Phone</label>_x000D_
    <input type="text" name="phone" id="phone" placeholder="8889988899"><br>  _x000D_
 _x000D_
    <label for="email">Email</label>_x000D_
    <input type="email" name="email" id="email" placeholder="[email protected]"><br>_x000D_
 _x000D_
    <label for="password">Password</label>_x000D_
    <input type="password" name="password" id="password" placeholder=""><br>_x000D_
 _x000D_
    <input name="submit" type="submit" id="submit" class="submit" value="Submit">_x000D_
  </form>_x000D_
</div>_x000D_
 _x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Javascript: Setting location.href versus location

Like as has been said already, location is an object. But that person suggested using either. But, you will do better to use the .href version.

Objects have default properties which, if nothing else is specified, they are assumed. In the case of the location object, it has a property called .href. And by not specifying ANY property during the assignment, it will assume "href" by default.

This is all well and fine until a later object model version changes and there either is no longer a default property, or the default property is changed. Then your program breaks unexpectedly.

If you mean href, you should specify href.

How can I see the entire HTTP request that's being sent by my Python application?

You can use HTTP Toolkit to do exactly this.

It's especially useful if you need to do this quickly, with no code changes: you can open a terminal from HTTP Toolkit, run any Python code from there as normal, and you'll be able to see the full content of every HTTP/HTTPS request immediately.

There's a free version that can do everything you need, and it's 100% open source.

I'm the creator of HTTP Toolkit; I actually built it myself to solve the exact same problem for me a while back! I too was trying to debug a payment integration, but their SDK didn't work, I couldn't tell why, and I needed to know what was actually going on to properly fix it. It's very frustrating, but being able to see the raw traffic really helps.

HTML5 Pre-resize images before uploading

The accepted answer works great, but the resize logic ignores the case in which the image is larger than the maximum in only one of the axes (for example, height > maxHeight but width <= maxWidth).

I think the following code takes care of all cases in a more straight-forward and functional way (ignore the typescript type annotations if using plain javascript):

private scaleDownSize(width: number, height: number, maxWidth: number, maxHeight: number): {width: number, height: number} {
    if (width <= maxWidth && height <= maxHeight)
      return { width, height };
    else if (width / maxWidth > height / maxHeight)
      return { width: maxWidth, height: height * maxWidth / width};
    else
      return { width: width * maxHeight / height, height: maxHeight };
  }

String.Format for Hex

Translate composed UInt32 color Value to CSS in .NET

I know the question applies to 3 input values (red green blue). But there may be the situation where you already have a composed 32bit Value. It looks like you want to send the data to some HTML CSS renderer (because of the #HEX format). Actually CSS wants you to print 6 or at least 3 zero filled hex digits here. so #{0:X06} or #{0:X03} would be required. Due to some strange behaviour, this always prints 8 digits instead of 6.

Solve this by:

String.Format("#{0:X02}{1:X02}{2:X02}", (Value & 0x00FF0000) >> 16, (Value & 0x0000FF00) >> 8, (Value & 0x000000FF) >> 0)

Getting path of captured image in Android using camera intent

try this

String[] projection = { MediaStore.Images.Media.DATA };
            @SuppressWarnings("deprecation")
            Cursor cursor = managedQuery(mCapturedImageURI, projection,
                    null, null, null);
            int column_index_data = cursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            image_path = cursor.getString(column_index_data);
            Log.e("path of image from CAMERA......******************.........",
                    image_path + "");

for capturing image:

    String fileName = "temp.jpg";
    ContentValues values = new ContentValues();
    values.put(MediaStore.Images.Media.TITLE, fileName);
    mCapturedImageURI = getContentResolver().insert(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
    values.clear();

PHP Session Destroy on Log Out Button

The folder being password protected has nothing to do with PHP!

The method being used is called "Basic Authentication". There are no cross-browser ways to "logout" from it, except to ask the user to close and then open their browser...

Here's how you you could do it in PHP instead (fully remove your Apache basic auth in .htaccess or wherever it is first):

login.php:

<?php
session_start();
//change 'valid_username' and 'valid_password' to your desired "correct" username and password
if (! empty($_POST) && $_POST['user'] === 'valid_username' && $_POST['pass'] === 'valid_password')
{
    $_SESSION['logged_in'] = true;
    header('Location: /index.php');
}
else
{
    ?>

    <form method="POST">
    Username: <input name="user" type="text"><br>
    Password: <input name="pass" type="text"><br><br>
    <input type="submit" value="submit">
    </form>

    <?php
}

index.php

<?php
session_start();
if (! empty($_SESSION['logged_in']))
{
    ?>

    <p>here is my super-secret content</p>
    <a href='logout.php'>Click here to log out</a>

    <?php
}
else
{
    echo 'You are not logged in. <a href="login.php">Click here</a> to log in.';
}

logout.php:

<?php
session_start();
session_destroy();
echo 'You have been logged out. <a href="/">Go back</a>';

Obviously this is a very basic implementation. You'd expect the usernames and passwords to be in a database, not as a hardcoded comparison. I'm just trying to give you an idea of how to do the session thing.

Hope this helps you understand what's going on.

Search a string in a file and delete it from this file by Shell Script

sed -i '/pattern/d' file

Use 'd' to delete a line. This works at least with GNU-Sed.

If your Sed doesn't have the option, to change a file in place, maybe you can use an intermediate file, to store the modification:

sed '/pattern/d' file > tmpfile && mv tmpfile file

Writing directly to the source usually doesn't work: sed '/pattern/d' file > file so make a copy before trying out, if you doubt it.

How to make Google Fonts work in IE?

Google Fonts uses Web Open Font Format (WOFF), which is good, because it's the recommended font format by the W3C.

IE versions older than IE9 don't support Web Open Font Format (WOFF) because it didn't exist back then. To support < IE9, you need to serve your font in Embedded Open Type (EOT). To do this you will need to write your own @font-face css tag instead of using the embed script from Google. Also you need to convert the original WOFF file to EOT.

You can convert your WOFF to EOT over here by first converting it to TTF and then to EOT: http://convertfonts.com/

Then you can serve the EOT font like this:

@font-face {
    font-family: 'MyFont';
    src: url('myfont.eot');
}

Now it works in < IE9. However, modern browsers don't support EOT anymore, so now your fonts won't work in modern browsers. So you need to specify them both. The src property supports this by comma seperating the font urls and specefying the type:

src: url('myfont.woff') format('woff'),
     url('myfont.eot') format('embedded-opentype');

However, < IE9 doesn't understand this, it just graps the text between the first quote and the last quote, so it will actually get:

myfont.woff') format('woff'),
url('myfont.eot') format('embedded-opentype

as the URL to the font. We can fix this by first specifying a src with only one url which is the EOT format, then specifying a second src property that's meant for the modern browsers and < IE9 will not understand. Because < IE9 will not understand it it will ignore the tag so the EOT will still be working. The modern browsers will use the last specified font they support, so probably WOFF.

src: url('myfont.eot');
src: url('myfont.woff') format('woff');

So only because in the second src property you specify the format('woff'), < IE9 won't understand it (or actually it just can't find the font at the url myfont.woff') format('woff) and will keep using the first specified one (eot).

So now you got your Google Webfonts working for < IE9 and modern browsers!

For more information about different font type and browser support, read this perfect article by Alex Tatiyants: http://tatiyants.com/how-to-get-ie8-to-support-html5-tags-and-web-fonts/

Run MySQLDump without Locking Tables

    mysqldump -uuid -ppwd --skip-opt --single-transaction --max_allowed_packet=1G -q db |   mysql -u root --password=xxx -h localhost db

How to check for changes on remote (origin) Git repository

I simply use

git fetch origin

to fetch the remote changes, and then I view both local and pending remote commits (and their associated changes) with the nice gitk tool involving the --all argument like:

gitk --all

SQL Server : converting varchar to INT

This question has got 91,000 views so perhaps many people are looking for a more generic solution to the issue in the title "error converting varchar to INT"

If you are on SQL Server 2012+ one way of handling this invalid data is to use TRY_CAST

SELECT TRY_CAST (userID AS INT)
FROM   audit 

On previous versions you could use

SELECT CASE
         WHEN ISNUMERIC(RTRIM(userID) + '.0e0') = 1
              AND LEN(userID) <= 11
           THEN CAST(userID AS INT)
       END
FROM   audit 

Both return NULL if the value cannot be cast.

In the specific case that you have in your question with known bad values I would use the following however.

CAST(REPLACE(userID COLLATE Latin1_General_Bin, CHAR(0),'') AS INT)

Trying to replace the null character is often problematic except if using a binary collation.

How to remove old Docker containers

This short script might help (compiled from previous answers)!

#!/bin/bash

# Remove dangling images

IMAGE_IDS=$(sudo docker images -f "dangling=true" -q)

if [ -n "$IMAGE_IDS" ]; then

    sudo docker rmi $IMAGE_IDS > /dev/null 2>&1
    echo 'Images removed' $IMAGE_IDS
fi


# Remove exited containers

CONTAINER_IDS=$(sudo docker ps -a -q -f status=exited)

if [ -n "$CONTAINER_IDS" ]; then

    sudo docker rm -v $CONTAINER_IDS > /dev/null 2>&1
    echo 'Containers remove $CONTAINER_IDS'
fi

In Node.js, how do I turn a string to a json?

You need to use this function.

JSON.parse(yourJsonString);

And it will return the object / array that was contained within the string.

How do you use MySQL's source command to import large files in windows

For importing a large SQL file using the command line in MySQL.

First go to file path at the command line. Then,

Option 1:

mysql -u {user_name} -p{password} {database_name}  < your_file.sql

It's give a warning mesaage : Using a password on the command line interface can be insecure.

Done.Your file will be imported.

Option 2:

mysql -u {user_name} -p {database_name}  < your_file.sql

in this you are not provide sql password then they asked for password just enter password and your file will be imported.

Spring REST Service: how to configure to remove null objects in json response

I've found a solution through configuring the Spring container, but it's still not exactly what I wanted.

I rolled back to Spring 3.0.5, removed and in it's place I changed my config file to:

    <bean
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <bean
                class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
                <property name="objectMapper" ref="jacksonObjectMapper" />
            </bean>
        </list>
    </property>
</bean>


<bean id="jacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper" />
<bean id="jacksonSerializationConfig" class="org.codehaus.jackson.map.SerializationConfig"
    factory-bean="jacksonObjectMapper" factory-method="getSerializationConfig" />
<bean
    class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="targetObject" ref="jacksonSerializationConfig" />
    <property name="targetMethod" value="setSerializationInclusion" />
    <property name="arguments">
        <list>
            <value type="org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion">NON_NULL</value>
        </list>
    </property>
</bean>

This is of course similar to responses given in other questions e.g.

configuring the jacksonObjectMapper not working in spring mvc 3

The important thing to note is that mvc:annotation-driven and AnnotationMethodHandlerAdapter cannot be used in the same context.

I'm still unable to get it working with Spring 3.1 and mvc:annotation-driven though. A solution that uses mvc:annotation-driven and all the benefits that accompany it would be far better I think. If anyone could show me how to do this, that would be great.

Entry point for Java applications: main(), init(), or run()?

This is a peculiar question because it's not supposed to be a matter of choice.

When you launch the JVM, you specify a class to run, and it is the main() of this class where your program starts.

By init(), I assume you mean the JApplet method. When an applet is launched in the browser, the init() method of the specified applet is executed as the first order of business.

By run(), I assume you mean the method of Runnable. This is the method invoked when a new thread is started.

  • main: program start
  • init: applet start
  • run: thread start

If Eclipse is running your run() method even though you have no main(), then it is doing something peculiar and non-standard, but not infeasible. Perhaps you should post a sample class that you've been running this way.

Understanding implicit in Scala

I had the exact same question as you had and I think I should share how I started to understand it by a few really simple examples (note that it only covers the common use cases).

There are two common use cases in Scala using implicit.

  • Using it on a variable
  • Using it on a function

Examples are as follows

Using it on a variable. As you can see, if the implicit keyword is used in the last parameter list, then the closest variable will be used.

// Here I define a class and initiated an instance of this class
case class Person(val name: String)
val charles: Person = Person("Charles")

// Here I define a function
def greeting(words: String)(implicit person: Person) = person match {
  case Person(name: String) if name != "" => s"$name, $words"
    case _ => "$words"
}

greeting("Good morning") // Charles, Good moring

val charles: Person = Person("")
greeting("Good morning") // Good moring

Using it on a function. As you can see, if the implicit is used on the function, then the closest type conversion method will be used.

val num = 10 // num: Int (of course)

// Here I define a implicit function
implicit def intToString(num: Int) = s"$num -- I am a String now!"

val num = 10 // num: Int (of course). Nothing happens yet.. Compiler believes you want 10 to be an Int

// Util...
val num: String = 10 // Compiler trust you first, and it thinks you have `implicitly` told it that you had a way to covert the type from Int to String, which the function `intToString` can do!
// So num is now actually "10 -- I am a String now!"
// console will print this -> val num: String = 10 -- I am a String now!

Hope this can help.

Differences between Oracle JDK and OpenJDK

Both OpenJDK and Oracle JDK are created and maintained currently by Oracle only.

OpenJDK and Oracle JDK are implementations of the same Java specification passed the TCK (Java Technology Certification Kit).

Most of the vendors of JDK are written on top of OpenJDK by doing a few tweaks to [mostly to replace licensed proprietary parts / replace with more high-performance items that only work on specific OS] components without breaking the TCK compatibility.

Many vendors implemented the Java specification and got TCK passed. For example, IBM J9, Azul Zulu, Azul Zing, and Oracle JDK.

Almost every existing JDK is derived from OpenJDK.

As suggested by many, licensing is a change between JDKs.

Starting with JDK 11 accessing the long time support Oracle JDK/Java SE will now require a commercial license. You should now pay attention to which JDK you're installing as Oracle JDK without subscription could stop working. source

Ref: List of Java virtual machines

What do I need to do to get Internet Explorer 8 to accept a self signed certificate?

If you're getting an address mismatch error, just allow address mismatches:

  1. Tools and select Internet Options
  2. select the Advanced tab
  3. Scroll down and uncheck Warn about certificate address mismatch

Remove empty lines in a text file via grep

If removing empty lines means lines including any spaces, use:

grep '\S' FILE

For example:

$  printf "line1\n\nline2\n \nline3\n\t\nline4\n" > FILE
$  cat -v FILE
line1

line2

line3

line4
$  grep '\S' FILE
line1
line2
line3
line4
$  grep . FILE
line1
line2

line3

line4

See also:

Getting full URL of action in ASP.NET MVC

This what you need to do.

@Url.Action(action,controller, null, Request.Url.Scheme)

Checking if a string array contains a value, and if so, getting its position

string x ="Hi ,World";
string y = x;
char[] whitespace = new char[]{ ' ',\t'};          
string[] fooArray = y.Split(whitespace);  // now you have an array of 3 strings
y = String.Join(" ", fooArray);
string[] target = { "Hi", "World", "VW_Slep" };

for (int i = 0; i < target.Length; i++)
{
    string v = target[i];
    string results = Array.Find(fooArray, element => element.StartsWith(v, StringComparison.Ordinal));
    //
    if (results != null)
    { MessageBox.Show(results); }

}

How to add a custom button to the toolbar that calls a JavaScript function?

This article may be useful too http://mito-team.com/article/2012/collapse-button-for-ckeditor-for-drupal

There are code samples and step-by-step guide about building your own CKEditor plugin with custom button.

Change PictureBox's image to image from my resources?

If you loaded the resource using the visual studio UI, then you should be able to do this:

picturebox.Image = project.Properties.Resources.imgfromresource

add item to dropdown list in html using javascript

Since your script is in <head>, you need to wrap it in window.onload:

window.onload = function () {
    var select = document.getElementById("year");
    for(var i = 2011; i >= 1900; --i) {
        var option = document.createElement('option');
        option.text = option.value = i;
        select.add(option, 0);
    }
};

You can also do it in this way

<body onload="addList()">

Visual C++ executable and missing MSVCR100d.dll

I got the same error.

I was refering a VS2010 DLL in a VS2012 project.

Just recompiled the DLL on VS2012 and now everything is fine.

What is the difference between H.264 video and MPEG-4 video?

H.264 is a new standard for video compression which has more advanced compression methods than the basic MPEG-4 compression. One of the advantages of H.264 is the high compression rate. It is about 1.5 to 2 times more efficient than MPEG-4 encoding. This high compression rate makes it possible to record more information on the same hard disk.
The image quality is also better and playback is more fluent than with basic MPEG-4 compression. The most interesting feature however is the lower bit-rate required for network transmission.
So the 3 main advantages of H.264 over MPEG-4 compression are:
- Small file size for longer recording time and better network transmission.
- Fluent and better video quality for real time playback
- More efficient mobile surveillance application

H264 is now enshrined in MPEG4 as part 10 also known as AVC

Refer to: http://www.velleman.eu/downloads/3/h264_vs_mpeg4_en.pdf

Hope this helps.

Determine which element the mouse pointer is on top of in JavaScript

You can use this selector to undermouse object and then manipulate it as a jQuery object:

$(':hover').last();

Convert array of strings into a string in Java

String[] strings = new String[25000];
for (int i = 0; i < 25000; i++) strings[i] = '1234567';

String result;
result = "";
for (String s : strings) result += s;
//linear +: 5s

result = "";
for (String s : strings) result = result.concat(s);
//linear .concat: 2.5s

result = String.join("", strings);
//Java 8 .join: 3ms

Public String join(String delimiter, String[] s)
{
    int ls = s.length;
    switch (ls)
    {
        case 0: return "";
        case 1: return s[0];
        case 2: return s[0].concat(delimiter).concat(s[1]);
        default:
            int l1 = ls / 2;
            String[] s1 = Arrays.copyOfRange(s, 0, l1); 
            String[] s2 = Arrays.copyOfRange(s, l1, ls); 
            return join(delimiter, s1).concat(delimiter).concat(join(delimiter, s2));
    }
}
result = join("", strings);
// Divide&Conquer join: 7ms

If you don't have the choise but to use Java 6 or 7 then you should use Divide&Conquer join.

Why is Java Vector (and Stack) class considered obsolete or deprecated?

Vector synchronizes on each individual operation. That's almost never what you want to do.

Generally you want to synchronize a whole sequence of operations. Synchronizing individual operations is both less safe (if you iterate over a Vector, for instance, you still need to take out a lock to avoid anyone else changing the collection at the same time, which would cause a ConcurrentModificationException in the iterating thread) but also slower (why take out a lock repeatedly when once will be enough)?

Of course, it also has the overhead of locking even when you don't need to.

Basically, it's a very flawed approach to synchronization in most situations. As Mr Brian Henk pointed out, you can decorate a collection using the calls such as Collections.synchronizedList - the fact that Vector combines both the "resized array" collection implementation with the "synchronize every operation" bit is another example of poor design; the decoration approach gives cleaner separation of concerns.

As for a Stack equivalent - I'd look at Deque/ArrayDeque to start with.

Save and load weights in keras

Here is a YouTube video that explains exactly what you're wanting to do: Save and load a Keras model

There are three different saving methods that Keras makes available. These are described in the video link above (with examples), as well as below.

First, the reason you're receiving the error is because you're calling load_model incorrectly.

To save and load the weights of the model, you would first use

model.save_weights('my_model_weights.h5')

to save the weights, as you've displayed. To load the weights, you would first need to build your model, and then call load_weights on the model, as in

model.load_weights('my_model_weights.h5')

Another saving technique is model.save(filepath). This save function saves:

  • The architecture of the model, allowing to re-create the model.
  • The weights of the model.
  • The training configuration (loss, optimizer).
  • The state of the optimizer, allowing to resume training exactly where you left off.

To load this saved model, you would use the following:

from keras.models import load_model
new_model = load_model(filepath)'

Lastly, model.to_json(), saves only the architecture of the model. To load the architecture, you would use

from keras.models import model_from_json
model = model_from_json(json_string)

Circular gradient in android

You can get a circular gradient using android:type="radial":

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient android:type="radial" android:gradientRadius="250dp"
        android:startColor="#E9E9E9" android:endColor="#D4D4D4" />
</shape>

Git clone without .git directory

since you only want the files, you don't need to treat it as a git repo.

rsync -rlp --exclude '.git' user@host:path/to/git/repo/ .

and this only works with local path and remote ssh/rsync path, it may not work if the remote server only provides git:// or https:// access.

Formatting a number with exactly two decimals in JavaScript

I'm fix the problem the modifier. Support 2 decimal only.

_x000D_
_x000D_
$(function(){_x000D_
  //input number only._x000D_
  convertNumberFloatZero(22); // output : 22.00_x000D_
  convertNumberFloatZero(22.5); // output : 22.50_x000D_
  convertNumberFloatZero(22.55); // output : 22.55_x000D_
  convertNumberFloatZero(22.556); // output : 22.56_x000D_
  convertNumberFloatZero(22.555); // output : 22.55_x000D_
  convertNumberFloatZero(22.5541); // output : 22.54_x000D_
  convertNumberFloatZero(22222.5541); // output : 22,222.54_x000D_
_x000D_
  function convertNumberFloatZero(number){_x000D_
 if(!$.isNumeric(number)){_x000D_
  return 'NaN';_x000D_
 }_x000D_
 var numberFloat = number.toFixed(3);_x000D_
 var splitNumber = numberFloat.split(".");_x000D_
 var cNumberFloat = number.toFixed(2);_x000D_
 var cNsplitNumber = cNumberFloat.split(".");_x000D_
 var lastChar = splitNumber[1].substr(splitNumber[1].length - 1);_x000D_
 if(lastChar > 0 && lastChar < 5){_x000D_
  cNsplitNumber[1]--;_x000D_
 }_x000D_
 return Number(splitNumber[0]).toLocaleString('en').concat('.').concat(cNsplitNumber[1]);_x000D_
  };_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Effect of NOLOCK hint in SELECT statements

In addition to what is said above, you should be very aware that nolock actually imposes the risk of you not getting rows that has been committed before your select.

See http://blogs.msdn.com/sqlcat/archive/2007/02/01/previously-committed-rows-might-be-missed-if-nolock-hint-is-used.aspx

ASP.NET custom error page - Server.GetLastError() is null

One important consideration that I think everybody is missing here is a load-balancing (web farm) scenario. Since the server that's executing global.asax may be different than the server that's about the execute the custom error page, stashing the exception object in Application is not reliable.

I'm still looking for a reliable solution to this problem in a web farm configuration, and/or a good explanation from MS as to why you just can't pick up the exception with Server.GetLastError on the custom error page like you can in global.asax Application_Error.

P.S. It's unsafe to store data in the Application collection without first locking it and then unlocking it.

Add 2 hours to current time in MySQL?

The DATE_ADD() function will do the trick. (You can also use the ADDTIME() function if you're running at least v4.1.1.)

For your query, this would be:

SELECT * 
FROM courses 
WHERE DATE_ADD(now(), INTERVAL 2 HOUR) > start_time

Or,

SELECT * 
FROM courses 
WHERE ADDTIME(now(), '02:00:00') > start_time

Install .ipa to iPad with or without iTunes

If you built the IPA using PhoneGap Build online you can download and install the IPA directly on your Ipad/Iphone by opening build.phonegap.com in Safari on the device, logging in and then clicking the iOS tab (the download ipa button). You will then be asked to install the app you built.

Direct link to this after logging in is: https://build.phonegap.com/apps/YOUR-BUILD-NUMBER/download/ios

When to use LinkedList over ArrayList in Java?

Summary ArrayList with ArrayDeque are preferable in many more use-cases than LinkedList. If you're not sure — just start with ArrayList.


TLDR, in ArrayList accessing an element takes constant time [O(1)] and adding an element takes O(n) time [worst case]. In LinkedList adding an element takes O(n) time and accessing also takes O(n) time but LinkedList uses more memory than ArrayList.

LinkedList and ArrayList are two different implementations of the List interface. LinkedList implements it with a doubly-linked list. ArrayList implements it with a dynamically re-sizing array.

As with standard linked list and array operations, the various methods will have different algorithmic runtimes.

For LinkedList<E>

  • get(int index) is O(n) (with n/4 steps on average), but O(1) when index = 0 or index = list.size() - 1 (in this case, you can also use getFirst() and getLast()). One of the main benefits of LinkedList<E>
  • add(int index, E element) is O(n) (with n/4 steps on average), but O(1) when index = 0 or index = list.size() - 1 (in this case, you can also use addFirst() and addLast()/add()). One of the main benefits of LinkedList<E>
  • remove(int index) is O(n) (with n/4 steps on average), but O(1) when index = 0 or index = list.size() - 1 (in this case, you can also use removeFirst() and removeLast()). One of the main benefits of LinkedList<E>
  • Iterator.remove() is O(1). One of the main benefits of LinkedList<E>
  • ListIterator.add(E element) is O(1). One of the main benefits of LinkedList<E>

Note: Many of the operations need n/4 steps on average, constant number of steps in the best case (e.g. index = 0), and n/2 steps in worst case (middle of list)

For ArrayList<E>

  • get(int index) is O(1). Main benefit of ArrayList<E>
  • add(E element) is O(1) amortized, but O(n) worst-case since the array must be resized and copied
  • add(int index, E element) is O(n) (with n/2 steps on average)
  • remove(int index) is O(n) (with n/2 steps on average)
  • Iterator.remove() is O(n) (with n/2 steps on average)
  • ListIterator.add(E element) is O(n) (with n/2 steps on average)

Note: Many of the operations need n/2 steps on average, constant number of steps in the best case (end of list), n steps in the worst case (start of list)

LinkedList<E> allows for constant-time insertions or removals using iterators, but only sequential access of elements. In other words, you can walk the list forwards or backwards, but finding a position in the list takes time proportional to the size of the list. Javadoc says "operations that index into the list will traverse the list from the beginning or the end, whichever is closer", so those methods are O(n) (n/4 steps) on average, though O(1) for index = 0.

ArrayList<E>, on the other hand, allow fast random read access, so you can grab any element in constant time. But adding or removing from anywhere but the end requires shifting all the latter elements over, either to make an opening or fill the gap. Also, if you add more elements than the capacity of the underlying array, a new array (1.5 times the size) is allocated, and the old array is copied to the new one, so adding to an ArrayList is O(n) in the worst case but constant on average.

So depending on the operations you intend to do, you should choose the implementations accordingly. Iterating over either kind of List is practically equally cheap. (Iterating over an ArrayList is technically faster, but unless you're doing something really performance-sensitive, you shouldn't worry about this -- they're both constants.)

The main benefits of using a LinkedList arise when you re-use existing iterators to insert and remove elements. These operations can then be done in O(1) by changing the list locally only. In an array list, the remainder of the array needs to be moved (i.e. copied). On the other side, seeking in a LinkedList means following the links in O(n) (n/2 steps) for worst case, whereas in an ArrayList the desired position can be computed mathematically and accessed in O(1).

Another benefit of using a LinkedList arise when you add or remove from the head of the list, since those operations are O(1), while they are O(n) for ArrayList. Note that ArrayDeque may be a good alternative to LinkedList for adding and removing from the head, but it is not a List.

Also, if you have large lists, keep in mind that memory usage is also different. Each element of a LinkedList has more overhead since pointers to the next and previous elements are also stored. ArrayLists don't have this overhead. However, ArrayLists take up as much memory as is allocated for the capacity, regardless of whether elements have actually been added.

The default initial capacity of an ArrayList is pretty small (10 from Java 1.4 - 1.8). But since the underlying implementation is an array, the array must be resized if you add a lot of elements. To avoid the high cost of resizing when you know you're going to add a lot of elements, construct the ArrayList with a higher initial capacity.

If the data structures perspective is used to understand the two structures, a LinkedList is basically a sequential data structure which contains a head Node. The Node is a wrapper for two components : a value of type T [accepted through generics] and another reference to the Node linked to it. So, we can assert it is a recursive data structure (a Node contains another Node which has another Node and so on...). Addition of elements takes linear time in LinkedList as stated above.

An ArrayList, is a growable array. It is just like a regular array. Under the hood, when an element is added at index i, it creates another array with a size which is 1 greater than previous size (So in general, when n elements are to be added to an ArrayList, a new array of size previous size plus n is created). The elements are then copied from previous array to new one and the elements that are to be added are also placed at the specified indices.

How do I copy the contents of a String to the clipboard in C#?

You can use System.Windows.Forms.Clipboard.SetText(...).

Get human readable version of file size?

If you're using Django installed you can also try filesizeformat:

from django.template.defaultfilters import filesizeformat
filesizeformat(1073741824)

=>

"1.0 GB"

Setting DEBUG = False causes 500 Error

Ok after trying soo many things, the correct solution is ...

you need to set DEBUG = 'FALSE' not False or FALSE, but 'FALSE' with ''

Intel HAXM installation error - This computer does not support Intel Virtualization Technology (VT-x)

If you dont find Hyper-V option in control panel as said in other responses here, try entering BIOS setup (restarting and pressing F-12 or ESC or other depending on your PC) and enabling Virtualization, located probably in CPU options.

How to debug a stored procedure in Toad?

Open a PL/SQL object in the Editor.

Click on the main toolbar or select Session | Toggle Compiling with Debug. This enables debugging.

Compile the object on the database.

Select one of the following options on the Execute toolbar to begin debugging: Execute PL/SQL with debugger () Step over Step into Run to cursor

Cannot uninstall angular-cli

This sometime happens when you had actually installed @angular/cli using yarn and not npm.

You can verify this by looking in to yarn's global install folder.

You can remove it from yarn using

yarn global remove @angular/cli

Convert comma separated string of ints to int array

Let us assume that you will be reading the string from the console. Import System.Linq and try this one:

int[] input = Console.ReadLine()
            .Split(',', StringSplitOptions.RemoveEmptyEntries)
            .Select(int.Parse)
            .ToArray();

Open Facebook Page in Facebook App (if installed) on Android

"fb://page/ does not work with newer versions of the FB app. You should use fb://facewebmodal/f?href= for newer versions.

This is a full fledged working code currently live in one of my apps:

public static String FACEBOOK_URL = "https://www.facebook.com/YourPageName";
public static String FACEBOOK_PAGE_ID = "YourPageName";

//method to get the right URL to use in the intent
public String getFacebookPageURL(Context context) {
        PackageManager packageManager = context.getPackageManager();
        try {
            int versionCode = packageManager.getPackageInfo("com.facebook.katana", 0).versionCode;
            if (versionCode >= 3002850) { //newer versions of fb app
                return "fb://facewebmodal/f?href=" + FACEBOOK_URL;
            } else { //older versions of fb app
                return "fb://page/" + FACEBOOK_PAGE_ID;
            }
        } catch (PackageManager.NameNotFoundException e) {
            return FACEBOOK_URL; //normal web url
        }
    }

This method will return the correct url for app if installed or web url if app is not installed.

Then start an intent as follows:

Intent facebookIntent = new Intent(Intent.ACTION_VIEW);
String facebookUrl = getFacebookPageURL(this);
facebookIntent.setData(Uri.parse(facebookUrl));
startActivity(facebookIntent);

That's all you need.

Fastest way to set all values of an array?

If you have another array of char, char[] b and you want to replace c with b, you can use c=b.clone();.

GridView sorting: SortDirection always Ascending

void dg_SortCommand(object source, DataGridSortCommandEventArgs e)
{
    DataGrid dg = (DataGrid) source;
    string sortField = dg.Attributes["sortField"];
    List < SubreportSummary > data = (List < SubreportSummary > ) dg.DataSource;
    string field = e.SortExpression.Split(' ')[0];
    string sort = "ASC";
    if (sortField != null)
    {
        sort = sortField.Split(' ')[0] == field ? (sortField.Split(' ')[1] == "DESC" ? "ASC" : "DESC") : "ASC";
    }
    dg.Attributes["sortField"] = field + " " + sort;
    data.Sort(new GenericComparer < SubreportSummary > (field, sort, null));
    dg.DataSource = data;
    dg.DataBind();
}

initialize a numpy array

Maybe something like this will fit your needs..

import numpy as np

N = 5
res = []

for i in range(N):
    res.append(np.cumsum(np.ones(shape=(2,4))))

res = np.array(res).reshape((10, 4))
print(res)

Which produces the following output

[[ 1.  2.  3.  4.]
 [ 5.  6.  7.  8.]
 [ 1.  2.  3.  4.]
 [ 5.  6.  7.  8.]
 [ 1.  2.  3.  4.]
 [ 5.  6.  7.  8.]
 [ 1.  2.  3.  4.]
 [ 5.  6.  7.  8.]
 [ 1.  2.  3.  4.]
 [ 5.  6.  7.  8.]]

capture div into image using html2canvas

you can try this code to capture a div When the div is very wide or offset relative to the screen

var div = $("#div")[0];
var rect = div.getBoundingClientRect();

var canvas = document.createElement("canvas");
canvas.width = rect.width;
canvas.height = rect.height;

var ctx = canvas.getContext("2d");
ctx.translate(-rect.left,-rect.top);

html2canvas(div, {
    canvas:canvas,
    height:rect.height,
    width:rect.width,
    onrendered: function(canvas) {
        var image = canvas.toDataURL("image/png");
        var pHtml = "<img src="+image+" />";
        $("#parent").append(pHtml);
    }
});

How to insert a new key value pair in array in php?

To add:

$arr["key"] = "value";

Then simply return $arr

Can't return directly like this way return $arr["key"] = "value";

IOS - How to segue programmatically using swift

Swift 3 - Also works with SpriteKit

You can use NSNotification.

Example:

1.) Create a segue in the storyboard and name the identifier "segue"

2.) Create a function in the ViewController you are segueing from.

func goToDifferentView() {

    self.performSegue(withIdentifier: "segue", sender: self)

}

3.) In the ViewDidLoad() of your ViewController you are segueing from create the observer.

NotificationCenter.default.addObserver(self, selector: #selector(goToDifferentView), name: "segue" as NSNotification.Name, object: nil)

Update - Last time I used this I had to change the .addObserver call to the following code to silence the errors.

NotificationCenter.default.addObserver(self, selector: #selector(goToDifferentView), name: NSNotification.Name(rawValue: "segue"), object: nil)

4.) In the ViewController or Scene you are segueing to, add the Post Method wherever you want the segue to be triggered.

NotificationCenter.default.post(name: "segue" as NSNotification.Name, object: nil)

Update - Last time I used this I had to change the .post call to the following code to silence the errors.

NotificationCenter.default.post(NSNotification(name: NSNotification.Name(rawValue: "segue"), object: nil) as Notification)

How to set HTML Auto Indent format on Sublime Text 3?

One option is to type [command] + [shift] + [p] (or the equivalent) and then type 'indentation'. The top result should be 'Indendtation: Reindent Lines'. Press [enter] and it will format the document.

Another option is to install the Emmet plugin (http://emmet.io/), which will provide not only better formatting, but also a myriad of other incredible features. To get the output you're looking for using Sublime Text 3 with the Emmet plugin requires just the following:

p [tab][enter] Hello world!

When you type p [tab] Emmet expands it to:

<p></p>

Pressing [enter] then further expands it to:

<p>

</p>

With the cursor indented and on the line between the tags. Meaning that typing text results in:

<p>
    Hello, world!
</p>

How to process images of a video, frame by frame, in video streaming using OpenCV and Python

This is how I would start to solve this:

  1. Create a video writer:

    import cv2.cv as cv
    videowriter = cv.CreateVideoWriter( filename, fourcc, fps, frameSize)
    

    Check here for valid parameters

  2. Loop to retrieve[1] and write the frames:

    cv.WriteFrame( videowriter, frame )
    

    WriteFrame doc

[1] zenpoy already pointed in the correct direction. You just need to know that you can retrieve images from a webcam or a file :-)

Hopefully I understood the requirements correct.

Changing element style attribute dynamically using JavaScript

There is also style.setProperty function:
https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/setProperty

document.getElementById("xyz").style.setProperty('padding-top', '10px');

// version with !important priority
document.getElementById("xyz").style.setProperty('padding-top', '10px', 'important');

How to set Default Controller in asp.net MVC 4 & MVC 5

I didnt see this question answered:

How should I setup a default Area when the application starts?

So, here is how you can set up a default Area:

var route = routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    ).DataTokens = new RouteValueDictionary(new { area = "MyArea" });

MacOSX homebrew mysql root password

I had this problem on a fresh install on Mac. I installed MariaDB with:

brew install mariadb 

Then started the service:

brew services start mariadb

I was unable to run 'mysql_secure_installation' as it prompted for the root password. Then I noticed in the install output:

mysql_install_db --verbose --user=jonny --basedir=/usr/local/Cellar/ ....

So I tried logging in as the username specified in the mysql_install_db output and was successful e.g.

mysql -u jonny

Then at the mysql prompt if you want to set a password for the root user:

SET PASSWORD FOR 'root'@'localhost' = PASSWORD('ToPsEcReT');

Plot a bar using matplotlib using a dictionary

I often load the dict into a pandas DataFrame then use the plot function of the DataFrame.
Here is the one-liner:

pandas.DataFrame(D, index=['quantity']).plot(kind='bar')

resulting plot

How do I remove the "extended attributes" on a file in Mac OS X?

Removing a Single Attribute on a Single File

See Bavarious's answer.


To Remove All Extended Attributes On a Single File

Use xattr with the -c flag to "clear" the attributes:

xattr -c yourfile.txt



To Remove All Extended Attributes On Many Files

To recursively remove extended attributes on all files in a directory, combine the -c "clear" flag with the -r recursive flag:

xattr -rc /path/to/directory



A Tip for Mac OS X Users

Have a long path with spaces or special characters?

Open Terminal.app and start typing xattr -rc, include a trailing space, and then then drag the file or folder to the Terminal.app window and it will automatically add the full path with proper escaping.

How to remove white space characters from a string in SQL Server

Remove new line characters with SQL column data

Update a set  a.CityName=Rtrim(Ltrim(REPLACE(REPLACE(a.CityName,CHAR(10),' '),CHAR(13),' ')))
,a.postalZone=Rtrim(Ltrim(REPLACE(REPLACE(a.postalZone,CHAR(10),' '),CHAR(13),' ')))  
From tAddress a 
inner Join  tEmployees p  on a.AddressId =p.addressId 
Where p.MigratedID is not null and p.AddressId is not null AND
(REPLACE(REPLACE(a.postalZone,CHAR(10),'Y'),CHAR(13),'X') Like 'Y%' OR REPLACE(REPLACE(a.CityName,CHAR(10),'Y'),CHAR(13),'X') Like 'Y%')

How does the SQL injection from the "Bobby Tables" XKCD comic work?

It drops the students table.

The original code in the school's program probably looks something like

q = "INSERT INTO Students VALUES ('" + FNMName.Text + "', '" + LName.Text + "')";

This is the naive way to add text input into a query, and is very bad, as you will see.

After the values from the first name, middle name textbox FNMName.Text (which is Robert'); DROP TABLE STUDENTS; --) and the last name textbox LName.Text (let's call it Derper) are concatenated with the rest of the query, the result is now actually two queries separated by the statement terminator (semicolon). The second query has been injected into the first. When the code executes this query against the database, it will look like this

INSERT INTO Students VALUES ('Robert'); DROP TABLE Students; --', 'Derper')

which, in plain English, roughly translates to the two queries:

Add a new record to the Students table with a Name value of 'Robert'

and

Delete the Students table

Everything past the second query is marked as a comment: --', 'Derper')

The ' in the student's name is not a comment, it's the closing string delimiter. Since the student's name is a string, it's needed syntactically to complete the hypothetical query. Injection attacks only work when the SQL query they inject results in valid SQL.

Edited again as per dan04's astute comment

super() fails with error: TypeError "argument 1 must be type, not classobj" when parent does not inherit from object

Also, if you can't change class B, you can fix the error by using multiple inheritance.

class B:
    def meth(self, arg):
        print arg

class C(B, object):
    def meth(self, arg):
        super(C, self).meth(arg)

print C().meth(1)

How can I return the sum and average of an int array?

If you are using visual studio 2005 then

public void sumAverageElements(int[] arr)
{
     int size =arr.Length;
     int sum = 0;
     int average = 0;

     for (int i = 0; i < size; i++)
     {
          sum += arr[i];
     }

     average = sum / size; // sum divided by total elements in array

     Console.WriteLine("The Sum Of Array Elements Is : " + sum);
     Console.WriteLine("The Average Of Array Elements Is : " + average);
}

Unnamed/anonymous namespaces vs. static functions

I recently began replacing static keywords with anonymous namespaces in my code but immediately ran into a problem where the variables in the namespace were no longer available for inspection in my debugger. I was using VC60, so I don't know if that is a non-issue with other debuggers. My workaround was to define a 'module' namespace, where I gave it the name of my cpp file.

For example, in my XmlUtil.cpp file, I define a namespace XmlUtil_I { ... } for all of my module variables and functions. That way I can apply the XmlUtil_I:: qualification in the debugger to access the variables. In this case, the _I distinguishes it from a public namespace such as XmlUtil that I may want to use elsewhere.

I suppose a potential disadvantage of this approach compared to a truly anonymous one is that someone could violate the desired static scope by using the namespace qualifier in other modules. I don't know if that is a major concern though.

How to file split at a line number

file_name=test.log

# set first K lines:
K=1000

# line count (N): 
N=$(wc -l < $file_name)

# length of the bottom file:
L=$(( $N - $K ))

# create the top of file: 
head -n $K $file_name > top_$file_name

# create bottom of file: 
tail -n $L $file_name > bottom_$file_name

Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so

split -l 300000 file_name

will output xaa with 300k lines and xab with 100k lines, for an input with 400k lines.

How to get a list of all files in Cloud Storage in a Firebase app?

Since Mar 2017: With the addition of Firebase Cloud Functions, and Firebase's deeper integration with Google Cloud, this is now possible.

With Cloud Functions you can use the Google Cloud Node package to do epic operations on Cloud Storage. Below is an example that gets all the file URLs into an array from Cloud Storage. This function will be triggered every time something's saved to google cloud storage.

Note 1: This is a rather computationally expensive operation, as it has to cycle through all files in a bucket / folder.

Note 2: I wrote this just as an example, without paying much detail into promises etc. Just to give an idea.

const functions = require('firebase-functions');
const gcs = require('@google-cloud/storage')();

// let's trigger this function with a file upload to google cloud storage

exports.fileUploaded = functions.storage.object().onChange(event => {

  const object = event.data; // the object that was just uploaded
  const bucket = gcs.bucket(object.bucket);
  const signedUrlConfig = { action: 'read', expires: '03-17-2025' }; // this is a signed url configuration object

  var fileURLs = []; // array to hold all file urls 

  // this is just for the sake of this example. Ideally you should get the path from the object that is uploaded :)
  const folderPath = "a/path/you/want/its/folder/size/calculated";

  bucket.getFiles({ prefix: folderPath }, function(err, files) {
    // files = array of file objects
    // not the contents of these files, we're not downloading the files. 

    files.forEach(function(file) {
      file.getSignedUrl(signedUrlConfig, function(err, fileURL) {
        console.log(fileURL);
        fileURLs.push(fileURL);
      });
    });

  });

});

I hope this will give you the general idea. For better cloud functions examples, check out Google's Github repo full of Cloud Functions samples for Firebase. Also check out their Google Cloud Node API Documentation

'Found the synthetic property @panelState. Please include either "BrowserAnimationsModule" or "NoopAnimationsModule" in your application.'

I ran into similar issues, when I tried to use the BrowserAnimationsModule. Following steps solved my problem:

  1. Delete the node_modules dir
  2. Clear your package cache using npm cache clean
  3. Run one of these two commands listed here to update your existing packages

If you experience a 404 errors like

http://.../node_modules/@angular/platform-browser/bundles/platform-browser.umd.js/animations

add following entries to map in your system.config.js:

'@angular/animations': 'node_modules/@angular/animations/bundles/animations.umd.min.js',
'@angular/animations/browser':'node_modules/@angular/animations/bundles/animations-browser.umd.js',
'@angular/platform-browser/animations': 'node_modules/@angular/platform-browser/bundles/platform-browser-animations.umd.js'

naveedahmed1 provided the solution on this github issue.

How to save S3 object to a file using boto3

# Preface: File is json with contents: {'name': 'Android', 'status': 'ERROR'}

import boto3
import io

s3 = boto3.resource('s3')

obj = s3.Object('my-bucket', 'key-to-file.json')
data = io.BytesIO()
obj.download_fileobj(data)

# object is now a bytes string, Converting it to a dict:
new_dict = json.loads(data.getvalue().decode("utf-8"))

print(new_dict['status']) 
# Should print "Error"

Show which git tag you are on?

git log --decorate

This will tell you what refs are pointing to the currently checked out commit.

What is a postback?

Postback refers to HTML forms. An HTML form has 2 methods: GET and POST. These methods determine how data is sent from the client via the form, to the server. A Postback is the action of POSTing back to the submitting page. In essence, it forms a complete circuit from the client, to the server, and back again.

Return string without trailing slash

I'd use a regular expression:

function someFunction(site)
{
// if site has an end slash (like: www.example.com/),
// then remove it and return the site without the end slash
return site.replace(/\/$/, '') // Match a forward slash / at the end of the string ($)
}

You'll want to make sure that the variable site is a string, though.

Stacking DIVs on top of each other?

I positioned the divs slightly offset, so that you can see it at work.
HTML

<div class="outer">
  <div class="bot">BOT</div>
  <div class="top">TOP</div>
</div>

CSS

.outer {
  position: relative;
  margin-top: 20px;
}

.top {
  position: absolute;
  margin-top: -10px;
  background-color: green;
}

.bot {
  position: absolute;
  background-color: yellow;
}

https://codepen.io/anon/pen/EXxKzP

how to add script src inside a View when using Layout

You can add the script tags like how we use in the asp.net while doing client side validations like below.

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<script type="text/javascript" src="~/Scripts/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
    $(function () {
       //Your code
    });
</script>

TypeError: 'bool' object is not callable

Actually you can fix it with following steps -

  1. Do cls.__dict__
  2. This will give you dictionary format output which will contain {'isFilled':True} or {'isFilled':False} depending upon what you have set.
  3. Delete this entry - del cls.__dict__['isFilled']
  4. You will be able to call the method now.

In this case, we delete the entry which overrides the method as mentioned by BrenBarn.

MySQL Data - Best way to implement paging?

Define OFFSET for the query. For example

page 1 - (records 01-10): offset = 0, limit=10;

page 2 - (records 11-20) offset = 10, limit =10;

and use the following query :

SELECT column FROM table LIMIT {someLimit} OFFSET {someOffset};

example for page 2:

SELECT column FROM table
LIMIT 10 OFFSET 10;

Sieve of Eratosthenes - Finding Primes Python

Using a bit of numpy, I could find all primes below 100 million in a little over 2 seconds.

There are two key features one should note

  • Cut out multiples of i only for i up to root of n
  • Setting multiples of i to False using x[2*i::i] = False is much faster than an explicit python for loop.

These two significantly speed up your code. For limits below one million, there is no perceptible running time.

import numpy as np

def primes(n):
    x = np.ones((n+1,), dtype=np.bool)
    x[0] = False
    x[1] = False
    for i in range(2, int(n**0.5)+1):
        if x[i]:
            x[2*i::i] = False

    primes = np.where(x == True)[0]
    return primes

print(len(primes(100_000_000)))

how to use getSharedPreferences in android

First get the instance of SharedPreferences using

SharedPreferences userDetails = context.getSharedPreferences("userdetails", MODE_PRIVATE);

Now to save the values in the SharedPreferences

Editor edit = userDetails.edit();
edit.putString("username", username.getText().toString().trim());
edit.putString("password", password.getText().toString().trim());
edit.apply();

Above lines will write username and password to preference

Now to to retrieve saved values from preference, you can follow below lines of code

String userName = userDetails.getString("username", "");
String password = userDetails.getString("password", "");

(NOTE: SAVING PASSWORD IN THE APP IS NOT RECOMMENDED. YOU SHOULD EITHER ENCRYPT THE PASSWORD BEFORE SAVING OR SKIP THE SAVING THE PASSWORD)

How do I split a string with multiple separators in JavaScript?

Not the best way but works to Split with Multiple and Different seperators/delimiters

html

<button onclick="myFunction()">Split with Multiple and Different seperators/delimiters</button>
<p id="demo"></p>

javascript

<script>
function myFunction() {

var str = "How : are | you doing : today?";
var res = str.split(' | ');

var str2 = '';
var i;
for (i = 0; i < res.length; i++) { 
    str2 += res[i];

    if (i != res.length-1) {
      str2 += ",";
    }
}
var res2 = str2.split(' : ');

//you can add countless options (with or without space)

document.getElementById("demo").innerHTML = res2;
</script>

How to calculate percentage with a SQL statement

You have to calculate the total of grades If it is SQL 2005 you can use CTE

    WITH Tot(Total) (
    SELECT COUNT(*) FROM table
    )
    SELECT Grade, COUNT(*) / Total * 100
--, CONVERT(VARCHAR, COUNT(*) / Total * 100) + '%'  -- With percentage sign
--, CONVERT(VARCHAR, ROUND(COUNT(*) / Total * 100, -2)) + '%'  -- With Round
    FROM table
    GROUP BY Grade

Using @property versus getters and setters

I feel like properties are about letting you get the overhead of writing getters and setters only when you actually need them.

Java Programming culture strongly advise to never give access to properties, and instead, go through getters and setters, and only those which are actually needed. It's a bit verbose to always write these obvious pieces of code, and notice that 70% of the time they are never replaced by some non-trivial logic.

In Python, people actually care for that kind of overhead, so that you can embrace the following practice :

  • Do not use getters and setters at first, when if they not needed
  • Use @property to implement them without changing the syntax of the rest of your code.

Decoding base64 in batch

Actually Windows does have a utility that encodes and decodes base64 - CERTUTIL

I'm not sure what version of Windows introduced this command.

To encode a file:

certutil -encode inputFileName encodedOutputFileName

To decode a file:

certutil -decode encodedInputFileName decodedOutputFileName

There are a number of available verbs and options available to CERTUTIL.

To get a list of nearly all available verbs:

certutil -?

To get help on a particular verb (-encode for example):

certutil -encode -?

To get complete help for nearly all verbs:

certutil -v -?

Mysteriously, the -encodehex verb is not listed with certutil -? or certutil -v -?. But it is described using certutil -encodehex -?. It is another handy function :-)

Update

Regarding David Morales' comment, there is a poorly documented type option to the -encodehex verb that allows creation of base64 strings without header or footer lines.

certutil [Options] -encodehex inFile outFile [type]

A type of 1 will yield base64 without the header or footer lines.

See https://www.dostips.com/forum/viewtopic.php?f=3&t=8521#p56536 for a brief listing of the available type formats. And for a more in depth look at the available formats, see https://www.dostips.com/forum/viewtopic.php?f=3&t=8521#p57918.

Not investigated, but the -decodehex verb also has an optional trailing type argument.

Does Python support short-circuiting?

Short-circuiting behavior in operator and, or:

Let's first define a useful function to determine if something is executed or not. A simple function that accepts an argument, prints a message and returns the input, unchanged.

>>> def fun(i):
...     print "executed"
...     return i
... 

One can observe the Python's short-circuiting behavior of and, or operators in the following example:

>>> fun(1)
executed
1
>>> 1 or fun(1)    # due to short-circuiting  "executed" not printed
1
>>> 1 and fun(1)   # fun(1) called and "executed" printed 
executed
1
>>> 0 and fun(1)   # due to short-circuiting  "executed" not printed 
0

Note: The following values are considered by the interpreter to mean false:

        False    None    0    ""    ()    []     {}

Short-circuiting behavior in function: any(), all():

Python's any() and all() functions also support short-circuiting. As shown in the docs; they evaluate each element of a sequence in-order, until finding a result that allows an early exit in the evaluation. Consider examples below to understand both.

The function any() checks if any element is True. It stops executing as soon as a True is encountered and returns True.

>>> any(fun(i) for i in [1, 2, 3, 4])   # bool(1) = True
executed
True
>>> any(fun(i) for i in [0, 2, 3, 4])   
executed                               # bool(0) = False
executed                               # bool(2) = True
True
>>> any(fun(i) for i in [0, 0, 3, 4])
executed
executed
executed
True

The function all() checks all elements are True and stops executing as soon as a False is encountered:

>>> all(fun(i) for i in [0, 0, 3, 4])
executed
False
>>> all(fun(i) for i in [1, 0, 3, 4])
executed
executed
False

Short-circuiting behavior in Chained Comparison:

Additionally, in Python

Comparisons can be chained arbitrarily; for example, x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

>>> 5 > 6 > fun(3)    # same as:  5 > 6 and 6 > fun(3)
False                 # 5 > 6 is False so fun() not called and "executed" NOT printed
>>> 5 < 6 > fun(3)    # 5 < 6 is True 
executed              # fun(3) called and "executed" printed
True
>>> 4 <= 6 > fun(7)   # 4 <= 6 is True  
executed              # fun(3) called and "executed" printed
False
>>> 5 < fun(6) < 3    # only prints "executed" once
executed
False
>>> 5 < fun(6) and fun(6) < 3 # prints "executed" twice, because the second part executes it again
executed
executed
False

Edit:
One more interesting point to note :- Logical and, or operators in Python returns an operand's value instead of a Boolean (True or False). For example:

Operation x and y gives the result if x is false, then x, else y

Unlike in other languages e.g. &&, || operators in C that return either 0 or 1.

Examples:

>>> 3 and 5    # Second operand evaluated and returned 
5                   
>>> 3  and ()
()
>>> () and 5   # Second operand NOT evaluated as first operand () is  false
()             # so first operand returned 

Similarly or operator return left most value for which bool(value) == True else right most false value (according to short-circuiting behavior), examples:

>>> 2 or 5    # left most operand bool(2) == True
2    
>>> 0 or 5    # bool(0) == False and bool(5) == True
5
>>> 0 or ()
()

So, how is this useful? One example is given in Practical Python By Magnus Lie Hetland:
Let’s say a user is supposed to enter his or her name, but may opt to enter nothing, in which case you want to use the default value '<Unknown>'. You could use an if statement, but you could also state things very succinctly:

In [171]: name = raw_input('Enter Name: ') or '<Unknown>'
Enter Name: 

In [172]: name
Out[172]: '<Unknown>'

In other words, if the return value from raw_input is true (not an empty string), it is assigned to name (nothing changes); otherwise, the default '<Unknown>' is assigned to name.

How to use CURL via a proxy?

Here is a well tested function which i used for my projects with detailed self explanatory comments


There are many times when the ports other than 80 are blocked by server firewall so the code appears to be working fine on localhost but not on the server

function get_page($url){

global $proxy;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
//curl_setopt($ch, CURLOPT_PROXY, $proxy);
curl_setopt($ch, CURLOPT_HEADER, 0); // return headers 0 no 1 yes
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return page 1:yes
curl_setopt($ch, CURLOPT_TIMEOUT, 200); // http request timeout 20 seconds
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Follow redirects, need this if the url changes
curl_setopt($ch, CURLOPT_MAXREDIRS, 2); //if http server gives redirection responce
curl_setopt($ch, CURLOPT_USERAGENT,
    "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7");
curl_setopt($ch, CURLOPT_COOKIEJAR, "cookies.txt"); // cookies storage / here the changes have been made
curl_setopt($ch, CURLOPT_COOKIEFILE, "cookies.txt");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // false for https
curl_setopt($ch, CURLOPT_ENCODING, "gzip"); // the page encoding

$data = curl_exec($ch); // execute the http request
curl_close($ch); // close the connection
return $data;
}

Switch statement for string matching in JavaScript

RegExp can be used on the input string not just technically but practically with the match method too.

Because the output of the match() is an array we need to retrieve the first array element of the result. When the match fails, the function returns null. To avoid an exception error we will add the || conditional operator before accessing the first array element and test against the input property that is a static property of regular expressions that contains the input string.

str = 'XYZ test';
switch (str) {
  case (str.match(/^xyz/) || {}).input:
    console.log("Matched a string that starts with 'xyz'");
    break;
  case (str.match(/test/) || {}).input:
    console.log("Matched the 'test' substring");        
    break;
  default:
    console.log("Didn't match");
    break;
}

Another approach is to use the String() constructor to convert the resulting array that must have only 1 element (no capturing groups) and whole string must be captured with quanitifiers (.*) to a string. In case of a failure the null object will become a "null" string. Not convenient.

str = 'haystack';
switch (str) {
  case String(str.match(/^hay.*/)):
    console.log("Matched a string that starts with 'hay'");
    break;
}

Anyway, a more elegant solution is to use the /^find-this-in/.test(str) with switch (true) method which simply returns a boolean value and it's easier to search without case sensitivity.

Copy/Paste/Calculate Visible Cells from One Column of a Filtered Table

I've found this to work very well. It uses the .range property of the .autofilter object, which seems to be a rather obscure, but very handy, feature:

Sub copyfiltered()
    ' Copies the visible columns
    ' and the selected rows in an autofilter
    '
    ' Assumes that the filter was previously applied
    '
    Dim wsIn As Worksheet
    Dim wsOut As Worksheet

    Set wsIn = Worksheets("Sheet1")
    Set wsOut = Worksheets("Sheet2")

    ' Hide the columns you don't want to copy
    wsIn.Range("B:B,D:D").EntireColumn.Hidden = True

    'Copy the filtered rows from wsIn and and paste in wsOut
    wsIn.AutoFilter.Range.Copy Destination:=wsOut.Range("A1")
End Sub

If else embedding inside html

You will find multiple different methods that people use and they each have there own place.

<?php if($first_condition): ?>
  /*$first_condition is true*/
<?php elseif ($second_condition): ?>
  /*$first_condition is false and $second_condition is true*/
<?php else: ?>
  /*$first_condition and $second_condition are false*/
<?php endif; ?>

If in your php.ini attribute short_open_tag = true (this is normally found on line 141 of the default php.ini file) you can replace your php open tag from <?php to <?. This is not advised as most live server environments have this turned off (including many CMS's like Drupal, WordPress and Joomla). I have already tested short hand open tags in Drupal and confirmed that it will break your site, so stick with <?php. short_open_tag is not on by default in all server configurations and must not be assumed as such when developing for unknown server configurations. Many hosting companies have short_open_tag turned off.

A quick search of short_open_tag in stackExchange shows 830 results. https://stackoverflow.com/search?q=short_open_tag That's a lot of people having problems with something they should just not play with.

with some server environments and applications, short hand php open tags will still crash your code even with short_open_tag set to true.

short_open_tag will be removed in PHP6 so don't use short hand tags.

all future PHP versions will be dropping short_open_tag

"It's been recommended for several years that you not use the short tag "short cut" and instead to use the full tag combination. With the wide spread use of XML and use of these tags by other languages, the server can become easily confused and end up parsing the wrong code in the wrong context. But because this short cut has been a feature for such a long time, it's currently still supported for backwards compatibility, but we recommend you don't use them." – Jelmer Sep 25 '12 at 9:00 php: "short_open_tag = On" not working

and

Normally you write PHP like so: . However if allow_short_tags directive is enabled you're able to use: . Also sort tags provides extra syntax: which is equal to .

Short tags might seem cool but they're not. They causes only more problems. Oh... and IIRC they'll be removed from PHP6. Crozin answered Aug 24 '10 at 22:12 php short_open_tag problem

and

To answer the why part, I'd quote Zend PHP 5 certification guide: "Short tags were, for a time, the standard in the PHP world; however, they do have the major drawback of conflicting with XML headers and, therefore, have somewhat fallen by the wayside." – Fluffy Apr 13 '11 at 14:40 Are PHP short tags acceptable to use?

You may also see people use the following example:

<?php if($first_condition){ ?>
  /*$first_condition is true*/
<?php }else if ($second_condition){ ?>
  /*$first_condition is false and $second_condition is true*/
<?php }else{ ?>
  /*$first_condition and $second_condition are false*/
<?php } ?>

This will work but it is highly frowned upon as it's not considered as legible and is not what you would use this format for. If you had a PHP file where you had a block of PHP code that didn't have embedded tags inside, then you would use the bracket format.

The following example shows when to use the bracket method

<?php
if($first_condition){
   /*$first_condition is true*/
}else if ($second_condition){
   /*$first_condition is false and $second_condition is true*/
}else{
   /*$first_condition and $second_condition are false*/
}
?>

If you're doing this code for yourself you can do what you like, but if your working with a team at a job it is advised to use the correct format for the correct circumstance. If you use brackets in embedded html/php scripts that is a good way to get fired, as no one will want to clean up your code after you. IT bosses will care about code legibility and college professors grade on legibility.

UPDATE

based on comments from duskwuff its still unclear if shorthand is discouraged (by the php standards) or not. I'll update this answer as I get more information. But based on many documents found on the web about shorthand being bad for portability. I would still personally not use it as it gives no advantage and you must rely on a setting being on that is not on for every web host.

Android Get Current timestamp?

You can use the SimpleDateFormat class:

SimpleDateFormat s = new SimpleDateFormat("ddMMyyyyhhmmss");
String format = s.format(new Date());

What's the difference between git clone --mirror and git clone --bare

$ git clone --mirror $URL

is a short-hand for

$ git clone --bare $URL
$ (cd $(basename $URL) && git remote add --mirror=fetch origin $URL)

(Copied directly from here)

How the current man-page puts it:

Compared to --bare, --mirror not only maps local branches of the source to local branches of the target, it maps all refs (including remote branches, notes etc.) and sets up a refspec configuration such that all these refs are overwritten by a git remote update in the target repository.

Hide Twitter Bootstrap nav collapse on click

I checked in menu is opened by checking 'in' class and then run the code.

$('.navbar-collapse a').on('click', function(){
    if ( $( '.navbar-collapse' ).hasClass('in') ) {
        $('.navbar-toggle').click();
    }
});

works perfectly.

org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException:

You are trying to access an XLS file. However, you are using XSSFWorkbook and XSSFSheet class objects. These classes are mainly used for XLSX files.

For XLS file: HSSFWorkbook & HSSFSheet
For XLSX file: XSSFSheet & XSSFSheet

So in place of XSSFWorkbook use HSSFWorkbook and in place of XSSFSheet use HSSFSheet.

So your code should look like this after the changes are made:

HSSFWorkbook workbook = new HSSFWorkbook(file);

HSSFSheet sheet = workbook.getSheetAt(0);

What is your favorite C programming trick?

Not specific to C, but I've always liked the XOR operator. One cool thing it can do is "swap without a temp value":

int a = 1;
int b = 2;

printf("a = %d, b = %d\n", a, b);

a ^= b;
b ^= a;
a ^= b;

printf("a = %d, b = %d\n", a, b);

Result:

a = 1, b = 2

a = 2, b = 1

Change hash without reload in jQuery

The accepted answer didn't work for me as my page jumped slightly on click, messing up my scroll animation.

I decided to update the entire URL using window.history.replaceState rather than using the window.location.hash method. Thus circumventing the hashChange event fired by the browser.

// Only fire when URL has anchor
$('a[href*="#"]:not([href="#"])').on('click', function(event) {

    // Prevent default anchor handling (which causes the page-jumping)
    event.preventDefault();

    if ( location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname ) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) +']');

        if ( target.length ) {    
            // Smooth scrolling to anchor
            $('html, body').animate({
                scrollTop: target.offset().top
            }, 1000);

            // Update URL
            window.history.replaceState("", document.title, window.location.href.replace(location.hash, "") + this.hash);
        }
    }
});

MVC Return Partial View as JSON

You can extract the html string from the PartialViewResult object, similar to the answer to this thread:

Render a view as a string

PartialViewResult and ViewResult both derive from ViewResultBase, so the same method should work on both.

Using the code from the thread above, you would be able to use:

public ActionResult ReturnSpecialJsonIfInvalid(AwesomenessModel model)
{
    if (ModelState.IsValid)
    {
        if(Request.IsAjaxRequest())
            return PartialView("NotEvil", model);
        return View(model)
    }
    if(Request.IsAjaxRequest())
    {
        return Json(new { error = true, message = RenderViewToString(PartialView("Evil", model))});
    }
    return View(model);
}

adding noise to a signal in python

... And for those who - like me - are very early in their numpy learning curve,

import numpy as np
pure = np.linspace(-1, 1, 100)
noise = np.random.normal(0, 1, 100)
signal = pure + noise

Utils to read resource text file to String (Java)

I made NO-dependency static method like this:

import java.nio.file.Files;
import java.nio.file.Paths;

public class ResourceReader {
    public  static String asString(String resourceFIleName) {
        try  {
            return new String(Files.readAllBytes(Paths.get(new CheatClassLoaderDummyClass().getClass().getClassLoader().getResource(resourceFIleName).toURI())));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
class CheatClassLoaderDummyClass{//cheat class loader - for sql file loading
}

How can I convert a .py to .exe for Python?

There is an open source project called auto-py-to-exe on GitHub. Actually it also just uses PyInstaller internally but since it is has a simple GUI that controls PyInstaller it may be a comfortable alternative. It can also output a standalone file in contrast to other solutions. They also provide a video showing how to set it up.

GUI:

Auto Py to Exe

Output:

Output

How to deal with SQL column names that look like SQL keywords?

I ran in the same issue when trying to update a column which name was a keyword. The solution above didn't help me. I solved it out by simply specifying the name of the table like this:

UPDATE `survey`
SET survey.values='yes,no'
WHERE (question='Did you agree?')

Export HTML page to PDF on user click using JavaScript

This is because you define your "doc" variable outside of your click event. The first time you click the button the doc variable contains a new jsPDF object. But when you click for a second time, this variable can't be used in the same way anymore. As it is already defined and used the previous time.

change it to:

$(function () {

    var specialElementHandlers = {
        '#editor': function (element,renderer) {
            return true;
        }
    };
 $('#cmd').click(function () {
        var doc = new jsPDF();
        doc.fromHTML(
            $('#target').html(), 15, 15, 
            { 'width': 170, 'elementHandlers': specialElementHandlers }, 
            function(){ doc.save('sample-file.pdf'); }
        );

    });  
});

and it will work.

Git resolve conflict using --ours/--theirs for all files

function gitcheckoutall() {
    git diff --name-only --diff-filter=U | sed 's/^/"/;s/$/"/' | xargs git checkout --$1
}

I've added this function in .zshrc file.

Use them this way: gitcheckoutall theirs or gitcheckoutall ours

How to make readonly all inputs in some div in Angular2?

You can do like this. Open a ts file ad there make an interface with inputs you want and in the page you want to show under export class write

readonly yourinterface = yourinterface
readonly level: number[] = [];

and in your template do like this *ngFor="let yourtype of yourinterface"

Is this how you define a function in jQuery?

jQuery.fn.extend({
    zigzag: function () {
        var text = $(this).text();
        var zigzagText = '';
        var toggle = true; //lower/uppper toggle
            $.each(text, function(i, nome) {
                zigzagText += (toggle) ? nome.toUpperCase() : nome.toLowerCase();
                toggle = (toggle) ? false : true;
            });
    return zigzagText;
    }
});

Hibernate error - QuerySyntaxException: users is not mapped [from users]

I was getting the same error while Spring with hibernate..I was using "user" in the lowercase in my createQuery statement and my class was User..So changed it to User in my query and problem was solved.

Query before:

Query query= em.createQuery("select u from user u where u.username=:usr AND u.password=:pass",User.class);

Query after:

Query query= em.createQuery("select u from User u where u.username=:usr AND u.password=:pass",User.class);

How do I escape reserved words used as column names? MySQL/Create Table

You should use back tick character (`) eg:

create table if not exists misc_info (
id INTEGER PRIMARY KEY AUTO_INCREMENT NOT NULL,
`key` TEXT UNIQUE NOT NULL,
value TEXT NOT NULL)ENGINE=INNODB;

Warning: #1265 Data truncated for column 'pdd' at row 1

As the message error says, you need to Increase the length of your column to fit the length of the data you are trying to insert (0000-00-00)

EDIT 1:

Following your comment, I run a test table:

mysql> create table testDate(id int(2) not null auto_increment, pdd date default null, primary key(id));
Query OK, 0 rows affected (0.20 sec)

Insertion:

mysql> insert into testDate values(1,'0000-00-00');
Query OK, 1 row affected (0.06 sec)

EDIT 2:

So, aparently you want to insert a NULL value to pdd field as your comment states ? You can do that in 2 ways like this:

Method 1:

mysql> insert into testDate values(2,'');
Query OK, 1 row affected, 1 warning (0.06 sec)

Method 2:

mysql> insert into testDate values(3,NULL);
Query OK, 1 row affected (0.07 sec)

EDIT 3:

You failed to change the default value of pdd field. Here is the syntax how to do it (in my case, I set it to NULL in the start, now I will change it to NOT NULL)

mysql> alter table testDate modify pdd date not null;
Query OK, 3 rows affected, 1 warning (0.60 sec)
Records: 3  Duplicates: 0  Warnings: 1

Composer update memory limit

In my case none of the answers helped. Finally it turned out, that changing to a 64 bit version of PHP (M$ Windows) fixed the problem immediately. I did not change any settings - it just worked.

How can I compare time in SQL Server?

SELECT timeEvent 
  FROM tbEvents 
 WHERE CONVERT(VARCHAR,startHour,108) >= '01:01:01'

This tells SQL Server to convert the current date/time into a varchar using style 108, which is "hh:mm:ss". You can also replace '01:01:01' which another convert if necessary.

getResourceAsStream() vs FileInputStream

getResourceAsStream is the right way to do it for web apps (as you already learned).

The reason is that reading from the file system cannot work if you package your web app in a WAR. This is the proper way to package a web app. It's portable that way, because you aren't dependent on an absolute file path or the location where your app server is installed.

Using onBackPressed() in Android Fragments

You can try to override onCreateAnimation, parameter and catch enter==false. This will fire before every back press.

@Override
public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {            
        if(!enter){
            //leaving fragment
            Log.d(TAG,"leaving fragment");
        }
        return super.onCreateAnimation(transit, enter, nextAnim);
    }

regular expression to validate datetime format (MM/DD/YYYY)

based on this

dd-mm-yy

I modified the original to this:

^(?:(?:(?:0?[13578]|1[02]|(?:Jan|Mar|May|Jul|Aug|Oct|Dec))(\/|-|\.)31)\1|(?:(?:0?[1,3-9]|1[0-2]|(?:Jan|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))(\/|-|\.)(?:29|30)\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:(?:0?2|(?:Feb))(\/|-|\.)(?:29)\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:(?:0?[1-9]|(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep))|(?:1[0-2]|(?:Oct|Nov|Dec)))(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$

test the regex here

How to filter a dictionary according to an arbitrary condition function?

Nowadays, in Python 2.7 and up, you can use a dict comprehension:

{k: v for k, v in points.iteritems() if v[0] < 5 and v[1] < 5}

And in Python 3:

{k: v for k, v in points.items() if v[0] < 5 and v[1] < 5}

How to format time since xxx e.g. “4 minutes ago” similar to Stack Exchange sites

Here's what I did (the object returns the unit of time along with its value):

_x000D_
_x000D_
function timeSince(post_date, reference)_x000D_
{_x000D_
 var reference = reference ? new Date(reference) : new Date(),_x000D_
  diff = reference - new Date(post_date + ' GMT-0000'),_x000D_
  date = new Date(diff),_x000D_
  object = { unit: null, value: null };_x000D_
 _x000D_
 if (diff < 86400000)_x000D_
 {_x000D_
  var secs  = date.getSeconds(),_x000D_
   mins  = date.getMinutes(),_x000D_
   hours = date.getHours(),_x000D_
   array = [ ['second', secs], ['minute', mins], ['hour', hours] ];_x000D_
 }_x000D_
 else_x000D_
 {_x000D_
  var days   = date.getDate(),_x000D_
   weeks  = Math.floor(days / 7),_x000D_
   months = date.getMonth(),_x000D_
   years  = date.getFullYear() - 1970,_x000D_
   array  = [ ['day', days], ['week', weeks], ['month', months], ['year', years] ];_x000D_
 }_x000D_
_x000D_
 for (var i = 0; i < array.length; i++)_x000D_
 {_x000D_
  array[i][0] += array[i][1] != 1 ? 's' : '';_x000D_
_x000D_
  object.unit  = array[i][1] >= 1 ? array[i][0] : object.unit;_x000D_
  object.value = array[i][1] >= 1 ? array[i][1] : object.value;_x000D_
 }_x000D_
_x000D_
 return object;_x000D_
}
_x000D_
_x000D_
_x000D_

gdb: "No symbol table is loaded"

Whenever gcc on the compilation machine and gdb on the testing machine have differing versions, you may be facing debuginfo format incompatibility.

To fix that, try downgrading the debuginfo format:

gcc -gdwarf-3 ...
gcc -gdwarf-2 ...
gcc -gstabs ...
gcc -gstabs+ ...
gcc -gcoff ...
gcc -gxcoff ...
gcc -gxcoff+ ...

Or match gdb to the gcc you're using.

How to store Node.js deployment settings/configuration files?

Convict is another option that adds a schema for validation. Like nconf, it supports loading settings from any combination of environment variables, arguments, files, and json objects.

Example from the README:

var convict = require('convict');
var conf = convict({
  env: {
    doc: "The applicaton environment.",
    format: ["production", "development", "test"],
    default: "development",
    env: "NODE_ENV"
  },
  ip: {
    doc: "The IP address to bind.",
    format: "ipaddress",
    default: "127.0.0.1",
    env: "IP_ADDRESS",
  },
  port: {
    doc: "The port to bind.",
    format: "port",
    default: 0,
    env: "PORT"
  }
});

Getting started article: Taming Configurations with node-convict

The provider is not compatible with the version of Oracle client

I only installed the Oracle Data Provider for .NET 2.0 (11.1.0.6.20) and I did not install the Oracle Instant Client (11.1.0.6.0).

I just installed it and the error disappeared!

How can I remove file extension from a website address?

Remove a file extension through .htaccess:

Original URL: http://ravinderrathore.herobo.com/contact.php

.htaccess rule to remove .php, .html, etc. file extensions from URLs:

RewriteRule ^(.*)$ $1.php

After Rewriting: http://ravinderrathore.herobo.com/contact

RewriteEngine on

RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/

RewriteRule ^index(.*)?$ index.php$1 [L,QSA]

RewriteRule ^login_success(/)?$ login_success.php [L,QSA]

RewriteRule ^contact(/)?$ contact.php [L,QSA]

Calling one method from another within same class in Python

To accessing member functions or variables from one scope to another scope (In your case one method to another method we need to refer method or variable with class object. and you can do it by referring with self keyword which refer as class object.

class YourClass():

    def your_function(self, *args):

        self.callable_function(param) # if you need to pass any parameter

    def callable_function(self, *params): 
        print('Your param:', param)

Draw text in OpenGL ES

For static text:

  • Generate an image with all words used on your PC (For example with GIMP).
  • Load this as a texture and use it as material for a plane.

For long text that needs to be updated once in a while:

  • Let android draw on a bitmap canvas (JVitela's solution).
  • Load this as material for a plane.
  • Use different texture coordinates for each word.

For a number (formatted 00.0):

  • Generate an image with all numbers and a dot.
  • Load this as material for a plane.
  • Use below shader.
  • In your onDraw event only update the value variable sent to the shader.

    precision highp float;
    precision highp sampler2D;
    
    uniform float uTime;
    uniform float uValue;
    uniform vec3 iResolution;
    
    varying vec4 v_Color;
    varying vec2 vTextureCoord;
    uniform sampler2D s_texture;
    
    void main() {
    
    vec4 fragColor = vec4(1.0, 0.5, 0.2, 0.5);
    vec2 uv = vTextureCoord;
    
    float devisor = 10.75;
    float digit;
    float i;
    float uCol;
    float uRow;
    
    if (uv.y < 0.45) {
        if (uv.x > 0.75) {
            digit = floor(uValue*10.0);
            digit = digit - floor(digit/10.0)*10.0;
            i = 48.0 - 32.0 + digit;
            uRow = floor(i / 10.0);
            uCol = i - 10.0 * uRow;
            fragColor = texture2D( s_texture, uv / devisor * 2.0 + vec2((uCol-1.5) / devisor, uRow / devisor) );
        } else if (uv.x > 0.5) {
            uCol = 4.0;
            uRow = 1.0;
            fragColor = texture2D( s_texture, uv / devisor * 2.0 + vec2((uCol-1.0) / devisor, uRow / devisor) );
        } else if (uv.x > 0.25) {
            digit = floor(uValue);
            digit = digit - floor(digit/10.0)*10.0;
            i = 48.0 - 32.0 + digit;
            uRow = floor(i / 10.0);
            uCol = i - 10.0 * uRow;
            fragColor = texture2D( s_texture, uv / devisor * 2.0 + vec2((uCol-0.5) / devisor, uRow / devisor) );
        } else if (uValue >= 10.0) {
            digit = floor(uValue/10.0);
            digit = digit - floor(digit/10.0)*10.0;
            i = 48.0 - 32.0 + digit;
            uRow = floor(i / 10.0);
            uCol = i - 10.0 * uRow;
            fragColor = texture2D( s_texture, uv / devisor * 2.0 + vec2((uCol-0.0) / devisor, uRow / devisor) );
        } else {
            fragColor = vec4(0.0, 0.0, 0.0, 0.0);
        }
    } else {
        fragColor = vec4(0.0, 0.0, 0.0, 0.0);
    }
    gl_FragColor = fragColor;
    
    }
    

Above code works for a texture atlas where numbers start from 0 at the 7th column of the 2nd row of the font atlas (texture).

Refer to https://www.shadertoy.com/view/Xl23Dw for demonstration (with wrong texture though)

Prevent Android activity dialog from closing on outside touch

Use setFinishOnTouchOutside(false) for API > 11 and don't worry because its android's default behavior that activity themed dialog won't get finished on outside touch for API < 11 :) !!Cheerss!!

Javascript geocoding from address to latitude and longitude numbers not working

You're accessing the latitude and longitude incorrectly.

Try

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">

var geocoder = new google.maps.Geocoder();
var address = "new york";

geocoder.geocode( { 'address': address}, function(results, status) {

  if (status == google.maps.GeocoderStatus.OK) {
    var latitude = results[0].geometry.location.lat();
    var longitude = results[0].geometry.location.lng();
    alert(latitude);
  } 
}); 
</script>

Moment get current date

Just call moment as a function without any arguments:

moment()

For timezone information with moment, look at the moment-timezone package: http://momentjs.com/timezone/

Auto-expanding layout with Qt-Designer

I've tried to find a "fit to screen" property but there is no such.

But setting widget's "maximumSize" to a "some big number" ( like 2000 x 2000 ) will automatically fit the widget to the parent widget space.

Can HTML checkboxes be set to readonly?

I happened to notice the solution given below. In found it my research for the same issue. I don't who had posted it but it wasn't made by me. It uses jQuery:

$(document).ready(function() {
    $(":checkbox").bind("click", false);
});

This would make the checkboxes read only which would be helpful for showing readonly data to the client.

System.currentTimeMillis vs System.nanoTime

System.nanoTime() isn't supported in older JVMs. If that is a concern, stick with currentTimeMillis

Regarding accuracy, you are almost correct. On SOME Windows machines, currentTimeMillis() has a resolution of about 10ms (not 50ms). I'm not sure why, but some Windows machines are just as accurate as Linux machines.

I have used GAGETimer in the past with moderate success.

How can I find the first occurrence of a sub-string in a python string?

find()

>>> s = "the dude is a cool dude"
>>> s.find('dude')
4

How to reset the bootstrap modal when it gets closed and open it fresh again?

also, you can clone your modal before open ;)

$('#myModal')
    .clone()
    .modal()
    .on('hidden.bs.modal', function(e) {
        $(this).remove();
    });

How to create a box when mouse over text in pure CSS?

This is a small tweak on the other answers. If you have nested divs you can include more exciting content such as H1s in your popup.

CSS

div.appear {
    width: 250px; 
    border: #000 2px solid;
    background:#F8F8F8;
    position: relative;
    top: 5px;
    left:15px;
    display:none;
    padding: 0 20px 20px 20px;
    z-index: 1000000;
}
div.hover  {
    cursor:pointer;
    width: 5px;
}
div.hover:hover div.appear {
    display:block;
}

HTML

<div class="hover">
<img src="questionmark.png"/>
    <div class="appear">
       <h1>My popup</h1>Hitherto and whenceforth.
    </div>
</div>

The problem with these solutions is that everything after this in the page gets shifted when the popup is displayed, ie, the rest of the page jumps downwards to 'make space'. The only way I could fix this was by making position:absolute and removing the top and left CSS tags.

Filtering array of objects with lodash based on property value

Use lodash _.filter method:

_.filter(collection, [predicate=_.identity])

Iterates over elements of collection, returning an array of all elements predicate returns truthy for. The predicate is invoked with three arguments: (value, index|key, collection).

with predicate as custom function

 _.filter(myArr, function(o) { 
    return o.name == 'john'; 
 });

with predicate as part of filtered object (the _.matches iteratee shorthand)

_.filter(myArr, {name: 'john'});

with predicate as [key, value] array (the _.matchesProperty iteratee shorthand.)

_.filter(myArr, ['name', 'John']);

Docs reference: https://lodash.com/docs/4.17.4#filter

Sticky Header after scrolling down

window bottom scroll to top scroll using jquery.

 <script> 

 var lastScroll = 0;

 $(document).ready(function($) {

 $(window).scroll(function(){

 setTimeout(function() { 
    var scroll = $(window).scrollTop();
    if (scroll > lastScroll) {

        $("header").removeClass("menu-sticky");

    } 
    if (scroll == 0) {
    $("header").removeClass("menu-sticky");

    }
    else if (scroll < lastScroll - 5) {


        $("header").addClass("menu-sticky");

    }
    lastScroll = scroll;
    },0);
    });
   });
 </script>

Delete rows with blank values in one particular column

Alternative solution can be to remove the rows with blanks in one variable:

df <- subset(df, VAR != "")

What does PHP keyword 'var' do?

Answer: From php 5.3 and >, the var keyword is equivalent to public when declaring variables inside a class.

class myClass {
  var $x;
}

is the same as (for php 5.3 and >):

class myClass {
  public $x;
}

History: It was previously the norm for declaring variables in classes, though later became depreciated, but later (PHP 5.3) it became un-depreciated.

C# Syntax - Split String into Array by Comma, Convert To Generic List, and Reverse Order

What your missing here is that .Reverse() is a void method. It's not possible to assign the result of .Reverse() to a variable. You can however alter the order to use Enumerable.Reverse() and get your result

var x = "Tom,Scott,Bob".Split(',').Reverse().ToList<string>()

The difference is that Enumerable.Reverse() returns an IEnumerable<T> instead of being void return

how to set font size based on container size?

Here is the function:

document.body.setScaledFont = function(f) {
  var s = this.offsetWidth, fs = s * f;
  this.style.fontSize = fs + '%';
  return this
};

Then convert all your documents child element font sizes to em's or %.

Then add something like this to your code to set the base font size.

document.body.setScaledFont(0.35);
window.onresize = function() {
    document.body.setScaledFont(0.35);
}

http://jsfiddle.net/0tpvccjt/

shuffling/permutating a DataFrame in pandas

Use numpy's random.permuation function:

In [1]: df = pd.DataFrame({'A':range(10), 'B':range(10)})

In [2]: df
Out[2]:
   A  B
0  0  0
1  1  1
2  2  2
3  3  3
4  4  4
5  5  5
6  6  6
7  7  7
8  8  8
9  9  9


In [3]: df.reindex(np.random.permutation(df.index))
Out[3]:
   A  B
0  0  0
5  5  5
6  6  6
3  3  3
8  8  8
7  7  7
9  9  9
1  1  1
2  2  2
4  4  4

SQL Plus change current directory

for me shelling-out does the job because it gives you possibility to run [a|any] command on the shell:

http://www.dba-oracle.com/t_display_current_directory_sqlplus.htm

in short see the current directory:

!pwd

change it

!cd /path/you/want

msvcr110.dll is missing from computer error while installing PHP

I am on a 64 bit system, and I only got this to work after installing both the 32 and 64 bit versions of the redistributable. I did not try the 64 bit version by itself due to the other posters' warnings about using the 32 bit version (and am too lazy to uninstall the 32 bit version now that I have it working), so I don't know if the 32 bit version is needed or not in cases like mine.

Redirect non-www to www in .htaccess

Try this, I used it in many websites, it works perfectly

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{HTTP_HOST} ^bewebdeveloper.com$
RewriteRule ^(.*) http://www.bewebdeveloper.com/$1  [QSA,L,R=301]

Operator overloading in Java

No, Java doesn't support user-defined operator overloading. The only aspect of Java which comes close to "custom" operator overloading is the handling of + for strings, which either results in compile-time concatenation of constants or execution-time concatenation using StringBuilder/StringBuffer. You can't define your own operators which act in the same way though.

For a Java-like (and JVM-based) language which does support operator overloading, you could look at Kotlin or Groovy. Alternatively, you might find luck with a Java compiler plugin solution.

WCF Service Returning "Method Not Allowed"

If you are using the [WebInvoke(Method="GET")] attribute on the service method, make sure that you spell the method name as "GET" and not "Get" or "get" since it is case sensitive! I had the same error and it took me an hour to figure that one out.

Bash script prints "Command Not Found" on empty lines

Had the same problem. Unfortunately

dos2unix winfile.sh
bash: dos2unix: command not found

so I did this to convert.

 awk '{ sub("\r$", ""); print }' winfile.sh > unixfile.sh

and then

bash unixfile.sh

Styling every 3rd item of a list using CSS?

:nth-child is the answer you are looking for.

Regular expression negative lookahead

Lookarounds can be nested.

So this regex matches "drupal-6.14/" that is not followed by "sites" that is not followed by "/all" or "/default".

Confusing? Using different words, we can say it matches "drupal-6.14/" that is not followed by "sites" unless that is further followed by "/all" or "/default"

How to set up datasource with Spring for HikariCP?

May this also can help using configuration file like java class way.

@Configuration
@PropertySource("classpath:application.properties")
public class DataSourceConfig {
    @Autowired
    JdbcConfigProperties jdbc;


    @Bean(name = "hikariDataSource")
    public DataSource hikariDataSource() {
        HikariConfig config = new HikariConfig();
        HikariDataSource dataSource;

        config.setJdbcUrl(jdbc.getUrl());
        config.setUsername(jdbc.getUser());
        config.setPassword(jdbc.getPassword());
        // optional: Property setting depends on database vendor
        config.addDataSourceProperty("cachePrepStmts", "true");
        config.addDataSourceProperty("prepStmtCacheSize", "250");
        config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
        dataSource = new HikariDataSource(config);

        return dataSource;
    }
}

How to use it:

@Component
public class Car implements Runnable {
    private static final Logger logger = LoggerFactory.getLogger(AptSommering.class);


    @Autowired
    @Qualifier("hikariDataSource")
    private DataSource hikariDataSource;


}

C convert floating point to int

Use in C

int C = var_in_float;

They will convert implicit

Python: maximum recursion depth exceeded while calling a Python object

Instead of doing recursion, the parts of the code with checkNextID(ID + 18) and similar could be replaced with ID+=18, and then if you remove all instances of return 0, then it should do the same thing but as a simple loop. You should then put a return 0 at the end and make your variables non-global.

Inline Form nested within Horizontal Form in Bootstrap 3

I had problems aligning the label to the input(s) elements so I transferred the label element inside the form-inline and form-group too...and it works..

<div class="form-group">
    <div class="col-xs-10">
        <div class="form-inline">
            <div class="form-group">
                <label for="birthday" class="col-xs-2 control-label">Birthday:</label>
            </div>
            <div class="form-group">
                <input type="text" class="form-control" placeholder="year"/>
            </div>
            <div class="form-group">
                <input type="text" class="form-control" placeholder="month"/>
            </div>
            <div class="form-group">
                <input type="text" class="form-control" placeholder="day"/>
            </div>
        </div>
    </div>
</div>

iOS: UIButton resize according to text length

If you want to resize the text as opposed to the button, you can use ...

button.titleLabel.adjustsFontSizeToFitWidth = YES;
button.titleLabel.minimumScaleFactor = .5;
// The .5 value means that I will let it go down to half the original font size 
// before the texts gets truncated

// note, if using anything pre ios6, you would use I think
button.titleLabel.minimumFontSize = 8;

Type Checking: typeof, GetType, or is?

1.

Type t = typeof(obj1);
if (t == typeof(int))

This is illegal, because typeof only works on types, not on variables. I assume obj1 is a variable. So, in this way typeof is static, and does its work at compile time instead of runtime.

2.

if (obj1.GetType() == typeof(int))

This is true if obj1 is exactly of type int. If obj1 derives from int, the if condition will be false.

3.

if (obj1 is int)

This is true if obj1 is an int, or if it derives from a class called int, or if it implements an interface called int.

Apache HttpClient Interim Error: NoHttpResponseException

HttpClient 4.4 suffered from a bug in this area relating to validating possibly stale connections before returning to the requestor. It didn't validate whether a connection was stale, and this then results in an immediate NoHttpResponseException.

This issue was resolved in HttpClient 4.4.1. See this JIRA and the release notes

list.clear() vs list = new ArrayList<Integer>();

list.clear() is going to keep the same ArrayList but the same memory allocation. list = new ArrayList<int>(); is going to allocate new memory for your ArrayList.

The big difference is that ArrayLists will expand dynamically as you need more space. Therefore, if you call list.clear() you will still, potentially, have a large amount of memory allocated for an ArrayList that might not be needed.

That said list.clear() will be faster but if memory maters you might want to allocate a new ArrayList.

What's the difference between Instant and LocalDateTime?

One main difference is the Local part of LocalDateTime. If you live in Germany and create a LocalDateTime instance and someone else lives in USA and creates another instance at the very same moment (provided the clocks are properly set) - the value of those objects would actually be different. This does not apply to Instant, which is calculated independently from time zone.

LocalDateTime stores date and time without timezone, but it's initial value is timezone dependent. Instant's is not.

Moreover, LocalDateTime provides methods for manipulating date components like days, hours, months. An Instant does not.

apart from the nanosecond precision advantage of Instant and the time-zone part of LocalDateTime

Both classes have the same precision. LocalDateTime does not store timezone. Read javadocs thoroughly, because you may make a big mistake with such invalid assumptions: Instant and LocalDateTime.

How can I open Windows Explorer to a certain directory from within a WPF app?

Process.Start("explorer.exe" , @"C:\Users");

I had to use this, the other way of just specifying the tgt dir would shut the explorer window when my application terminated.

Javascript Date: next month

You'll probably find you're setting the date to Feb 31, 2009 (if today is Jan 31) and Javascript automagically rolls that into the early part of March.

Check the day of the month, I'd expect it to be 1, 2 or 3. If it's not the same as before you added a month, roll back by one day until the month changes again.

That way, the day "last day of Jan" becomes "last day of Feb".

EDIT:

Ronald, based on your comments to other answers, you might want to steer clear of edge-case behavior such as "what happens when I try to make Feb 30" or "what happens when I try to make 2009/13/07 (yyyy/mm/dd)" (that last one might still be a problem even for my solution, so you should test it).

Instead, I would explicitly code for the possibilities. Since you don't care about the day of the month (you just want the year and month to be correct for next month), something like this should suffice:

var now = new Date();
if (now.getMonth() == 11) {
    var current = new Date(now.getFullYear() + 1, 0, 1);
} else {
    var current = new Date(now.getFullYear(), now.getMonth() + 1, 1);
}

That gives you Jan 1 the following year for any day in December and the first day of the following month for any other day. More code, I know, but I've long since grown tired of coding tricks for efficiency, preferring readability unless there's a clear requirement to do otherwise.

JQuery add class to parent element

Specify the optional selector to target what you want:

jQuery(this).parent('li').addClass('yourClass');

Or:

jQuery(this).parents('li').addClass('yourClass');

How do I make a simple makefile for gcc on Linux?

all: program
program.o: program.h headers.h

is enough. the rest is implicit

How to return first 5 objects of Array in Swift?

Update for swift 4:

[0,1,2,3,4,5].enumerated().compactMap{ $0 < 10000 ? $1 : nil }

For swift 3:

[0,1,2,3,4,5].enumerated().flatMap{ $0 < 10000 ? $1 : nil }

How to write into a file in PHP?

Consider fwrite():

<?php
$fp = fopen('lidn.txt', 'w');
fwrite($fp, 'Cats chase mice');
fclose($fp);
?>

Java Object Null Check for method

First you should check if books itself isn't null, then simply check whether books[i] != null:

if(books==null) throw new IllegalArgumentException();

for (int i = 0; i < books.length; i++){
   if(books[i] != null){
        total += books[i].getPrice();
   }
}

A simple scenario using wait() and notify() in java

Not a queue example, but extremely simple :)

class MyHouse {
    private boolean pizzaArrived = false;

    public void eatPizza(){
        synchronized(this){
            while(!pizzaArrived){
                wait();
            }
        }
        System.out.println("yumyum..");
    }

    public void pizzaGuy(){
        synchronized(this){
             this.pizzaArrived = true;
             notifyAll();
        }
    }
}

Some important points:
1) NEVER do

 if(!pizzaArrived){
     wait();
 }

Always use while(condition), because

  • a) threads can sporadically awake from waiting state without being notified by anyone. (even when the pizza guy didn't ring the chime, somebody would decide try eating the pizza.).
  • b) You should check for the condition again after acquiring the synchronized lock. Let's say pizza don't last forever. You awake, line-up for the pizza, but it's not enough for everybody. If you don't check, you might eat paper! :) (probably better example would be while(!pizzaExists){ wait(); }.

2) You must hold the lock (synchronized) before invoking wait/nofity. Threads also have to acquire lock before waking.

3) Try to avoid acquiring any lock within your synchronized block and strive to not invoke alien methods (methods you don't know for sure what they are doing). If you have to, make sure to take measures to avoid deadlocks.

4) Be careful with notify(). Stick with notifyAll() until you know what you are doing.

5)Last, but not least, read Java Concurrency in Practice!

Selecting last element in JavaScript array

How to access last element of an array

It looks like that:

var my_array = /* some array here */;
var last_element = my_array[my_array.length - 1];

Which in your case looks like this:

var array1 = loc['f096012e-2497-485d-8adb-7ec0b9352c52'];
var last_element = array1[array1.length - 1];

or, in longer version, without creating new variables:

loc['f096012e-2497-485d-8adb-7ec0b9352c52'][loc['f096012e-2497-485d-8adb-7ec0b9352c52'].length - 1];

How to add a method for getting it simpler

If you are a fan for creating functions/shortcuts to fulfill such tasks, the following code:

if (!Array.prototype.last){
    Array.prototype.last = function(){
        return this[this.length - 1];
    };
};

will allow you to get the last element of an array by invoking array's last() method, in your case eg.:

loc['f096012e-2497-485d-8adb-7ec0b9352c52'].last();

You can check that it works here: http://jsfiddle.net/D4NRN/

How do I get sed to read from standard input?

use the --expression option

grep searchterm myfile.csv | sed --expression='s/replaceme/withthis/g'

Abort a Git Merge

as long as you did not commit you can type

git merge --abort

just as the command line suggested.

Setting session variable using javascript

You could better use the localStorage of the web browser.

You can find a reference here

How to check if C string is empty

If you want to check if a string is empty:

if (str[0] == '\0')
{
    // your code here
}

Escape double quote in VB string

Another example:

Dim myPath As String = """" & Path.Combine(part1, part2) & """"

Good luck!

MySQL Job failed to start

First make a backup of your /var/lib/mysql/ directory just to be safe.

sudo mkdir /home/<your username>/mysql/
cd /var/lib/mysql/
sudo cp * /home/<your username>/mysql/ -R

Next purge MySQL (this will remove php5-mysql and phpmyadmin as well as a number of other libraries so be prepared to re-install some items after this.

sudo apt-get purge mysql-server-5.1 mysql-common

Remove the folder /etc/mysql/ and it's contents

sudo rm /etc/mysql/ -R

Next check that your old database files are still in /var/lib/mysql/ if they are not then copy them back in to the folder then chown root:root

(only run these if the files are no longer there)

sudo mkdir /var/lib/mysql/
sudo chown root:root /var/lib/mysql/ -R
cd ~/mysql/
sudo cp * /var/lib/mysql/ -R

Next install mysql server

sudo apt-get install mysql-server

Finally re-install any missing packages like phpmyadmin and php5-mysql.

SQL User Defined Function Within Select

If it's a table-value function (returns a table set) you simply join it as a Table

this function generates one column table with all the values from passed comma-separated list

SELECT * FROM dbo.udf_generate_inlist_to_table('1,2,3,4')

How to cherry-pick from a remote branch?

The commit should be present in your local, check by using git log.

If the commit is not present then try git fetch to update the local with the latest remote.

How can I use PHP to dynamically publish an ical file to be read by Google Calendar?

There is an excellent eluceo/ical package that allows you to easily create ics files.

Here is an example usage from docs:

// 1. Create new calendar
$vCalendar = new \Eluceo\iCal\Component\Calendar('www.example.com');

// 2. Create an event
$vEvent = new \Eluceo\iCal\Component\Event();
$vEvent->setDtStart(new \DateTime('2012-12-24'));
$vEvent->setDtEnd(new \DateTime('2012-12-24'));
$vEvent->setNoTime(true);
$vEvent->setSummary('Christmas');

// Adding Timezone (optional)
$vEvent->setUseTimezone(true);

// 3. Add event to calendar
$vCalendar->addComponent($vEvent);

// 4. Set headers
header('Content-Type: text/calendar; charset=utf-8');
header('Content-Disposition: attachment; filename="cal.ics"');

// 5. Output
echo $vCalendar->render();