Transfer files using SCP Command in Linux

Author : Piyush Gupta

SCP (Secure Copy) is a command line tool for Linux systems for securely transfer files from local to remote server or vice a versa. SCP uses SSH protocol for transferring files between two systems which is more secure than ftp.

  • Syntax: (Local to Remote)

scp /path/to/local/file.txt user@192.168.10.100:/remote/path/

  • Syntax: (Remote to Local)

scp user@192.168.10.100:/remote/file.txt /path/to/local/

Transfer File Local to Remote Server

Following command will copy myfile.txt from current directory of local system to remote server’s /opt directory using root authentication. We are assuming remote server hostname is example.com.

$ scp myfile.txt root@example.com:/opt/ 

Transfer File Remote Server to Local

Following command will copy /opt/myfile.txt from remote system to local system’s /opt directory.

$ scp root@example.com:/opt/myfile.txt /opt/

Define Port with SCP Command

In case SSH is running on different port on remote server, use -P switch followed by port number with scp command.
$ scp -P 2344 myfile.txt root@example.com:/opt/myfile.txt

Transfer Directory Local to Remote Server Recursively

Following command will copy /opt/mydir directory from local system to remote system’s /opt directory recursively.

$ scp -r /opt/mydir root@example.com:/opt/

Transfer Directory Remote Server to Local Recursively

Following command will copy /opt/mydir directory from remote system to remote system’s /opt directory recursively.
$ scp -r root@example.com:/opt/mydir /opt/

JavaScript Interview Questions

Author : Piyush Gupta

1. What is JavaScript?
JavaScript is a client-side as well as server side scripting language that can be inserted into HTML pages and is understood by web browsers. JavaScript is also an Object based Programming language
2. Enumerate the differences between Java and JavaScript?
Java is a complete programming language. In contrast, JavaScript is a coded program that can be introduced to HTML pages. These two languages are not at all inter-dependent and are designed for the different intent. Java is an object – oriented programming (OOPS) or structured programming language like C++ or C whereas JavaScript is a client-side scripting language.
3. What are JavaScript Data Types?
Following are the JavaScript Data types:
  • Number
  • String
  • Boolean
  • Object
  • Undefined
4. What is the use of isNaN function?
isNan function returns true if the argument is not a number otherwise it is false.
5. Between JavaScript and an ASP script, which is faster?
JavaScript is faster. JavaScript is a client-side language and thus it does not need the assistance of the web server to execute. On the other hand, ASP is a server-side language and hence is always slower than JavaScript. Javascript now is also a server side language (nodejs).
6. What is negative infinity?
Negative Infinity is a number in JavaScript which can be derived by dividing negative number by zero.
7. Is it possible to break JavaScript Code into several lines?
Breaking within a string statement can be done by the use of a backslash, ‘\’, at the end of the first line
Example:

$ document.write("This is \a program");
And if you change to a new line when not within a string statement, then javaScript ignores break in line.
Example:

var x=1, y=2,
z= x+y;
The above code is perfectly fine, though not advisable as it hampers debugging.
8. Which company developed JavaScript?
Netscape is the software company who developed JavaScript.
9. What are undeclared and undefined variables?
Undeclared variables are those that do not exist in a program and are not declared. If the program tries to read the value of an undeclared variable, then a runtime error is encountered.
Undefined variables are those that are declared in the program but have not been given any value. If the program tries to read the value of an undefined variable, an undefined value is returned.
10. Write the code for adding new elements dynamically?
 

t1

function addNode() { var newP = document.createElement("p");
var textNode = document.createTextNode(" This is a new text node");
newP.appendChild(textNode); document.getElementById("firstP").appendChild(newP); }


firstP


11. What are global variables? How are these variable declared and what are the problems associated with using them?
Global variables are those that are available throughout the length of the code, that is, these have no scope. The var keyword is used to declare a local variable or object. If the var keyword is omitted, a global variable is declared.
Example:

// Declare a global globalVariable = "Test";
The problems that are faced by using global variables are the clash of variable names of local and global scope. Also, it is difficult to debug and test the code that relies on global variables.
12. What is a prompt box?
A prompt box is a box which allows the user to enter input by providing a text box. Label and box will be provided to enter the text or number.
13. What is ‘this’ keyword in JavaScript?
‘This’ keyword refers to the object from where it was called.
14. Explain the working of timers in JavaScript? Also elucidate the drawbacks of using the timer, if any?
Timers are used to execute a piece of code at a set time or also to repeat the code in a given interval of time. This is done by using the functions setTimeout, setInterval and clearInterval.
The setTimeout(function, delay) function is used to start a timer that calls a particular function after the mentioned delay. The setInterval(function, delay) function is used to repeatedly execute the given function in the mentioned delay and only halts when cancelled. The clearInterval(id) function instructs the timer to stop.
Timers are operated within a single thread, and thus events might queue up, waiting to be executed.
15. Which symbol is used for comments in Javascript?
// for Single line comments and

