Monday, 17 November 2014

How things look like in BLL in ASP.NET

namespace BLL
{
    public class Person
    {
        int _personId;

        public int PersonId
        {
            get { return _personId; }
            set { _personId = value; }
        }

        public static Person GetPerson(int personId)
        {
            Person person = new Person();
            person.PersonId = personId;
            person.Fetch(personId);
            return person;
        }

        public static Person GetPerson(PersonManager.Person personData)
        {
            Person person = new Person();

            person.PersonId = personData.PersonId;
            person.FirstName = personData.FirstName;
           
            return person;
        }

        private void Fetch(int personId)
        {
            PersonManager.Person fetchedPerson = PersonManager.GetPerson(personId);
            this.PersonId = fetchedPerson.PersonId;
            this.FirstName = fetchedPerson.FirstName;
        }

        public void Save()
        {
            if (this._personId == 0)
            {
                // Means this is a new Person record and needs
                // to be inserted into the database

                PersonManager.Person newPerson = new PersonManager.Person();
                newPerson.PersonCode = this.PersonCode;

                this.PersonId = PersonManager.InsertPerson(newPerson).PersonId;
            }
            else
            {
                // Means this Person record is already present
                // in the database and needs to be updated

                PersonManager.Person empToUpdate = new PersonManager.Person();
                empToUpdate.PersonId = this.PersonId;

                PersonManager.UpdatePerson(empToUpdate);
            }
        }
    }
}





namespace BLL
{
    public class PersonList : List<Person>
    {
        private PersonList()
        {
        }

        public static PersonList GetAllPersons()
        {
            PersonList list = new PersonList();
            list.FetchAll();
            return list;
        }

        private void FetchAll()
        {
            List<PersonManager.Person> allPersons = PersonManager.GetAllPersons();

            foreach (var item in allPersons)
            {
                Person person = Person.GetPerson(item);
                this.Add(person);
            }
        }

        public static PersonList GetSearchedPersons(Person personSearched)
        {
            PersonManager.Person person = new PersonManager.Person();
            person.FirstName = personSearched.FirstName;
            person.LastName = personSearched.LastName;
            person.DateOfJoining = personSearched.DateOfJoining;
            person.DepartmentId = personSearched.DepartmentId;
            person.PersonCode = personSearched.PersonCode;
            person.DepartmentName = personSearched.DepartmentName;


            PersonList list = new PersonList();
            list.FetchSearchedPersons(person);

            return list;
        }

        private void FetchSearchedPersons(PersonManager.Person personSearched)
        {
            List<PersonManager.Person> allPersons = PersonManager.SearchPersons(personSearched);
            foreach (var item in allPersons)
            {
                Person person = Person.GetPerson(item);
                this.Add(person);
            }
        }
    }
}

How things look like in DAL in ASP.NET

using System.Data;
using System.Data.SqlClient;

namespace DAL
{
    public static class PersonManager
    {
        public struct Person
        {
            public int PersonId;
            public string FirstName;
            public DateTime DOB;
            public int DepartmentId;
        }

     
        public static Person GetPerson(int personId)
        {
            Person personData = new Person();
            personData.PersonId = personId;

            using (SqlConnection cn = new SqlConnection(Database.PersonPortalString))
            {
                cn.Open();
                using (SqlCommand cm = cn.CreateCommand())
                {
                    cm.CommandText = "GetPerson";
                    cm.CommandType = CommandType.StoredProcedure;
                    cm.Parameters.AddWithValue("@personId", personData.PersonId);

                    using (SqlDataReader dr = cm.ExecuteReader())
                    {
                        if (dr.Read())
                        {
                            personData = ReadPerson(dr);
                        }
                        else
                        {
                            throw new ApplicationException(string.Format("Person({0}) not found.", personData.PersonId));
                        }
                    }
                }
            }
            return personData;
        }

        private static Person ReadPerson(SqlDataReader dr)
        {
            Person personData = new Person();
            personData.DOB = (DateTime)dr["DOB"];
            return personData;
        }

