Sunday, June 24, 2012

First try on HTML 5 . :) :) Awesome experience :)


Here, I have implemented a simple drag and drop in action. J  . I’ll de­fine a drag­gable image that can be dropped into a circle.


The Complete source code ::

<!DOCTYPE html>

<html lang="en">
<head>
    <title>Basic drag and drop example</title>
    <style>

        .drop-div {
            width: 150px;
            height: 150px;
            border: 3px dashed #224163;
            background-color: #AABACC;
            margin-top: 15px;
            border-radius: 80px;
            text-align: center;
        }

        [draggable=true] {
            -khtml-user-drag: element;
            -webkit-user-drag: element;
            -khtml-user-select: none;
            -webkit-user-select: none;
            cursor: pointer;
            margin-top: 50px;
        }
    </style>
    <script>

        function dragStartHandler(event) {
            event.dataTransfer.setData('Text', 'text');
        }
        function dropHandler(event) {
            preventDefaults(event);
            if (!event.target) {
                event.target = event.srcElement
            }
            event.target.appendChild(document.getElementById('draggable-img'));
        }
        function dragOverHandler(event) {
            preventDefaults(event);
        }

        function preventDefaults(event) {
            if (event.preventDefault) {
                event.preventDefault();
            }

            try {
                event.returnValue = false;
            }
            catch (exception) {}
        }
    </script>
</head>

<body>

<img draggable="true"
     ondragstart="dragStartHandler(event);"
     class="draggable-img"
     id="draggable-img"
     src="C:\Users\Dipayan\Desktop\ball.png "/>
<div class="drop-div"
     ondragover="dragOverHandler(event);"
     ondrop="dropHandler(event)"
     id="drop-div"></div>

</body>
</html>


What It Looks Like


















You can then click on the red ball , drag the ball to in­side the circle, and drop it to pro­duce this:












Saturday, May 5, 2012

DSN-Less MSAccess connection

public Connection getConnection() throws Exception {  
 try{
                // Load the driver
                    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                        String filename = "C:/Users/Dipayan/Desktop/dic.mdb";
    String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
    database+=filename.trim() + ";DriverID=22;READONLY=true}";
    Connection conn=DriverManager.getConnection(database,"","");    
                        System.out.println("Connected to the dictionary");  
                     // Create a Statement
                        Statement stmt = conn.createStatement();
                        System.out.println("Statement Created"); 
                        // Create a query String
                        
                        ResultSet rs = stmt.executeQuery("SELECT meaning FROM dictionary where word='"+str+"'");
                        System.out.println("Query Executed"); 
                        while(rs.next())
                        {
                          text = rs.getString(1).toString();
                         // System.out.print(t);
                         
                        } 
                              
                        stmt.close();
                        conn.close();
                        System.out.println("Disconnected from database");
                }
                catch(SQLException e) {
                            e.printStackTrace();
                } catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


Friday, April 13, 2012

Expanding Dictionary Of Acoustic Model



 Today I’m going to tell you how to expand dictionary of acoustic model for Sphinx4. In simple words, This tutorial will tell you how you can add more words in Sphinx’s words database (Dictionary) and let it recognize those words, which are not available in default acoustic models provided by CMU Sphinx. This tutorial is based on “HelloWorld” example provided by CMU Sphinx.


Important Files in this example :
1 ) HelloWorld.java
2) hello.gram
3) helloworld.config.xml
Acoustic Model used in this example :
WSJ_8gau_13dCep_16k_40mel_130Hz_6800Hz.jar
Lets say, We are creating a SR system for ABC National airlines. Everything will go fine and Sphinx will recognize most of the words except the name of cities and states of India.  Now, I will tell you, How to add name of cities and states in dictionary.
PART ONE
Step 1 : Create a txt file “words.txt”, Write all the names of cities and states in it and save.
Step 2 : Open this link : http://www.speech.cs.cmu.edu/tools/lmtool.html
Step 3 : On that page, go to “Sentence corpus file:” section, Browse to “words.txt” file and click “Compile Knowledge Base”.
Step 4 : On next page, Click on “Dictionary” link and save that .DIC file.
PART TWO
Step 1 : Extract WSJ_8gau_13dCep_16k_40mel_130Hz_6800Hz.jar file.
Step 2 : Go to edu\cmu\sphinx\model\acoustic\WSJ_8gau_13dCep_16k_40mel_130Hz_6800Hz\dict folder.
Step 3 : Open “cmudict.0.6d” file in that folder.
Step 4 : Copy data from .DIC file, you have downloaded in PART ONE, paste it in “cmudict.0.6d” file and save.
Step 5 : Zip the extracted hierarchy back as it was and Zip file named should be same as JAR file.
Now, remove “WSJ_8gau_13dCep_16k_40mel_130Hz_6800Hz.jar” file from Project’s CLASSPATH and add “WSJ_8gau_13dCep_16k_40mel_130Hz_6800Hz.zip” instead of it.
That’s it ! We are done.  Now Sphinx will also recognize all name of cities and states that we wrote in “words.txt” file.
Now, FAQ time. I will be posting FAQ and few important notes in comments. 
:)
If you have any quires, Please feel free to ask.
Regards,


