2013年1月30日水曜日

Rubyを始めました。

Ruby
Gem
DevKit
Rails
を順番にインストールしてから、
ここのチュートリアルを見ながら、やってみたら、
http://guides.rubyonrails.org/getting_started.html
いきなり、こんなエラーが出てきました。
ExecJS::RuntimeError in Home#index
Showing C:/TestGround/RubyTest/blog/app/views/layouts/application.html.erb where line #6 raised:
(in C:/TestGround/RubyTest/blog/app/assets/javascripts/home.js.coffee)
Extracted source (around line #6):
3: <head>
4:   <title>Blog</title>
5:   <%= stylesheet_link_tag    "application", :media => "all" %>
6:   <%= javascript_include_tag "application" %>
7:   <%= csrf_meta_tags %>
8: </head>
9: <body>
Rails.root: C:/TestGround/RubyTest/blog
Application Trace | Framework Trace | Full Trace
app/views/layouts/application.html.erb:6:in `_app_views_layouts_application_html_erb___30976759_29317332'

いろいろ調べたら、
node.jsをインストールしたら解決できそうですが、
こんなわけないだろうと思って・・・
http://www.jamiestarke.com/2012/01/28/fixed-execjs-runtimeerror-and-fatal-error-v8contextnew-when-deploying-rails-to-shared-hosting/
書いた方法通り、pipelineをfalseにした後、
無事に出来ました!3939!

2013年1月24日木曜日

HaskellでGlossライブラリーを試してみました。

いっぱいサンプルがありますが、もっと簡単の作りたいですから、
まる一個だけ作りました。
import Graphics.Gloss
import Graphics.Gloss.Interface.Pure.Simulate

data Cir = Cir     Float
                Float
                deriving (Show)

render::Cir->Picture
render (Cir x y) = ThickCircle x y

start:: Cir
start = Cir 100.0 10.0

trans::ViewPort -> Float -> Cir -> Cir
trans _ _ (Cir x y) = Cir x y

main::IO()
main = simulate (InWindow "NATZ" (800,600) (10,10))
        (makeColor 0.5 1.0 0.5 1.0)
        0
        start
        render
        trans

WindowsにHaskell gnuplotとdarcsのインストール

普通に
cabal install gnuplot
はできなかった。
エラーメッセージを見たら、ずっとdependencyのcolourをダウンロードできなかったと・・・

そこで、直接ソースからインストールしようと思って、
これってやってみよう!
darcs get http://code.haskell.org/gnuplot/

じゃ、darcsは必要じゃん。
cabal install darcs
はだめだった。

darcsのホームページをみたら、
正解はこれだ。
cabal install darcs -f-curl

2013年1月23日水曜日

HaskellとGTKでHello World

helloworld.hs
import Graphics.UI.Gtk

main = do
    initGUI
    window <- windowNew
    button <- buttonNew
    set window [ containerBorderWidth := 10, containerChild := button ]
    set button [ buttonLabel := "Hello World" ]
    onClicked button (putStrLn "Hello World")
    onDestroy window mainQuit
    widgetShowAll window
    mainGUI
Compile時は
ghc --make -optl-mwindows helloworld.hs 

WindowsにHaskell HDBC-sqlite3のインストール

普通に
cabal install HDBC-sqlite3
を実行するだけじゃ、こんなエラーが出てきます。
setup: Missing dependency on a foreign library: * Missing C library: sqlite3 
This problem can usually be solved by installing the system package 
that provides this library (you may need the "-dev" version). 
If the library is already installed but in a non-standard location 
then you can use the flags --extra-include-dirs= and --extra-lib-dirs= 
to specify where it is.
問題の解決は
1.このサイトSQLiteから、
sqlite-dll-win32-x86-3071502.zip
をダウンロードして解凍してから、
中の.dllファイルを環境変数%PATH%中にあるDirectoryに入れる。
たとえば、system32とか・・・C:\Foo\とか

2.同じサイトから
sqlite-amalgamation-3071502.zip
をダウンロードして解凍してから、
中の.hファイルを同じフォルダに入れる。

3.再びコンソールでインストール

cabal install HDBC-sqlite3 \
--extra-lib-dirs="C:\Foo" --extra-include-dirs="C:\Foo"

2013年1月21日月曜日

Haskell GUI Programming >>= Windows環境のGTK+とGtk2Hsのインストール

必要のは勿論HaskellのGHCとcabal install. Haskellのインストールは簡単なので、ここ略します。

1.GTKの準備
  GTK+で、all in one bundleをダウンロード後、解凍して、好きなフォルダに移動してください。
  注意すべきのは、フォルダのPathにSpaceがあったら、だめです。
  そして、環境変数%PATH%に、GTKのサブフォルダbinのPATHを追加する。

2.以上終わったら、これでチェックする。
  pkg-config --cflags gtk+-2.0 
  もし間違いがなければ、binのPATHが中に入ってるはずです。
  もう一つの方法はconsoleでgtk-demoを実行できれば、OKです。

3.Gtk2Hsのインストール
  cabal install cabal-install
  cabal install gtk2hs-buildtools
  cabal install gtk
  エラーがなければ、これで終了です。

4.成功したかどうかのチェック
  下のコードをファイルhello.hsにコピーペーストして、
-- A simple program to demonstrate Gtk2Hs.
module Main (Main.main) where

import Graphics.UI.Gtk

main :: IO ()
main = do
  initGUI
  -- Create a new window
  window <- windowNew
  -- Here we connect the "destroy" event to a signal handler.
  -- This event occurs when we call widgetDestroy on the window
  -- or if the user closes the window.
  onDestroy window mainQuit
  -- Sets the border width and tile of the window. Note that border width
  -- attribute is in 'Container' from which 'Window' is derived.
  set window [ containerBorderWidth := 10, windowTitle := "Hello World" ]
  -- Creates a new button with the label "Hello World".
  button <- buttonNew
  set button [ buttonLabel := "Hello World" ]
  -- When the button receives the "clicked" signal, it will call the
  -- function given as the second argument.
  onClicked button (putStrLn "Hello World")
  -- Gtk+ allows several callbacks for the same event.
  -- This one will cause the window to be destroyed by calling
  -- widgetDestroy. The callbacks are called in the sequence they were added.
  onClicked button $ do
    putStrLn "A \"clicked\"-handler to say \"destroy\""
    widgetDestroy window
  -- Insert the hello-world button into the window.
  set window [ containerChild := button ]
  -- The final step is to display this newly created widget. Note that this
  -- also allocates the right amount of space to the windows and the button.
  widgetShowAll window
  -- All Gtk+ applications must have a main loop. Control ends here
  -- and waits for an event to occur (like a key press or mouse event).
  -- This function returns if the program should finish.
  mainGUI

  ghc --make Hello.hs -o hello
  でCompile成功したら、OKです。  

2013年1月19日土曜日

HaskellでHTTP接続

import Network.HTTP (simpleHTTP, getRequest, getResponseBody, Request)

resStr::Request String
resStr =  getRequest "http://www.google.co.jp"

main::IO()
main = do 
            header <- simpleHTTP resStr
            body <- getResponseBody header
            print header 
            print body

2013年1月17日木曜日

C#でGoogle RSSを取得する

·Google ReaderのAPIを使うため必要な知識はこちらのリンクへご参考を
http://code.google.com/p/google-reader-api/w/list
特に難しい認証の部分はこちらの説明に
http://www.yoheim.net/blog.php?q=20120608
C#で書いてみました。こんな感じです。
using System;
using System.IO;
using System.Net;
using System.Text;
 
namespace GoogleReaderDemo
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var sw = new StreamWriter("Feed.txt");
            Console.SetOut(sw);
 
            // Setup Request, uri, method, contenttype, contentlength and write the post data to requeststream.
            var res = (HttpWebRequestWebRequest.Create(new Uri(@"https://www.google.com/accounts/ClientLogin"));
            res.Method = "POST";
            res.ContentType = "application/x-www-form-urlencoded";
 
            const string postData = "Email=yourname@gmail.com&Passwd=yourpassword&service=reader";
            byte[] bytes = Encoding.ASCII.GetBytes(postData);
            res.ContentLength = bytes.Length;
 
            string rspBody = "";
            using (Stream s = res.GetRequestStream())
            {
                s.Write(bytes0bytes.Length);
                WebResponse rsp = res.GetResponse();
                var streamReader = new StreamReader(rsp.GetResponseStream());
                streamReader.ReadLine();
                streamReader.ReadLine();
                rspBody = streamReader.ReadToEnd();
            }
 
            // Request RSS with a name:value pair:  Authorization:GoogleLogin AUTH=..."
            res = (HttpWebRequestWebRequest.Create(new Uri(@"http://www.google.com/reader/atom/"));
            res.Headers.Add("Authorization""GoogleLogin " + rspBody);
            rspBody = new StreamReader(res.GetResponse().GetResponseStream()).ReadToEnd();
            Console.Write(rspBody);
 
            Console.ReadLine();
        }
    }
}

ATOM形式で返してくるので、どっかのParserがあればいいですね・・・自分書くのが面倒で・・・
Nugetで探したら、すぐ出てきました。
http://qdfeed.codeplex.com/
これでいけそう!
やってみました。
using System;
using System.IO;
using System.Net;
using System.Text;
using QDFeedParser;
 
namespace GoogleReaderDemo
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            // Setup Request, uri, method, contenttype, contentlength and write the post data to requeststream.
            var res = (HttpWebRequestWebRequest.Create(new Uri(@"https://www.google.com/accounts/ClientLogin"));
            res.Method = "POST";
            res.ContentType = "application/x-www-form-urlencoded";
 
            const string postData = "Email=youremail@gmail.com&Passwd=yourpassword&service=reader";
            byte[] bytes = Encoding.ASCII.GetBytes(postData);
            res.ContentLength = bytes.Length;
 
            string rspBody = "";
            using (Stream s = res.GetRequestStream())
            {
                s.Write(bytes0bytes.Length);
                WebResponse rsp = res.GetResponse();
                var streamReader = new StreamReader(rsp.GetResponseStream());
                streamReader.ReadLine();
                streamReader.ReadLine();
                rspBody = streamReader.ReadToEnd();
            }
 
            // Request RSS with a name:value pair:  Authorization:GoogleLogin AUTH=..."
            res = (HttpWebRequestWebRequest.Create(new Uri(@"http://www.google.com/reader/atom/"));
            res.Headers.Add("Authorization""GoogleLogin " + rspBody);
            rspBody = new StreamReader(res.GetResponse().GetResponseStream()).ReadToEnd();
 
            File.WriteAllText(@"C:\Users\Z\Desktop\Feed.txt"rspBody);
            IFeedFactory factory = new FileSystemFeedFactory();
            IFeed feed = factory.CreateFeed(new Uri(@"C:\Users\Z\Desktop\Feed.txt"));
            foreach (BaseFeedItem i in feed.Items)
            {
                Console.WriteLine("_____________________________________________________");
                Console.WriteLine("Title : " + i.Title + Environment.NewLine); 
                Console.WriteLine("Link  : " + i.Link + Environment.NewLine); 
                Console.WriteLine("Date  : " + i.DatePublished);
            }
            Console.ReadLine();
        }
    }
}

Haskell Tree Forest!

まず、Data.Treeの中身をのぞいてみます。
data Tree a = Node {rootLabel :: a, subForest :: Forest a}
instance [safe] Eq a => Eq (Tree a)
instance [safe] Monad Tree
instance [safe] Functor Tree
instance [safe] Read a => Read (Tree a)
instance [safe] Show a => Show (Tree a) 
Prelude Data.Tree> :t unfoldTree
unfoldTree :: (b -> (a, [b])) -> b -> Tree a
Prelude Data.Tree> :browse
type Forest a = [Tree a]
data Tree a = Node {rootLabel :: a, subForest :: Forest a}
drawForest :: Forest String -> String
drawTree :: Tree String -> String
flatten :: Tree a -> [a]
levels :: Tree a -> [[a]]
unfoldForest :: (b -> (a, [b])) -> [b] -> Forest a
unfoldForestM ::
  Monad m => (b -> m (a, [b])) -> [b] -> m (Forest a)
unfoldForestM_BF ::
  Monad m => (b -> m (a, [b])) -> [b] -> m (Forest a)
unfoldTree :: (b -> (a, [b])) -> b -> Tree a
unfoldTreeM :: Monad m => (b -> m (a, [b])) -> b -> m (Tree a)
unfoldTreeM_BF :: Monad m => (b -> m (a, [b])) -> b -> m (Tree a)
目標は二三分間でTreeを作って出してみたいですから、
drawTreeかdrawForestを使いたいな・・・
ただし、drawTreeはTree Stringしか描画できないです。
ということは、aのところで、Stringを入れ替える必要がありますね。

あともう一つ、どうやって枝のない葉っぱをつくるの問題が残ってます・・・
よく見たら、Node中のsubForestのtype、実際は [ ] Tree a !
Listです!!
[ ]をすれば、葉っぱができるはず!

早速作りました!あの人が何年もかけて作った会社を
import Data.Tree

type Human = Forest String
type Occupation = Tree String

boss,worker,newbie::Occupation
newbie = Node "Baby Door" []
worker = Node "Bill Door" [newbie, newbie,newbie]
boss = Node "Bill Gate" [worker, worker]

guys::Human
guys = [newbie,worker,boss]

main::IO()
main = do
    putStr "\n <------------------------ Microsoft !\n"
    putStr $ drawTree boss
    putStr "\n <------------------------ All the guys !\n"
    putStr $ drawForest guys

2013年1月16日水曜日

Haskellのinstance、class、 dataそれぞれとtype-parameterの組み合わせ


まず、Num aクラスのinstanceを見てみます。
class Num a where
  (+) :: a -> a -> a
  (*) :: a -> a -> a
  (-) :: a -> a -> a
  negate :: a -> a
  abs :: a -> a
  signum :: a -> a
  fromInteger :: Integer -> a
instance Num Integer
instance Num Int
instance Num Float
instance Num Double
Num aはtype-parameterがありますので、Numはtype constructorである。したがって、
foo::Num
foo = 3
ということはできません。

クラス中の演算子+、*、-及び関数negate、abs、signumを使いたい場合は、
クラス中のinstanceになるしかない。たとえば、
foo::Float
foo = 3
下のような感じで考えるほうがいいかもしれません。(実際はないですけど・・・)
data Float = Float deriving (Num)
FloatがNumの性質を持たせるみたいに。
ほかのNum aインスタンスInteger、Int、Doubleも同じく、
演算子+、*、-及び関数negate、abs、signumを使えるはずです。

つぎは、data中のtype-parameterを見てます。
data Maybe a = Nothing | Just a 
instance Eq a => Eq (Maybe a)
instance Monad Maybe
instance Functor Maybe
instance Ord a => Ord (Maybe a)
instance Read a => Read (Maybe a)
instance Show a => Show (Maybe a)
上の推理によって、type-parameterがあるから、こういうこと
foo::Maybe
foo = Just 3
はできません。
幸いMaybeはalgebraic data typeで宣言してますので、
aに型をつけて、さらに|の左か右を一つvalue constructorを選ぶだけで
foo,bar::Maybe Int
foo = Just 1
bar = Just 1
fooとbarがインスタンスEq aの性質を持つことになります。
*Main> foo == bar
True

今度はtype constrain (=>)についてみてみます。

2013年1月15日火曜日

Haskell State Without Monad

Inspired by an articl
Monad for the Working Haskell Programmer -- a short tutorial Theodor Norvell
I tried to make it more clear and coded the following.

And the result is

*Main> (cutDummy >=> downgradeIfEven) Six
(Five,"Downgraded")

*Main> (cutDummy >=> downgradeIfEven) Dummy
(Two,"Upgraded")

data State = Dummy | One | Two | Three | Four | Five | Six
                deriving (Show,Eq,Enum,Ord,Read)

type GroupStateAndFlag = State->(State, Int)
cutDummy::GroupStateAndFlag
cutDummy s 
            | s == Dummy = (One, fromEnum $ succ s)
            | otherwise = (s, fromEnum s)

type ChangeGradeAndInfo = State->(State,String)
downgradeAndInfo,upgradeAndInfo::ChangeGradeAndInfo
downgradeAndInfo s 
            | s== One = (Six, "Downgraded and Reversed")
            | otherwise = (pred s, "Downgraded") 

upgradeAndInfo s 
            | s== Six = (One, "Upgraded and Reversed")
            | otherwise = (succ s, "Upgraded") 

downgradeIfEven::Int->ChangeGradeAndInfo
downgradeIfEven a
                | even a =  downgradeAndInfo
                | otherwise = upgradeAndInfo


(>=>)::GroupStateAndFlag->(Int->ChangeGradeAndInfo)->ChangeGradeAndInfo
stateManupilator1 >=> evaluator = 
                \ state1 -> let     
                                (state2, result) = stateManupilator1 state1      
                                -- Manupilate the State, pack it with a result 
                                stateManupilator2 = evaluator result             
                                -- Pass the result to a evaluator, 
                                -- pass it to another state manupilator
                             in stateManupilator2 state2

ret::a->State->(State,a)
ret result = \state -> (state, result)

2013年1月14日月曜日

Haskell Syntax Highlighting

Thanks for the website,
http://tohtml.com/haskell/
I can now have haskell syntax highlight in my blog.
{- Match functions before call. Even type    -}
data WeekDay = Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday  deriving (Eq, Ord, Show, Read, Bounded, Enum)
workingDay::WeekDay -> Bool
workingDay Saturday = False
workingDay Sunday = False
workingDay _ = True
    
{-    The usage of @    -}
isSaturday::[WeekDay] -> String
isSaturday [] = "Empty!"
isSaturday [_] = "Only one"
isSaturday full@(reverse -> (y:_)) = if y == read "Saturday" 
                                        then show y ++ " is at the end of " ++ show full
                                        else "Not Saturday"

{-    Use where     -}
overC::(RealFloat a) => a -> a -> a -> String
overC a b c
    | rate > 1    = ">"
    | rate == 1 = "="
    | rate < 1    = "<"
    where rate = (a^2 + b^2)/c^2
            
{-    Use let        -}
sumToMax::Int -> Int
sumToMax maxV = let s = maxV
                in if s>0 then s + sumToMax (s-1)
                    else 0

{-    Pattern matching in function use case     -}
isMonday,isTuesday::WeekDay->String

isMonday wd = case wd of
                Monday -> "It is Monday."
                _    -> "It is not Monday."

isTuesday wd     | wd == Tuesday = "It is Tuesday"
                | otherwise = "It is not Tuesday"

{-    Mix up case with where -}
fridayZeroKiller::Int->WeekDay->String
fridayZeroKiller x wd = case wd of
                            Friday -> killEven x
                            _ -> "Busy on other day."
                            where     
                                killEven 0 = "Killed."
                                killEven _ = "I only kill zero."

2013年1月8日火曜日

WPF Drawing

A simple way to draw in wpf.
<Window x:Class="DrawingGroupDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        Width="525"
        Height="350">
    <Grid>
        <Image Width="200" Height="200">
            <Image.Source>
                <DrawingImage>
                    <DrawingImage.Drawing>
                        <DrawingGroup x:Name="DrawingGroup" />
                    </DrawingImage.Drawing>
                </DrawingImage>
            </Image.Source>
        </Image>
    </Grid>
</Window>
Draw it in code.
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Animation;
 
namespace DrawingGroupDemo
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DrawingContext dc = DrawingGroup.Open();
 
            // Draw a rectangle.
            dc.DrawRectangle(new SolidColorBrush(Colors.BurlyWood), new Pen(new SolidColorBrush(Colors.Coral), 10.0),
                             new Rect(new Size(100100)));
 
            // Draw a line.
            dc.DrawLine(new Pen(new SolidColorBrush(Colors.Chartreuse), 10.0), new Point(0.050.0),
                        new Point(100.050.0));
 
            // Draw text.
            dc.DrawText(
                new FormattedText("Hello"CultureInfo.CurrentCultureFlowDirection.LeftToRight,
                                  new Typeface(new FontFamily("Times New Roman"), FontStyles.NormalFontWeights.Black,
                                               FontStretches.Normal), 30.0new SolidColorBrush(Colors.Purple)),
                new Point(15.050.0));
 
            // Apply animation to ellipse center.
            AnimationClock animationClock =
                new PointAnimation(new Point(1.01.0), new Point(100.0100.0), new Duration(new TimeSpan(003)))
                    .CreateClock();
            dc.DrawEllipse(new SolidColorBrush(Colors.Aqua), new Pen(new SolidColorBrush(Colors.Orange), 2.0),
                           new Point(5.05.0), animationClock4.0null4.0null);
 
            // Close to activate. Or use "using DrawingGroup.Open()".
            dc.Close();
        }
    }
}

What Is An Event In C#


using System;
 
namespace EventDemo
{
    //Event handler is a type of delegate like the following. Only the parameter type is different.
    public delegate void ChangeHandler(string oldnamestring newname);
 
    public class MySystem
    {
        // An event is a delegate of the event handler type.
        public event ChangeHandler OnChanged;
        private string _name = "Microsoft";
 
        public string Name
        {
            get { return _name; }
            set
            {
                if (_name == valuereturn;
                // The system fires up the event inside by calling the delegates.
                // However the system does not care what is delegated.
                OnChanged(_namevalue);
                _name = value;
            }
        }
    }
 
    internal class Program
    {
        private static void Main(string[] args)
        {
            var sample = new MySystem();
            // We tell the system what the event should delegate. 
            sample.OnChanged += sample_OnChanged;
            // And we "accidentally" makes an event happens.
            sample.Name = "Google";
            Console.ReadLine();
        }
 
        // Only we know what to is the event delegated.
        private static void sample_OnChanged(string senderstring e)
        {
            Console.WriteLine("Name changed!");
        }
    }
}

2013年1月6日日曜日

Drap and Drop Shapes in WPF


using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
 
namespace DrapDropDemo
{
    public partial class MainWindow : Window
    {
        private bool isDragging;
 
        public MainWindow()
        {
            InitializeComponent();
 
            var rect = new Rectangle
                {
                    Width = 100,
                    Height = 100,
                    Fill = new SolidColorBrush(Colors.Chartreuse)
                };
            rect.MouseLeftButtonDown += rect_MouseLeftButtonDown;
            rect.MouseLeftButtonUp += rect_MouseLeftButtonUp;
            rect.MouseMove += rect_MouseMove;
            var canvas = new Canvas();
            canvas.Children.Add(rect);
            Content = canvas;
        }
 
        private void rect_MouseMove(object senderMouseEventArgs e)
        {
            if (!isDraggingreturn;
            var rect = sender as Rectangle;
            rect.SetValue(Canvas.LeftPropertye.GetPosition(rect.Parent as Canvas).X - rect.ActualWidth/2);
            rect.SetValue(Canvas.TopPropertye.GetPosition(rect.Parent as Canvas).Y - rect.ActualHeight/2);
        }
 
        private void rect_MouseLeftButtonUp(object senderMouseButtonEventArgs e)
        {
            isDragging = false;
            (sender as Rectangle).ReleaseMouseCapture();
        }
 
        private void rect_MouseLeftButtonDown(object senderMouseButtonEventArgs e)
        {
            isDragging = true;
            (sender as Rectangle).CaptureMouse();
        }
    }
}