        public static List<Person> SearchPersons(Person personData)
        {
            List<Person> persons = new List<Person>();

            using (SqlConnection cn = new SqlConnection(Database.PersonPortalString))
            {
                cn.Open();
                using (SqlCommand cm = cn.CreateCommand())
                {
                    cm.CommandText = "SearchPersons";
                    cm.CommandType = CommandType.StoredProcedure;

                    if (string.IsNullOrEmpty(personData.PersonCode) == true)
                    {
                        cm.Parameters.AddWithValue("@personCode", Convert.DBNull);
                    }
                    else
                    {
                        cm.Parameters.AddWithValue("@personCode", personData.PersonCode);
                    }

                    if(personData.DateOfJoining== DateTime.MinValue)
                        cm.Parameters.AddWithValue("@dateOfJoining", Convert.DBNull);
                    else
                        cm.Parameters.AddWithValue("@dateOfJoining", personData.DateOfJoining);

                    if (personData.DepartmentId == 0)
                    {
                        cm.Parameters.AddWithValue("@departmentID", Convert.DBNull);
                    }
                    else
                    {
                        cm.Parameters.AddWithValue("@departmentID", personData.DepartmentId);
                    }
                    using (SqlDataReader dr = cm.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            persons.Add(ReadSearchedPerson(dr));
                        }
                    }
                }
            }

            return persons;
        }
    }
}

General things for ASP.NET project

Comma Separated Data With Whitespace:

string[] inputData = Console.ReadLine().Split(',').Select(x=>x.Trim()).ToArray();


How to Add Connection String in C#:
In your project Add Reference "System.Configuration".

Create an App.Config file and add the following code:

<connectionStrings>

   <add name=<YourConnectionString> connectionString="Data Source=<ServerName>; DataBase=<DatabaseName>;Uid=sa;Pwd=Passw0rd;"/>

</connectionStrings>

Create a Database.cs file and add the following code:

using System.Configuration;

namespace DAL
{
    public class Database
    {
        public static string PortalString
        {
            get
            {
                return ConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString;
            }
        }
    }
}

Make private constructor in BLL, underscore-prefixed private fields and CamelCase Properties


To get Active Notices:
N.StartDate < CAST(GETDATE() AS DATE) AND N.ExpirationDate > CAST(GETDATE() AS DATE)

Procedure for Searching a Person:
USE [Portal]
GO

CREATE PROCEDURE [dbo].[SearchPersons]
     (
           @personCode varchar(50),
           @dateOfJoining datetime,
           @firstName varchar(50),
           @lastName varchar(50),
           @departmentID int
     )
AS
BEGIN
     SET NOCOUNT ON
    
     SELECT PersonId, PersonCode, DateOfJoining, FirstName, LastName, DepartmentId
     FROM Persons
     WHERE
      (@personCode IS NULL OR PersonCode LIKE '%' + @personCode + '%')
     AND
     (@dateOfJoining IS NULL OR DateOfJoining = @dateOfJoining)
     AND
     (@firstName IS NULL OR FirstName LIKE '%' + @firstName + '%')
     AND
     (@lastName IS NULL OR LastName LIKE '%' + @lastName + '%')
     AND
     (@departmentID IS NULL OR DepartmentId = @departmentID)
    
     SELECT @@Identity
END
GO



How a GridView in ASP.NET looks like:
    <div>
        <asp:GridView ID="EmpGridView" runat="server" AllowPaging="True" AutoGenerateColumns="False"
            CellPadding="4" EnableModelValidation="True" ForeColor="#333333" GridLines="None"
            OnPageIndexChanging="EmpGridView_PageIndexChanging" PageSize="4" Width="100%">
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
            <EditRowStyle BackColor="#999999" />
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <Columns>
                <asp:TemplateField HeaderText="Employee Code">
                    <ItemTemplate>
                        <asp:Label ID="Label1" runat="server" Text='<%# Bind("EmployeeCode") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Name">
                    <ItemTemplate>
                        <asp:Label ID="Label2" runat="server" Text='<%# String.Format("{0} {1}", Eval("FirstName"), Eval("LastName")) %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Date of Joining">
                    <ItemTemplate>
                        <asp:Label ID="Label3" runat="server" Text='<%#Eval("DateOfJoining", "{0:dd-MMM-yyyy}")%>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Department">
                    <ItemTemplate>
                        <asp:Label ID="Label4" runat="server" Text='<%# Bind("DepartmentName") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# string.Format("~/Employee/AddEditEmployee.aspx?id={0}&op={1}",
