Monday, 19 October 2015

get used to PROGRAMMING: Fixed point combinator in Python



Consider we need to print 

1
22
333
4444
55555
......

The best solution is using Fixed point combinator

for i in range(1,input()+1):
    print (((pow(10,i))-1)/(9))*i



Read more ...

Export and Import Schema in Oracle 11g



Export Schema from Oracle 11g:

After installation start database by running "Start Database" from all programs.

Open Command Prompt

Execute the following command

exp

Hit enter and enter Username and Password

now enter Buffer Size and export file name with directory (d:/data/oracle-export.dmp) with .dmp extension

Now Select

1 to export entire schema
2 to export only users 
3 to export only tables

Now enter permissions for  grants,table data,extents (use yes  to backup all data in the schema)

Import Schema to Oracle 11g from .DMP file:

Run the following command to import data to Oracle 11g

imp system/system file=d:/data/oracle-export.dmp full=yes

Where system/system is like <username>/<password>.




Read more ...

Sunday, 11 October 2015

get used to PROGRAMING: Python Installation


This page describes how to install Python and the other packages (Numpy, Scipy, IPython, IPython Notebook, Matplotlib) required for the course for Mac OS X, Linux and Windows.

Linux
In Linux, the installation instructions are pretty straightforward. Assuming that you are running Debian or Ubuntu, you just need to execute the following command in the terminal:

sudo apt-get install python-numpy python-scipy python-matplotlib ipython-notebook

For Fedora users, you can use the yum tool.

Mac OS X, Linux, Windows
I recommend downloading and installing the Anaconda Python distribution. The installations instructions are available here.

Just download the installer and execute it with bash.

Anaconda includes most of the packages we will use and it is pretty easy to install additional packages if required, using the conda or pip command-line tools.


If the above two methods do not work for OS X

The MacPorts way
You can try installing everything using MacPorts. First download and install macports and then issue the following command in a terminal:

sudo port install py27-zmq py27-tornado py27-nose

The avove dependencies are required in order to run IPython notebook. Then run:

sudo port install py27-numpy py27-matplotlib py27-scipy py27-ipython

The advantage of this method is that it easy to do. The downsides:

It can take a couple of hours to finish the installation depending on your machine and internet connection, since macports will download and compile everything as it goes.
If you like having the bleeding edge versions, note that it can take a while for them to be released on macports
Finally, macports can create conflicts between different python interpreters installed in your system

Using Apple’s Python interpreted and pip
If you feel adventurous, you can use Apple’s builtin python interpreter and install everything using pip.
If you run into trouble
Leave a comment here with the issue you found.
Read more ...

get used to PROGRAMMING : Python Datatypes

Lists

When we talk about storing multiple values in a container-like data-structure, the first thing that comes to mind is a list.

You can initialize a list as

>>> arr = list()
or simply
>>> arr = []
or with a few elements as

>>> arr = [1,2,3]

Elements can be accessed easily like you do in most programming languages.

>>> print arr[0]
1
>>> print arr[0] + arr[1] + arr[2]
6

Lists in python are very versatile. If you ask what you can add in a Python List, the answer is practically anything!

In python you can create a list of any object, be it string, integers, or even lists. You can even add multiple types in a single list! Isn't that exciting?

Let's look at some of the methods you can use on List.

1) append(x) 
Adds a single element 'x' to the end of list.

>>> arr.append(9)   
>>> print arr  
[1, 2, 3, 9]

2) extend(L) 
Merges another list 'L' to the end.

>>> arr.extend([10,11])
>>> print arr
[1, 2, 3, 9, 10, 11]

3) insert (i,x) 
Inserts element 'x' at position 'i'.

>>> arr.insert(3,7)
>>> print arr
[1, 2, 3, 7, 9, 10, 11]

4) remove(x) 
Removes the first occurrence of element x.

>>> arr.remove(10)  
>>> arr  
[1, 2, 3, 7, 9, 11]

5) pop() 
Removes the last element of list. If an argument is passed, that index item is popped out.

>>> temp = arr.pop()
>>> print temp 
11

6) index(x) 
Returns the first index of a value in the list. Throws error if it's not found.

>>> temp = arr.index(3)
>>> print temp
2

7) count(x) 
Counts the number of occurrences of an element x.

