Wednesday, December 26, 2012

Create a MySql Trigger to run shell script on insert




delimiter ;;
create trigger smf_message_trigger
after insert on smf_messages
for each row
begin
set @stupid_var=sys_exec(CONCAT('/home2/luxefash/triggers/smf.sh  '+ id_topic ));
end;
;;
delimiter ;


Shell script:


#/usr/bin/sh

echo "test " >> /tmp/smf.log


Monday, October 22, 2012

My PC is slow when I try to shut down


Check your EventViewer and localize the error. This can depends on something is wrong with Windows Update and need to be reparated.

Go to
http://fixitcenter.support.microsoft.com/Portal
and download their tool and run it to fix all possible problems.

Tuesday, October 2, 2012

AssemblyInfo.cs' could not be opened ('Unspecified error ')


Error AssemblyInfo.cs could not be opened



So you open a project in Visual Studio 2010 and get an odd error:
AssemblyInfo.cs' could not be opened ('Unspecified error ')
What this means is that the AssemblyInfo.cs file is either missing from the Properties folder in the project or there is a permissions issue. If permissions, update the ACL (File > Properties > Security), close and re-open the project. If missing altogether, you just need to recreate it using the following steps:
  1. Within Visual Studio 2010, select Tools > Create GUID
  2. Click Copy (or New GUID then Copy)
  3. Click Exit
  4. Expand the Properties folder in the Solution Explorer (Control + W, S to open)
  5. Delete the AssemblyInfo.cs file shown with the exclaimation point
  6. Double click on the Properties folder - this should open the Properties window
  7. On the Application Tab, click the Application Information... button
  8. Fill in the application information, paste the GUID you copied into the GUID field - when done click OK

Monday, October 1, 2012

The database could not be exclusively locked to perform the operation. (Microsoft SQL Server, Error: 5030)

When you try to rename a database, you get the following error message:

Problem:
The database could not be exclusively locked to perform the operation. (Microsoft SQL Server, Error: 5030)

This can be resolved by the following:

sp_who

Check which Process id use your database (dbname) and kill the process:

kill 15

Where spid = 15 is the process that lock the database you are trying to have a lock on.

Monday, September 17, 2012

NHibernate.MappingException: No persister for:



This can have at least the following reason:
You may forget du add for example HasMany for the persisting class to make a relationship.

 HasMany(x => x.myTableId).KeyColumn("mytableID");


Sunday, September 16, 2012

No message body writer has been found for response class

No message body writer has been found for response class
You need to add the following in maven:



<dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-jaxrs</artifactId>
        <version>1.3.0</version>
</dependency>



Error serializing the response, please check the server logs, response class

Add the following:

              <dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
<version>1.9.9</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-xc</artifactId>
<version>1.9.9</version>
</dependency>

Tuesday, September 11, 2012

Unit test



 [TestMethod]
        public void can_save_and_read_pbentity2()
        {
            object id;

            // Save to database using PbPlatsannonsEntity
            using ( var tx = CurrentSession.BeginTransaction())
            {
                id =
                    CurrentSession.Save(
                        new PbPlatsannonsEntity
                            {   Annonsrubrik = "Rubrik annons",
                                AnnonstextXml = "XML annonstext",
                                AntalPlatser = 12
                               
                            });
                    tx.Commit();
            }
            CurrentSession.Clear();

            //Read from database
            using ( var tx = CurrentSession.BeginTransaction() )
            {
                var pbPlatsannonsEntity = CurrentSession.Get<PbPlatsannonsEntity>(id);
                Assert.Equals("Rubrik annons", pbPlatsannonsEntity.Annonsrubrik);
                Assert.Equals("XML annonstext", pbPlatsannonsEntity.AnnonstextXml);
                Assert.Equals(12, pbPlatsannonsEntity.AntalPlatser);
                //Assert.Equals(new DateTime(2000, 1, 1), pbPlatsannonsEntity.Created);
                tx.Commit();

            }

        }

Tuesday, September 4, 2012

Collections.sort java: sorting java object




//Sort aktlist
final Comparator< aktlist > DATE_ORDER =
                            new Comparator< aktlist >() {
@Override
public int compare( aktlist a1,  aktlist a2) {
   return a2.getDatum().compareTo(a1.getDatum());
}
};
Collections.sort( aktlist , DATE_ORDER);

More information:
http://docs.oracle.com/javase/tutorial/collections/interfaces/order.html

Saturday, August 25, 2012

Android: Preventing destroying the activity when changes made by rotation of the device

Preventing destroying the activity when changes made by rotation of the device, use
android:configChanges="orientation"

Example:


<activity
            android:configChanges="orientation"
            android:name=".QuizStartActivity"
            android:label="@string/title_activity_quiz_start" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

Thursday, July 12, 2012

Polic virus with fine payment

