{{error}}
{{(quickSearchResults.length>10)?'10+':(quickSearchResults.length)}} {{(quickSearchResults.length==1)?'result':'results'}}
{{result.title}} {{result.timeStamp | mysql2ymd }}
I am sorry, no such article was written yet.
How much do you know about .NET?
1 files attached: Program.cs
Program.cs
namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            float nan = float.NaN;
            Console.WriteLine(Object.Equals(nan, nan));//true
            Console.WriteLine(Object.ReferenceEquals(nan, nan));//false
            Console.WriteLine(nan == nan);//false
            Console.WriteLine(nan.GetType());//System.single
            
            Object nano = float.NaN;
            Console.WriteLine(Object.Equals(nano, nano));//true
            Console.WriteLine(Object.ReferenceEquals(nano, nano));//true
            Console.WriteLine(nano == nano);//true
            Console.WriteLine(nano.GetType());//System.single
            Console.ReadKey();
        }
    }
}
Ranorex C# automation for MFC Windows GUI
The following code supposes you have Ranorex linked to your C# solution.
3 files attached: Main.script Repository.properties Program.cs
Main.script
rem call main
kill
start
type @login.password schilling
click @login.ok
click title=Schilling;text=Firmavalg
click title=Schilling;innertext=SPS.UK$,href=4$
doubleClick title=Schilling;text=Main.menu
doubleClick title=Schilling;text=Publisher
doubleClick title=Schilling;text=Product.management
REM Step 1
click title=Schilling;*=Product.management.project

rem ocr_click Project 3 0.5
type /form[@title~'^Product\smanagement\s-\sedit']/?/?/container[@caption~'^Product\smanagement\s-\sedit']/element/element[6]/text[@class='Edit'] 21321131231

REM Step 3
click *=Product.management;text=Create.project$
REM Step 4
click *=Product.management;*=Create.project;*=Other.projects..F7.
REM 5
click *=Product.management;text=Get.serial.number
REM 6
click *=Product.management;text=Accept$
rem ocr_click @Name: 0.5 0.5
REM 10
rem type *=Product.management;*=Save.project.as CrashCourseCardiology\t\t\t\t\t\t\t\tCrash
type @pm.edit.saveas.new-project-number {ts}
type @pm.edit.saveas.name "Crash Course Cardiology"
type @pm.edit.saveas.title "Crash Course Cardiology"
rem click on title
type @pm.edit.saveas.main-group 07
type @pm.edit.saveas.sub-group 021
type @pm.edit.saveas.dimension-1 002

click @pm.edit.saveas.new-project-number
click @pm.edit.saveas.name
click @pm.edit.saveas.new-project-number
click @pm.edit.saveas.name


click "*=Product.management;text=Create project$"
rem click "/form[@title='Error']/button[@text='OK']"
rem click "*=Product.management;text=Create project$"	
click "/form[@title='Question']/button[@text='&Yes']"

click @pm.edit.details.tab

wait 1000
clickAt @pm.edit.details.stackholders 100 20
clickAt @pm.edit.details.stackholders 10 20
clickAt @pm.edit.details.stackholders 100 20
wait 1000
type "/form[@title~'^Product\ management\ -\ edit']/?/?/container[@caption~'^Product\ management\ -\ edit']/?/?/container[@caption='Details']/?/?/container[@caption='Stakeholders']/?/?/element[@class='OaseGrid']/element/element[4]/text[@class='Edit']" "R"
wait 1000
clickAt @pm.edit.details.stackholders 200 20
wait 200
clickAt @pm.edit.details.stackholders 200 20
type "/form[@title~'^Product\ management\ -\ edit']/?/?/container[@caption~'^Product\ management\ -\ edit']/?/?/container[@caption='Details']/?/?/container[@caption='Stakeholders']/?/?/element[@class='OaseGrid']/element/element[31]/text[@class='Edit']" "Aut"
rem wait 1000
rem clickAt @pm.edit.details.stackholders 300 20
rem clickAt @pm.edit.details.stackholders 10 20
rem clickAt @pm.edit.details.stackholders 300 20
rem type "/form[@title~'^Product\ management\ -\ edit']/?/?/container[@caption~'^Product\ management\ -\ edit']/?/?/container[@caption='Details']/?/?/container[@caption='Stakeholders']/?/?/element[@class='OaseGrid']/element/element[4]/text[@class='Edit']" "Author	"
wait 1000
clickAt @pm.edit.details.stackholders 700 20
wait 200
clickAt @pm.edit.details.stackholders 700 20
type "/form[@title~'^Product\ management\ -\ edit']/?/?/container[@caption~'^Product\ management\ -\ edit']/?/?/container[@caption='Details']/?/?/container[@caption='Stakeholders']/?/?/element[@class='OaseGrid']/element/element[22]/text[@class='Edit']" "p2012-009"
rem Aut	Author	p2012-009	