/* Multi

Line

Comment

*/
16. What is the difference between ViewState and SessionState?
‘ViewState’ is specific to a page in a session.
‘SessionState’ is specific to user specific data that can be accessed across all pages in the web application.
17. What is === operator?
=== is called as strict equality operator which returns true when the two operands are having the same value without any type conversion.
18. Explain how can you submit a form using JavaScript?
To submit a form using JavaScript use document.form[0].submit();

document.form[0].submit();
19. Does JavaScript support automatic type conversion?
Yes JavaScript does support automatic type conversion, it is the common way of type conversion used by JavaScript developers
20. How can the style/class of an element be changed?
It can be done in the following way:

document.getElementById("myText").style.fontSize = "20?;
or

document.getElementById("myText").className = "anyclass";
21. Explain how to read and write a file using JavaScript?
There are two ways to read and write a file using JavaScript
  • Using JavaScript extensions
  • Using a web page and Active X objects
22. What are all the looping structures in JavaScript?
Following are looping structures in Javascript:
  • For
  • While
  • do-while loops
23. What is called Variable typing in Javascript?
Variable typing is used to assign a number to a variable and the same variable can be assigned to a string.
Example
i = 10;
i = "string";
This is called variable typing.
24. How can you convert the string of any base to integer in JavaScript?
The parseInt() function is used to convert numbers between different bases. parseInt() takes the string to be converted as its first parameter, and the second parameter is the base of the given string.
In order to convert 4F (of base 16) to integer, the code used will be –

parseInt ("4F", 16);
25. Explain the difference between “==” and “===”?
“==” checks only for equality in value whereas “===” is a stricter equality test and returns false if either the value or the type of the two variables are different.
26. What would be the result of 3+2+”7″?
Since 3 and 2 are integers, they will be added numerically. And since 7 is a string, its concatenation will be done. So the result would be 57.
27. Explain how to detect the operating system on the client machine?
In order to detect the operating system on the client machine, the navigator.platform string (property) should be used.
28. What do mean by NULL in Javascript?
The NULL value is used to represent no value or no object. It implies no object or null string, no valid boolean value, no number and no array object.
29. What is the function of delete operator?
The delete keyword is used to delete the property as well as its value.
Example
var student= {age:20, batch:"ABC"};
delete student.age;
30. What is an undefined value in JavaScript?
Undefined value means the
  • Variable used in the code doesn’t exist
  • Variable is not assigned to any value
  • Property doesn’t exist
31. What are all the types of Pop up boxes available in JavaScript?
  • Alert
  • Confirm and
  • Prompt
32. What is the use of Void(0)?
Void(0) is used to prevent the page from refreshing and parameter “zero” is passed while calling.
Void(0) is used to call another method without refreshing the page.
33. How can a page be forced to load another page in JavaScript?
The following code has to be inserted to achieve the desired effect:


34. What is the data type of variables of in JavaScript?
All variables in the JavaScript are object data types.
35. What is the difference between an alert box and a confirmation box?
An alert box displays only one button which is the OK button.
But a Confirmation box displays two buttons namely OK and cancel.

36. What are escape characters?

Escape characters (Backslash) is used when working with special characters like single quotes, double quotes, apostrophes and ampersands. Place backslash before the characters to make it display.
Example:
document.write "I m a "good" boy"
document.write "I m a \"good\" boy"

37. What are JavaScript Cookies?

Cookies are the small test files stored in a computer and it gets created when the user visits the websites to store information that they need. Example could be User Name details and shopping cart information from the previous visits.

38. Explain what is pop()method in JavaScript?

The pop() method is similar as the shift() method but the difference is that the Shift method works at the start of the array. Also the pop() method take the last element off of the given array and returns it. The array on which is called is then altered.
Example:
var cloths = ["Shirt", "Pant", "TShirt"];
cloths.pop();
//Now cloth becomes Shirt,Pant

39. Whether JavaScript has concept level scope?

No. JavaScript does not have concept level scope. The variable declared inside the function has scope inside the function.

40. Mention what is the disadvantage of using innerHTML in JavaScript?

If you use innerHTML in JavaScript the disadvantage is
  • Content is replaced everywhere
  • We cannot use like “appending to innerHTML”
  • Even if you use +=like “innerHTML = innerHTML + ‘html'” still the old content is replaced by html
  • The entire innerHTML content is re-parsed and build into elements, therefore its much slower
  • The innerHTML does not provide validation and therefore we can potentially insert valid and broken HTML in the document and break it