If your computer is hacked by a Police Virus requiring you to pay a fine , your computer most likely is infected.
You can remove the virus folowing the steps below:
1) Log in in Safe mode by restarting and klick on F8
2) Open regedit and search for HKLM\Software\Wow6432Node\Micxrosoft\Windows\CurrentVersion\Run
3) Remove the entry with infected program. Most likely your program is installed in
C:\User\Your log name\AppData\Roaming\*.exe


You can also use free Microsoft Safty Scanner to remove this Police Virus if the above mentioned action did not help to remove the Police Virus.

You find the scanner at: http://www.microsoft.com/security/scanner/en-gb/default.aspx

Tuesday, July 10, 2012

"Updating Maven Project". Unsupported IClasspathEntry kind=4



This occure if you are upgrading to maven 3.

Make sure that the version of the m2e(clipse) plugin that you're running is at least 1.1.0. The update site is here: https://repository.sonatype.org/content/repositories/forge-sites/m2e/1.1.0/N/LATEST/

and run:
mvn eclipse:clean

Wednesday, June 27, 2012

Behavior-driven development framework för Javascript


Jasmine is a behavior-driven development framework for testing JavaScript code. It does not depend on any other JavaScript frameworks. It does not require a DOM. And it has a clean, obvious syntax so that you can easily write tests.
Check out : http://pivotal.github.com/jasmine/

Tuesday, June 26, 2012

Webscraping using Javascript



There are a number of Javascript frameworks you can use to web scraping:

1) Selenium, check out Seleinum Grid.
Selenium has been adopted as the primary technology for functional testong of web applications within Google.
Selenium now wraps htmlunit so you don´t need start a browser anymore. The new WebDriver api is very easy to use too. The first example use htmlunit driver
2) Watir (Ruby)
3) PhantomJS
4) CasperJS
5) Zombie for Node.js
6) Pjscrap based on PhantomJS and JQuery
7) HTMLUnit (Java)


Friday, May 25, 2012

Why BPEL ?


 BPEL is for process/workflow technology what SQL is for relational databases. This is a way to bridge method war from different business school.
If you ahve several web services around the world, you should use BPEL to orchestrate them all into some new service.

Why using Maven is better than Ant?

In Ant you have to set up the classpath and configure and invoke the tool tasks for compilation and packaging.
Maven automatically downloads all dependencies, makes them available to your aplication and plugs them into the build life cycle phase.

Open source Live Profiling of Java ?



There are a lot of tools for profiling Java and the following is a list:

  • HPROF
           http://java.sun.com/developer/technicalArticles/Programming/HPROF.html
           $java -agentlib:hprof[=options] ToBeProfiledClass
           You get a dump AFTER running your application. This is not a live heap watching.

  •  Jmap, jps
         With command line tools  Jmap,jps you do not need to download anything. This comes with JAVA2SE.
         You must know the pid of the Java application to
  • EurekaJ and BTrace
           You can add inside Java code annotations to be gathered by BTrace.

  • AspectJ

         This is the preferred method.

Generally any metric-gathering can take up to 2500 nanoseconds, so use it only when necessary. For example disc access takes 40 milliseconds, servlet processing up to a second so adding 2500 nanoseconds for each of the methods would be negligible.

However the best way is to use AOP for performance monitoring and metric gathering consider JMetrix 
From AspectJ you can read the following:

3. What are some common development aspects?
Aspects for logging, tracing, debugging, profiling or performance monitoring, or testing.

4. What are some common production aspects?
Aspects for performance monitoring and diagnostic systems, display updating or notifications generally, security, context passing, and error handling.

How to restore iexplorer in windows?


If you get problem with iexplorer and can not for example visit sites, just follow the following instruction:
Open Start and write "inetcpl.cpl" in the field. Then reset then iexplorer:

Thursday, May 24, 2012

Cannot find the main class after converting java project to maven



This is because by default, Eclipse puts Java codes in src, but maven conventions are src/main/java. If you do not place or move the Java code to this place Maven will not find any main in your Eclipse when you are trying to run or compile.

Java error: SEVERE: StandardServer.await: create[8005]

Problem:

org.apache.catalina.core.StandardServer await
SEVERE: StandardServer.await: create[8005]:

Explanation:
This is because som application (javaw.exe to be exactly) listening on 8005.
Use tcpview from Sysinternals.com to locate the javaw.exe occupying 8005 and close this and restart the Tomcat server.

Tuesday, May 22, 2012

How to restore your file type association to .bat (batchfile)



If you have associated the extention file of .bat to for example Notepad, you have to remove this manually from Registry. Microsoft obviously did not provide a way to restore back to default program for .bat!
Do as follows:


From a command prompt run the following:
> assoc .bat
that should return with
..bat=batfile
If not run :
> assoc .bat=batfile
to restore the default file type association.

> ftype batfile
should return with
batfile="%1" %*
If not run:
> ftype batfile="%1" %*

