月曜日, 4月 02, 2012

Javaの内部匿名クラスからローカル変数にアクセス

Javaの内部匿名クラスから、実はローカル変数にアクセスできたわけですね。

finalをつけておくとコンパイルできます。

(finalでなければコンパイルできません。)


 public class Closure
{
    class Test{};
    
    Closure()
    {
    final int i=0;
    (new Test()
    {
        void test()
        {
        System.out.println(i);
        }
        }).test();
    }

    public static void main(String args[])
    {
    Closure closure=new Closure();
    }
}

もちろん値は変更できません。:)


水曜日, 3月 14, 2012

PHP: get relative path expression

The following code calculate the difference of paths given and return a relative path expression.
 

function getCommonPos($s0,$s1) {   $len=strlen($s0);   $len1=strlen($s1);   if($len1<$len)     {       $len=$len1;     }   while($s0[$i]==$s1[$i] && ++$i<$len1);   return $i; } function diffStr($s0, $s1) {   $pos=getCommonPos($s0,$s1);   $end=strrpos(substr($s0,0,$pos),"\\");   return substr($s0,$end); } function countSlashes($str) {   return substr_count($str,"\\"); } function getRelativePath($p0,$p1) {   $p0=realpath($p0);   $p1=realpath($p1);   $dir=diffStr($p0,$p1);   if(!empty($dir))     {       $n=countSlashes($dir);       $path="";       for($i=0;$i<$n;$i++)     {       $path.="..";       if($i<$n-1)         {           $path.="\\";         }     }     }   $newDir=diffStr($p0,$p1);   $newDir=$path.$newDir;     if(empty($newDir))     $newDir=".";   return $newDir; }

日曜日, 3月 11, 2012

Creating bookmarks with Silhouette Cameo

As the Silhouette Cameo is here, I wrote a Java program to draw regular convex polygons and cut out shapes from paper.  The photo shows the final product, a bookmark.  You can put any of your design into 'production'.  With Silhouette Cameo, you get the final products right away. 



The Studio software detects the outline of shapes automatically.  The procedure would be as follows:

  1. Print out shapes with your own software or draw it with Studio.
  2. Select Object|Trace... from the menu. 
          

            
    1. Click the "Select Trace Area" button.
            
    2. Select the area of the figure.
            
    3. Select "Trace Outer Edge".
            
    4. The red line appears surrounding the image.
            
    5. Delete the original image.
            
    6. Edit the outline.  Typically you would want to "Edit Points" from the left column of the window.
            
    7. When the editing is done, click the Silhouette icon from the tool menu.
            
    8. Place the paper on the cutting mat and set it to the machine.
            
    9. Click "Cut" button when everything is ready.
           


Send any shapes to Silhouette and find designs of your choice.  Try cutting shapes and figure out balances and sizes that fit your needs.  

土曜日, 3月 10, 2012

Silhouette Cameo arrived

Silhouette Cameo, the cutting machine arrived yesterday.

Silhouette Cameo

This is the machine of the future. Basically what this machine does is to cut flat and thin materials in any shapes that you specify. It should cut anything paper made that you look at in our lives, including packages, cards, paper craft, etc.

Shamrock

What more, it can detect markings on a printed surface. Any figures that can be printed out on a piece of paper can be cut out. There are a lot of designs for 3D models made out of paper.


A word of caution is that creating cutting pattern can be a little tricky and time consuming. Very thin materials such as copy paper needs extra caution to take it off from the adhesive mat. Heavier thicker paper than copy paper would do a better job.

This paper cutting machine opens up great many fronts in many areas of technologies, sciences, and crafting. This is an excellent tool for education as well. Cut shapes would appeal more to students. The assembled 3D models is much more than the printed images of polygons. Printing out the images of makes 3D modeling not only makes it much more fun but means even more to students of science when it has three dimensions.

Free download of the Silhouette Cameo Studio is here: silhouettestudio

金曜日, 3月 02, 2012

Screen refresh trigger of an input element value or src change