>>> temp = arr.count(1)
>>> print temp
1

8) sort() 
Sorts the list.

>>> arr.sort()
>>> print arr
[1, 2, 3, 7, 9]

9) reverse() 
Reverses the list.

>>> arr.reverse()
>>> print arr
[9, 7, 3, 2, 1]


Tuples

Tuples are a data structure just like list; the prime difference is that tuples are immutable, which means that once created, you can not modify them.

This surely restricts us in using them as we cannot add, remove, or assign values. But it gives us advantage in space and time complexities.

A cool use of tuple we do without realizing is swapping two numbers

a,b = b,a 
Here a,b is a tuple and assigns itself values of b,a.

Another awesome use of tuples is that they can be used as keys in a dictionary; in other words, tuples are hashable.


Read more ...

Friday, 9 October 2015

get used to PROGRAMMING : Python Introduction

Python is a widely used general-purpose, high-level programming language.Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than would be possible in languages such as C++ or Java.The language provides constructs intended to enable clear programs on both a small and large scale.

Python is an interactive language that allows us to execute statements individually and see their results. In other words, you don't have to write a full code and compile it before you see the results as in other languages like C++ and Java.

print "Hello World!" 


my_string = "Hello World!"
print my_string

Let's look at Python's input reading method.

>>> name = raw_input("Hey what's your name?\n")
Hey what's your name?
Arunkumar Palaniappan
>>> print name
Arunkumar Palaniappan

That's one way of doing it for yourself. But in competitive programming we don't ask questions. We only answer them. So we will only use raw_input() to read a string without asking any question to the system.

Now, the three basic arithmetic operators are the following:

Addition (+)
Subtraction (-)
Multiplication (*)


In Python there are two kinds of divisions, namely integer division and float division.

A long time ago during the era of Python 2, when you divided an integer with another integer, no matter the result, it was always an integer.

Example

>>> 4/3 
1
And in order to make this a float division, you'd need to convert one of the arguments into a float.

Example

>>> 4/3.0
1.3333333333333333
Since Python doesn't have data types declared in advance, you never know when you want integers and when you want a float. And since floats lose precision, it's inadvisable to use them in integral calculations.

To solve this problem, future Python modules included a new type of division called integer division given by the operator //

Now / performs float division and // performs integer division.

In Python 2 we will import a module from __future__ called division.

>>> from __future__ import division
>>> print 4/3
1.3333333333333333 
>>> print 4//3
1

One of the built-in functions of Python is divmod, which takes two arguments a and b and returns a tuple containing the quotient of a/b (a//b) and remainder a.

Here a/b can be compared with integer division a//b.

>>> print divmod(177,10)
(17, 7)
Here 177/10 => 17 and 177%10 => 7

We have only heard of the powers of Python, so far; now we will witness them :)

Power or exponent in Python can be calculated using the built-in power function. Which can be called as for ab

>>> pow(a,b) 
or

>>> a**b
It's also possible to calculate abmodm.

>>> pow(a,b,m)  
This is very helpful in computations where you have to print result % mod.

Note that here a and b can be floats and even negatives; but if a third argument is present, b cannot be negative.

Integers in Python can be as big as the bytes in your machine's memory. There is no limit of 2^31−1 (c++ int) or 263−1 (C++ long long int).

Loops are control structures that iterate over a range to perform a certain task.

There are two kinds of loops in Python.

For Loop

for i in range(0,5):
    print i


While loop

i = 0
while i < 5:
    print i
    i+=1
range(0,5) returns a list of integers from 0 to 5 [0,1,2,3,4].

Lets see about Python Datatypes in another post.
Read more ...

Thursday, 8 October 2015

get used to PROGRAMMING : Merge Sort



Hi, Lets see the solution to implement Merge Sort in C

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int* merge(int* Array1, int n, int* Array2, int m) 

 int x = m + n - 1; 
 int i = m-1; int j = n-1; 
 while (i >= 0 && j >= 0) 
 { 
  if (Array1[i] >= Array2[j]) 
  { 
   Array2[x] = Array1[i]; 
   i--; 
  } 
  else
  { 
   Array2[x] = Array2[j]; 
   j--; 
  } 
  x--; 
 } 
 if (i >= 0) 
  memcpy(Array2, Array1, (i + 1) * sizeof(int)); 
 return Array2; 
}
int main()
{
 int size;
 scanf("%d",&size);
 int array1[size];
 for(int i=0;i<size;i++)
    scanf("%d",&array1[i]);
 int array2[size+size];
 for(int i=0;i<size;i++)
    scanf("%d",&array2[i]);
 int *Output = merge(array1,size,array2,size);
 for(int i=0;i<size+size;i++)
 {
  printf("%d ",Output[i]);
 }
 return 0;
}