Finally remove from your Registry the associated program:
Look for
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts
and delete the key named and this should looks like below:

Creating a new webservice in Eclipse from Java methods


Following this tutorial will show how this is easy to create a webservices from your existing POJO java mathods. If you have good java application with all methods, simply follow this to expose your methods to the world. If you want to keep it private, use Shiro to keep your webservice available only to your applications.
Use jsSHA to encrypt your Javascript.

Tutorial:
http://www.eclipse.org/webtools/community/tutorials/BottomUpAxis2WebService/bu_tutorial.html

Java Architecture for XML Binding (JAXB)



http://www.oracle.com/technetwork/articles/javase/index-140168.html
PHP example:
http://www.pibx.de/documentation/code-examples/books/

Friday, May 18, 2012

Why Flash is better than Processing when displaying or programming

Display differences between Flash and Processing
In Processing the screen is a bitmap, a grid of pixels where you can draw, similar to the Canvas object in HTML5. Once you draw an ellipse, it becomes pixels. The display has no knowledge of objects. If you want to know if an object was clicked, you have to calculate yourself if the mouse action took place on top of some object in the screen. But you have to keep track yourself of sizes and locations of your objects.


In Flash/ActionScript the display is like a tree. You can add objects to the Stage, and objects inside objects. Each object has x, y, width, height, rotation and alpha properties which can be modified at any time. This makes it very easy to animate objects and also to detect mouse interaction. By default the programmer knows which object in the screen was clicked, rolled over or out, because Flash keeps track of all elements in the screen. If you draw an ellipse, it stays an ellipse. Unless you want to work in a way similar to Processing, in which case you can work with just one bitmap on the Stage and forget about the whole Flash Display Model.

Rotation of objects in Flash is usually also simpler. You can access the .rotation property of any object and change it. By default the center of rotation is the center or corner of each object, but it can be modified. To rotate in Processing you should first translate() the axes, then rotate() them and finally draw your object on the screen.

Wednesday, May 16, 2012

Java heap, preformance analysis tool


http://java.sun.com/developer/technicalArticles/Programming/HPROF.html

The best way to analysis the preformance and heap is to use HPROF from Java.

Convert your existing java object model to XML


This tutorial shows how to convert yoyur existing Java Object Model to XML without using metadata:
http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted

If you have a scheme and wat to generate Java Object Model, see the following link:
Generating a Java Model from an XML Schema
 EclipseLink MOXy is an extension.

The EclipseLink project delivers a comprehensive open-source Java persistence solution addressing relational, XML, and database web services. More information cab be found on  http://www.eclipse.org/eclipselink/

Monday, May 14, 2012

How to colve "javax.servlet.UnavailableException" or Servlet is not a javax.servlet.Servlet

If you get the following error message:


javax.servlet.UnavailableException: Servlet class com.example.test.myServlet is not a javax.servlet.Servlet

This is because you did not extends the class  com.example.test.myServlet with HttpServler.

The class below will cause javax.servlet.UnavailableException

public class myServlet {
   public void doPost(HttpServletRequest req, HttpServletResponse resp) {
        ...
   }

}

You solve this by extending this class with HttpRequest:
public class myServlet extends HttpServlet  {
   public void doPost(HttpServletRequest req, HttpServletResponse resp) {
        ...
   }

}

Saturday, May 12, 2012

Android Multitouch events using MotionEvent



 ACTION_POINTER_DOWN and ACTION_POINTER_UP are fired whenever a secondary pointer goes down or up.
  • If there is already a pointer on the screen and a new one goes down, you will receive ACTION_POINTER_DOWN instead of ACTION_DOWN. Subsequent pointers will fire  ACTION_POINTER_DOWN too and to get the actual pointer ID us with ACTION_POINTER_INDEX_MASK. 
  • If a pointer goes up but there is still at least one touching the screen, you will receive ACTION_POINTER_UP instead of ACTION_UP.

Friday, May 11, 2012

javax.servlet.UnavailableException at Google APp Engine

If you get the following error:


javax.servlet.ServletContext log: unavailable
javax.servlet.UnavailableException: Servlet class myServlet is not a javax.servlet.Servlet

This is due to version conflict between your Java installed and what Google App Engine is supposed to be supported.

Thursday, May 10, 2012

Best Javascript framework?


Node.js is build upon Chrome Javascript runtime and is widely used by eBay, LinkedIn, Google etc.
See what other said about the node.js:


Uber
Node has allowed us to build a global, real-time logistics system without having to think twice about locking or concurrency issues.
Cloud9 IDE
Node.js allows us to build our real-time cloud IDE with a single language front to back. It makes life easier for both us and our users to write, run, and debug code, anywhere, anytime.
LinkedIn
On the server side, our entire mobile software stack is completely built in Node. One reason was scale. The second is Node showed us huge performance gains.

