はてなキーワード: Consoleとは
http://mame8814.blog87.fc2.com/blog-entry-574.html
その他参考サイト
http://optimizationtheory.blog.fc2.com/blog-entry-105.html
https://ask.fm/mame8814/answers/118473784982
http://lq9u5t.blogspot.jp/2015/05/csgo_21.html
http://steamcommunity.com/app/730/discussions/0/666828127037750832
マジレスすると、U+00a5なら使える。俺なら設計を修正させるけど。
Path.GetInvalidFileNameChars メソッド (System.IO)
using System; using System.IO; namespace TestInvalidFileName { class Program { static void Main(string[] args) { // Get a list of invalid file characters. char[] invalidFileChars = Path.GetInvalidFileNameChars(); Console.WriteLine("The following characters are invalid in a filename:"); ShowChars(invalidFileChars); Console.WriteLine(); string fileName = '\u00a5' + "108"; using (var fs = File.Create(fileName)) { if (fs != null) { Console.WriteLine("File was created:" + fileName); fs.Close(); } else { Console.WriteLine("File was not created:" + fileName); } } } public static void ShowChars(char[] charArray) { Console.WriteLine("Char\tHex Value"); // Display each invalid character to the console. Array.Sort(charArray); foreach (char someChar in charArray) { if (Char.IsWhiteSpace(someChar)) { Console.WriteLine(",\t{0:X4}", (int)someChar); } else { Console.WriteLine("{0:c},\t{1:X4}", someChar, (int)someChar); } } } } }
The following characters are invalid in a filename: Char Hex Value (中略) ", 0022 **, 002A /, 002F :, 003A >, 003C >, 003E ?, 003F \, 005C |, 007C File was created:\108
こういうのを望んでいるなら、不可能。
var i = 10; [1,2,3, ... ,99,100].each(function(i) { // 何かの処理 }); console.log(i); // 10と出て欲しい
jashkenasはこう主張している
if they do clash, shadowing the variable is the wrong answer. It completely prevents you from making use of the original value for the remainder of the current scope. Shadowing doesn't fit well in languages with closures-by-default ... if you've closed over that variable, then you should always be able to refer to it.
衝突が起こるとしても、変数の隠蔽(shadowing)は間違った解決法だ。スコープ内のその他のすべての変数に関して、オリジナルの値の利用を完全に塞いでしまう。隠蔽は、クロージャが標準(closures-by-default)な言語にはうまくマッチしない。その変数を閉じ込めているならば、常に参照出来るべきだ。
ソース:http://www.sixapart.jp/techtalk/2012/01/coffeescript.html
はてな One が始まってから 7 か月。こんなに使えば使うほど発見があったサービスはありませんでした。クローズドなコミュニケーションって本当に楽しい!ってことを思い出させてくれました。ありがとうはてな One!さようならはてな One!
プログラムはclassに記述します。たとえばSampleという名前のclassを作る場合、Sample.csファイル内に次のように書きます。(C#の場合、ファイル名とクラス名は同一でなくても良い。複数のクラスを書いても良い)
public class Sample { }
プログラムはclass内のMainメソッドの先頭から実行されます。Mainメソッドは次のように書きます。
public class Sample { public static void Main( String[] args ) { // 処理を書く } }
Console.WriteLine( "Hello world" );
コメントです。
// 一行コメント /* 複数行コメント */
// 変数 int num;
データ型です。C#のデータ型には値型と参照型とがあります。以下は値型のデータ型です。
// int(整数)型 int num; // char(文字)型 char c; // float(単精度浮動小数点)型 float val; // double(倍精度浮動小数点)型 double val; // bool(論理)型 bool flag; // DateTime(日付)型 DateTime date;
以下は参照型のデータ型です。
// String型 String s; // 配列型 String[] array;
プログラムをコンパイルするには、コマンドラインで以下のようにします。
csc Sample.cs
プログラムを実行するには、コマンドラインで以下のようにします。
Sample.exe
mono ./Sample.exe
int、float、double型の変数に数値を代入できます。int型には整数だけ代入できます。float、double型には整数でも小数でも代入できます。
int i = 2; int i = 100000000; float num = 1.234f; double num = 1.234;
四則演算です。
num = 1 + 1; num = 1 - 1; num = 1 * 2; num = 1 / 2;
商の求め方です。割る数と割られる数が両方とも整数の場合、計算結果の小数点以下が切り捨てられます。
num = 1 / 2; // 0
割る数と割られる数のどちらかが小数の場合、計算結果の小数点以下が切り捨てられません。
num = 1.0 / 2; // 0.5 num = 1 / 2.0; // 0.5 num = 1.0 / 2.0; // 0.5
余りの求め方です。
// 余り mod = 4 % 2
インクリメントとデクリメントです。
// インクリメント ++i; // デクリメント --i;
String str = "abc";
// 結合 String join = "aaa" + "bbb"; // 分割 String[] record = "aaa,bbb,ccc".Split( "," ); // 長さ int length = "abcdef".Length(); // 切り出し "abcd".Substring( 0, 2 ) // abc // 検索 int result = "abcd".IndexOf( "cd" ) // 見つかった場合はその位置、見つからなかった場合は-1が返る
配列です。
// 配列の宣言 int[] array;
配列の生成です。配列の生成時には要素数を指定するか、初期データを指定します。
int[] array; // 要素数を指定して配列を生成 array = new int[5]; // 初期データを指定して配列を生成 array = new int[] { 1, 2, 3 }; // 宣言と同時に配列を生成 int[] array2 = new int[5];
配列の要素の参照と代入です。
// 要素の参照 array[0] array[1] // 要素の代入 array[0] = 1; array[1] = 2;
array_num = array.Length;
int[] from = new int[] { 1, 2, 3 }; int[] to = new int[5]; from.CopyTo(to, 0);
if文です。
if ( 条件 ) { }
if ~ else文です。
if ( 条件 ) { } else { }
if ~ else if文です。
if ( 条件 ) { } else if ( 条件 ) { }
while文です。
int i = 0; while ( i < 5 ) { // 処理 ++i; }
for文です。
for ( int i = 0; i < 5; ++i ) { // 処理 }
int[] fields = new int[] { 1, 2, 3 }; foreach (int field in fields) { // 処理 }
C#では関数をメソッドと言います。メソッドを作るには次のようにします。戻り値を返却するにはreturn文を使います。
static int sum( int num1, int num2 ) { int total; total = num1 + num2; return total; }
ファイル入出力です。ファイル入出力を行うには、プログラムの先頭に以下を記述します。
using System.IO;
以下がファイル入力の雛形になります。ファイルのオープンや読み込みに失敗した場合、catch節に処理が移ります。
String filename = "text.txt"; StreamReader reader = null; try { reader = new StreamReader(filename); String line; while ((line = reader.ReadLine()) != null) { } } catch (IOException e) { // エラー処理: } finally { if (reader != null) { try { reader.Close(); } catch (IOException e) { } } }
またはC#ではusing ステートメントと言うものがあり、この様にも書ける
String filename = "text.txt"; using (StreamReader reader = new StreamReader(filename)) { try { String line; while ((line = reader.ReadLine()) != null) { // 読み込んだ行を処理 } } catch (IOException e) { // エラー処理: } }
usingをつかうとCloseがなくなったことからわかるようにusing(){}を抜けるときに自動的にDisposeメソッドを呼び出し、オブジェクトを廃棄する。その分コードがスッキリするが、使いにくい場面もあるので考えて使うこと。
以下がファイル出力の雛形になります。ファイルのオープンや書き込みに失敗した場合、catch節に処理が移ります。
String filename = "text.txt"; StreamWriter writer = null; try { writer = new StreamWriter(filename)); writer.WriteLine("abc"); writer.WriteLine("def"); writer.WriteLine("fgh"); } catch (IOException e) { // エラー処理: } finally { if (writer != null) { writer.Close(); } }
こちらもusingを使って書ける。が、割愛する。
C#でよく出てくる知っておいたほうがよい文法の一覧です。
繰り返し文の途中で抜けるにはbreak文を使用します。
for ( i = 0; i < 5; ++i ) { if ( 条件 ) { break; // 条件を満たす場合、for文を抜ける。 } }
残りの部分処理をスキップし、次の繰り返しに進むにはcontinue文を使用します。
for ( i = 0; i < 5; ++i ) { if ( 条件 ) { continue; // 条件を満たす場合、残りの部分処理をスキップし、次の繰り返しに進む。 } }
例外を投げるにはthrow文を使用します。
throw new Exception( "Error messsage" );
try { // 例外が発生する可能性のある処理 } catch ( Exception e ) { // 例外発生時の処理 }
■ C
for( const char *s="12345"; *s; ++s ) if( '2'<*s&&*s<'5' ) printf( "%d", (*s-'0')*2 );
console.log([1,2,3,4,5].filter(function (i){ return (i > 2 && i < 5 ); }).map(function(i){ return 2 * i; }));
■ Python
print(map(lambda x: x*2, filter(lambda x: x>2 and x<5, [1,2,3,4,5])))
■ Ruby
puts [1,2,3,4,5].select{|i| i > 2 and i < 5}.map{|i| i*2}
■ C#
new{}{ 1,2,3,4,5 }.Where(x => 2 < x && x < 5).Select(x => x*2);
(print (loop for x in '(1 2 3 4 5) if (< 2 x 5) collect (* x 2)))
■ Haskell
print [x*2| x <-[1,2,3,4,5], x > 2, x < 5]
■ J
■ R
print((function(){x<-c(1,2,3,4,5);x[2<x&x<5]*2})())</p>
■ Clojure
(print (for [x [1,2,3,4,5] :when (< 2 x 5)] (* x 2)))
(1 to: 5) select: [:x | x between: 3 and: 4] thenCollect: [:x | x * 2]
class MyClass constructor: -> name = 'unknown' @getName = -> return name @setName = (newName) -> name = newName MyClass:: = do -> _greet = -> console.log('どうも、' + @getName() + 'です。') return { constructor: MyClass greet: _greet } myInstance = new MyClass() myInstance.setName('純子') myInstance.greet() #どうも、純子です。
CoffeeScript で @なんとかのプロパティが全部パブリックになるのが気になってて。
Windows 7 - Firefox 8.0 - Norton Internet Security(NIS) 2011 の場合。
(xはバージョン番号)
1. NIS - 設定 - その他の設定 - 製品セキュリティ で「Norton製品の改変対策」を「OFF」にする。
2. C:\ProgramData\Norton\{0C55C096-0F1D-4F28-AAA2-85EF591126E7}\NIS_xx.x.x.x\
・coFFPlgn_xxxx_x_x_x → coFFPlgn_xxxx_x_x_xOLD
・IPSFFPlgn → IPSFFPlgnOLD
※WindowsXPでは C:\Documents and Settings\All Users\Application Data\Norton\{0C55C096-0F1D-4F28-AAA2-85EF591126E7}\NIS_xx.x.x.x\ (未確認)
元に戻したい時は、リネームしたフォルダを戻して「Norton製品の改変対策」を「ON」にする。
なお、OSを再起動するとフォルダが強制的に作成されるようなので、その都度2.の実施が必要。
C:\Program Files\Mozilla Firefox\extensions\
P.340
・パスにスペースの入らない(たとえば、My Documentsなどは、途中にスペースが入っているのでエラーになる。アンダーバー「_」は可。)
フォルダ(C\Testなど)を作る。 →以下フォルダAとする。
2/ 実行ファイルを作りたいスクリプト(○○.rb)ファイル自体も、2バイト文字、半角でもスペースの入らないファイル名にする。
→「5-05-04 ride block.rb」といったファイル名は、スペースが入っているのでダメ。
3/ フォルダAに、ActiveScriptRubyをインストールするとできる「ruby console」ショートカット(everythingで検索)のショートカットを、そのフォルダにコピーする。
4/ フォルダAに、実行ファイルを作りたいスクリプト(○○.rb)を、Imgフォルダ等と共にコピーする。
5/ フォルダAに、fontを、fontsフォルダごとコピーする。
6/ フォルダAに、Ruby/SDLのDLLをそのフォルダにコピーする。15種類。
→DLLフォルダを、ではなく、exeファイルの置かれる場所に、DLLファイルそのものを直接並べる。
フォルダAにコピーしたruby consoleを起動 →コマンドプロンプトの後に、「ruby ○○.rb」とし、スクリプトの起動を確認する。
8/ フォルダAにコピーしたruby consoleを起動 →コマンドプロンプトの後に、「mkexy ○○.rb」とする。
→ゲームが起動するので、終了させる。
9/ ○○.exy ファイルを、メモ帳等のテキストエディタで開く
10/ 初期値は「core: cui」となっているのを、「core: gui」に変える。
→変えなくてもいいが、その場合、実行時にコマンドプロンプト窓が出てきて邪魔になる。
11/ フォルダAにコピーしたruby consoleを起動 →コマンドプロンプトの後に、「exerb ○○.exy」←今作ったファイル とする。
12/ 「○○.exe」をダブルクリックして実行、起動しなかった場合、2~5のプロセスに、コピーし忘れがある。
13/ 配布物は以下の通り。
・実行ファイル「○○.exe」 →ファイル名は任意に変更可。(もちろん.exe以外の名前)
・fontsフォルダ
http://anond.hatelabo.jp/20110316202255
亀仙流やつ鶴仙流など、世の中にはいくつかの流派があり、それぞれ カメハメ波やドドン波、舞空術などの技(メソッド)がある。 実際に技を使う場合、技を覚えているZ戦士(インスタンス)が必要。
クラス = 流派
メソッド = 技
インスタンス = Z 戦士
というのはおもしろいと思うし, 例えばゲームを作るなら実際にそういう実装になると思う.
例)セルを作りましょう。 class Cell extends Goku,Veget,Picoro,Tenshinhan,Kuririn{ .... } cell_inst = new Cell(); cell_inst.shotKienzan(); //Kuririnをextendsしているので気円斬が使えます。
しかし, ここではクラス = Z 戦士になってしまっているので, 混乱を招くだろう.
むしろ, 「JavaScript における prototype」 に絞って説明するのはどうだろう.
(ついでに「撃つ」の現在形は shot でなく shoot ですね)
var Goku = function () {}; Goku.prototype.shootKamehameha = function () { console.log("波!!!"); }; var goku = new Goku; goku.shootKamehameha(); // 波!!! var Gohan = function () {}; Gohan.prototype = new Goku; var gohan = new Gohan; gohan.shootKamehameha(); // 波!!!
そしてセルによる吸収は, 動的な継承として考えるのがより自然だろう.
var Goku = function () {}; Goku.prototype.shootKamehameha = function () { console.log("波!!!"); }; var Vegeta = function () {}; Vegeta.prototype.shootBigBangAttack = function () { console.log("ビッグバンアタック!!!"); }; var Cell = function () {}; // 吸収メソッド Cell.prototype.absorb = function (target) { for (var method in target) { this[method] = target[method]; } }; var goku = new Goku; var vegeta = new Vegeta; var cell = new Cell; cell.absorb(goku); // 悟空を吸収 cell.absorb(vegeta); // ベジータを吸収 cell.shootKamehameha(); // 波!!! cell.shootBigBangAttack(); // ビッッグバンアタック!!!
そして次にクロージャの使用例として挙げられた次の例.
例)連続エネルギー波 var shotRenzokuEnergy = function( count ){ var shotEnergy = function(){ //エネルギー波を放ちます }; for(var i=0;i<count;i++){ shotEnergy(); } };
この実装では, shotRenzokuEnergy を実行するたびに shotEnergy が毎回定義されてしまい, 非効率である.
以下のように書き換えることで, shootEnergy の定義は, shootRenzokuEnergy の定義時の 1 回のみとなる.
var shootRenzokuEnergy = (function () { var shootEnergy = function () { console.log("エネルギー波!!!"); }; return function (count) { for (var i = 0; i < count; i++) { shootEnergy(); } }; })(); shootRenzokuEnergy(10); // エネルギー波!!! x 10
http://okajima.air-nifty.com/b/2011/01/2011-ffac.html
ぷよぷよを解く問題をやってみた
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { StringBuilder[] blocks = { new StringBuilder("**GYRR"), new StringBuilder("RYYGYG"), new StringBuilder("GYGYRR"), new StringBuilder("RYGYRG"), new StringBuilder("YGYRYG"), new StringBuilder("GYRYRG"), new StringBuilder("YGYRYR"), new StringBuilder("YGYRYR"), new StringBuilder("YRRGRG"), new StringBuilder("RYGYGG"), new StringBuilder("GRYGYR"), new StringBuilder("GRYGYR"), new StringBuilder("GRYGYR") }; bool updated = true; while (updated) { breaked: DumpBlock(blocks); for (int i = 0; i < blocks.Length; i++) { for (int j = 0; j < blocks[i].Length; j++) { char c = blocks[i][j]; if (c == '*') continue; updated = false; if (KillBlocks(blocks, i, j)) { updated = true; goto breaked; } } } } DumpBlock(blocks); Console.Read(); } struct Point { public int x, y; public Point(int x, int y) { this.x = x; this.y = y; } } static bool KillBlocks(StringBuilder[] blocks, int x, int y) { bool[,] visted = new bool[blocks.Length,blocks[0].Length]; MarkBlock(visted, blocks, x, y); Queue<Point> queque = new Queue<Point>(); for (int i = x; i < blocks.Length; i++) for (int j = y; j < blocks[i].Length; j++) if(visted[i,j] == true) queque.Enqueue(new Point(j,i)); if (queque.Count < 4) return false; while (queque.Count > 0) { Point p = queque.Dequeue(); RemoveBlock(blocks, p.x, p.y); } return true; } static void MarkBlock(bool[,] visted, StringBuilder[] blocks, int x, int y) { if (x < 0 || y < 0 || x >= blocks.Length || y >= blocks[0].Length || visted[x, y] == true) return; char c = blocks[x][y]; visted[x, y] = true; if (x + 1 < blocks.Length && blocks[x + 1][y] == c) MarkBlock(visted, blocks, x + 1, y); if (y + 1 < blocks[0].Length && blocks[x][y + 1] == c) MarkBlock(visted, blocks, x, y + 1); if (x > 0 && blocks[x - 1][y] == c) MarkBlock(visted, blocks, x - 1, y); if (y > 0 && blocks[x][y - 1] == c) MarkBlock(visted, blocks, x, y - 1); } static void DumpBlock(StringBuilder[] blocks) { foreach (StringBuilder s in blocks) Console.WriteLine(s); Console.WriteLine(); } static void RemoveBlock(StringBuilder[] blocks,int x,int y) { int i; if (y == 0) { blocks[y][x] = '*'; return; } for (i = y; i > 0; i--) { blocks[i][x] = blocks[i - 1][x]; } blocks[i][x] = '*'; } } }
http://okajima.air-nifty.com/b/2010/01/post-abc6.html
迷路の最短経路を求める問題が出たので解いてみた
幅優先探索を使えばいいのがわかっていたのですんなりかけたのだが、無限ループになる個所があったので動くようになるまで時間がかかった
using System; using System.Collections.Generic; using System.Text; using System.Linq; namespace MazeFind { class Point { public int x; public int y; public Point before; public Point(int x, int y,Point before) { this.x = x; this.y = y; this.before = before; } } class Program { static void Main(string[] args) { const char BreakChar = 'B'; const char GoalChar = 'G'; const char WallChar = '*'; const char BeforeChar = '.'; StringBuilder[] maze = new StringBuilder[]{ new StringBuilder("**************************"), new StringBuilder("*S* * *"), new StringBuilder("* * * * ************* *"), new StringBuilder("* * * ************ *"), new StringBuilder("* * *"), new StringBuilder("************** ***********"), new StringBuilder("* *"), new StringBuilder("** ***********************"), new StringBuilder("* * G *"), new StringBuilder("* * *********** * *"), new StringBuilder("* * ******* * *"), new StringBuilder("* * *"), new StringBuilder("**************************"), }; Point start = new Point(1, 1,null); //最短経路を探索する Queue<Point> queque = new Queue<Point>(); queque.Enqueue(start); while (queque.Count > 0) { Point now = queque.Dequeue(); if (maze[now.y][now.x] == BreakChar) Console.WriteLine("break"); if (maze[now.y][now.x] == WallChar || maze[now.y][now.x] == BeforeChar) continue; else if (maze[now.y][now.x] == GoalChar) { Point p = now.before; while (p != null) { maze[p.y][p.x] = '@'; p = p.before; } break; } if (maze[now.y - 1][now.x] != '#') { queque.Enqueue(new Point(now.x, now.y - 1, now)); maze[now.y][now.x] = '.'; } if (maze[now.y][now.x + 1] != '#') { queque.Enqueue(new Point(now.x + 1, now.y, now)); maze[now.y][now.x] = '.'; } if (maze[now.y + 1][now.x] != '#') { queque.Enqueue(new Point(now.x, now.y + 1, now)); maze[now.y][now.x] = '.'; } if (maze[now.y][now.x - 1] != '#') { queque.Enqueue(new Point(now.x - 1, now.y, now)); maze[now.y][now.x] = '.'; } } //結果を出力する foreach (StringBuilder s in maze) Console.WriteLine(s.ToString().Replace(BeforeChar,' ')); Console.ReadLine(); } } } <||
さてどこから消すか
これで40分。
タイムアタックってことでアルゴリズムは全幅探索で書き上げました。
エラーチェック皆無。
A*ならもう5分ほど延びるかな?
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace Maze { class Program { // 探索用地図 static int[,] maze; // 始点終点 static Position Start = new Position(0, 0), Goal = new Position(0, 0); static void Main(string[] args) { //////////////////////////// まずは各行のリストとして読み込み string[] inMaze; using (var fp = new FileStream(args[0], FileMode.Open, FileAccess.Read)) using (var iStream = new StreamReader(fp)) inMaze = iStream.ReadToEnd().Split('\n'); // 迷路幅 int height = inMaze.Length; // 迷路高さ int width = inMaze[0].Length; /////////////////////////// 読み込んだ迷路を作業用地図に展開 maze = new int[width, height]; for (int y = 0; y < height; ++y) { string line = inMaze[y]; for (int x = 0; x < line.Length; ++x) { maze[x, y] = line[x] == '*' ? -1 : 0; if (line[x] == 'S') Start = new Position(x, y); if (line[x] == 'G') Goal = new Position(x, y); } } // 探索実行 int dist = Search(maze, Start); // 探索結果から最短経路を再現 Position backTracer = Goal; while (dist>1){ --dist; backTracer = backTracer.Nearbys.First(pos => maze[pos.X,pos.Y] == dist); maze[backTracer.X, backTracer.Y] = -2; } //////////////////// 最短経路こみのアスキー地図に変換 char[,] outMaze = new char[width, height]; for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { outMaze[x, y] = maze[x, y] == -2 ? '$' : maze[x, y] == -1 ? '*' : ' '; } } outMaze[Start.X, Start.Y] = 'S'; outMaze[Goal.X, Goal.Y] = 'G'; ////////////////////// 結果は標準出力に。 for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) Console.Write(outMaze[x, y]); Console.WriteLine(); } Console.ReadLine(); } /// <summary> /// 探索する。SG間の道のりを返す(道のり=SGが隣接しているなら1) /// </summary> private static int Search(int[,] maze, Position Start) { List<Position> FrontLine = new List<Position>(); FrontLine.Add(Start); int dist = 1; for (; ; ) { List<Position> NextFrontLine = new List<Position>(); foreach (var pos in FrontLine) { foreach (var nextPos in pos.Nearbys) { if (nextPos == Goal) return dist; if (maze[nextPos.X, nextPos.Y] == 0) { maze[nextPos.X, nextPos.Y] = dist; NextFrontLine.Add(nextPos); } } } FrontLine = NextFrontLine; ++dist; } } } struct Position { public readonly int X, Y; public Position(int x, int y) { X = x; Y = y; } public IEnumerable<Position> Nearbys { get { return new[]{ new Position(X-1,Y), new Position(X,Y-1), new Position(X+1,Y), new Position(X,Y+1), }; } } public static bool operator==(Position p1, Position p2){ return p1.X == p2.X && p1.Y == p2.Y; } public static bool operator!=(Position p1, Position p2){ return p1.X != p2.X || p1.Y != p2.Y; } } }
http://d.hatena.ne.jp/j5ik2o/20091024/1256369305 の
// 1.0 - 9 * 0.1 BigDecimal b1 = new BigDecimal(1.0); BigDecimal b2 = new BigDecimal(-9); BigDecimal b3 = new BigDecimal("0.1"); BigDecimal result = b1.add(b2.multiply(b3)); System.out.println(result.toString());
を見て悲しくなった。Javaってひどい。0.1は文字列で渡さないと誤差が出るってさ。泣ける。
C#なら
Console.WriteLine( 1.00M - 9M * .10M );
でOK
http://snowleopard.wikidot.com/ に載ってるのも試してみた。
ねとらじ用アプリが全滅で残念。
if("0x0a" == 10) console.log("おっと、javascriptの悪口はそこまでだ。"); if("0x0a" === 10) console.log("(´ε` )チュッ"); else console.log("\(^o^)/");
Deploy Merb, Sinatra, or any Rack App to Heroku
http://blog.heroku.com/archives/2009/3/5/32_deploy_merb_sinatra_or_any_rack_app_to_heroku/
http://heroku.com/pages/quickstart
HerokuをGit経由で使ってみる
http://d.hatena.ne.jp/aki-s-119/20081110/1226335713
http://github.com/guides/using-git-and-github-for-the-windows-for-newbies
http://d.hatena.ne.jp/kusakari/20080715/1216091060
http://code.google.com/p/msysgit/
http://net-newbie.com/putty.html
>heroku help === General Commands help # show this usage list # list your apps create [<name>] # create a new app keys # show your user's public keys keys:add [<path to keyfile>] # add a public key keys:remove <keyname> # remove a key by name (user@host) keys:clear # remove all keys === App Commands (execute inside a checkout directory) info # show app info, like web url and git repo open # open the app in a web browser rename <newname> # rename the app sharing:add <email> # add a collaborator sharing:remove <email> # remove a collaborator domains:add <domain> # add a custom domain name domains:remove <domain> # remove a custom domain name domains:clear # remove all custom domains rake <command> # remotely execute a rake command console <command> # remotely execute a single console command console # start an interactive console to the remote restart # restart app servers logs # fetch recent log output for debugging logs:cron # fetch cron log output bundles # list bundles for the app bundles:capture [<bundle>] # capture a bundle of the app's code and dat bundles:download # download most recent app bundle as a tarba bundles:download <bundle> # download the named bundle bundles:animate <bundle> # animate a bundle into a new app bundles:destroy <bundle> # destroy the named bundle destroy # destroy the app permanently === Example story: rails myapp cd myapp (...make edits...) git init git add . git commit -m "my new app" heroku create myapp git remote add heroku git@heroku.com:myapp.git git push heroku master
http://kenz0.s201.xrea.com/weblog/2008/10/post_144.html
を見て
http://anond.hatelabo.jp/20061209160227
を思い出して
に行く。
この間どっかの記事で見つけて(これ自体は数年前から海外では言われていたことだが)ターゲットを探そうと頑張ってたんだけどいろいろと理由があってここで公開することにする。
javascriptは以下のようにコンストラクタを再定義できる。
function Array() { var obj = this; var ind = 0; var getNext = function(x) { obj[ind++] setter = getNext; if (x) { console.log(x.toString());//細工。 } }; this[ind++] setter = getNext; }
実はこれが問題で例えば、配列を含むオブジェクトをJSONで渡す際に必ずArrayコンストラクタが呼び出される。
上記のように少し細工をしておけばcallbackとかついてなくても内容を処理できるのでクロスドメイン対策がされている場合でもJSONからデータを読み取ることが出来る。
余談だが、Gmailなどではこれを回避するためにwhile 1を先頭につけることで無限ループさせている。
http://anond.hatelabo.jp/20071030034313 の二番煎じ
あまりのアホさに、作ってて気が狂いかけた
方針
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.IO; using System.Reflection; using Microsoft.CSharp; delegate void ConvertTemplateDelegate(TextWriter tw, Dictionary<object, object> args); static class TemplateGenerator { public static ConvertTemplateDelegate Generate(string code) { CompilerParameters param = new CompilerParameters(); param.GenerateInMemory = true; param.ReferencedAssemblies.Add("System.Web.dll"); CompilerResults rs = new CSharpCodeProvider().CompileAssemblyFromSource(param, ParseTemplate(code)); if (0 < rs.Errors.Count) { StringWriter sw = new StringWriter(); sw.WriteLine("Compile Error..."); foreach (CompilerError err in rs.Errors) sw.WriteLine(err.ToString()); throw new Exception(sw.ToString()); } return (ConvertTemplateDelegate) Delegate.CreateDelegate(typeof(ConvertTemplateDelegate), rs.CompiledAssembly.GetType("Template", true).GetMethod("Convert")); } private static string ParseTemplate(string code) { using (StringWriter sw = new StringWriter()) { sw.WriteLine("using System; using System.Collections.Generic; using System.IO; using System.Web;"); sw.WriteLine("public static class Template {"); sw.WriteLine("public static void Convert(TextWriter tw, Dictionary<object, object> args) {"); int index = 0; while (0 <= index && index < code.Length) { int i = code.IndexOf("<%", index); sw.WriteLine("tw.Write(\"{0}\");", EscapeString(i < 0 ? code.Substring(index) : code.Substring(index, i - index))); if (0 <= i) { i += 2; int i2 = code.IndexOf("%>", i); if (0 <= i2) { string cc = code.Substring(i, i2 - i); if (cc.StartsWith("=")) sw.WriteLine("tw.Write(HttpUtility.HtmlEncode(\"\"+({0})));", cc.Substring(1)); else sw.WriteLine(cc); i = i2 + 2; } } index = i; } sw.WriteLine("}}"); return sw.ToString(); } } private static string EscapeString(string code) { return code.Replace("\\", "\\e").Replace("\"", "\\\"").Replace("\t", "\\t").Replace("\n", "\\n").Replace("\r", "\\r").Replace("\\e", "\\\\"); } }
サンプル C# コード。ためしにテンプレートから Xml 生成して、標準出力してみる。
class Program { static void Main(string[] args) { ConvertTemplateDelegate func = TemplateGenerator.Generate(TemplateEngine.Resource1.template); using (StringWriter sw = new StringWriter()) { Dictionary<object, object> arg = new Dictionary<object, object>(); arg["title"] = "template sample"; arg["data"] = new string[] { "foo", "fooo", "<strong>foooooooooo!</strong>" }; func(sw, arg); Console.WriteLine(sw); } } }
サンプルテンプレート
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title><%= args["title"] %></title> </head> <body> <h1><%= args["title"] %></h1> <table> <% string[] data = (string[]) args["data"]; %> <% for(int i = 0; i < data.Length; i++) { %> <tr bgcolor="<%= i % 2 == 0 ? "#FFCCCC" : "#CCCCFF" %>"> <td><%= i %></td> <td><%= data[i] %></td> </tr> <% } %> </table> </body> </html>
出力例
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>template sample</title> </head> <body> <h1>template sample</h1> <table> <tr bgcolor="#FFCCCC"> <td>0</td> <td>foo</td> </tr> <tr bgcolor="#CCCCFF"> <td>1</td> <td>fooo</td> </tr> <tr bgcolor="#FFCCCC"> <td>2</td> <td><strong>foooooooooo!</strong></td> </tr> </table> </body> </html>
CodeDom 使って動的コンパイル……って、このコードのままだとセキュリティ的に大問題な気がするな。
素直に ASP.NET 使ったほうが楽だと直感した。
あと EscapeString すっごく自信ない。たぶん修正が必要だと思うw