Saturday, March 17, 2012

Basics of Java Speech Grammar Format



 Basics of Java Speech Grammar Format (JSGF)

Hello Everyone,
This post is going to be very basic and essentials of Java Speech Grammar Format (JSGF).
Every single file defines a single grammar only. Each grammar contains two parts:
The grammar header and the grammar body.
Grammar header format: #JSGF version char-encoding locale;
“#JSGF” is required and “version char-encoding locale;” is optional.
Grammar header example: #JSGF V1.0; & #JSGF V1.0 ISO8859-5 en;


After declaring Grammar Header, We need to specify the Grammar name.
Grammar name format: grammar grammarName;
This is a mandatory line. Else javax.speech.recognition.GrammarException will be thrown. Not only on Grammar Name, you will get GrammarExpection If you made any kind of mistake in grammar file.
Grammar Name Example: grammar helloWorld;


Once you are done with above part, you next step will be defining Grammar body.
The grammar body defines rules. You can define a rule only once. If you declare same rule twice then it will overwritten.
Rule Definition Format: public <ruleName> = ruleExpansion;
“public” is optional and remaining part is mandatory.
The rule expansion defines how the rule may be spoken. It is a logical combination of tokens (text that may be spoken) and references to other rules.
Rule Example: public <greet> = Hello;
The rule <greet> refers to a single token Hello. So to say rule <greet>, User must say word “Hello”.
A simple rule expansion can refer to one or more tokens or rules.
public <greet> = Hello;
public <completeGreet> = <greet> World;
Now, rule <completeGreet> refers to rule <greet> and token World. To say rule <completeGreet>, User must say “Hello World”.
Lets complete a simple “Hello World” grammar file.
#JSGF V1.0;                                                             

grammar simpleExample;

public <greet> = Hello;
public <completeGreet> = <greet> World;
This grammar file will allow you SR application to recognize 2 sentences. “Hello” and “Hello World”.
Now let’s play a little bit with rule expansions.
Alternatives: “|”
public <greet> = Hello | Hey | Hi;
To say rule <greet>, User must say “Hello” or “Hey” or “Hi” But ONLY one of these three words.
Parentheses: “( )”
public <greet> = Hello (World | User | Friend);
public <command> = ( Open | Close ) ( Door | Window );
To say rule <greet>, User must say “Hello World” or “Hello User” or “Hello Friend”.
And, to say rule <command>, User must say “Open Door” or “Open Window” or “Close Door” or “Close Window”.
Optional Grouping : “[ ]”
public <greet> = [ Hello ] World;
To say rule <greet>, User must say “Hello World” or “World”. As “Hello” is defined inside the Optional Grouping. So user may say it or not but “World” is mandatory.
Kleene Star : “*”
public <greet> = ( Hello | Hey | Hi )* World;
Any group or expansion followed by asterisk symbol indicates that it may be spoken zero or more times. For example “Hey Hello World” or “World” or “Hello Hello Hello World”.
Plus Operator : “+”
public <greet> = ( Hello | Hey | Hi )+ World;
A Plus Operator works same as “Kleene Star”, The only thing that makes difference is any group or expansion followed by plus symbol indicates that it may be spoken one ( NOT ZERO ) or more times.
You can also add comments in grammar file.
// One line comment
/* Multiple lines comment*/
/**
* Documentation comment
* @author Dipayan Dev*/