Transloadit
Node.js allows us to execute our many independent background processes in a non-blocking way. This is essential to make file uploading and encoding the way we do it a great user experience.

Simple webserver using node.js:
This simple web server written in Node responds with "Hello World" for every request.

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

Installing in Linux/Unix without sudo permission:

$ git clone https://github.com/joyent/node.git
$ cd node
$ mkdir ~/opt
$ export PREFIX=~/opt; ./configure
$ make
$ make install
$ echo 'export PATH=~/opt/bin:${PATH}' >> ~/.bashrc

Wednesday, May 9, 2012

Securing your RESTful service


There are different options to secure your web service:
Authentication:
      Identify who the user is using the web service.
      PKI, Active Directory is used for authentication.

Authorization:
    What the user can do with the web service.
     authorization service, LDAP is used for authorization.

There are several implementation solution to ecure the web service. Below is a list:
OAuth 1.0  is vulnerable to a session-fixation attack and could result in an attacker stealing the identity of an API end-user.
OAuth is secure API authorization in a simpleand standard. See the specification of OAuth at http://tools.ietf.org/html/rfc5849.


Good to know that HTTPS and HTTP authorization schemes based on HMAC (hash-based message authentication code) are used by Amazon S3 or Windows Azure are some of the measures for greater security.

If your API is free and read only you can use single key-based authentication.

Interesting article about Oauth and security to be read at http://hueniverse.com/oauth/guide/security/.

Read also what NSA say about implementation of RestFul service:
http://www.nsa.gov/ia/_files/support/guidelines_implementation_rest.pdf

More readings:
Http Authentication - http://docs.oracle.com/javase/6/docs/technotes/guides/net/http-auth.html
certificate based authority: http://docs.oracle.com/cd/E19316-01/820-2765/gdzeb/index.html

For Apache Shiro working with RestFul service check the blog:
http://blog.xebia.com/2011/04/18/apache-shiro/

Shiro integrating with Spring:
http://shiro.apache.org/spring.html

You can as well take a look at mo_security with Apache.
Oracle has a document on security:
http://www.oracle.com/us/products/middleware/identity-management/059410.pdf
And from Google:
http://lcsd05.cs.tamu.edu/slides/keynote.pdf

From Java.net:
http://weblogs.java.net/blog/gmurray71/archive/2006/08/restricting_acc.html

See how Amazon use Rest Security:
http://docs.amazonwebservices.com/AmazonSimpleDB/latest/DeveloperGuide/HMACAuth.html?r=6357
http://www.thebuzzmedia.com/designing-a-secure-rest-api-without-oauth-authentication/

Tomcat Realm and JASS
http://tomcat.apache.org/tomcat-5.5-doc/realm-howto.html

Also http://www.modsecurity.org/

  • Negative Security Model - looks for known bad, malicious requests. This method is effective at blocking a large number of automated attacks, however it is not the best approach for identifying new attack vectors. Using too many negative rules may also negatively impact performance.
  • Positive Security Model - When positive security model is deployed, only requests that are known to be valid are accepted, with everything else rejected. This approach works best with applications that are heavily used but rarely updated.
  • Virtual Patching - Its rule language makes ModSecurity an ideal external patching tool. External patching is all about reducing the window of opportunity. Time needed to patch application vulnerabilities often runs to weeks in many organizations. With ModSecurity, applications can be patched from the outside, without touching the application source code (and even without any access to it), making your systems secure until a proper patch is produced.
  • Extrusion Detection Model - ModSecurity can also monitor outbound data and identify and block information disclosure issues such as leaking detailed error messages or Social Security Numbers or Credit Card Numers.



Definition of Authentication and Authorization


Sometimes people are confused what Authentication and Authorization are and these two can eb mixed up together.

Read more on: http://www.acm.uiuc.edu/workshops/security/auth.html
An authentication system is how you identify yourself to the computer. The goal behind an authentication system is to verify that the user is actually who they say they are.


Authorization
Once the system knows who the user is through authentication, authorization is how the system decides what the user can do.



Error: Could not find the required version of the Java(TM) 2 Runtime Environment in '(null)'.




This is due to the fact you have not installed the Java package correctly. Just simply download and install again.

Tuesday, May 8, 2012

How to deal with ConcurrentModificationException using iterator


Reason:
You are using ArrayList and trying to iterate thorugh this array after some change in the Collection.

This can be handled by using Synchronized on Classes like the following:


private Object pathlist;
publid void Pathlist() {
      synchronized(pathlist) {

     }
}

This will guranatee a synchronized way of handling the object pathlist, no two concurrent thread will access this in the same time but in Synchronized way.

If you are usinf Iterator somewhere in your code and get ConcurrentModificationException pay special attention to List. Use ListIterator instead of Iterator.

For example the code below will cause a ConcurrentModificationException :