HttpUtility.UrlEncode(Eval("EmployeeId").ToString()), "edit")%>' Text="Edit"></asp:HyperLink>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:HyperLink ID="HyperLink2" runat="server" onclick="javascript:return confirm('Are you sure you want to delete ?');"
                            NavigateUrl='<%# Eval("EmployeeId", "DeleteEmployee.aspx?id={0}") %>' Text="Delete"></asp:HyperLink>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>

Page-Indexing in Gridview:

namespace UI
{
    public partial class ManagePersons : System.Web.UI.Page
    {
        PersonList persons;
        protected void Page_Load(object sender, EventArgs e)
        {
            persons = PersonList.GetAllPersons();
            EmpGridView.PageIndex = 0;
            EmpGridView.DataSource = persons;
            EmpGridView.DataBind();
        }


        protected void AddPersonBtn_Click(object sender, EventArgs e)
        {
            Response.Redirect("AddEditPerson.aspx?op=add");
        }

        protected void EmpGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            EmpGridView.PageIndex = e.NewPageIndex;
            EmpGridView.DataSource = persons;
            EmpGridView.DataBind();
        }
    }
}


How to Use Query String for ADD/Edit Common Page in c#:
using System.Globalization;

namespace UI
{
    public partial class AddEditPerson : System.Web.UI.Page
    {
        private int    personId;
        private string operation;

        protected void Page_Load(object sender, EventArgs e)
        {
            operation = Request.QueryString["op"];
            if (operation != GlobalConstants.ADD)
            {
                int.TryParse(Request.QueryString["id"], out this.personId);
            }

            if (!Page.IsPostBack)
            {
                DepartmentList departments = DepartmentList.GetAllDepartments();
                ddDepartment.Items.Add(new ListItem("--Please Select--", "NA"));
               
                foreach (var department in departments)
                {
                    ddDepartment.Items.Add(new ListItem(department.DepartmentName, department.DepartmentId.ToString()));
                }
            }
        }

        protected void CancelBtn_Click(object sender, EventArgs e)
        {
                Response.Redirect("../Default.aspx");
        }

        protected void AddPersonBtn_Click(object sender, EventArgs e)
        {
            int departmentId;
            int.TryParse(ddDepartment.SelectedValue, out departmentId);

            DateTime inputBirthDateTime;
            DateTime.TryParseExact(DateOfBirthBox.Text, GlobalConstants.YMD, CultureInfo.InvariantCulture, DateTimeStyles.None, out inputBirthDateTime);

            BLL.Person person = new BLL.Person
            {
                PersonId      = this.personId,
                FirstName       = FirstNameBox.Text,
                DateOfBirth     = inputBirthDateTime,
                DepartmentId    = departmentId
            };

            person.Save();
        }
    }
}



Wednesday, 16 October 2013

How to implement Short Quines in C?


1) Quine Using Macros :

#define Z(x)t=#x;x
Z(main(){printf("#define Z(x)t=#x;x\nZ(%s)",t);})

2) Use a variable without declaring
b;main(a,s){printf(s="b;main(a,s){printf(s=%c%s%c,34,s,34,a,b);}",34,s,34,a,b);}

In the above quine, there is no need to declare s char *s


3) Initialize variables without assigning values explicitly
b;main(a,s){printf(s="b;main(a,s){printf(s=%c%s%c,34,s,34,a,b);}",34,s,34,a,b);}

In the above quine, a and b are integer variables initialized to 1 and 0 respectively.