click @pm.edit.texts.tab


click @pm.edit.calculation.tab

type @pm.edit.calculation.version 3
type @pm.edit.calculation.price 9
click @pm.edit.calculation.version
click @pm.edit.calculation.price
click *=Product.management;text=Accept$
Repository.properties Program.cs
Basic image recognition function in Java
Simple algorithm to find the (first) position of a smaller image in a larger one. Tip: to run faster, you may check for diagonal or few random points inside the small image before comparing all the other pixels.
1 files attached: ImageDetector.java
ImageDetector.java
package eu.sorescu.mmx;

import java.awt.Rectangle;
import java.awt.image.BufferedImage;

public class ImageDetector {
	public static Rectangle getImagePosition(BufferedImage bigImage,
			BufferedImage smallImage) {
		int w1 = bigImage.getWidth();
		int h1 = bigImage.getHeight();
		int w2 = smallImage.getWidth();
		int h2 = smallImage.getHeight();
		int[] bigPixels = bigImage.getRGB(0, 0, w1, h1, null, 0, w1);
		int[] smallPixels = smallImage.getRGB(0, 0, w2, h2, null, 0, w2);
		for (int x1 = 0; x1 <= w1 - w2; x1++)
			imageLoop: for (int y1 = 0; y1 <= h1 - h2; y1++) {
				for (int y2 = 0; y2 < h2; y2++)
					if (!compare(bigPixels, smallPixels, w1 * (y1 + y2) + x1,
							w2 * y2, w2))
						continue imageLoop;
				return new Rectangle(x1, y1, w2, h2);
			}
		return null;
	}

	private static boolean compare(int[] array1, int[] array2, int a1, int a2,
			int length) {
		for (int i = 0; i < length; i++)
			if (array1[a1 + i] != array2[a2 + i])
				return false;
		return true;
	}
}
My too-simple-to-be-true SMTP web server
My minimal SMTP server in JAVA - I needed it during email functionality tests because:
  • does not require mailbox creation in order to receive an email on any email address;
  • integrated with a minimal HTML page, I can instantly query for the message once it was sent, without waiting for virus scanning, etc.;
  • the server is domain-agnostic (it does not matter on what domain I send the email, as long as it reaches my machine);
  • I have full access to the email source immediately it reached the server, so the automated software can analyse subtle details under the hood of the email representation (alternate representations, email hidden headers, etc.).
All the code is invoked in SMTPServer.
2 files attached: SMTPThread.java SMTPServer.java
SMTPThread.java SMTPServer.java
Parallel JUnit execution runner - just annotate your @Parametrized class with @Parallelized
1 files attached: Parallelized.java
Parallelized.java
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.junit.runners.Parameterized;
import org.junit.runners.model.RunnerScheduler;

public class Parallelized extends Parameterized {

	private static class ThreadPoolScheduler implements RunnerScheduler {
		private ExecutorService executor;

		public ThreadPoolScheduler() {
			int numThreads = GenericTestCase.getIntProperty("threads");
			executor = Executors.newFixedThreadPool(numThreads);
		}

		@Override
		public void finished() {
			executor.shutdown();
			try {
				executor.awaitTermination(10, TimeUnit.MINUTES);
			} catch (InterruptedException exc) {
				throw new RuntimeException(exc);
			}
		}

		@Override
		public void schedule(Runnable childStatement) {
			executor.submit(childStatement);
		}
	}

	public Parallelized(Class klass) throws Throwable {
		super(klass);
		setScheduler(new ThreadPoolScheduler());
	}
}
My Java-Groovy joint builder (based on the UberCompile ant task)
(Some of the) Advantages:
  • No Maven or Gradle required;
  • No dependency (except JAVA_HOME and required JARs);
  • Can compile interdependent Java and Groovy code;
(Some of the) Disadvantages:
  • you need to indicate the path to the JARs;
  • Designed to work on Sun VMs;
The eu.sorescu.reflect.JARLoader is written based on Runtime dynamic loading of JARs.
1 files attached: GroovyProjectCompiler.java
GroovyProjectCompiler.java
How to make Java ignore the certificate errors
1 files attached: SSLUtil.java
SSLUtil.java
package dms.os;