public void removePathline(int pointerID) {
synchronized (this) {
Iterator<Pathline> it=pathlist.iterator();    // 1) This will throw                            
                                                                                      //ConcurrentModificationException 
//ListIterator<Pathline> it=pathlist.listIterator();   // 2) this should be used
       while(it.hasNext())
       {
          Pathline pl = (Pathline) it.next();
          synchronized ( pl ) {
          if ( pl.getPointerID() == pointerID ) {
          pathlist.remove(pl);
          }
          }
       }
}
}


The code above is removing the object while it is iterating. The iterator will check if the List has been modified and if the list has been changed, it throw a ConcurrentModificationException
In solution number 2 will solve the problem.

Java Collection classes are fail-fast which means that if the Collection will be changed while some thread is traversing over it using iterator, the iterator.next() will throw a ConcurrentModificationException.



To Avoid ConcurrentModificationException in multi-threaded environment:

1. You can convert the list to an array and then iterate on the array. This approach works well for small or medium size list but if the list is large then it will affect the performance a lot.

2.Use synchronized block. This approach is not recommended in multithreading environment if you want to use the benefits of multithreading. For the case of iterator, Synchronized approch will not solve your problem. See preferred approch below.

3. Use ConcurrentHashMap and CopyOnWriteArrayList classes if you are using JDK1.5 or higher. It is the recommended approach.







Friday, May 4, 2012

Installing Perl modules in a different directory



If you have various old Perl modules and want to install Perl modules in another directories without root  or administrator privileges use Perlbrew 
For more information check this out:
http://www.cpan.org/modules/INSTALL.html


Tuesday, April 24, 2012

Error message: cannot be loaded because the execution of scripts is disabled on this system

Trying to run Powershell script? Just set the following:

PS > Set-ExecutionPolicy RemoteSigned

Alternatively, you can set the execution policy to AllSigned (all scripts, including those you write yourself, must be signed by a trusted publisher) or Unrestricted (all scripts will run, regardless of where they come from and whether or not they’ve been signed). 

Then test it again:

param($Argument1,$Argument2)

"Argument1 is: $Argument1"
"Argument2 is: $Argument2"

Monday, April 23, 2012

How many sites per FreeBSD / mySQL / postgreSQL dedicated server?


You canm have one FreeBSD / mySQL / postgreSQL dedicated server with about 200 sites
hosted on it with Roughly 30,000 queries per day and have no performance
issues with database connections..

Tuesday, April 17, 2012

Java Data Objects JDO with App engine



To bind data to Java Objects and store it in Google App Engine the following API can be used and recommended:


Objectify is a very simple and convenient interface to the App Engine Datastore that helps you avoid some of the complexities presented by JDO/JPA and the low-level Datastore.
Twig is a configurable object persistence interface that improves support for inheritance, polymorphism, and generic types. Like Objectify, Twig also helps you avoid complexities posed by JDO and the low-level Datastore.
Slim3 is a full-stack model-view-controller framework that you can use for a wide variety of App Engine functions, including (but not limited to) the Datastore.



Monday, April 16, 2012

"Access is denied." when you run "./RedistMaker.bat y 32 y"

When you run
$ ./RedistMaker.bat y 32 y

You may see "Access is denied" in the output as follows:
*******************************************
*** Running the Redist OpenNI script... ***
*******************************************
Access is denied.

This is due to the Windows is unable to run  Python program Redist_OpenNi.py. You solve it by 

Running Play framwork in Cygwin om windows


If you run Play in command line of Cygwin om Windows and get the folowing:

$ play
Error: Unable to access jarfile /cygdrive/e/tools/play/framework/sbt/sbt-launch.jar


This is due to the fact that play.bat is a Windows bat. This works if you run:
$play.bat




Java Security frameworks



1) Shiro
2) Spring Security (Use Shiro?)

Freetds problem: odbcinst: SQLGetPrivateProfileString failed with .


Problem:
bash-3.2# odbcinst -q -s

odbcinst: SQLGetPrivateProfileString failed with .

Solution:

bash-3.2# ODBCINI=/local/umdac/home/platsbanken/.odbc.ini
bash-3.2# odbcinst -j
unixODBC 2.3.0
DRIVERS............: /usr/local/etc/odbcinst.ini
SYSTEM DATA SOURCES: /usr/local/etc/odbc.ini
FILE DATA SOURCES..: /usr/local/etc/ODBCDataSources
USER DATA SOURCES..: //.odbc.ini
SQLULEN Size.......: 4
SQLLEN Size........: 4
SQLSETPOSIROW Size.: 2
bash-3.2# export ODBCINI




bash-3.2#  odbcinst -q -s
[MSSQLServer]
[MSSQLAnother]
bash-3.2#

Sunday, April 15, 2012

change password to Administrator in Windows 7