4) Use ternary operators if possible
#define Z(x)t=#x;x
Z(main(i){for(;12%++i;);printf(i-12?"#define Z(x)t=#x;x\nZ(%s)":"YES",t);})

The above program acts as a quine if a number is composite else prints “Yes”.
Replace 12 by other numbers to check.

5) Use logical operators:

Example :
The code :

if(n%2==0)
n=n/2;
else
n=n*2;
printf(“%d\n”, n);

can be rewritten as :

printf("%d\n", n%2?n*2:n/2);

Tuesday, 15 October 2013

Shortest Quine Ever in Python

(Hint: empty source file)

Sorted subsequence of size 3 in O(n) time and O(n) extra space

#include<stdio.h>
#include<stdlib.h>
void size3Subsequence(int arr[], int n)
{
    int max = n-1, min=0, i;
     int *smaller = (int*)malloc(sizeof(int)*n);
     smaller[0] = -1;
     for (i = 1; i < n; i++)
    {
        if (arr[i] <= arr[min])
        {
            min = i;
            smaller[i] = -1;
        }
       
        else
            smaller[i] = min;
   }

    for (i = n-2; i >= 0; i--)
    {
        if (arr[i] >= arr[max])
            max = i;

        else if(smaller[i]!=-1)
        {
            printf("%d %d %d\n", arr[smaller[i]], arr[i], arr[max]);
                free(smaller);
            return;
        }  
    }

    printf("No such triplet found\n");
    free(smaller);
    return;
}

int main()
{
    int arr[] = {1,3,0, 2, 5, 4};
    int n = sizeof(arr)/sizeof(arr[0]);
    size3Subsequence(arr, n);
    return 0;
}

Monday, 14 October 2013

Maximum of all subarrays of size k in O(n) time and O(1) extra space !!

#include<stdio.h>
#include<limits.h>

void printKMax(int *arr, int n , int k)
{
    int max=INT_MIN, sec_max=INT_MIN, tag=0,cnt=0;
    int i, max_i, sec_max_i;
   
    for(i=0;i<n;i++)
    {
        if(arr[i]>=max)
        {
            max = arr[i];
            max_i=i-cnt;
        }
       
        else if(arr[i]>=sec_max)
        {
            sec_max = arr[i];
            sec_max_i=i-cnt;
        }
       
        if(i==k-1)
            tag=1;
       
        if(tag)
        {
            cnt++;
            printf("%d ", max);
                   
            max_i--;
            sec_max_i--;
           
            if(max_i==-1)
            {
                max_i = sec_max_i;
                max=sec_max;
                sec_max = INT_MIN;
            }
        }
    }
        printf("\n");
}

int main()
{
    int arr[] ={3,7,1,213, 12, 312};
    int n = sizeof(arr)/sizeof(arr[0]);
    int k = 3;
    printKMax(arr, n, k);
    return 0;
}

Tuesday, 19 February 2013

Number to Word

# Python code for 8315. Number to Word Problem code: NUMWORD

