Pages

Tuesday, May 17, 2016

Ref and Type in XML Schema

Ref is used to refer to another XML element.


<xsd:element name="Product">
    <xsd:complexType>
        <xsd:sequence>
            <xsd:element name="ProductName" type="xsd:string" />
            <xsd:element ref="Customer" />
        </xsd:sequence>
    </xsd:complexType>
</xsd:element>
<xsd:element name="Customer">
    <xsd:complexType>
        <xsd:sequence>
            <xsd:element name="FullName" type="xsd:string" />
            <xsd:element name="Age" type="xsd:string" />
            <xsd:element name="Age" type="xsd:occupation" />
       </xsd:sequence>
    </xsd:complexType>
</xsd:element>


Type is used to refer to a complexType, simpleType or a built-in type.


<xsd:element name="Product">
    <xsd:complexType>
        <xsd:sequence>
            <xsd:element name="ProductName" type="xsd:string" />
            <xsd:element name="Customer" type="Cust" />
        </xsd:sequence>
    </xsd:complexType>
</xsd:element>

    <xsd:complexType name="Cust" >
        <xsd:sequence>
            <xsd:element name="FullName" type="xsd:string" />
            <xsd:element name="Age" type="xsd:string" />
            <xsd:element name="Age" type="xsd:occupation" />
       </xsd:sequence>
    </xsd:complexType>

Sunday, May 8, 2016

Compile C++ program using C++11

C++11 is the standard of the programming language C++ approved by ISO in 12th August, 2011 replacing C++03. The name follows the tradition of naming language versions by the publication year of the specification, though it was formerly named C++0x because it was expected to be published before 2010.

To compile a C++ program using this version and make use of all the libraries added in this version we need to use the argument c++0x in the command line.

For Eg.:  g++ -std=c++0x hello.cpp -o hello  //Note:its c++ and numeral 0 and x.

Sunday, March 27, 2016

Reflection in Java

   Reflection is the ability of a computer program to examine and modify the structure and behavior of program at run time.

In layman's language it is a powerful and scary feature that should be used with caution. It is used to subvert the norm of information hiding in OOP. It has the ability to modify private members at runtime and thus the term class manipulator fits much better for Reflection.

Core abilities of Reflection:

1. Inspecting constructors, methods and their parameters
2. Inspecting class and method modifiers (private, public, final, abstract)
3. Getting/setting private data
4. Invoking public/private methods

1. Inspecting constructors, methods and their parameters

package com.reflection;
import java.lang.reflect.Method;