Monday, March 12, 2012

Speech Recognition By Java :: A sphinx4 implementation

Speech recognition is one of the challenging areas in computer science, a lot of pattern recognition methodology tried to resolve a good way and higher percentage of recognition. I tried lots of technology. 
VB.net, C#.net etc.  But ultimately found Java the most simpler and easy way. 

One of the best ways to be use is Hidden Markov Model :





"The process of speech recognition is to find the best possible sequence of words (or units) that will fit the given input speech. It is a search problem, and in the case of HMM-based recognizers, a graph search problem. The graph represents all possible sequences of phonemes in the entire language of the task under consideration. The graph is typically composed of the HMMs of sound units concatenated in a guided manner, as specified by the grammar of the task."

There are a lot of Java Based Speech Recognition Engines, you can find them here:

In this post I will select one of the famous open source Java speech recognition software that I used in my final year project.

1) Download the software:

Here is the download link:

2) Create new Java project:

Add to class-path 3 jars from the lib folder: jsapi.jar (if not exist jsapi.exe will extract it on windows or jsapi.sh will extract it) ,sphinx4.jar (APIs Jar),WSJ_8gau_13dCep_16k_40mel_130Hz_6800Hz.jar (this is the jar containing the speech)
3) Create a new class to write the logic on it: e.g. ListenToMe.java
Let the package name dipayan_java

4) Add the file dict.gram to the same package: dipayan_java
It should looks like:
#JSGF V1.0;
grammar hello; 
public = (Good morning | Hello | Hi | Welcome) ( Dipayan | Paul | Philip | Rita | Will );

The structure is to write the alternative words between () and separated by |.

The grammar specs in this URL:
A quick tutorial you can find in my blog !

 5) Add the config file myconfig.xml to the same package: dipayan_java
You can get the file structure from the jar in bin folder HelloWorld.jar in the location "HelloWorld.jar\edu\cmu\sphinx\demo\helloworld\helloworld.config.xml"

You need to edit the following entry:
<component name="jsgfGrammar" type="edu.cmu.sphinx.jsgf.JSGFGrammar">
<property name="dictionary" value="dictionary"/>
<property name="grammarLocation"
value="resource:/dipayan_java/"/>
<property name="grammarName" value="dict"/>
<property name="logMath" value="logMath"/>
</component>

6) Write the following code in the created class:

import edu.cmu.sphinx.frontend.util.Microphone;
import edu.cmu.sphinx.recognizer.Recognizer;
import edu.cmu.sphinx.result.Result;
import edu.cmu.sphinx.util.props.ConfigurationManager;

public static void main(String args[]){
ConfigurationManager cm = new ConfigurationManager(ListenToMe.class.getResource("myconfig.xml"));
Recognizer recognizer = (Recognizer)cm.lookup("recognizer");
recognizer.allocate();
Microphone microphone = (Microphone)cm.lookup("microphone");
if(!microphone.startRecording()){
System.out.println("Cannot start microphone.");
recognizer.deallocate();
System.exit(1);
}
System.out.println("Say: (Good morning | Hello | Hi | Welcome) (Dipayan | Paul | Philip | Rita | Will )");
do {
System.out.println("Start speaking. Press Ctrl-C to quit.\n");
Result result = recognizer.recognize();
if(result != null) {
String resultText = result.getBestFinalResultNoFiller();
System.out.println((new StringBuilder()).append("You said: ").append(resultText).append('\n').toString());
} else {
System.out.println("I can't hear what you said.\n");
}
} while(true);
}