41. What is break and continue statements?

Break statement exits from the current loop.
Continue statement continues with next statement of the loop.

42. What are the two basic groups of dataypes in JavaScript?

They are as –
  • Primitive
  • Reference types.
Primitive types are number and Boolean data types. Reference types are more complex types like strings and dates.

43. How generic objects can be created?

Generic objects can be created as:

var I = new object();

44. What is the use of type of operator?

‘Typeof’ is an operator which is used to return a string description of the type of a variable.

45. Which keywords are used to handle exceptions?

Try… Catch—finally is used to handle exceptions in the JavaScript
Try{
Code
}
Catch(exp){
Code to throw an exception
}
Finally{
Code runs either it finishes successfully or after catch
}

46. Which keyword is used to print the text in the screen?

document.write(“Welcome”) is used to print the text – Welcome in the screen.

47. What is the use of blur function?

Blur function is used to remove the focus from the specified object.

48. What is variable typing?

Variable typing is used to assign a number to a variable and then assign string to the same variable. Example is as follows:
i= 8;
i="john";

49. How to find operating system in the client machine using JavaScript?

The ‘Navigator.appversion’ is used to find the name of the operating system in the client machine.

50. What are the different types of errors in JavaScript?

There are three types of errors:
  • Load time errors: Errors which come up when loading a web page like improper syntax errors are known as Load time errors and it generates the errors dynamically.
  • Run time errors: Errors that come due to misuse of the command inside the HTML language.
  • Logical Errors: These are the errors that occur due to the bad logic performed on a function which is having different operation.

51. What is the use of Push method in JavaScript?

The push method is used to add or append one or more elements to the end of an Array. Using this method, we can append multiple elements by passing multiple arguments

52. What is unshift method in JavaScript?

Unshift method is like push method which works at the beginning of the array. This method is used to prepend one or more elements to the beginning of the array.

53. What is the difference between JavaScript and Jscript?

Both are almost similar. JavaScript is developed by Netscape and Jscript was developed by Microsoft .

54. How are object properties assigned?

Properties are assigned to objects in the following way –

obj["class"] = 12;
or

obj.class = 12;

55. What is the ‘Strict’ mode in JavaScript and how can it be enabled?

Strict Mode adds certain compulsions to JavaScript. Under the strict mode, JavaScript shows errors for a piece of codes, which did not show an error before, but might be problematic and potentially unsafe. Strict mode also solves some mistakes that hamper the JavaScript engines to work efficiently.
Strict mode can be enabled by adding the string literal “use strict” above the file. This can be illustrated by the given example:
function myfunction() {
"use strict";
var v = "This is a strict mode function";
}

56. What is the way to get the status of a CheckBox?

The status can be acquired as follows –

alert(document.getElementById('checkbox1').checked);
If the CheckBox will be checked, this alert will return TRUE.

57. How can the OS of the client machine be detected?

The navigator.appVersion string can be used to detect the operating system on the client machine.

58. Explain window.onload and onDocumentReady?

The onload function is not run until all the information on the page is loaded. This leads to a substantial delay before any code is executed.
onDocumentReady loads the code just after the DOM is loaded. This allows early manipulation of the code.

59. How will you explain closures in JavaScript? When are they used?

Closure is a locally declared variable related to a function which stays in memory when the function has returned.
For example:
function greet(message) {

console.log(message);

}

function greeter(name, age) {

return name + " says howdy!! He is " + age + " years old";

}

// Generate the message

var message = greeter("James", 23);

// Pass it explicitly to greet

greet(message);

This function can be better represented by using closures

function greeter(name, age) {

var message = name + " says howdy!! He is " + age + " years old";

return function greet() {

console.log(message);

};

}

// Generate the closure

var JamesGreeter = greeter("James", 23);

// Use the closure

JamesGreeter();

60. How can a value be appended to an array?

A value can be appended to an array in the given manner –

arr[arr.length] = value;

61. Explain the for-in loop?

The for-in loop is used to loop through the properties of an object.
The syntax for the for-in loop is –
for (variable name in object){
statement or block to execute
}
In each repetition, one property from the object is associated to the variable name, and the loop is continued till all the properties of the object are depleted.

62. Describe the properties of an anonymous function in JavaScript?

A function that is declared without any named identifier is known as an anonymous function. In general, an anonymous function is inaccessible after its declaration.
Anonymous function declaration –
var anon = function() {
alert('I am anonymous');
};
anon();