To which extent does a browser redraw the screen?  Would an element's value change trigger refreshing the screen?  

It turns out to be that the Javascript's setting values of an element, actually does not trigger redrawing. 

document.getElementById("test").value="new value";

What puzzled me was, why then the browser redraw the screen in case with setting an img element's src?

document.getElementById("test").src="data:image/png;base64, ...";

This makes it trickier to implement functions that changes value, or src since the behavior will differ when you would want to retain some values for the session.  

I hit upon this problem when I tried to implement a div section that is shown and hidden at a trigger of pressing a button.  The functionality was implemented in the Javascript function and first I implemented it so that it alter the value of an input element.  It worked.  When you press the button, the Javascript function altered the value of the type='button' input element, without refreshing the screen, that is retaining all the variable values.  Then I switched it so that it would alter an image of an type='image' input element.  Now it does not work.  It reset and initialized the screen, namely to a certain initial state and not the state that was specified as. 

日曜日, 2月 19, 2012

Holiday thoughts; high-tech items of the (very near) future

There are four items that I want to purchase.  All of them, I feel the future; with the advancement of technology, or rather, the availability of it.  So much can be accomplished with the right idea, better concepts, and better management. 

One is, Raspberry Pi, a small Linux box that costs $25, or $35 with network connection.  Just at those prices, the full fledged net book equivalent machine power will be offered to so many people in the world.  The 'charitable' organizations offer them 'for educational purposes' -- never a Windows machine.  With its graphics chip that can connect to TV screens, however, this can be a game changer. 

Another is, Craft ROBO, a cutting plotter.  There are numerous other machines that cuts paper, plastic, vinyl sheets, and other materials, but this machine, cuts items that are drawn on your PC.  No cartridges, no nonsense about those black-boxes to set cut patterns.  Its software takes a figure, calculate the outline, and the machine cuts it out for you.  Unfortunately, the latest model is out of stock.  Its manufacturer, Graphtech Inc, says the new model would be coming in March 2012. 

The other is, iPad3 or Windows 8 tablet PC.  App-wise, the share number one is the Android machines, however.  The Windows 8 tablet PC on ARM is yet to come, reportedly in March. 

Lastly, it is the 3D printer.  There are many types of them; stacking shaped plastic lump, cutting out a shape from a resin block, or even binding composite powder layer by layer.  iModela might be the one, but I need more research on these.  Taking out a plastic material, shape them in the way that you like as in printing figures on paper, and use them as in any way that you like, in modeling for fun and for any other useful purposes in research and engineering, replaceable parts of an equipment anywhere, etc.

水曜日, 2月 15, 2012

PHP's overload: __call()

In my last blog, I wrote about PHP's get/set "overload", or hooking those methods for private members. There are more overloading method in PHP. The __call() method overload methods. This method "overloads" hidden member functions; including those methods that are non-existent. That is, you can create on the spot a brand new method just by calling __call().
class Test
{
  function __call($name,$parameter)
  {
    $value=$parameter[0];
    switch($name)
      {
      case "round":
        $value=round($value);
        break;
      case "floor":
        $value=floor($value);
        break;
      case "ceil":
        $value=ceil($value);
        break;
      }
    return $value;
  }
}

$test=new Test;
echo "Rounding: round(16.4) = ".$test->round(16.4);
echo "<br />";
echo "Floor: floor(16.4) = ".$test->floor(16.4);
echo "<br />";
echo "Ceiling: ceil(16.4) = ".$test->ceil(16.4);
echo "<br />";
This actually is a potential technological breakthrough -- in that the methods bears arbitrary names that are pseudo-defined and typed not dynamically then at programming time. This is a conceptual revolution in the programming. Remember, OOP is just a different form of C's structure.
Rounding: round(16.4) = 16
Floor: floor(16.4) = 16
Ceiling: ceil(16.4) = 17

月曜日, 2月 13, 2012

"Overload"? or hooking get/set in PHP

In PHP, there are a set of functions that hooks getting and setting private member variables.  When the variable is set, __set() method will be called.  When the variable is accessed, __get() method is called.  In PHP's terminology, hooking variable definition and retrieval are called overloading. 