For more details about the usage you can refer to this URL:



NOTE :: I did this project on ecllipse . If you want to do it on the same, while running the program,you will find a OutOfMemory exception. This is because , the available Virtual Memory is not enough for Sphinx4.

The thing you have to do, is just increase the heap memory of ecllipse . Go to Virtual memory arguement ,  type    " -Xmx256m  "


Thanks :)
For any query feel free to mail me @dev.dipayan16@gmail.com








Saturday, March 10, 2012

How to Fix a Computer Crash

If your computer crashes unexpectedly, everything comes to a halt. Prior to crashing your computer will likely start freezing up. This is an indication that your computer has to be fixed before it gives up completely. Fixing the computer does not need to involve replacement of the computer with a new one. Your current computer likely just needs a little attention.

Identifying the reason for crashing is essential prior to fixing the computer. The initial step is to reboot your computer. If the rebooting goes smoothly, it is apparent that you are facing a problem with your registry. If you cannot reboot instantly, then rebooting your computer in safe mode and locating a registry cleaner to fix your problem is essential.

Every file present in your registry contains a command or direction for every program and application on your computer. Registry files are the files that give your computer the instructions for what to do next. If these registry files get corrupt or misplaced, your computer fails to understand what to do. In these instances, your computer loses control, eventually leading to a crash.

At this stage the priority is to fix these registry files. In such situations it is suggested that you do not try to fix the registry yourself. Immediately find registry cleaner software and scan your computer to locate any errors. This software will identify all the missing entries or errors, restoring them right away. In many cases, your computer will be back to normal. It is recommended that you run this software once a month for best results.

Another cause of crashes is when new software is installed. If you have recently installed a new program or file, this could also be the source of the problem. You should locate the program and uninstall it. In case you are incapable of booting up your computer in normal mode, you are advised to try booting in safe mode first. If the new program is at fault, removing it should solve the problem. Obviously you would not re-install that program later on.

Most computer crashes occur due to a problem with the computer's registry files. This is the core reason for any crash. So, running registry cleaning software and eliminating all errors is essential to avoid computer crashes in the future. Subsequently, fixing the registry files will keep you from having to ask the question 'how do I fix a computer crash' again.



 For any more queries..feel free to mail me @ dev.dipayan16@gmail.com 

Tuesday, January 17, 2012

Box with J2SE 5.0


Wondering what Boxing's got to do with Java? And I didn't mean Laila Ali, the first woman to win a World Boxing Council title, either! You wouldn't like to mess with her, would you?


So, what is Boxing in Java? Boxing refers to the automatic conversion from a primitive to its corresponding wrapper type: Boolean, Byte, Short, Character, Integer, Long, Float or Double. Since this happens automatically, it's also referred to as autoboxing. The reverse is also true, ie. J2SE 5.0 automatically converts wrapper types to primitives and is known as unboxing.


Before you can try out this simple example, you must install and set the environment variables 'path' and 'classpath' for J2SE 5.0.


The example is quite trivial and you could try compiling it with an earlier version of J2SE, to see the compilation errors flagged out.



public class BoxingUnBoxing
{
  public static void main(String[] args)
  {
    // Boxing
    int var = 10;
    Integer wInt = var;
    int result = var * wInt;
    System.out.println("Value of result = " + result);

    // Unboxing
    int conv = wInt;
    if (conv < 100)
      System.out.println("True");
  }
}


Boxing and Unboxing save us the bother of converting from a primitive to it's wrapper and vice-versa. This feature is definitely a time-saver :) :)