t="teen"
N="nine"
S="seven"
U={0:'zero' ,1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',7:S,8:'eight',9:N,10:'ten',11:'eleven',12:'twelve',13:'thir'+t,14:'four'+t,15:'fif'+t,16:'six'+t,17:S+t,18:'eigh'+t,19:N+t,20:'twenty',30:'thirty',40:'forty',50:'fifty',60:'sixty',70:S+'ty',80:'eighty',90:N+'ty',100:'hundred',1000:'thousand'}
def f(m):return U.get(m)
n=input()
b=len(str(n))-1
T=10
if b>3:b=3
k=T**b
if b==0:print f(n),
while n:
    m=n/k
    if k==T:
        m=n/T
        s=n%T
        if s:
            x=f(m*T+s)
            if x:print x,
            else:print f(m*T),f(s),
        else:print f(m*T),  
    if k>T:
        x=f(m)
        y=f(k)
        if x:
            if m:print x,y,
        else:
            x=m/T
            z=m%T
            X=f(x*T)
            if z:print X,f(z),y,
            else:print X,y,      
    n%=k
    if n==0:print
    k/=T

Saturday, 16 February 2013

Tiling a Grid With Dominoes

# Python code for 2530. Tiling a Grid With Dominoes Problem code: GNY07H

def tiles(n):
    a = [1,1,5,11,36,95,281]
    if n<7:
        return a[n]
    else:
        i=7
        while i!=n+1:
            k=a[i-1]+5*a[i-2]+a[i-3]-a[i-4]
            a.append(k)
            i+=1
    return a[n]           
h=input
for t in range(h()):
    n =h()
    print t+1, tiles(n)

Friday, 15 February 2013

Househoder Method and Jacobi Rotaion

/* C code to tridiagonalize a Matrix using Householder's Method and then finding the eigen values using Jacobi Rotation Method*/

#include<stdio.h>
#include<math.h>
#define ERROR 0.0000001
//Function to read input matrix
void read_matrix(int order ,float matrix[][order])
{
    int i, j;
    for (i=0; i<order;i++)
        for (j=0;j<order;j++)
            scanf("%f",&matrix[i][j]);
}

//Function to print the matrix
void print_matrix(int order , float matrix[][order])
{
    int i, j;
    for (i=0; i<order;i++)
    {
        for (j=0;j<order;j++)
            printf("%.4f\t",matrix[i][j]);
        printf("\n");
    }
}

int check_symmetric(int n , float a[][n])
{
    int i, j, tag=1;
    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
        {
            if (a[i][j]!=a[j][i])
            {
                tag=0;
                break;
            }   
        }
       
        if (tag==0)
            break;
    }

    return tag;
}

//Function to multiply two matrices "a" and "b" and put the result in matrix "c"
float multiply(int n , float a[][n], float b[][n] , float c[][n] )
{
    int i,j,k ;
    float sum;

    for(i=0;i<n;i++)
        for(j=0;j<n;j++)
        {
            sum=0;
            for(k=0;k<n;k++)
                sum=sum+(a[i][k])*(b[k][j]);
            c[i][j]=sum;
        }
}   

/*Function to get an identity matrix*/
void identity(int n , float S[][n])
{
    int i , j;
    for (i=0; i<n;i++)
        for (j=0;j<n;j++)
        {
            if (i==j)
                S[i][i]=1;
            else
                S[i][j]=0;   
        }
}

/*Function to copy one matrix into another matrix*/
void copy(int n, float a[][n] , float b[][n])
{
    int i , j;
    for (i=0;i<n;i++)
        for(j=0;j<n;j++)
            a[i][j]=b[i][j];
}

void transpose_vector(int n, float vector[] , float matrix[][n])
{
    int i,j;
    float sum=0;
   
    for(i=0;i<n;i++)
    {
        for (j=0;j<n;j++)
        {
            matrix[i][j] = vector[i]*vector[j];
        }
    }
}

void print_vector(int n, float a[])
{
    int i;
    for (i=0;i<n;i++)
    {
        printf("%12.4f  ",a[i]);
    }
    printf("\n");   
}

void swap(float a[], int i, int j)
{
    float temp;
    temp=a[i];
    a[i]=a[j];
    a[j]=temp;
}

void bubblesort( int n, float a[])
{
    int i , j;
     for(j=n-2;j>=1;j--)
         for(i=0;i<=j;i++)
             if(a[i]>a[i+1])
                 swap(a,i,i+1);        
}