If you forget password to Administrator in Windows 7 you can solve as follows: I spent hours to test various solutions, used and burned different Crack password programs from open source such as PC Log in Now and many others but nothing helped.  You can see the list below as no one helped me change or crack the password to theAdministrator:
Ophcrack
Offline NT Password & Registry Editor
PC Login Now
When I tested a few of them I realised that no other solution would help if the best one above can not solve my problem about forgetting a password to Administrator.They are require not corrupted users information. Here is the best solution:
1) Have some Linux LiveCD. I used Puppy 4.1.2 because this is very fast liveCD than for example Ubuntu that do not provide LiveCD in the latest version. I tried the Try Demo but this did not work and this take more time to start up the Ubuntu than Puppy which is very fast and you can save to USB the last session if you want.

2) Using Puppy , open a terminal and locate the mounts where windows resides and change inside System32 as follows:
cd /mnt/sda3/
cd Windows/System32
#Save this before you change
cp sethc.exe sethc.exe.saveit
cp cmd.exe sethc.exe

3)Reboot your computer and when you see the log-on screen and press Shift key five times.
4) You will see a black terminal windows. Write the following to change the password to your user Administrator:
net user MyAdministratorUser MyNewPassword
and try to log in with the new password MyNewPassword to your administrator.

You can add new user as follows if you have Administrators group:
net user root /add

net localgroup Administrators root /add

net localgroup Users root /delete


5) Once inside your computer change back , i.e. restore the Sticky Keys application:
 copy /y c:/windows/system32/sethc.exe.saveit c:/windows/system32/sethc.exe

You can also try to get the Administrator visible as follows:
net user administrator /active:yes 


But this did not helped me in my case. So my solution above is the best one.

Tuesday, April 3, 2012

How to remove duplicate location in Eclipse?


You remove the duplicated location threough Preferences->Install/Update/Available Software Sites and remove the old duplicate before you install new software. Do not forget to restart Eclipse after changing:





Friday, March 30, 2012

Developing Android App in Scala



This is possible. The following links are useful if you plan to use Scala to develop Android app:

Use Gradle to build android app: https://github.com/jvoegele/gradle-android-plugin/wiki/ and http://www.gradle.org

Developing for ANdroid using Scala/Eclipse: http://www.assembla.com/wiki/show/scala-ide/Developing_for_Android

Example of developing for Android: http://chneukirchen.org/blog/archive/2009/04/programming-for-android-with-scala.html



Complete list of available Archetype Catalogs

Here is a list of Maven repositories:
http://scala-tools.org/repo-releases/


Run as follows:
mvn archetype:generate -DarchetypeCatalog=http://slim3.googlecode.com/svn/trunk/repository

Here is a list of all available Maven Archetype Catalogs:
Verified list:
https://oss.sonatype.org/content/groups/scala-tools/archetype-catalog.xml
http://slim3.googlecode.com/svn/trunk/repository

http://cocoon.apache.org
http://myfaces.apache.org
http://download.java.net/maven/2
http://oss.sonatype.org/content/repositories/appfuse



Not verified list:
http://repo.fusesource.com/maven2
http://tapestry.formos.com/maven-repository
http://www.terracotta.org/download/reflector/maven2/  (is empty)




Tuesday, March 27, 2012

Why you should use NIO for scalability


The key to scalability is NON-BLOCKING IO. Most operating systems support non-blocking I/O, which actually means that when you utilize an I/O resource for reading or writing (say the streams from a socket) there is no blocking operation. So if you read from a stream your read function would immediately return regardless of whether there is data available or not. In Java, non-blocking I/O is provided by the Java New I/O (NIO) library using Selectors and perhaps the Reactor pattern [F]  [F] A nice overview of NIO is athttp://gee.cs.oswego.edu/dl/cpjslides/nio.pdf. This has a major impact on scalability because the threads are only held as long as there is work to do. Once they’re finished with the available data, they are returned to the thread pool so that they may be reused for processing other requests. In this model the threads are allocated to connections only when data is available for processing, which inherently leads to better resource utilization.

Note: This is somewhat off-topic, but if you’re looking to do a lot of work with NIO and networking, we recommend looking at the Apache MINA project at http://mina.apache.org/. MINA provides some nice abstractions for NIO that allows you use a stateful approach to developing NIO applications without having to deal with a lot of the underlying details of using NIO.

Comet or Ajax ?

Which one you should choose ? Ajax or Comet ?
Comet changes the traditional model by using a long-polling HTTP request in the background that allows the server to push data to the browser without requiring additional requests. Essentially this is like AJAX, except in the opposite direction.
While the AJAX model increases the richness of the User Experience for a single client at a time, Comet can do the same for multiple users.

Friday, March 23, 2012

Problem to display characters from other language than English


If  you are, for example, unable to display Swedish characters, this can mainly means that you probably have the language file written in UTF-8 and not in ISO-8859-1. There is no way an ISO-8859-1 environment will display characters from a different charset like UTF-8.

You may have saved data in database in UTF-8 for example. If you want to display correctly the data must be converted to a ISO-8859-1.