63. What is the difference between .call() and .apply()?

The function .call() and .apply() are very similar in their usage except a little difference. .call() is used when the number of the function’s arguments are known to the programmer, as they have to be mentioned as arguments in the call statement. On the other hand, .apply() is used when the number is not known. The function .apply() expects the argument to be an array.
The basic difference between .call() and .apply() is in the way arguments are passed to the function. Their usage can be illustrated by the given example.
var someObject = {
myProperty : 'Foo',

myMethod : function(prefix, postfix) {

alert(prefix + this.myProperty + postfix);
}
};
someObject.myMethod(''); // alerts ''
var someOtherObject = {

myProperty : 'Bar'

};
someObject.myMethod.call(someOtherObject, ''); // alerts ''

someObject.myMethod.apply(someOtherObject, ['']); // alerts ''

64. Define event bubbling?

JavaScript allows DOM elements to be nested inside each other. In such a case, if the handler of the child is clicked, the handler of parent will also work as if it were clicked too.

65. Is JavaScript case sensitive? Give an example?

Yes, JavaScript is case sensitive. For example, a function parseInt is not same as the function Parseint.

66. What boolean operators can be used in JavaScript?

The ‘And’ Operator (&&), ‘Or’ Operator (||) and the ‘Not’ Operator (!) can be used in JavaScript.
*Operators are without the parenthesis.

67. How can a particular frame be targeted, from a hyperlink, in JavaScript?

This can be done by including the name of the required frame in the hyperlink using the ‘target’ attribute.

68. What is the role of break and continue statements?

Break statement is used to come out of the current loop while the continue statement continues the current loop with a new recurrence.

69. Write the point of difference between web-garden and a web-farm?

Both web-garden and web-farm are web hosting systems. The only difference is that web-garden is a setup that includes many processors in a single server while web-farm is a larger setup that uses more than one server.

70. How are object properties assigned?

Assigning properties to objects is done in the same way as a value is assigned to a variable. For example, a form object’s action value is assigned as ‘submit’ in the following manner – Document.form.action=”submit”

71. What is the method for reading and writing a file in JavaScript?

This can be done by Using JavaScript extensions (runs from JavaScript Editor), example for opening of a file –

fh = fopen(getScriptPath(), 0);

72. How are DOM utilized in JavaScript?

DOM stands for Document Object Model and is responsible for how various objects in a document interact with each other. DOM is required for developing web pages, which includes objects like paragraph, links, etc. These objects can be operated to include actions like add or delete. DOM is also required to add extra capabilities to a web page. On top of that, the use of API gives an advantage over other existing models.

73. How are event handlers utilized in JavaScript?

Events are the actions that result from activities, such as clicking a link or filling a form, by the user. An event handler is required to manage proper execution of all these events. Event handlers are an extra attribute of the object. This attribute includes event’s name and the action taken if the event takes place.

74. Explain the role of deferred scripts in JavaScript?

By default, the parsing of the HTML code, during page loading, is paused until the script has not stopped executing. It means, if the server is slow or the script is particularly heavy, then the webpage is displayed with a delay. While using Deferred, scripts delays execution of the script till the time HTML parser is running. This reduces the loading time of web pages and they get displayed faster.

75. What are the various functional components in JavaScript?

The different functional components in JavaScript are-
First-class functions: Functions in JavaScript are utilized as first class objects. This usually means that these functions can be passed as arguments to other functions, returned as values from other functions, assigned to variables or can also be stored in data structures.
Nested functions: The functions, which are defined inside other functions, are called Nested functions. They are called ‘everytime’ the main function is invoked.

76. Write about the errors shown in JavaScript?

JavaScript gives a message if it encounters an error. The recognized errors are –
  • Load-time errors: The errors shown at the time of the page loading are counted under Load-time errors. These errors are encountered by the use of improper syntax, and thus are detected while the page is getting loaded.
  • Run-time errors: This is the error that comes up while the program is running. It is caused by illegal operations, for example, division of a number by zero, or trying to access a non-existent area of the memory.
  • Logic errors: It is caused by the use of syntactically correct code, which does not fulfill the required task. For example, an infinite loop.

77. What are Screen objects?

Screen objects are used to read the information from the client’s screen. The properties of screen objects are –
  • AvailHeight: Gives the height of client’s screen
  • AvailWidth: Gives the width of client’s screen.
  • ColorDepth: Gives the bit depth of images on the client’s screen
  • Height: Gives the total height of the client’s screen, including the taskbar
  • Width: Gives the total width of the client’s screen, including the taskbar

78. Explain the unshift() method ?