public class Test {
 public static void main(String[] args){
  Class c = "foo".getClass();
  System.out.println(c.getName());

  Method[] strMethods = c.getDeclaredMethods();
  for(Method m : strMethods){
   	System.out.println(m.getName());
   	Class parameterType[] = m.getParameterTypes();

   for(int i=0;i < parameterType.length;i++){
    System.out.println("\t" + parameterType[i].getName());
   }
  }
Output:

java.lang.String
equals
 java.lang.Object
toString
hashCode
compareTo
 java.lang.String
compareTo
 java.lang.Object
indexOf
 java.lang.String
 int
indexOf
 java.lang.String
indexOf
 int
 int
indexOf
 int
2. Inspecting class and method modifiers (private, public, final, abstract)

Lets define a class first named TestClass:

package com.reflection;

public class TestClass {
 private int foobar = 42;
 private String zap = "Not accessibe";
 
 public int foo(){
  return 1;
 }
 
 private String bar(String a){
  return a;
 }
}

Lets define a second class with main method:
package com.reflection;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class Test {
 public static void main(String[] args){
  TestClass t = new TestClass();
  Class c1 = t.getClass();
  Field[] fields = c1.getDeclaredFields();
  for(Field f : fields){
   System.out.println(f.getName() + " is a " +
      Modifier.toString(f.getModifiers()) + "  field");
  }
  Method[] methods = c1.getDeclaredMethods();
  for(Method m : methods){
   System.out.println(m.getName() + " is a " +
      Modifier.toString(m.getModifiers()) + "  field");
  }
 }  
}
Output:
foobar is a private  field
zap is a private  field
bar is a private  field
foo is a public  field

3.  Getting/setting private data


Using the same TestClass here, we can get the values of fields using the following code.

package com.singleton;

import java.lang.reflect.*;

public class Test {
	   public static void main(String[] args) {
	     try {          
	    	 TestClass t = new TestClass();
	    	 Class c1 = t.getClass();
	    	 Field[] fields = c1.getDeclaredFields();
	    	 for(Field f : fields){
	    		 f.setAccessible(true);
	    		 System.out.println("The value of field " + 
f.getName() + " is: " + f.get(t)); //Here, note that parameter
//for get is instance of a class i.e. t and not c1.      }         }     catch(Exception e) {        System.out.println(e.toString());     }   } }
Output:

The value of field foobar is: 42
The value of field zap is: Not accessible

Saturday, February 27, 2016

Difference between Abstraction and Encapsulation

One of the most confusing concept for developers to understand is the difference between abstraction and encapsulation. This is because the definition seem to say the same thing using different words.

Abstraction is defined as the process of  generalization thus showing only what is necessary.
Encapsulation on the other hand is defined as process of hiding the unnecessary details.

A real world example of abstraction and encapsulation is TV and a remote.

TV hides the complex circuitry inside it. This is similar to encapsulation. Remote provides us an interface to operate the TV without knowing the internal details. This is similar to abstraction.

In programming, encapsulation is achieved by using getters , setters and access modifiers. Also, every method is encapsulation as it hides the internal details.

Abstraction is achieved by using abstract classes and interfaces. They provide a common implementation which is used by derived classes thus providing generalization.


Thursday, February 25, 2016

Implement SQL EXISTS and IN operator using LINQ

LINQ (Language Integrated Query) is a set of features that extends query capabilities to language syntax of C# and Visual Basic.

In this post, we will see LINQ implementation of EXISTS condition and IN operator used in SQL.

Implement IN using LINQ:

    IN operator is used in SQL to check whether a value is contained in the sequence defined using IN operator. The syntax is as follows:

SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1,value2,...)

Two important aspects of this operator is that it needs a column name(column_name in this case) and a set of values(value1, value2,... in this case) with which the column value is compared.

In LINQ, a similar implementation looks like below. It uses the Contains extension method

IEnumerable str = from c in db.table_name
        where new List(){value1,value2,...}.Contains(c.column_name) 
        select c;


Here db is the datacontext this is defined using the LINQ to SQL classes.

Implement EXISTS using LINQ:

    EXISTS operator checks whether at least one value satisfies the condition.

SELECT *
FROM customers
WHERE EXISTS (SELECT *
              FROM orders
              WHERE customers.customer_id = orders.customer_id);

The above query will select all results from customers if the sub query returns at least one result.

In LINQ, a similar implementation looks like below. It uses the Any element operator
if(db.Test1s.Any(s => s.name == "abc"))
{
   var str = from c in db.Test1s
             select c;
}
Here, the condition inside Any is equivalent to subquery and the statement inside if is equivalent to the main query in sql.

Saturday, February 20, 2016

Async and Await Keyword in C#

Async and Await keywords are used together to run a method asynchronously(not multi-threaded).  An async method will be run synchronously if it does not contain an await keyword. An async method either returns void or a task.

With these keywords, we run methods in an asynchronous way. Threads are optional. This style of code is more responsive. A network access can occur with no program freeze.

Eg: In the following example, the task run asynchronously. Thus, the two console.writeline statements are executed before the task completes.

using System;
using System.Threading.Tasks;
using System.Threading;
internal class Program
{
    private static void Main(string[] args)
    {
        var task = DoWork();
        Console.WriteLine("Task status: " + task.Status);
        Console.WriteLine("Waiting for ENTER");
        Console.ReadLine();
    }

    private static async Task DoWork()
    {
        Console.WriteLine("Entered DoWork(). Sleeping 3");
        // imitating time consuming code
        // in a real-world app this should be inside task, 
        // so method returns fast
        Thread.Sleep(3000);

        await Task.Run(() =>
            {
                for (int i = 0; i < 10; i++)
                {
                    Console.WriteLine("async task iteration " + i);
                    // imitating time consuming code
                    Thread.Sleep(1000);
                }
            });

        Console.WriteLine("Exiting DoWork()");
    }
}
Output:
Entered DoWork(). Sleeping 3
async task iteration 0
Task status: WaitingForActivation
Waiting for ENTER
async task iteration 1
async task iteration 2
async task iteration 3
async task iteration 4
async task iteration 5
async task iteration 6
async task iteration 7
async task iteration 8
async task iteration 9
Exiting DoWork()

Friday, February 19, 2016

Setting Up Multithreading in PHP

Multi-threading in PHP is a very useful feature to take advantage of multi-core processors that is common today. However, multi-threading is not enabled by default.

To set up multi-threading in PHP, follow the following steps.

1. Check the PHP Extension Build for the php version you are using:

 After you have set up your website, go to the link:

localhost:8080/?phpinfo=1

The port number depends on the port you have used, it may be default 80 or any other port number
Look for PHP Extension Build in that page. Check the VC number. For me, its VC11. VC stands for Visual C++, the compiler version that was used to build the version of PHP that you are using. It is interesting to note that PHP which is itself a programming language is built using C and C++. Thus, a compiler need to be used to compile C code.

2. Go to http://windows.php.net/downloads/pecl/releases/pthreads/:

Click on the link above and select and download the latest version of zip file that has the same VC number as that of php version that you are using. For VC11, its 2.0.9. I downloaded php_pthreads-2.0.9-5.6-ts-vc11-x64.zip as I am using a 64 bit computer.

3. Extract the zip.

Move php_pthreads.dll to the php\ext\ directory.
Move pthreadVC2.dll to the php\ directory.

4. Change php.ini file

Open php\php.ini and add

extension=php_pthreads.dll

5. Restart your web server