Wednesday, March 7, 2012

How to Local Repository path in Eclipse for Maven



If you want to change Maven Local Repository to point to another repository than those of Eclipse pre-configured, you have to do the following steps:
1) Windows->Preferences->User settings
2) Change in the c:\yourMavenDirectory\apache-maven-2.2.1\conf\settings.xml
Locate and add the following in settings.xml

<localRepository>C:\yourmavenrepository\maven\.m2\repository</localRepository>

You can use any path. This is recommended you should not have any spaces inside your path. This may work, but to avoid any further unnecessary or unexpected errors, do rust Windows will handle it gracefully.

Then Click Apply. You can as well click Update Settings. Eclipse will read the new settings and change
the path in your Local Repository to point to the new repository.



Embedded error: Server returned HTTP response code: 403 for URL: http://localhost:8080/manager/deploy?path


You are not authorized to view this page.
If you have already configured the Manager application to allow access and you have used your browser's back button, used a saved book-mark or similar then you may have triggered the cross-site request forgery (CSRF) protection that has been enabled for the HTML interface of the Manager application. You will need to reset this protection by returning to the main Manager page. Once you return to this page, you will be able to continue using the Manager appliction's HTML interface normally. If you continue to see this access denied message, check that you have the necessary permissions to access this application.
If you have not changed any configuration files, please examine the file conf/tomcat-users.xml in your installation. That file must contain the credentials to let you use this webapp.
For example, to add the manager-gui role to a user named tomcat with a password of s3cret, add the following to the config file listed above.
<role rolename="manager-gui"/>
<user username="tomcat" password="s3cret" roles="manager-gui"/>
Note that for Tomcat 6.0.30 onwards, the roles required to use the manager application were changed from the single manager role to add the following four roles. (The manager role is still available but should not be used as it avoids the CSRF protection). You will need to assign the role(s) required for the functionality you wish to access.
  • manager-gui - allows access to the HTML GUI and the status pages
  • manager-script - allows access to the text interface and the status pages
  • manager-jmx - allows access to the JMX proxy and the status pages
  • manager-status - allows access to the status pages only
The HTML interface is protected against CSRF but the text and JMX interfaces are not. To maintain the CSRF protection:
  • users with the manager-gui role should not be granted either the manager-script or manager-jmx roles.
  • if the text or jmx interfaces are accessed through a browser (e.g. for testing since these interfaces are intended for tools not humans) then the browser must be closed afterwards to terminate the session.
For more information - please see the Manager App HOW-TO.


You get the error message above when you try to use Maven to deploy your war-application to Tomcat or try to put http://localhost:8080/manager/deploy?path=yourWar.war in the browser. If you install Tomcat windows installer you will have the following pre-configuration in your tomcat-users.vml file ( located under C:\Program Files\Apache Software Foundation\Tomcat 6.0\conf ). You have to change or add the following:



<tomcat-users>
<role rolename="manager"/>
<user username="admin" password="edison" roles="manager"/>

....
</tomcat-users>





In your POM.xml you should have the following:


<!--  tomcat-server -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>tomcat-maven-plugin</artifactId>
<configuration>
<server>tomcat-server</server>
<path>/arbetsformedling</path>
</configuration>
</plugin>



In order to get the maven deploy via the following at command line:
$mvn tomcat:deploy 
or
$mvn tomcat:undeploy

More useful information about this see
https://issues.apache.org/bugzilla/show_bug.cgi?id=51147



Sunday, March 4, 2012

Access sqlite within Emulator from your sell command



$ adb -s emulator-5554 shell
## sqlite3 /data/data/[Your Package Name Here]/databases/[Your Databasefile name here]
sqlite3 /data/data/ [Your Package Name Here] /databases/[Your Databasefile name here]
SQLite version 3.6.22
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .dump
.dump
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE android_metadata (locale TEXT);
INSERT INTO "android_metadata" VALUES('en_US');
CREATE TABLE  [Your Databasefile name here] (_id integer primary key autoincrement,contactI
D integer, ImagePath TEXT);
INSERT INTO " [Your Databasefile name here] " VALUES(1,3,'/mnt/sdcard/rebeca.jpg');
DELETE FROM sqlite_sequence;
INSERT INTO "sqlite_sequence" VALUES(' [Your Databasefile name here] ',1);
COMMIT;
sqlite>



Using the ContactsContract in phone lookup



This is very important that you make difference between

alt 1:  int contactID = c.getColumnIndexOrThrow(ContactsContract.Contacts._ID);

alt 2: String  contactID  = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));

