スキップしてメイン コンテンツに移動

投稿

8月, 2012の投稿を表示しています

Youtube API + GAEJ + FreeMarker + Spring

I have developed very very simple youtube sample application on Google App Engine. Internally I have used FreeMarker and Spring. The purpose of this blog entry is just giving hints how to use Spring + FreeMarker on GAEJ with youtube API example. Youtube API Here is the code for extracting video url etc from Youtube API response. I frequently use JDOM for parsing XML. package com.dukesoftware.gaej.youtube; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.Namespace; import org.jdom.input.SAXBuilder; import org.jdom.xpath.XPath; import com.dukesoftware.utils.io.JDOMUtils; import com.dukesoftware.utils.io.MinimumIOUtils; public class YouTube { private final static XPath XPATH_MEDIA; private final static Namespace NS_MEDIA = Namesp...

C#: Download All Image Links from Html Page

I know this is not perfect way. But I would like to give hints to anyone who would like to download all links in html page. Example usage is something like this. // only download "jpg" files HttpUtils.SaveFirstLevelLinksToFile("", Encoding.UTF8, "c:/temp/", link => link => ".jpg".Equals(Path.GetExtension(link.Link), StringComparison.OrdinalIgnoreCase) ); Main code is below. // main entry point method public static void SaveFirstLevelLinksToFile(string baseUri, Encoding enc, string dir, Func<LinkAttr, bool> filter) { ProcessAllExtractedLinksInHtmlText(GetPage(baseUri, enc), link => { try { if (!filter(link)) return; Uri uri = ConvertToAbsoluteURL(baseUri, link.Link); var filePath = dir + uri.AbsoluteUri.GetFileName().Replace("?", ""); uri.AbsoluteUri.GetAndSaveToFile(filePath); ...

ActionScript 3.0: Loading Bytes from URL

I wrote a utility class for loading bytes from URL because the official method needs a lot of preparation. Here is the usage. var loader:ByteLoadHelper = new ByteLoadHelper(); loader.addEventListener(ByteLoadEvent.COMPLETE, completeHandler); loader.load(url); function completeHandler(evt:ByteLoadEvent):void { loader.removeEventListener(ByteLoadEvent.COMPLETE, completeHandler); var bytes:ByteArray = evt.data; // do something nice :D } Here is the core code. package utils.tool { import flash.events.Event; import flash.events.EventDispatcher; import flash.net.URLLoader; import flash.net.URLLoaderDataFormat; import flash.net.URLRequest; import flash.utils.ByteArray; public class ByteLoadHelper extends EventDispatcher { public function ByteLoadHelper() { } public function load(url:String):void { var urlLoader:URLLoader = new URLLoader(); urlLoader.dataFormat = URLLoa...

ActionScript 3.0: Dictionary Utility Methods (Delete All Entries, Count All Entries, etc.))

public class DictionaryUtils { public function DictionaryUtils() { } public static function forEachBySortedValue(dict:Dictionary, compare:Function, callback:Function):void { var v:Vector.<Object> = extractValues(dict); v.sort(compare); for each(var value:Object in v) { callback(value); } } public static function forEachBySortedKey(dict:Dictionary, compare:Function, callback:Function):void { var v:Vector.<Object> = extractKeys(dict); v.sort(compare); for each(var key:Object in v) { callback(key, dict[key]); } } public static function extractValues(dict:Dictionary):Vector.<Object> { var v:Vector.<Object> = new Vector.<Object>(); for each(var value:Object in dict) { v.push(value); } return v; } public static function extractKeys(dict:Dictionary):Vector.<Object> { var v:Vector.<Object> = new Vector.<Object>(); for (var key:Object in dict) { v.push(key); } return v; } pu...

ActionScript 3.0: Digging Directory Recursively And Process Each File

This class aims to parse directory and do something for each file. You should just override proper methods, then call process method like this. new DirectoryDigger().process("c:/temp"); package utils.file { import flash.filesystem.File; public class DirectoryDigger { public function DirectoryDigger() { } public function process(path:String):Object { var file:File = new File(path); preProcess(file); processBody(file); return postProcess(file); } protected function processBody(file:File):void { if (file.isDirectory) { preProcessDir(file); var files : Array = file.getDirectoryListing(); for (var i : int = 0; i Here is the simplest example - just print all files under directories. package utils.tool { import flash.filesystem.File; import utils.f...

C#: Capture Screen

Here is the code for capturing current screen in given Rectangle region. public static Bitmap CaptureFromScreen(Rectangle rc) { var bmp = new Bitmap(rc.Width, rc.Height, PixelFormat.Format32bppArgb); using (var g = Graphics.FromImage(bmp)) { g.CopyFromScreen(rc.X, rc.Y, 0, 0, rc.Size, CopyPixelOperation.SourceCopy); } return bmp; } You can give something like below as a Rectangle argument // full screen area Screen.PrimaryScreen.Bounds; // 640 x 480 rectamgle from left side corner new Rectangle(0, 0, 640, 480); // working area Screen.PrimaryScreen.WorkingArea; The following links are helpful. http://homepage1.nifty.com/yasunari/VB/VB2005/DrawToScreen.htm : Sorry this page is written in Japanese... http://www.bobpowell.net/capture.htm http://msdn.microsoft.com/en-us/library/dd144871(VS.85).aspx http://msdn.microsoft.com/en-us/library/dd162920(VS.85).aspx

Solving Unimodal Function by Brent's Method

Introduction I faced a mathematical problem for solving a root from a unimodal function like quadratic function. Of course we can solve the root if the function is mono decreasing or mono increasing in the target range. However if the function is in potentially there are 2 solutions or no solutions in the target range. I know this article is not perfect yet. I will keep improving this article :) Main Requirements There are mainly 2 requirements when solving the root. Minimize the function call as much as possible: because the function needs heavy calculation Robustness against oscillating: Maybe the below figure helps your understanding. If we solve the root strictly, there can be a lot of solutions in the range because of the small oscillating. However we should choose reasonable accrual solution from candidate points. Solution I have tried Newton method, but it didn’t work well because of the above bullet point 2. I have also tried fitting 3 dimensional function ...

C#: Extract A Href Links from Html Text

// I know 1, 2, 3 is bad grouping name X( private readonly static Regex LINK_REGEX = new Regex( @"<a\s+[^>]*href\s*=\s*(?:(?<3>'|"")(?<1>[^\3>]*?)\3|(?<1>[^\s>]+))[^>]*>(?<2>.*?)</a>", RegexOptions.IgnoreCase | RegexOptions.Compiled ); public static void ExtractLinks(string text, ICollection<string> links) { LINK_REGEX.ApplyAllMatched(text, (m) => links.Add(m.Groups[1].Value)); } Helper method which processes matched string for each. public static void ApplyAllMatched(this Regex regex, string text, Action apply) { for (var m = regex.Match(text); m.Success; ) { apply(m); m = m.NextMatch(); } }

C#: Save Image as JPEG or PNG format

Just a simple code tips for saving image as JPEG or PNG format in C#. Save image as JPEG with Quality parameter public static readonly ImageCodecInfo JPEG_CODEC = GetEncoderInfo("image/jpeg"); public static void SaveImageAsJpeg(this Image src, string fileName, int quality) { var eps = new EncoderParameters(1); var ep = new EncoderParameter(Encoder.Quality, quality); eps.Param[0] = ep; src.Save(fileName.ChangeExtension("jpg"), JPEG_CODEC, eps); } public static ImageCodecInfo GetEncoderInfo(string mineType) { return ImageCodecInfo.GetImageEncoders().First(enc => enc.MimeType == mineType); } Save image as PNG public static void SaveImageAsPng(this Image src, string fileName) { src.Save(fileName.ChangeExtension("png"), ImageFormat.Png); }

C#: Resize Image

// Default parameters are almost the highest quality setting. public static Bitmap Resize(this Image src, int w, int h, SmoothingMode smoothingMode = SmoothingMode.AntiAlias, InterpolationMode interpolationMode = InterpolationMode.HighQualityBicubic, PixelOffsetMode pixelOffsetMode = PixelOffsetMode.HighQuality) { var newImage = new Bitmap(w, h); using (var gr = Graphics.FromImage(newImage)) { gr.SmoothingMode = smoothingMode; gr.InterpolationMode = interpolationMode; gr.PixelOffsetMode = pixelOffsetMode; gr.DrawImage(src, 0, 0, w, h); } return newImage; } // resize image based on given percentage public static Bitmap ResizedByPercentage(this Image src, double percent) { var rW = (int)Math.Round(src.Width * percent, 0); var rH = (int)Math.Round(src.Height * percent, 0); return src.Resize(rW, rH); } // resize image limited in given w, h parameter public static Bitmap ResizeImageIn(this Image src, int w, i...

C#: Extract Charset from Html Meta Tag

private static readonly Regex META_TAG_CHARSET_REGEX = new Regex(@"<META\s+http-equiv\s*=\s*Content-Type\s+content=\s*""[^""]*\s+charset\s*=\s*(?<charset>[^""\s]*).*""\s*>", RegexOptions.IgnoreCase | RegexOptions.Compiled); public static string ExtractCharset(string htmlText) { string result = null; var m = META_TAG_CHARSET_REGEX.Match(htmlText); if (m.Success) { result = m.Groups["charset"].Value; } return result; } Note: System.Text.RegularExpressions.Regex class is thread safe according to this msdn doc .

ActionScript 3.0: Load SWF, JPG, PNG

Hey guys! I wrote small utility method for loading swf, jpg, png etc. in ActionScript 3.0. public static function loadFromURL(url:String):Loader { var img:Loader = new Loader(); img.load(new URLRequest(url)); return img; } public static function loadFromFile(path:String):Loader { var img:Loader = new Loader(); img.loadBytes(IOUtils.readByteData(path)); return img; } public static function load(url:String, format:String):URLLoader { var loader:URLLoader = new URLLoader(); loader.dataFormat = format; loader.addEventListener(Event.COMPLETE, completeHandler); loader.load(new URLRequest(url)); function completeHandler(event:Event):void { loader.removeEventListener(Event.COMPLETE, completeHandler); //trace(event.target.data); } return loader; }

C#: XPath and HtmlTextWriter Example

Hey guys!! This post show you how to use XPath in C#. I wrote program for formatting rss feed (xml) to html for its example. XPath in C# The simplest way is just creating XmlDocument and call SelectNodes method. var xmlString = "some xml string...." // create XmlDocment var doc = new XmlDocument(); doc.LoadXml(xmlString); // selecting nodes by xpath string doc.SelectNodes("/rss/channel/item"); RSS Xml to Html Example Okay here is a simple XPath example - converting rss xml to html. using System.IO; using System.Web.UI; using System.Web; namespace Utility { public class RSStoHtmlWriter : HTMLWriteHelper { private readonly string url; public RSStoHtmlWriter(string url) { this.url = url; } public override void WriteBody(HtmlTextWriter htmlWriter) { using (var reader = new XmlTextReader(url)) { // **** using XPath!! **** // As you n...

PHP: Extract Values on Specific Key in Array

I wrote tiny utility method - which is for extracting values on specific key in array. Code function extractValuesForSpecificKey(array& $sourceArray, $key){ $retArray = array(); foreach ($sourceArray as $sourceElem){ $retArray[] = $sourceElem[$key]; } return $retArray; } Example $source = array( array('id' => 1, 'name' =>'Joe'), array('id' => 2, 'name' =>'Chris'), ); $result = extractValuesForSpecificKey($source, 'id'); var_dump($result); The result should be: array(2) { [0]=> int(1) [1]=> int(2) }

CMSL (Connected Multilayer Spring Layout)

I finally announce Java Web Start Demo for CMSL (Connected Multilayer Spring Layout) is available!! 2013/11 Sorry, looks like jnlp not works very well. I stopped make the demo public. I developed the CMSL originally in 2008. Screenshots Source Code The source code is available on CMSL on sourceforge. Future Plan I know I need to do a lot of refactoring for the code, put functionality for playing music, support more flexible data structure, etc.... X( I will keep updates on this blog if something of CMSL is improved. Currently In order to improve the calculation speed for layout of elements, am working on following tasks Cell division algorithm Multi-threading The limit of number of elements frame rate which meet achieving 30fps is about 1000. Am targeting to achieve 10000 elements. Not sure people can see 1000 elements at a time though :P

JDK7 + EMMA

I recently upgraded my JDK from 6 to 7. When I ran my JUnit tests with EMMA, all tests suddenly became failed with the following error: java.lang.ClassFormatError: Illegal local variable table length 11 in method ..... I have googled and found that the solution from here . What I have done is adding -XX:-UseSplitVerifier option when JUnit runs. After I added this option, everything works fine. (The cause looks like new try-catch resource feature according to the above stackoverflow trace but I have not confirmed yet.)

JavaでGUIアプリケーション開発: Swing, SWT, Java3D, Animation

JavaでもリッチなUIやアニメーションを作りたいという方向けにリンクと書籍を紹介します。 今は、JQueryやTwitter Bootstrapなどのjavascript、HTML5でリッチなUIを作る人が多いと思いますが、Javaも捨てたものじゃないということで参考にしていただければと思います。 Swing JavaのGUIといえばSwing! 2D系の処理は手軽に何でもできるので、非常に便利です。 Swing Tutorial Native Swing JGoodies Filthy Rich Clients アニメーションとグラフィカルエフェクトを使ったデスクトップJavaアプリケーション (The Java Series) JavaのSwingでColl & Richなアプリケーションを開発しようと思ったら、 絶対 にはずせない書籍です。 私にとってのJavaのSwing開発のバイブルです :) 特に画像のスケーリングについては、画像の補間方法、性能比較なども含め本当に詳しく紹介されています。 またアニメーションのタイミングフレームワークについても深く掘り下げて説明されています。 個人的にはもっと注目されてもいい書籍だと思うのですが。。。かなりお値段は張りますが、購入する価値の十分ある書籍です。 書籍中で出てくるソースコードは、下記リンクですべて公開されています。 http://filthyrichclients.org/ java.net上の http://java.net/projects/filthyrichclients/ からもチェックアウトできます。 Java Swing Hacks ―今日から使える驚きのGUIプログラミング集 2006年刊行の本ですが、Swingをここまで使いこなせている人は、未だに少ないのではないでしょうか。 テキストボックスのオートコンプリートの作成、ドラッグアンドロップ、サムネイル付JFileChooserの作成などなど。。すばらしい Hack が満載です!! SWT Eclipseで使われているライブラリです。良くも悪くもOSに依存したNativeなライブラリです。 私はJavaからIEのWebブラウザが使いたかったことがあり、触った...

Taking Diff bewteen Two Repositories

I wrote a bash script for taking diffs between two repositories. #!/bin/bash SVN_USERNAME=dukesoftware SVN_PASSWORD=some_password SVN_COMMON_COMMAND="svn --username $SVN_USERNAME --password $SVN_PASSWORD --non-interactive --ignore-externals --quiet" SVN_COMMON_UPDATE_COMMAND="$SVN_COMMON_COMMAND update --set-depth infinity" SVN_COMMON_CHECKOUT_COMMAND="$SVN_COMMON_COMMAND co --depth immediates" SVN_BASE_URL=http://svn.repository.dummy.com/projects/ # comparison svn urls SVN_URL1=$SVN_BASE_URL/url1 SVN_URL2=$SVN_BASE_URL/url2 DIR1=target1 DIR2=target2 OUTPUT_DIR=diff_out EXCLUDE_FILES=(".svn" "jquery-*.min.js") # To minimize number of checkout files, set below constants CHECKOUT_DIRS=("dir1" "dir2" "lib") DIFF_TARGETS=("dir1/sub1" "dir1/sub2" "dir2" "lib") # function definitions build_base_diff_command(){ DIFF_BASE_COMMAND="diff -E -B -b -u -r" fo...