import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashSet;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public final class SSLUtil {
	private static HashSet<KeyManager> keyManagers = new HashSet<KeyManager>();
	static {
		trustAllHosts();
	}
	public static TrustManager[] _trustManagers = new TrustManager[] { new X509TrustManager() {
		private final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {};

		public void checkClientTrusted(X509Certificate[] chain, String authType) {
		}

		public void checkServerTrusted(X509Certificate[] chain, String authType) {
		}

		public X509Certificate[] getAcceptedIssuers() {
			return (_AcceptedIssuers);
		}
	} };

	public static void addClientCertificate(byte[] data, String password)
			throws KeyManagementException, NoSuchAlgorithmException,
			UnrecoverableKeyException, KeyStoreException, CertificateException,
			FileNotFoundException, IOException {
		SSLContext context = SSLContext.getInstance("TLS");
		for (KeyManager km : getKeyManagers(data, password))
			keyManagers.add(km);
		context.init(keyManagers.toArray(new KeyManager[keyManagers.size()]),
				_trustManagers, new SecureRandom());
		HttpsURLConnection.setDefaultSSLSocketFactory(context
				.getSocketFactory());
	}

	private static KeyManager[] getKeyManagers(byte[] data, String password)
			throws UnrecoverableKeyException, KeyStoreException,
			NoSuchAlgorithmException, CertificateException,
			FileNotFoundException, IOException {
		KeyManagerFactory tmf = null;
		char[] passwKey = password.toCharArray();
		KeyStore ts = KeyStore.getInstance("PKCS12");
		ts.load(new ByteArrayInputStream(data), passwKey);
		tmf = KeyManagerFactory.getInstance("SunX509");
		tmf.init(ts, passwKey);
		return tmf.getKeyManagers();
	}

	public static void trustAllHosts() {

		HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
			public boolean verify(String hostname,
					javax.net.ssl.SSLSession session) {
				return (true);
			}
		});
	}
}
Java class overloading/reloading - how two objects apparently belonging to the same class but they do not
Questions and answers for people that understand the code below:
  • why didn't I reload some java.lang.XXX? Because I needed to start the instrumentation agent to manipulate the AST - extra lines in article due to the standard Sun JVM behaviour on class loader priority imposed by the ClassLoader.getSystemClassLoader(); laziness...
  • Why didn't I reload also the AbstractButton so that my button can access it? Because the access octopus would spread far away...
  • Why could I reload a class that otherwise was accessible by the standard JVM class loader? The Oracle site says you cannot...; answer - I broke the Class Loading priority  convention - it's a convention, not an imposed rule to ask first the ClassLoader.parent.; second - I indicated explicitly the class loader I wanted to use.
  • Who would use such a thing?!? Java Web Start, Java Applets, and java Servlet containers, at least. :)
Expected outcome:
class hashCode
1952592365
1457769401
----------------------
check if new JButton().getClass() == our class
Original class: true
Artificial class: false
----------------------
toString for classes
originalClass: class javax.swing.JButton
artificialClass: class javax.swing.JButton
------------------
Check if classes are the same...
artificialButton.getClass() == button.getClass(): false
syntheticObject instanceof JButton: false
java.lang.ClassCastException: javax.swing.JButton cannot be cast to javax.swing.JButton
Cannot cast from class javax.swing.JButton to class javax.swing.JButton!?!
This is the genuine button toString(): javax.swing.JButton[,0,0,0x0,invalid,alignmentX=0.0,alignmentY=0.5,border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource@5abbfa4c,flags=296,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=2,left=14,bottom=2,right=14],paintBorder=true,paintFocus=true,pressedIcon=,rolloverEnabled=true,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=,defaultCapable=true]
java.lang.IllegalAccessError: tried to access field javax.swing.AbstractButton.defaultCapable from class javax.swing.JButton
Cannot run toString for the artificial button because:
AbstractButton.defaultCapable is hidden for classes that don't inherit the AbstractButton.
And our artificialButton JButton tried to access the AbstractButton protected field.
And that AbstractButton is the JVM standard class loader - remember if (name.equals("javax.swing.JButton"))?
1 files attached: Test.java
Test.java
Windows Media Encoder 9 - small, efficient, and powerful enough for screen capturing and streaming
Open the link http://www.microsoft.com/en-us/download/details.aspx?id=17792; choose downloading; next next next... accept T&C... next next next... install...
Wait few seconds, and you're done.
Once you start the program, choose Capture screen option, then choose between Specific window, Region of the screen, or Entire screen.
Then, enjoy the recording and the very small size of the encoded file - but still capturing all the details from your display.
Runtime dynamic loading of JARs (valid only on Sun JVMs)
Shortest (as of now) way for me to dynamically load classes from JARs that are not defined in the project.
public static synchronized void loadJAR(File jar) throws ClassNotFoundException {
	try {
		URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader();
		URL url = jar.toURI().toURL();
		if (Arrays.asList(loader.getURLs()).contains(url))
			return;
		Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { java.net.URL.class });
		method.setAccessible(true);
		method.invoke(loader, new Object[] { url });
	} catch (final ReflectiveOperationException e) {
		throw new ClassFormatError(e.getMessage());
	} catch (final java.net.MalformedURLException e) {
		throw new ClassNotFoundException(e.getMessage());
	}
}