Monday, January 16, 2012

Cache-timing attacks on AES

AES  [via: Schneier on Security]
                Daniel J. Bernstein published a profound paper on AES Timing attack. There is very little new in the article from cryptology or cyptography point of view. The side-channel timing attacks of this nature are well known for decades. Moreover, the attacks are not against AES algorithm as such, but against a specific software implementation (OpenSSL on Pentium III).

However it's clear that it is applicable to any other modern CPU, and to any software implementation of any cryptographic algorithm which uses S-boxes. This and other things that I will point out later, led me to conclude that the article and its implications are truly profound. But first of all a quote from the article:

Was there some careless mistake in the OpenSSL implementation of AES? No. The problem lies in AES itself: it is extremely difficult to write constant-time high-speed AES software for common general-purpose CPUs. The underlying problem is that it is extremely difficult to load an array entry in time that does not depend on the entry's index. I chose to focus on OpenSSL because OpenSSL is one of today's most popular cryptographic toolkits. (Constant time low-speed AES software is fairly easy to write but is also unacceptable for many applications. Rijndael would obviously not have survived the fist round of AES competition if it had been implemented in this way.) Is AES the only cryptographic function vulnerable to this type of attack? No. The relevant feature of AES software, namely its heavy reliance upon S-boxes, is shared by cryptographic software for many other functions.

Emphasis is mine. If you don't know the particulars of clock-resolution performance of modern CPUs, just take his word for it. If you do, most likely you don't know half of it. Read the article for all the gory details. The bad news is that an attacker doesn't even need to understand any of the detils. He just need to know that time depends on index, and simply measure it.

Any software algorithm on any modern CPU which involves a table lookup, like S-boxes, for example, is subject to timing attacks. Since many algorithms, including AES, can be implemented without table lookups, it wouldn't be a terribly big deal, if it weren't for one fact: apparently cryptographers participating in AES standardization were completely unaware of the fact that table lookups are a vulnerability. Again quoting from the article: (note that [19] refers to "Report on the Development of the Advanced Encryption Standard (AES)" and [9] refers to "Resistance Against Implementation Attacks: A Comparative Study of the AES Proposals")

Installation of VLC in Ubuntu through Terminal.


The ubuntu installs all the necessary drivers, if you are having any video and sound problem , then there is problem in your movie player, you just need to install vlc movie player or mplayer or any other player. just type the following command in your terminal
sudo apt-get update
sudo apt-get install vlc
make sure you have active internet connection.
enjoy……………………..[:-)]

sleep function in c program !



hmm while working with the loops, that is so fast.. that just give us  the final output !! but if we want to put some delay in that so that
user can c that how the process is going , and that ll make ur code  looks different from the other regular codes. so try to use that(if u
want) in ur code.
for that just put :- sleep(1000)
thats it, now it will delay the process by 1sec. and start again !
Example :-
int main()
{
int i;
for(i=1;i<=10;i++)
{
//print the number
printf(“%d \n”,i);
//delay for 1sec.
sleep(1000);
}
getch();
}
have a happy coding!

How To Listen the contents of the Text file(.txt) using the Java Speech Synthesizer.



 Now a days the need and the use of the speech synthesizer is increasing everyday and there are lots and lots of new innovations are going on in this field of synthesizer.