Output:

Read more ...

get used to PROGRAMMING: Number of Duplicate elements in an Array



Lets see the solution to find Number of Duplicate elements in an Array,

#include <stdio.h>
long long int cmpfunc (const void * a, const void * b)
{
   return ( *(long long int*)a - *(long long int*)b );
}
int main()
{
    long long int size,count=0;

    scanf("%lld",&size);
    int array[size];
    for(int i=0;i<size;i++)
    scanf("%lld",&array[i]);    
    qsort(array, size, sizeof(long long int), cmpfunc);
    for(int i=0;i<size;i++){
      if(array[i]==array[i+1])
            count++;
    }
    printf("%lld\n",count);
    return 0;
}

Output:

Read more ...

Wednesday, 7 October 2015

Unexplained Mysteries of Internet : Has anyone ever seen 410? It must be 404...

404 is an HTTP status code. Every time you visit a web page, your computer or mobile or in a tablet (the ‘client’) is requesting data from a server using HTTP(Hypertext Transfer Protocol). Before the web page is even displayed in your browser, the web server has sent the HTTP header, which contains the status code. Not surprisingly, your browser has sent the server its own headers, which contain a lot more information about you than you think!

For a normal web page, the status is 200 OK. You don’t see this because the server proceeds to send you the contents of the page. It’s only when you encounter an error that you see the actual status code, such as 404 Not Found.

Where does status codes born?

HTTP status codes were established by the World Wide Web Consortium (W3C) in 1992, as a part of the HTTP 0.9 spec. They were defined by Tim Berners-Lee, the same person who single-handedly invented the web and the first web browser in 1990. We at the 404 Research Lab like to think of him as The Man Who Made All Of This Possible.

Berners-Lee based the HTTP status codes on FTP status codes, which were already well established by 1990; the official FTP spec is dated 1985, although FTP has actually been in use much longer.

What is 404 mean?

Let’s dissect 404.

The first 4 indicates a client error. The server is saying that you’ve done something wrong, such as misspell the URL or request a page which is no longer there. Conversely, a 5xx error indicates a server-side problem. It also indicates an error which may be transient; if you try it again, it may work.

The middle 0 refers to a general syntax error. This could indicate a spelling mistake.

The last 4 just indicates the specific error in the group of 40x, which also includes 400: Bad Request, 401: Unauthorized, etc.

According to the W3C, 404 Not Found is only supposed to be used in cases where the server cannot find the requested location and is unsure of its status. If a page has permanently been deleted, it is supposed to use 410: Gone to indicate a permanent change. But has anyone ever seen 410? It must be 404…
Read more ...

Monday, 5 October 2015

How to enable HSTS in IIS / Azure



Before proceeding read more about hsts at http://blog.arunkumarpalaniappan.me/2015/09/http-strict-transport-security-hsts.html


In this post we will go through the steps to enable HSTS in IIS or Azure Web Applications

First locate web.config in C:\inetpub\wwwroot (if you use IIS)  or /site/wwwroot (In Azure web Applications), if no such file is found ,Create new file named web.config


Add the following content to the file

<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="HTTP to HTTPS redirect" stopProcessing="true">
                    <match url="(.*)" />
                    <conditions>
                        <add input="{HTTPS}" pattern="off" ignoreCase="true" />
                    </conditions>
                    <action type="Redirect" url="https://{HTTP_HOST}/{R:1}"
                        redirectType="Permanent" />
                </rule>
            </rules>
            <outboundRules>
                <rule name="Add Strict-Transport-Security when HTTPS" enabled="true">
                    <match serverVariable="RESPONSE_Strict_Transport_Security"
                        pattern=".*" />
                    <conditions>
                        <add input="{HTTPS}" pattern="on" ignoreCase="true" />
                    </conditions>
                    <action type="Rewrite" value="max-age=31536000" />
                </rule>
            </outboundRules>
        </rewrite>
    </system.webServer>