If you use logcat to see the result you will see same contactID  if you use alt 1, but with alt 2 you will see different strings.
Be aware of this!
Sample code to lookup phone and e-mail using the latest class ContactsContract
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
while (cursor.moveToNext()) {
String contactId = cursor.getString(cursor.getColumnIndex(
ContactsContract.Contacts._ID));
String hasPhone = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (Boolean.parseBoolean(hasPhone)) {
// You know it has a number so now query it like this
Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId, null, null);
while (phones.moveToNext()) {
String phoneNumber = phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER));
}
phones.close();
}

Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId, null, null);
while (emails.moveToNext()) {
// This would allow you get several email addresses
String emailAddress = emails.getString(
emails.getColumnIndex(ContactsContract.CommonDataKinds.CommonDataColumns.DATA));
}
emails.close();
cursor.close();

Saturday, March 3, 2012

Pitfalls in Android/Eclipse

Be aware of this pitfall. The Android/Eclipse never tell you that this is a wrong way. You will not be aable to find any reason to runtime errors. Avoid to write so!

findViewById(R.layout.main);

Tuesday, February 21, 2012

Using System.Configuration


If I am looking to get connection string from my app.config I may write as followis:

using System.Configuration;

...
Trying to access ConfigurationManager would not be successful if you do not add a reference to System.Configuration.dll. Visual Studio would not complain that you miss System.Configuration.dll. This is very strange. VS 2010 do not show any indication of missing System.Configuration.dll.
So if you have the following
using using System.Configuration;

But can not access any methods from this, you miss a reference to this DLL. Visual Studio will not notice you if you have default configuration.

Thursday, February 16, 2012

SMTP service not supplied in Windows 7


IIS (Internet Information Server) 7.0 in Windows 7 no longer includes the SMTP service. If you need that Mail service, you need to download Remote Server Administration Tools for Windows® 7
 from:
http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=7887

Tuesday, February 14, 2012

Solution to problem to run gem install



If you get the following error message when you try to install via gem:


ERROR:  While executing gem ... (Errno::ENOENT)
 No such file or directory - H:/

Reason:
one of the environment variables (most of the time HOME,USERPROFILE or HOMEDRIVE and HOMEPATH) point to H:/

You   can temporary or permanently change it:


set HOMEDRIVE=C:
and run again gem.

Word list


Sometimes you need access to a complete list of word in various languages.
Here is a list of word lists in zipped format:

  1. http://wordlist.sourceforge.net/
  2. For other languages you 
  3. http://borel.slu.edu/crubadan/

Friday, February 10, 2012

OpenCV.dll: Can't find dependent libraries


If you get the follwoing erro message when using OpenCV + processing:


!!! required library not found : ...\processing-1.5.1-windows\processing-1.5.1\libraries\opencv_01\OpenCV\library\OpenCV.dll: Can't find dependent libraries
Verify that the java.library.path property is correctly set and the '\path\to\OpenCV\bin' exists in your system PATH

Exception in thread "Animation Thread" java.lang.UnsatisfiedLinkError: hypermedia.video.OpenCV.capture(III)V
at hypermedia.video.OpenCV.capture(Native Method)
at hypermedia.video.OpenCV.capture(OpenCV.java:945)
at Bubble.setup(Bubble.java:40)
at processing.core.PApplet.handleDraw(Unknown Source)
at processing.core.PApplet.run(Unknown Source)
at java.lang.Thread.run(Thread.java:662)



This can be solved by installing  opnCV version 1.0.

Thursday, February 9, 2012

What is matchmoving?

Matchmoving  = Camera Tracking + Camera Matching

Matchmoving make it possible to reconstruct 3D from 2D footages.

More information : http://code.google.com/p/libmv/

To have ideas how this really works, this is worth to watch it at youtube:
http://www.youtube.com/watch?v=pDGI7tyUfp8&feature=endscreen&NR=1
http://vimeo.com/25516157

Monday, February 6, 2012

Augmented Reality Libraries


To develop an Aumented Reality application you need libraries. Below is a list of libraries for different plattforms:
Stand Alone Application Development:
Web Application Development:
Mobile Application Development:

Of all the above I would recommend opensource AR from http://www.artoolworks.com.

Friday, February 3, 2012

Failed to allocate memory in Android and Eclipse

Problem:
While you run Android from Eclipse you get the following error:

[2012-02-03 15:57:38 - Emulator] Failed to allocate memory: 1455


Solution:
Open Android Virtual Device Manager and add or change the value to device ram size to 15 or a value smaller or higher:

Thursday, February 2, 2012

Generate Proxy Class to access a Webservice in .Net

In any language in order to access a web service you can generate autiomatically a proxy class from wsdl.
In .Net you can use WSDL.exe located in C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin
to generate a Proxy class to call methods in web services.

If you want to run wsdl.exe from anywhere, add
C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin
in your PATH in system variable.
In order to create a client proxy class in c# for an XML web service located at a specified URL at some location run the following command:

$wsdl /out:ClientProxyClass.cs http://servername/WebserviceRoot/SomeWebservice?WSDL




See  more documentation about this at http://msdn.microsoft.com/en-us/library/7h3ystb6%28VS.71%29.aspx