class HookTest
{
private $a=1;

public function __get($name)
{
  echo "$name is being retrieved<br />";
  return $this->$name;
}

public function __set($name,$value)
{
  echo "$name is being set<br />";
  $this->$name=3;
}
}

echo "<pre>";

$test=new HookTest;
$test->a=2;
echo $test->a;

金曜日, 2月 10, 2012

Newline in select-option tags

Our site had a list of fonts available for our clients. The list included, European and Cyrillic fonts. We put them in a drop-down list.

List of fonts:
     European
     Cyrillic

Then, it turned out to be that Cyrillic fonts were included in European fonts. We had to select/deselect both at the same time. The trouble is, the HTML's select's option does not take br tags, or new lines. All lines have to be in a single line. Here is a jQuery code that select/deselect European and Cyrillic fonts at the same time. The code hooks any click on the European fonts to a handler that select/deselect Cyrillic fonts.
 
    $('#European').live("click",function(){
     var selected=$('#European').attr("selected");
     if(selected=="selected") 
  {
      $('#Cyrillic').attr("selected","selected");      
  }
     else
  {
      $('#Cyrillic').attr("selected",false);      
  }    
 });

Here is a word of caution; we had yet another problem with the Cyrillic option with the reset operation. The Cyrillic option has to be deselected manually.
 
    // de-selects the Cyrillic option.
    $("#reset").click(function(){
         $('#Cyrillic').attr("selected",false);      
 });

水曜日, 1月 25, 2012

同じエレメントを指定して、なぜか表示が変わらない。

スタイルシートというのは、いまだ原始的な形態を保ち続け、多少なりとも論理を重視するプログラマ人種にとっての頭痛の種といえるでしょう。進化を続けるネット世界で、基準を設定するのは至難の業、軍閥割拠のジャングルのなかで右往左往してサバイバルゲームを続けるしかない。

で、今日の話題はエレメントの指定方法。スタイルシートで、同じエレメントを指定して、なぜか表示が変わらない。

table.background tr td
{
background-color:red;
}
table.background td
{
background-color:blue;
}

赤い指定をオーバーライドしているのに、これが青くならない。

<table class="background">
<tr><td>test<td>test
<tr><td>test<td>test
</table>

上記のスタイルの指定をよく見てみると、エレメントの指定方法に違いがあります。なぜか tr タグの指定が効いてるんですね。構造を書くと、そちらが優先されるアルゴリズムであるわけです。

これが意味のある基準であるかどうかはさておいて、知っておかないと他人のスタイルシートを使うときに困ることは間違いなしです。

金曜日, 12月 30, 2011

Javascriptの多次元配列

やられましたね。これ。Javascriptの多次元配列。

var array=new Array();
array[0,0]=0;
array[1,0]=1;

alert(array[0,0]);
alert(array[1,0]);

結論的には、双方ともに1を表示します。

皆さんも気をつけましょう。

謹賀新年

月曜日, 12月 12, 2011

桁数を取得するコード

間違い探し、です。よくありそうな感じもしますが載せておきます。

ある数字の桁数を得たいとします。valに格納されていると仮定してください。

10進法であるか、16進法であるか、ベースはbaseで示すことにします。

  int index=1;
  while(val/=base && ++index<len);

一見これで桁数が出る... と思った方。

悩みましたね。これだと浮動小数点エラーが出ます。GCC使ってます。

知ってしまえばどうということはないことです。

ここであっさりと書いておきますが、オペレーターの優先順位の問題でした。

括弧で囲ってやると正常に機能します。

お騒がせしました。

金曜日, 11月 18, 2011

Multiple OS's causes DLL problems.

Theoretically -- is it a theory -- any program that runs on the particular Framework should run in the same way. But -- WINDOWS, how else could it be? The application does not find COM components and fails to initialize classes. Is it the issue of registry keys damaged by the installation?