</configuration>

save and replace with existing web.config

Now check the http://{URL} in  the browse, you will automatically redirected to https://{URL}, Great HSTS is sucessfully implemented in IIS / Azure.

Read more ...

Wednesday, 30 September 2015

HTTP Strict Transport Security (HSTS) - An Overview


HTTP Strict Transport Security (HSTS) is a web security policy that is made to protect secure HTTPS websites against downgrade attacks that is used to perform Man in the middle attacks. “Once a supported browser receives this header that browser will prevent any communications from being sent over HTTP to the specified domain and will instead send all communications over HTTPS. It also prevents HTTPS click through prompts on browsers”.
The downgrade attack can occur when the user request a website in HTTP. When the user requested in HTTP:// URL, the server redirects the user to a secure HTTPS:// URL. Without HSTS, an attacker in the same network is able to stop the user from using the HTTPS version of the site and forcing the user to use the HTTP version, where the attacker is able to control user’s data and hijack the user’s session.
The HTTPS stripping attack that relates to the unuse of HSTS policy can be done via open-source tools, such as SSLStrip by Moxie Marlinspike. The tool has been publicly released on February 2009, and since then many browsers and websites have mitigated the issue.
Preventing the issue should be from two sides: the website, and the client. The website has that is already using HTTPS should apply HSTS policy to prevent the attack. The client has to use an updated version that supports HSTS policy.
The current advisory is tend to inform users that there is still modern browsers that do not support HSTS policy until today.

The following browsers do not support HSTS policy:

1.Internet Explorer (all stable versions do not support HSTS. Only Microsoft Edge and Internet Explorer 10 Technical Preview support it)
2.Android Browser ( All versions upto 4.4.2 do not support HSTS policy. Newer versions might not be supporting it too)
3.Opera Mini (all versions, including Opera Mini 8)
4.Maxthon browser
5.UC browsers (including UC browser, UC mini, UC browser HD)
6.Opera for Android

    Testing Browsers for MITM(Man In The Middle) attacks due to Lack of HSTS policy:
    You can follow the instructions in the following link to check if the browser supports HSTS policy.
    Recommendations:
    1.Always use the latest version of browsers
    2.If you are concerned about your security, do not use a browser that does not support HSTS policy.
    3.If you are using a browser that is not listed above, you should test if it supports HSTS policy, and if it does not support it, you should stop using it.
      Notes:
      1.Even if the website is using the maximum SSL encryption possible, if the client’s browser does not support HSTS, the client is vulnerable to man in the middle attacks.
      2.If the client made an initial request to the website in HTTP, an attacker can manipulate the response to uninclude the HSTS header, and would be able to perform MITM attacks too. Therefore, if you are making an initial request to secured site, you should request it in HTTPS to avoid HTTPS stripping that leads to MITM attacks.
        The list might be updated for newer information. If there is a mistake on the list, you can comment to correct it.
        References:
        Read more ...

        Tuesday, 29 September 2015

        What is svchost.exe or Service host Process And Why Is It Running always?


        According to Microsoft: 

        "svchost.exe is a generic host process name for services that run from dynamic-link libraries". 

        Some time ago, Microsoft started moving all of the functionality from internal Windows services into .dll files instead of .exe files. From a programming perspective this makes more sense for reusability… but the problem is that you can't launch a .dll file directly from Windows, it has to be loaded up from a running executable (.exe). Thus the svchost.exe process was born.

        Why Are There So Many svchost.exes Running?

        If you've ever taken a look at the Services section in control panel you might notice that there are a Lot of services required by Windows. If every single service ran under a single svchost.exe instance, a failure in one might bring down all of Windows… so they are separated out.

        Those services are organized into logical groups, and then a single svchost.exe instance is created for each group. For instance, one svchost.exe instance runs the 3 services related to the firewall. Another svchost.exe instance might run all the services related to the user interface, and so on.

        So What Can I Do About It?

        You can trim down unneeded services by disabling or stopping the services that don't absolutely need to be running. Additionally, if you are noticing very heavy CPU usage on a single svchost.exe instance you can restart the services running under that instance.
        Read more ...