void jacobi_rotation(int n , float a[][n])
{
    int i,j;
    float pi = 3.1415926;
    float S[n][n] , invS[n][n] ,temp1[n][n] ,temp2[n][n], theta;   

    identity(n,S);
    identity(n,invS);

    int u,v,tag=1;
    while(1)
    {
        tag=1;
        for (i=0;i<n;i++)
        {
           
            for (j=i+1 ; j <n;j++)
            {
                if ((a[i][j])!=0)
                {
                    if (a[i][i]!=a[j][j])
                        theta = (atan(2*a[i][j]/(a[i][i]-a[j][j])))/2;

                    else
                    {
                        if (a[i][j]>0)
                            theta = pi/4;
                       
                        else if (a[i][j]<0)
                            theta = -pi/4;
                    }
                                           
                   
                    identity(n,S);
                    identity(n,invS);

                    S[i][i]= invS[i][i]= invS[j][j]=S[j][j]=cos(theta);
                    S[i][j]= invS[j][i]= -sin(theta);
                    S[j][i]= invS[i][j]=  sin(theta);

                    multiply(n,invS,a,temp1);
                    multiply(n,temp1,S,temp2);
   
                    copy(n,a,temp2);
                   
                }
                else continue;
            }   
        }   
   
        for (u=0;u<n;u++)
        {
            for (v=u+1;v<n;v++)
            {
                if (abs(a[u][v]) > ERROR)
                {
                    tag=0;
                    break;
                }   
            }
            if (tag==0)
                break;
        }
   
        if (tag==1)
            break;
   
    }   
}


/*main function*/
int main()
{
    int n,i,j,sign,k;
    scanf("%d",&n);

    float a[n][n] , P[n][n] ,temp1[n][n] ,temp2[n][n] , I[n][n] , w[n], transpose[n][n], x , sum,s,temp;
    read_matrix(n,a);

    int check;
    check = check_symmetric(n,a);
    if (check==0)
    {
        printf("Given matrix is not symmetric\n");
        return 0;
    }
   
    for(i=0;i<n-2;i++)
    {
        j=0;
        sum=0;
        while(j<=i)
        {
            w[j++]=0;
        }
       
        for(k=i+1;k<n;k++)
            sum=sum+a[i][k]*a[i][k];   
       
        s= sqrt(sum);
        if (s==0)
            continue;
        //printf("s : %f\n",s);
        if (j==i+1)
        {
            if (a[i][j]<0)
                sign=-1;
            else
                sign=1;
               
            temp = (1+a[i][j]*sign/s)/2;
            x=sqrt(temp);
            w[j]=x;
            j++;
        }
       
        for (j=i+2;j<n;j++)
        {
            w[j]=(a[i][j]*sign)/(2*s*x);
        }
       
        identity(n, I);
        transpose_vector(n,w,transpose);
       
        for(k=0;k<n;k++)
        {
            for(j=0;j<n;j++)
            {
                P[k][j]=I[k][j]-2*transpose[k][j];
            }
        }

        //print_matrix(n, P);

        multiply(n,a,P,temp1);
       
        multiply(n,P,temp1,temp2);       
        copy(n,a,temp2);
       
        //print_matrix(n, a);
    }
   
    //printf("\nTridiagonal matrix using Householder Method is : \n\n");
    //printf("\n");
    print_matrix(n,a);
   
    //printf("\nEigne values of Tridiagonal  : \n\n");
    jacobi_rotation(n, a);

    float eigen[n];
    for (i=0;i<n;i++)
        eigen[i]=a[i][i];
       
    bubblesort(n,eigen);   
    //printf("\n");
    for (i=n-1;i>=0;i--)
        printf("%.4f\n",eigen[i]);
   
    return 0;   
}

Thursday, 14 February 2013

Circular Track

// C code for 9199. Circular Track Problem code: SPEED

#include<stdio.h>
int gcd(int a, int b)
{
    int r ;
        while (b!=0)
        {
            r=a%b;
            a=b;
            b=r;
        }
        return a;
}

int main()
{
    int t,m,n,ans;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&m,&n);
        ans=m>n?m-n:n-m;
        m*=(m<0?-1:1);
        n*=(n<0?-1:1);
        printf("%d\n",ans/(gcd(m,n)));
    }
    return 0;
}

Wednesday, 13 February 2013

Tuesday, 12 February 2013

Tanks

// C code for  13675. Tanks Problem code: NEWTANK