After close monitoring of Windows event, it turned out that when multiple OS's are installed in a machine, the OS seems to assume C: drive even when the system is installed in other drives. The application looks for drivers -- but in which drive, is the question. The C: drive application looks for D: DLL's when E: application looks for E: DLL's. Either case does not work. Only the D: application with D: DLL's worked.

日曜日, 11月 13, 2011

OAuth

Twitter uses OAuth for id verification. The encryption of the data is
using HMAC-SHA1 algorithm.

HMAC, Keyed-Hashing for Message Authentication Code
hash((key xor 0x5c5c...5c)
or (key xor 0x3636...36)
or message)

SHA, Secure Hash Algorithm
SHA-1 160 bit, MD4 based encoding

水曜日, 11月 09, 2011

C#: FontDialog unable to set font sizes; Firefox 8

The FontDialog class of C# is not overridable to change its settings. There are flags to remove underline and strike options, but there is no ways to limit font styles nor font sizes.

However, C# is a language that has ready-to-use off-the-shelf components that can replace the font dialog with ones of your own.



The new features in Firefox 8:
- twitter search
- delay loading tabs at start ups (when you set it the opening screen)
- WebGL, HTML5 improvements

月曜日, 11月 07, 2011

C#: WebBrowser.DocumentText does not support the += operator

WebBrowser.DocumentText does not support the += operator.

That is it. It does not. The String class should be formatted separately and assigned to that member variable.

金曜日, 11月 04, 2011

C# DataGridView's SetValue

When a DataTable is set for a DataGridView, the value can not be set
to DataGridViewCellFormattingEventArgs.Value, which is passed by to a
method that is hooked to CellFormatting event.

The way to avoid it, is to access to the cell value directly.
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
  if(e.ColumnIndex==5)
    {
      // If set, the following will be shown in the cell.  The Cell's value typed as an int will not be set correctly.
      //e.Value = "1";
                        
      // Instead, directly access the Cell object.
      int row = e.RowIndex;
      int col = e.ColumnIndex;
      dataGridView1.Rows[row].Cells[col].Value = 1;
                   
      break;
    } 
}

木曜日, 10月 27, 2011

C#: TimeZoneInfo.GetSystemTimeZones()

TimeZoneInfo.GetSystemTimeZones() returns a reference to a same instance, no matter how many times it is called.

When the time zone list is added to combo boxes, they select the same values.

comboBox1.DataSource = TimeZoneInfo.GetSystemTimeZones();
comboBox2.DataSource = TimeZoneInfo.GetSystemTimeZones();

The Collection class must be copied to some other forms.

System.Collections.ObjectModel.ReadOnlyCollection list 
= TimeZoneInfo.GetSystemTimeZones();
TimeZoneInfo[] tzList = list.ToArray();
comboBox1.Items.AddRange(tzList);
comboBox2.Items.AddRange(tzList);

火曜日, 10月 18, 2011

Excel / VBA: type conversion from integer to text

Excel uses VBA for its macros. The programming language, or the formula format, differs. Whereas Excel uses "TEXT()" with a format string as its argument, VBA uses "CStr()" to convert types from integer to string.

月曜日, 10月 10, 2011

C# field initializers

C# differs from Java in that the field initializers must be static.

This is perfectly OK in Java.

public class InitTest
{
    int test=0;
    InitTestClass testClass=new InitTestClass(test);
    
    public static void main(String args[])
    {
 InitTest test=new InitTest(); 
    }
}

class InitTestClass
{
    int test=0;
    InitTestClass(int test)
    {
 this.test=test;
    }
}

The following code, however, is not (C#).

namespace InitTest
{
    class Program
    {
        int test = 0;
        // Error
        InitTestClass testClass = new InitTestClass(test);

        static void Main(string[] args)
        {
        }
    }

    class InitTestClass
    {
        int test = 0;
        public InitTestClass(int test)
        {
            this.test = test;
        }
    }
}

PHP: 定数を扱う

プロジェクトごとの定数を扱うクラス Config\Constants の紹介です。 <?php namespace Config; class Constants {     public const DB_USER = "linguist...