The synthesizer is the one which will convert your text input to the speech and for that we’ll be using the Speech Engine that will help us to fulfill our need.
1:
To use the functionality of this you first require to use the Freetts which will provide the functionality of Text to Speech
FreeTTS is a speech synthesis engine written entirely in the Java programming language. FreeTTS was written by the Sun Microsystems Laboratories Speech Team and is based on CMU’s Flite engine. FreeTTS also includes a partial JSAPI 1.0You can download this with the single click here.
Once you have downloaded that .zip then all you need to do is to extract it and have a look inside the folder and move in side the lib. folder “\freetts-1.2.2-bin\freetts-1.2\lib” here you will see collection of .jar files and also the setup for the jsapi.jar file double click on that and that will generate the jsapi.jar file.
Once you have generated the jsapi.jar file now you need to set all this .jar files to the CLASSPATH so that you can import it without any kinda errors.
Else if you are using the Eclipse IDE for your Java Coding than it will be lot easier for you to add all the .jar files to you program by just following step:-
1:- Right click on the new/existing project.
2:-Go to the  properties and java Build path — Libraries — add external Jars–select and ok.
else download the .doc that i have used to display the actual way to import it. click here -> Example to import
3:- after importing write the Code
This following code that i have developed through which you can create your speech synthesizer in java.
import java.applet.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.speech.Central;
import javax.speech.EngineList;
import javax.speech.EngineCreate;
import javax.speech.synthesis.SynthesizerModeDesc;
import javax.speech.synthesis.Synthesizer;
import javax.speech.synthesis.Voice;
import com.sun.speech.freetts.jsapi.FreeTTSEngineCentral;
import java.util.Locale;
//import java.awt.Event;
@SuppressWarnings(“serial”)
public class voisedemo extends Applet implements ActionListener
{

 public Synthesizer synth;
 private static Voice kevinHQ;
 TextField t1;

 public void init()
 {
 Button b1 = new Button(“press me”);
 add(b1);
 b1.addActionListener(this);
 t1 = new TextField(50);
 add(t1);

 }

 public void start()
 {
 }


 public void actionPerformed(ActionEvent e)
 {
 // synthesizer.speakPlainText(“Hello, world!”, null);
  try {
  
    // create SynthesizerModeDesc that will match the FreeTTS Synthesizer
   // System.out.print( ”  Loading voice…” );

  setKevinHQ(new Voice(“Dipayan”,
  Voice.AGE_NEUTRAL,
  Voice.GENDER_MALE,
  null ));



   System.setProperty(“freetts.voices”, “com.sun.speech.freetts.en.us.cmu_us_kal.KevinVoiceDirectory”);
   SynthesizerModeDesc modeDesc = new SynthesizerModeDesc(
  null,
  “general”, /* use “time” or “general” */
  Locale.US,
  Boolean.FALSE,
  null);
   //try{}catch(Exception e){}

  FreeTTSEngineCentral central = new FreeTTSEngineCentral();
  Synthesizer synthesizer = null;
  synthesizer = Central.createSynthesizer( modeDesc );
  // synthesizer.getSynthesizerProperties().setPitchRange(0.0f);
  EngineList list = central.createEngineList(modeDesc);
  if (list.size() > 0) {
  EngineCreate creator = (EngineCreate) list.get(0);
  synthesizer = (Synthesizer) creator.createEngine();
  }

  if (synthesizer == null) {
  System.err.println(“Cannot create synthesizer”);
  System.exit(1);
  }
  //get ready to speak
  synthesizer.allocate();
  synthesizer.resume();
  // say hello world
  String s1 = t1.getText();
  synthesizer.speakPlainText(s1, null);
  // synthesizer.speakPlainText(“Hello, world!”, null);
  // wait until speaking is done and clean up
  synthesizer.waitEngineState(Synthesizer.QUEUE_EMPTY);
  synthesizer.deallocate();
  } catch (Exception eq) {
  eq.printStackTrace();
  }
  }
 /**
  * @param kevinHQ the kevinHQ to set
  */
 public static void setKevinHQ(Voice kevinHQ) {
 voisedemo.kevinHQ = kevinHQ;
 }
 /**
  * @return the kevinHQ
  */
 public static Voice getKevinHQ() {
 return kevinHQ;
 }
 public void paint(Graphics g)
 {

 //g.drawString(“Hello world”,50,50);
 }
}
/*
<applet code=”voisedemo” width=1000 height=1000>
</applet>
*/