This method is functional at the starting of the array, unlike the push(). It adds the desired number of elements to the top of an array. For example –
var name = [ "john" ];
name.unshift( "charlie" );
name.unshift( "joseph", "Jane" );
console.log(name);
The output is shown below:

[" joseph "," Jane ", " charlie ", " john "]

79. Define unescape() and escape() functions?

The escape () function is responsible for coding a string so as to make the transfer of the information from one computer to the other, across a network.
For Example:

document.write(escape("Hello? How are you!"));

Output:

Hello%3F%20How%20are%20you%21
The unescape() function is very important as it decodes the coded string.
It works in the following way. For example:

document.write(unescape("Hello%3F%20How%20are%20you%21"));

Output:

Hello? How are you!

80. What are the decodeURI() and encodeURI()?

EncodeURl() is used to convert URL into their hex coding. And DecodeURI() is used to convert the encoded URL back to normal.

var uri="my test.asp?name=ståle&car=saab";

document.write(encodeURI(uri)+ "
");

document.write(decodeURI(uri));

Output:

my%20test.asp?name=st%C3%A5le&car=saab

my test.asp?name=ståle&car=saab

81. Why it is not advised to use innerHTML in JavaScript?

innerHTML content is refreshed every time and thus is slower. There is no scope for validation in innerHTML and, therefore, it is easier to insert rouge code in the document and, thus, make the web page unstable.

82. What does the following statement declares?

var myArray = [[[]]];

It declares a three dimensional array.

83. How are JavaScript and ECMA Script related?

ECMA Script are like rules and guideline while Javascript is a scripting language used for web development.

84. What is namespacing in JavaScript and how is it used?

Namespacing is used for grouping the desired functions, variables etc. under a unique name. It is a name that has been attached to the desired functions, objects and properties. This improves modularity in the coding and enables code reuse.

85. How can JavaScript codes be hidden from old browsers that don’t support JavaScript?

For hiding JavaScript codes from old browsers:
Add “<!–" without the quotes in the code just after the tag.
Add “//–>” without the quotes in the code just before the tag.
Old browsers will now treat this JavaScript code as a long HTML comment. While, a browser that supports JavaScript, will take the “” as one-line comments

grep command in Linux

Author : Piyush Gupta

The grep filter searches a file for a particular pattern of characters, and displays all lines that contain that pattern. The pattern that is searched in the file is referred to as the regular expression (grep stands for globally search for regular expression and print out).

Syntax:

grep [options] pattern [files]
Options Description
-c : This prints only a count of the lines that match a pattern
-h : Display the matched lines, but do not display the filenames.
-i : Ignores, case for matching
-l : Displays list of a filenames only.
-n : Display the matched lines and their line numbers.
-v : This prints out all the lines that do not matches the pattern
-e exp : Specifies expression with this option. Can use multiple times.
-f file : Takes patterns from file, one per line.
-E : Treats pattern as an extended regular expression (ERE)
-w : Match whole word
-o : Print only the matched parts of a matching line,
with each such part on a separate output line.

Examples:

We assuming file name is piyush.txt

1. Case insensitive search : 

The -i option enables to search for a string case insensitively in the give file. It matches the words like “UNIX”, “Unix”, “unix”.
$grep -i "UNix" piyush.txt

2. Displaying the count of number of matches : 

We can find the number of lines that matches the given string/pattern
$grep -c "unix" piyush.txt

3. Display the file names that matches the pattern : 

We can just display the files that contains the given string/pattern.
$grep -l "unix" *

or

$grep -l "unix" f1.txt f2.txt f3.xt f4.txt

4. Checking for the whole words in a file : 

By default, grep matches the given string/pattern even if it found as a sub-string in a file. The -w option to grep makes it match only the whole words.
$ grep -w "unix" piyush.txt

5. Displaying only the matched pattern : 

By default, grep displays the entire line which has the matched string. We can make the grep to display only the matched string by using the -o option.
$ grep -o "unix" piyush.txt

6. Show line number while displaying the output using grep -n : 

To show the line number of file with the line matched.
$ grep -n "unix" piyush.txt

7. Inverting the pattern match : 

You can display the lines that are not matched with the specified search sting pattern using the -v option.
$ grep -v "unix" piyush.txt

8. Matching the lines that start with a string : 

The ^ regular expression pattern specifies the start of a line. This can be used in grep to match the lines which start with the given string or pattern.
$ grep "^unix" piyush.txt

9. Matching the lines that end with a string : 

The $ regular expression pattern specifies the end of a line. This can be used in grep to match the lines which end with the given string or pattern.
$ grep "os$" piyush.txt

How are parameters sent in an HTTP POST request?

Author Piyush Gupta

The values are sent in the request body, in the format that the content type specifies.
Usually the content type is application/x-www-form-urlencoded, so the request body uses the same format as the query string:
parameter=value&also=another
When you use a file upload in the form, you use the multipart/form-data encoding instead, which has a different format. It’s more complicated, but you usually don’t need to care what it looks like.
The content is put after the HTTP headers. The format of an HTTP POST is to have the HTTP headers, followed by a blank line, followed by the request body. The POST variables are stored as key-value pairs in the body.
You can see this in the raw content of an HTTP Post, shown below:
POST /path/script.cgi HTTP/1.0
From: frog@jmarshall.com
User-Agent: HTTPTool/1.0
Content-Type: application/x-www-form-urlencoded
Content-Length: 32

home=Cosby&favorite+flavor=flies

What is application/x-www-form-urlencoded or multipart/form-data?

Author Piyush Gupta

TL;DR
Summary; if you have binary (non-alphanumeric) data (or a significantly sized payload) to transmit, use multipart/form-data. Otherwise, use application/x-www-form-urlencoded.

The MIME types you mention are the two Content-Type headers for HTTP POST requests that user-agents (browsers) must support. The purpose of both of those types of requests is to send a list of name/value pairs to the server. Depending on the type and amount of data being transmitted, one of the methods will be more efficient than the other. To understand why, you have to look at what each is doing under the covers.
For application/x-www-form-urlencoded, the body of the HTTP message sent to the server is essentially one giant query string — name/value pairs are separated by the ampersand (&), and names are separated from values by the equals symbol (=). An example of this would be: 
MyVariableOne=ValueOne&MyVariableTwo=ValueTwo
According to the specification:
[Reserved and] non-alphanumeric characters are replaced by `%HH’, a percent sign and two hexadecimal digits representing the ASCII code of the character
That means that for each non-alphanumeric byte that exists in one of our values, it’s going to take three bytes to represent it. For large binary files, tripling the payload is going to be highly inefficient.
That’s where multipart/form-data comes in. With this method of transmitting name/value pairs, each pair is represented as a “part” in a MIME message (as described by other answers). Parts are separated by a particular string boundary (chosen specifically so that this boundary string does not occur in any of the “value” payloads). Each part has its own set of MIME headers like Content-Type, and particularly Content-Disposition, which can give each part its “name.” The value piece of each name/value pair is the payload of each part of the MIME message. The MIME spec gives us more options when representing the value payload — we can choose a more efficient encoding of binary data to save bandwidth (e.g. base 64 or even raw binary).
Why not use multipart/form-data all the time? For short alphanumeric values (like most web forms), the overhead of adding all of the MIME headers is going to significantly outweigh any savings from more efficient binary encoding.

How do control web page caching, across all browsers?

Author Piyush Gupta

Introduction

The correct minimum set of headers that works across all mentioned clients (and proxies):
Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Expires: 0
The Cache-Control is per the HTTP 1.1 spec for clients and proxies (and implicitly required by some clients next to Expires). The Pragma is per the HTTP 1.0 spec for prehistoric clients. The Expires is per the HTTP 1.0 and 1.1 specs for clients and proxies. In HTTP 1.1, the Cache-Control takes precedence over Expires, so it’s after all for HTTP 1.0 proxies only.
If you don’t care about IE6 and its broken caching when serving pages over HTTPS with only no-store, then you could omit Cache-Control: no-cache.
Cache-Control: no-store, must-revalidate
Pragma: no-cache
Expires: 0
If you don’t care about IE6 nor HTTP 1.0 clients (HTTP 1.1 was introduced 1997), then you could omit Pragma.
Cache-Control: no-store, must-revalidate
Expires: 0
If you don’t care about HTTP 1.0 proxies either, then you could omit Expires.
Cache-Control: no-store, must-revalidate
On the other hand, if the server auto-includes a valid Date header, then you could theoretically omit Cache-Control too and rely on Expires only.
Date: Wed, 24 Aug 2016 18:32:02 GMT
Expires: 0
But that may fail if e.g. the end-user manipulates the operating system date and the client software is relying on it.
Other Cache-Control parameters such as max-age are irrelevant if the abovementioned Cache-Control parameters are specified. The Last-Modified header as included in most other answers here is only interesting if you actually want to cache the request, so you don’t need to specify it at all.

How to set it?

Using PHP:
header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1.
header
("Pragma: no-cache"); // HTTP 1.0.
header
("Expires: 0"); // Proxies.
Using Java Servlet, or Node.js:
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
response
.setHeader("Pragma", "no-cache"); // HTTP 1.0.
response
.setHeader("Expires", "0"); // Proxies.
Using ASP.NET-MVC
Response.Cache.SetCacheability(HttpCacheability.NoCache);  // HTTP 1.1.
Response.Cache.AppendCacheExtension("no-store, must-revalidate");
Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0.
Response.AppendHeader("Expires", "0"); // Proxies.
Using ASP.NET Web API:
// `response` is an instance of System.Net.Http.HttpResponseMessage
response
.Headers.CacheControl = new CacheControlHeaderValue
{
NoCache = true,
NoStore = true,
MustRevalidate = true
};
response
.Headers.Pragma.ParseAdd("no-cache");
// We can't use `response.Content.Headers.Expires` directly
// since it allows only `DateTimeOffset?` values.
response
.Content?.Headers.TryAddWithoutValidation("Expires", 0.ToString());
Using ASP.NET:
Response.AppendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0.
Response.AppendHeader("Expires", "0"); // Proxies.
Using ASP:
Response.addHeader "Cache-Control", "no-cache, no-store, must-revalidate" ' HTTP 1.1.
Response
.addHeader "Pragma", "no-cache" ' HTTP 1.0.
Response
.addHeader "Expires", "0" ' Proxies.
Using Ruby on Rails, or Python/Flask:
headers["Cache-Control"] = "no-cache, no-store, must-revalidate" # HTTP 1.1.
headers
["Pragma"] = "no-cache" # HTTP 1.0.
headers
["Expires"] = "0" # Proxies.
Using Python/Django:
response["Cache-Control"] = "no-cache, no-store, must-revalidate" # HTTP 1.1.
response
["Pragma"] = "no-cache" # HTTP 1.0.
response
["Expires"] = "0" # Proxies.
Using Python/Pyramid:
request.response.headerlist.extend(
(
('Cache-Control', 'no-cache, no-store, must-revalidate'),
('Pragma', 'no-cache'),
('Expires', '0')
)
)
Using Go:
responseWriter.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") // HTTP 1.1.
responseWriter
.Header().Set("Pragma", "no-cache") // HTTP 1.0.
responseWriter
.Header().Set("Expires", "0") // Proxies.
Using Apache .htaccess file:
<IfModule mod_headers.c>
Header set Cache-Control "no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires 0
Using HTML4:
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />

HTML meta tags vs HTTP response headers

Important to know is that when an HTML page is served over an HTTP connection, and a header is present in both the HTTP response headers and the HTML  tags, then the one specified in the HTTP response header will get precedence over the HTML meta tag. The HTML meta tag will only be used when the page is viewed from a local disk file system via a file:// URL. See also W3 HTML spec chapter 5.2.2. Take care with this when you don’t specify them programmatically because the webserver can namely include some default values.
Generally, you’d better just not specify the HTML meta tags to avoid confusion by starters and rely on hard HTTP response headers. Moreover, specifically those  tags are invalid in HTML5. Only the http-equiv values listed in HTML5 specification are allowed.

What is the difference between a URI, URL and URN?

Author Piyush Gupta

URI — Uniform Resource Identifier

URIs are a standard for identifying documents using a short string of numbers, letters, and symbols. They are defined by RFC 3986 – Uniform Resource Identifier (URI): Generic Syntax. URLs, URNs, and URCs are all types of URI.

URL — Uniform Resource Locator

Contains information about how to fetch a resource from its location. For example:
  • http://example.com/mypage.html
  • ftp://example.com/download.zip
  • mailto:user@example.com
  • file:///home/user/file.txt
  • tel:1-888-555-5555
  • http://example.com/resource?foo=bar#fragment
  • /other/link.html (A relative URL, only useful in the context of another URL)
URLs always start with a protocol (http) and usually contain information such as the network host name (example.com) and often a document path (/foo/mypage.html). URLs may have query parameters and fragment identifiers.

URN — Uniform Resource Name

Identifies a resource by a unique and persistent name, but doesn’t necessarily tell you how to locate it on the internet. It usually starts with the prefix urn: For example:
  • urn:isbn:0451450523 to identify a book by its ISBN number.
  • urn:uuid:6e8bc430-9c3a-11d9-9669-0800200c9a66 a globally unique identifier
  • urn:publishing:book – An XML namespace that identifies the document as a type of book.
URNs can identify ideas and concepts. They are not restricted to identifying documents. When a URN does represent a document, it can be translated into a URL by a “resolver”. The document can then be downloaded from the URL.

Differences between SOAP vs REST

Author Piyush Gupta

SOAP and REST can’t be compared directly, since the first is a protocol (or at least tries to be) and the second is an architectural style. This is probably one of the sources of confusion around it, since people tend to call REST any HTTP API that isn’t SOAP.
Pushing things a little and trying to establish a comparison, the main difference between SOAP and REST is the degree of coupling between client and server implementations. A SOAP client works like a custom desktop application, tightly coupled to the server. There’s a rigid contract between client and server, and everything is expected to break if either side changes anything. You need constant updates following any change, but it’s easier to ascertain if the contract is being followed.
A REST client is more like a browser. It’s a generic client that knows how to use a protocol and standardized methods, and an application has to fit inside that. You don’t violate the protocol standards by creating extra methods, you leverage on the standard methods and create the actions with them on your media type. If done right, there’s less coupling, and changes can be dealt with more gracefully. A client is supposed to enter a REST service with zero knowledge of the API, except for the entry point and the media type. In SOAP, the client needs previous knowledge on everything it will be using, or it won’t even begin the interaction. Additionally, a REST client can be extended by code-on-demand supplied by the server itself, the classical example being JavaScript code used to drive the interaction with another service on the client-side.
I think these are the crucial points to understand what REST is about, and how it differs from SOAP:
  • REST is protocol independent. It’s not coupled to HTTP. Pretty much like you can follow an ftp link on a website, a REST application can use any protocol for which there is a standardized URI scheme.
  • REST is not a mapping of CRUD to HTTP methods.
  • REST is as standardized as the parts you’re using. Security and authentication in HTTP are standardized, so that’s what you use when doing REST over HTTP.
  • REST is not REST without hypermedia and HATEOAS. This means that a client only knows the entry point URI and the resources are supposed to return links the client should follow. Those fancy documentation generators that give URI patterns for everything you can do in a REST API miss the point completely. They are not only documenting something that’s supposed to be following the standard, but when you do that, you’re coupling the client to one particular moment in the evolution of the API, and any changes on the API have to be documented and applied, or it will break.
  • REST is the architectural style of the web itself. If we designed the web the way people think REST should be done, instead of having a home page with links to Questions and Answers, we’d have a static documentation explaining that in order to view a question, you have to take the URI localhost.com/questions/, replace id with the Question.id and paste that on your browser. That’s nonsense, but that’s what many people think REST is.
This last point can’t be emphasized enough. If your clients are building URIs from templates in documentation and not getting links in the resource representations, that’s not REST. Roy Fielding, the author of REST, made it clear on this blog post: REST APIs must be hypertext-driven.
With the above in mind, you’ll realize that while REST might not be restricted to XML, to do it correctly with any other format you’ll have to design and standardize some format for your links. Hyperlinks are standard in XML, but not in JSON. There are draft standards for JSON, like HAL.
Finally, REST isn’t for everyone, and a proof of that is how most people solve their problems very well with the HTTP APIs they mistakenly called REST and never venture beyond that. REST is hard to do sometimes, especially in the beginning, but it pays over time with easier evolution on the server side, and client’s resilience to changes. If you need something done quickly and easily, don’t bother about getting REST right. It’s probably not what you’re looking for. If you need something that will have to stay online for years or even decades, then REST is for you.
Refer : Stackoverflow

How to show all hidden characters in Notepad++

Author Piyush Gupta

The way to enable this depends on your version of Notepad++. 
On newer versions you can use:

Menu View → Show Symbol → *Show All Characters`

or

Menu View → Show Symbol → Show White Space and TAB


On older versions you can look for:

Menu View → Show all characters

or

Menu View → Show White Space and TAB

How to count the number of Lines, Words, and, Characters in a File using terminal

Author Piyush Gupta

The most easiest way to count the number of lines, words, and characters in text file is to use the Linux command “wc” in terminal.
The command “wc” basically means “word count” and with different optional parameters one can use it to count the number of lines, words, and characters in a text file.
To count the number of lines, use “wc” with “l” as
$ wc -l yourTextFile
To count the number of words, use “wc” with “w” option as
$ wc -w yourTextFile
And to count the total number of characters, use “wc” with “c” as
$ wc -c yourTextFile
Using wc with no options will get you the counts of bytes, lines, and words (-c, -l and -w option).
$ wc sample.txt 
1065 5343 40559 sample.txt

Example:

Following command will count number of lines in /etc/passwd files and print on terminal. We can also use –lines in place of -l as command line switch.
$ wc -l /etc/passwd

Count Total Character in File:

Use -m or –chars switch with wc command to count number of characters in a file and print on screen.
$ wc -m /etc/passwd

Count Total Words in File:

Use -w or –words switch with wc command to count number of words in a file and print on screen.
$ wc -w /etc/passwd
Design a site like this with WordPress.com
Get started