#include<stdio.h>
int main()
{
    int test,v,t,i;
    scanf("%d",&test);
    for(i=1;i<=test;i++)
    {
        scanf("%d%d",&v,    &t);
        printf("Case #%d: %d\n",i,v*t);
    }
    return 0;
}

H Number

// C code for 13662. H Number Problem code: HNUM

#include<stdio.h>
int main()
{
    int test, n,i;
    scanf("%d",&test);
   
    for(i=1;i<=test;i++)
    {
        scanf("%d",&n);
        if (n%30==0)
            printf("Case #%d: H-Number\n",i);
        else
            printf("Case #%d: Not H-Number\n",i);   
    }
    return 0;
}

Azooz

// C code for 13677. Azooz Problem code: AZOOZ

#include<stdio.h>
int main()
{
    int t,n,i,j,k;
    scanf("%d",&t);
    for(i=1;i<=t;i++)
    {
        k=1;
        scanf("%d",&n);
        k=3*(n*(n+1)/2);
       
        printf("Case #%d: %d\n",i,k);   
    }
    return 0;
}

Word To Number

#Python code for  7225. Word To Number Problem code: WORDNUM


import re
c="teen";s="seven";e="eigh";n="nine";f="four";X="six";T="thir";y="ty"
U ={'zero':0,'one':1,'two':2,'three':3,f:4,'five':5,X:6,s:7,e+'t':8,n:9,'ten':10,'eleven':11,'twelve':12,T+c:13,f+c:14,'fif'+c:15,X+c:16,s+c:17,e+c:18,n+c:19,'twen'+y:20,T+y:30,'for'+y:40,'fif'+y:50,X+y:60,s+y:70,e+y:80,n+y:90}
M={'thousand':1000,'hundred':100}
def x(s):
 a=re.split(r"[\s-]+",s)
 n=g=0
 for w in a:
  x=U.get(w)
  if x:
   g+=x
  x=M.get(w)
  if x:n+=g*x;g=0
 print n+g
for t in range(input()):x(raw_input())

Egypt

// C code for 9754. Egypt Problem code: SCPC11D

#include<stdio.h>
int main()
{
    int a,b,c;
   
    scanf("%d%d%d",&a,&b,&c);
    while(a&&b&&c)
    {
        if (a>b&&a>c&&b*b+c*c==a*a)
            printf("right\n");
       
        else if (b>c && b>a && c*c+a*a==b*b)   
            printf("right\n");
       
        else if (a*a+b*b==c*c)
            printf("right\n");
        else
            printf("wrong\n");       
   
        scanf("%d%d%d",&a,&b,&c);       
    }
    return 0;
}

Pizza

#Python code for  7169. Pizza Problem code: EGYPIZZA

import math
m=0
n=0
k=0
test=input()
i=0

while i!=test:
    a=raw_input()

    if len(a)!=0:
        if a=="3/4":
            m=m+1
        if a=="1/2":
            n=n+1       
        if a=="1/4":
            k=k+1
        i=i+1           
if m>=k:
    ans=math.ceil(m+n/2.0)

elif m<k:
    k=k-m
    if n%2==0:
        ans = math.ceil(m+n/2.0+k/4.0)
           
    else:
        k=k-2
        ans= math.ceil(m + n/2.0 + k/4.0)

print  int(ans+1)       

GCD (very large numbers)

#Python code to find GCD of two very large numbers

for i in range(input()):
    a,b = [long(i) for i in raw_input().split()]
    while b :
        a,b = b,long(a%b)
    print a

Binary GCD

#Python code to find GCD of two numbers using Binary GCD algorithm

def gcd (a,b):
    if a==0:
        return b
    if b==0:
        return a
   
    shift=0
   
    while (a|b)&1 ==0:
        a>>=1
        b>>=1
        shift+=1
   
    while a&1==0:
        a>>=1
           
    while b:
        while b&1==0:
            b>>=1
        if a>b:
            t=a
            a=b
            b=t
       
        b=b-a
       
    return a<<shift               
   

for i in range(input()):
    a,b=raw_input().split()
    n=int(a)
    m=int(b)
   
    print gcd(n,m)