プログラマメモ2 - programmer no memo2

さあえびせでぃっくその2 2010/09/23

さあEBCDICその2


の表をもとに、バイトを読めるように変換してみます。
wikipediaの表をもとにして、文字列を連結して、配列にみたてて変換してるだけです。

これで無理くり読めるようにはなるのかな...

package d;

import java.io.UnsupportedEncodingException;

public class TestEBCDIC2 {

public static void main(String[] args) throws UnsupportedEncodingException {
b();
}

static void b() throws UnsupportedEncodingException {
int[] bs = { 0xC7, 0xF4, 0xF0, 0xF1 };//G401と表示されることを期待している
for (int b : bs) {
System.out.print("[" + EBCDIC(b) + "]");
}
}

/**
* EBCDIK?からの変換
* 制御文字は考慮してない。
* @param b
* @return
* @throws UnsupportedEncodingException
*/
static String EBCDIC(int b) throws UnsupportedEncodingException {
// System.out.printf("%d %d %d %n", 0x40, pos, 0xf9);
if (b < 0x40 || 0xf9 < b)
return "";
String BASE = " 。「」、・ヲァィ¢.<(+│&ゥェォャュョッーア!$*);¬-/イウエオカキクケ|,%_>?コサシスセソタチツ`:#@'=\"テabcdefghiトナニヌネノハjklmnopqrヒフヘホマミム~stuvwxyzメモヤユヨラリルレロワン゛゜ {ABCDEFGHI }JKLMNOPQR \\ STUVWXYZ 0123456789 ";
char[] cs = BASE.toCharArray();
String s = Character.toString(cs[b - 0x40]);
return s;
}
}

さあEBCDIC 2010/09/23

文字コードです。
世の中人知れず、文字コードで悩み苦しんでいる人がたくさんいるのだなーと思う今日この頃です。
時間にするとかなりな時間になるのだろうなーと思います。
僕の知らないところで規格を考えている人たちに敬意を表します。

EBCDICというのがあるそうです。



wikipediaをちらちら見てますと、ホストコンピュータというのはぜんぶIBM起源なのですかね?

wikipediaにあった表を変換してます。

NUL SOH STX ETX SEL HT RNL DEL GE SPS RPT VT FF CR SO/LS1 SI/LS0
DLE DC1 DC2 DC3 RES/ENP NL BS POC CAN EM UBS CU1 IFS IGS IRS IUS/ITB
DS SOS FS WUS BYP/INP LF ETB ESC SA SFE SM/SW CSP MFA ENQ ACK BEL
(予約) (予約) SYN IR PP TRN NBS EOT SBS IT RFF CU3 DC4 NAK (予約) SUB
sp 。 「 」 、 ・ ヲ ァ ィ ¢ . < ( + │
& ゥ ェ ォ ャ ュ ョ ッ ー ア ! $ * ) ; ¬
- / イ ウ エ オ カ キ ク ケ | , % _ > ?
コ サ シ ス セ ソ タ チ ツ ` : # @ ' = "
テ a b c d e f g h i ト ナ ニ ヌ ネ ノ
ハ j k l m n o p q r ヒ フ ヘ ホ マ ミ
ム ~ s t u v w x y z メ モ ヤ ユ ヨ ラ
リ ル レ ロ ワ ン ゛ ゜
{ A B C D E F G H I
} J K L M N O P Q R
\ S T U V W X Y Z
0 1 2 3 4 5 6 7 8 9 EO


で、上のデータをもとにHTMLに表にしてます。

0123456789abcdef
0NULSOHSTXETXSELHTRNLDELGESPSRPTVTFFCRSO/LS1SI/LS0
1DLEDC1DC2DC3RES/ENPNLBSPOCCANEMUBSCU1IFSIGSIRSIUS/ITB
2DSSOSFSWUSBYP/INPLFETBESCSASFESM/SWCSPMFAENQACKBEL
3(予約)(予約)SYNIRPPTRNNBSEOTSBSITRFFCU3DC4NAK(予約)SUB
4sp?.<(+
5&!$*);?
6-/|,%_>?
7:#@'="
8abcdefghi
9jklmnopqr
a?stuvwxyz
b
c{ABCDEFGHI
d}JKLMNOPQR
e\STUVWXYZ
f0123456789EO



ソース
package d;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;

import u.Utils;

public class TestEBCDIC {
public static void main(String[] args) throws URISyntaxException,
IOException {
a();
}

static void a() throws URISyntaxException, IOException {
File file = new File(TestEBCDIC.class.getResource("doc-files/tbl.txt")
.toURI());
String tbl = Utils.getAtOnce(file, "utf-8");
// System.out.println(tbl);
String[] lines = tbl.split("\n");
{
System.out.print(" ");
for (int i = 0; i <= 0xf; i++) {
System.out.printf("%h ", i);
}
System.out.println();
int c = 0;
for (String line : lines) {
System.out.printf("%h ", c++);
String[] ss = line.split("\t");
for (String s : ss) {
System.out.printf("%s ", s);
}
System.out.println();
}
}

{// HTML table
System.out
.println("<table width='400' border='1' style='font-size: 8pt;'>");
System.out.print("<tr>");
System.out.printf("<td></td>");
for (int i = 0; i <= 0xf; i++) {
System.out.printf("<td>%h</td>", i);
}
System.out.println("</tr>");
int c = 0;
for (String line : lines) {
System.out.print("<tr>");
System.out.printf("<td>%h</td>", c++);
String[] ss = line.split("\t");
for (String s : ss) {
System.out.printf("<td>%s</td>", s);
}
System.out.println("</tr>");
}

System.out.println("</table>");
}

}
}

文字コードのための手習いその1 2010/09/21

Javaです。
現行とか次期とかいう用語がでてくるプロジェクトにはかならずといっていいほどでてきて頭を悩ますのがおそらく文字コードだろうと思われます。

ちょっといろいろ理解不足なので、プログラム書いて納得していこうかと思います。

import java.io.UnsupportedEncodingException;

public class TestJis {

public static void main(String[] args) throws UnsupportedEncodingException {
a();
b();
}

static void a() throws UnsupportedEncodingException {
String s = "日本語";
byte[] sjis = s.getBytes("sjis");
byte[] jis = new String(sjis, "sjis").getBytes("jis");
String s_jis = new String(jis, "jis");
System.out.println(s_jis);
for (byte b : sjis) {
System.out.print(Integer.toHexString((int) b) + " ");
}
System.out.println();
int cnt = 0;
for (byte b : jis) {
System.out.print(Integer.toHexString((int) b) + " ");
cnt++;
}
System.out.println();
System.out.println("==>" + cnt);
}

static void b() throws UnsupportedEncodingException{

// 46 7c 4b 5c 38 6c
byte[] top = {0x1b, 0x24, 0x42};
byte[] bottom = {0x1b, 0x28, 0x42};

byte[] bs = {0x46, 0x7c, 0x4b, 0x5c, 0x38, 0x6c};
byte[] jis = sandwich(top, bs, bottom);
System.out.println(new String(jis, "jis"));
for (byte b : jis) {
System.out.print(Integer.toHexString((int) b) + " ");
}
}

/**
* バイトの配列を結合していきます。
*
* @param top
* @param bs
* @param bottom
* @return
*/
static byte[] sandwich(byte[] top, byte[] bs, byte[] bottom) {
byte[] ret = new byte[top.length + bs.length + bottom.length];
int[] pos = {0, top.length, top.length + bs.length};
System.arraycopy(top, 0, ret, pos[0], top.length);
System.arraycopy(bs, 0, ret, pos[1], bs.length);
System.arraycopy(bottom, 0, ret, pos[2], bottom.length);
return ret;
}

}



実行結果はこんな感じででてきますよ。
日本語
ffffff93 fffffffa ffffff96 7b ffffff8c ffffffea
1b 24 42 46 7c 4b 5c 38 6c 1b 28 42
==>12
日本語
1b 24 42 46 7c 4b 5c 38 6c 1b 28 42

いまだにCSVその2 2010/09/18

Javaです。CSVを処理します。
とりあえず、JUnit4(使ったことがなかったので)でテスト用意して、自分のニーズに対応しているだろうことを確認。
これでCSVから離れられる....
テスト用データ、ソースは全部、コミット。
CSVUtils.java - quicklunch - Project Hosting on Google Code

package quicklunch.e2.goodies.utils;

import static org.junit.Assert.*;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.junit.Test;

public class CSVUtilsTest {

static InputStream getStream(String filename) {
return CSVUtilsTest.class.getResourceAsStream("doc-files/csv/"
+ filename);
}

@Test
public void testParse001() throws IOException {
// fail("Not yet implemented");
CSVUtils.parse(getStream("001.csv"), new CSVUtils.AbstractExecutor() {
@Override
public void exec(long row, List<String> line) {
assertEquals(0, row);
assertEquals(3, line.size());
}
});

CSVUtils.parse(getStream("002.csv"), new CSVUtils.AbstractExecutor() {
@Override
public void exec(long row, List<String> line) {
assertEquals(0, row);
assertEquals(5, line.size());
assertEquals("", line.get(0));// empty field
assertEquals("bbb", line.get(1));
assertEquals("", line.get(2));
assertEquals("ccc", line.get(3));
assertEquals("", line.get(4));
}
});

CSVUtils.parse(getStream("003.csv"), new CSVUtils.AbstractExecutor() {
@Override
public void exec(long row, List<String> line) {

if (0 == row) {
assertEquals(3, line.size());
assertEquals("aaa", line.get(0));
assertEquals("bbb", line.get(1));
assertEquals("ccc", line.get(2));
}

if (1 == row) {
assertEquals(4, line.size());
assertEquals("000", line.get(0));
assertEquals(" 111 ", line.get(1));
// space
assertEquals(" 222", line.get(2));
// space
assertEquals("333 ", line.get(3));
}
}
});
}

@Test
public void testParse002() throws IOException {
// fail("Not yet implemented");
CSVUtils.parse(getStream("004.csv"), new CSVUtils.AbstractExecutor() {
@Override
public void exec(long row, List<String> line) {
if (row == 0) {
// empty line
assertEquals(0, line.size());
}
if (row == 1) {
assertEquals(1, line.size());
// space
assertEquals(" ", line.get(0));
}

if (row == 2) {
assertEquals(2, line.size());
assertEquals("", line.get(0));// empty field
assertEquals("", line.get(1));// empty field
}

if (row == 3) {
assertEquals(2, line.size());
assertEquals(" ", line.get(0));// space
assertEquals("", line.get(1));// empty field
}

if (row == 4) {
// empty line
assertEquals(0, line.size());
}

if (row == 5) {
assertEquals(1, line.size());
assertEquals(" ", line.get(0));// space
}
}
});
}

@Test
public void testParse003() throws IOException {
// fail("Not yet implemented");
{
long n = CSVUtils.parse("日本語", new CSVUtils.AbstractExecutor() {
@Override
public void exec(long row, List<String> line) {
assertEquals(0, row);
assertEquals(1, line.size());
assertEquals("日本語", line.get(0));
}
});
assertEquals(1, n);
}
{
long n = CSVUtils.parse("", new CSVUtils.AbstractExecutor() {
@Override
public void exec(long row, List<String> line) {
assertEquals(0, row);
assertEquals(0, line.size());
}
});
assertEquals(0, n);
}
{
long n = CSVUtils.parse("日本語\n", new CSVUtils.AbstractExecutor() {
@Override
public void exec(long row, List<String> line) {
if (row == 0) {
assertEquals(1, line.size());
assertEquals("日本語", line.get(0));
}
}
});
assertEquals(1, n);
}
}

@Test
public void testParse004() throws IOException {
{
// encode
long n = CSVUtils.parse(getStream("005_utf8_crlf.csv"),
new CSVUtils.AbstractExecutor() {
@Override
public void exec(long row, List<String> line) {

if (0 == row) {
assertEquals(5, line.size());
assertEquals("日本語1", line.get(0));
assertEquals("日本語2", line.get(1));
assertEquals("日本語3", line.get(2));
assertEquals(" 日本語4", line.get(3));// space
assertEquals("日本語5 ", line.get(4));// space
}

if (1 == row) {
assertEquals(5, line.size());
assertEquals("dd\r\neeee", line.get(0));
assertEquals("fff", line.get(1));
assertEquals(" gg ", line.get(2));
assertEquals("", line.get(3));// epmty field
assertEquals("hhh", line.get(4));
}

if (2 == row) {
assertEquals(5, line.size());
assertEquals("aaa", line.get(0));
assertEquals("bbb\r\nッッ", line.get(1));
assertEquals("ccc", line.get(2));
assertEquals("dddd", line.get(3));
assertEquals("", line.get(4));// epmty field
}
}
}, "utf8");

assertEquals(3, n);
}
}

}



package quicklunch.e2.goodies.utils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PushbackReader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;


/**
*
*
* @author nakawakashigeto
*
*/
public abstract class CSVUtils {

public interface IExecutor {
public void pre();

/**
*
* @param row
* start 0
* @param line
*/
public void exec(long row, List<String> line);

public void post();
}

abstract static public class AbstractExecutor implements IExecutor {
public void pre() {
}

public void exec(long row, List<String> line) {
}

public void post() {
}
}// end

// ===================

public enum TT {
EOF("EOF"), FIELD("FIELD"), COMMA("COMMA"), CRLF("CRLF"), CR("CR"), LF(
"LF");

String s;

TT(String s) {
this.s = s;
}

public String toString() {
return s;
}
}

/**
*
* @author nakawakashigeto
*
*/
public static class Token {
TT type;
public StringBuilder val = new StringBuilder();

public Token build(TT type) {
this.type = type;
return this;
}

public void append(int ch) {
this.val.append((char) ch);
}

public void append(String s) {
this.val.append(s);
}

public String toString() {
return "T:[" + type + "] V:[" + val + "]";
}
}

/**
*
* @author nakawakashigeto
*
*/
public static class CSVTokenizer {

PushbackReader reader;

static final int DQUOTE = '"';
static final int QUOTE = '\'';
static final int COMMA = ',';
static final int EOF = -1;
static final int CR = '\r';
static final int LF = '\n';

/* STATE */
static final int ST_nonescaped = 1;
static final int ST_escaped = 2;
static final int ST_escaped_single_quote = 3;

public CSVTokenizer(String s) {
this.reader = new PushbackReader(new BufferedReader(
new StringReader(s)));
}

public CSVTokenizer(InputStream inputStream) {
this.reader = new PushbackReader(new BufferedReader(
new InputStreamReader(inputStream)));
}

public CSVTokenizer(InputStream inputStream, String charasetname)
throws UnsupportedEncodingException {
this.reader = new PushbackReader(new BufferedReader(
new InputStreamReader(inputStream, charasetname)));
}

public Token token() throws IOException {

int state = 0;

Token token = new Token();
loop: while (true) {
int ch = read();

switch (state) {
case 0:
/*
* -- START --
*/
if (ch == EOF) {
return token.build(TT.EOF);
}

// dpuble quote
if (ch == DQUOTE) {
state = ST_escaped;
token.type = TT.FIELD;
break;
}

// single quote
if (ch == QUOTE) {
state = ST_escaped_single_quote;
token.type = TT.FIELD;
break;
}

if (ch == COMMA) {
token.append(ch);
return token.build(TT.COMMA);
}

if (ch == CR) {
ch = read();
if (ch == LF) {
// default CRLF
return token.build(TT.CRLF);
}

// suport CR
unread(ch);
return token.build(TT.CR);
}

// suport LF
if (ch == LF) {
return token.build(TT.LF);
}

state = ST_nonescaped;
token.type = TT.FIELD;
case ST_nonescaped:
/*
* -- non-escaped --
*/
if (ch == EOF || ch == CR || ch == LF || ch == DQUOTE) {
unread(ch);
return token;
}

if (!isTextdata(ch)) {
unread(ch);
return token;
}

token.append(ch);
break;
case ST_escaped:
/*
* -- escaped(double quote) --
*/

if (ch == EOF) {
return token.build(TT.FIELD);
}

// 2DQUOTE
if (ch == DQUOTE) {
ch = read();
if (ch == DQUOTE) {
token.append("\"");
state = ST_escaped;
break;
}
unread(ch);
return token;
}

token.append(ch);
break;

case ST_escaped_single_quote:
/*
* -- escaped(single quote) --
*/
if (ch == EOF) {
return token.build(TT.FIELD);
}

// 2DQUOTE
if (ch == QUOTE) {
ch = read();
if (ch == QUOTE) {
token.append("\'");
state = ST_escaped_single_quote;
break;
}
unread(ch);
return token;
}

token.append(ch);
break;

default:
break loop;
}
}

return token;
}

boolean isTextdata(int ch) {
if (notEq(ch, '\r') && notEq(ch, '\n') && notEq(ch, '"')
&& notEq(ch, ',')) {
return true;
}
return false;
}

int read() throws IOException {
if (reader != null)
return reader.read();
return -1;
}

boolean notEq(int l, int r) {
return (l != r);
}

void unread(int ch) throws IOException {
if (reader != null && ch != -1) {
reader.unread(ch);
}
}

public void close() {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
}
} // end

public static long parse(InputStream inputStream, IExecutor executor,
String charasetname) throws IOException {
long row = 0;

executor.pre();

try {
CSVTokenizer tokenizer = new CSVTokenizer(inputStream, charasetname);
CSVUtils.Token token = null;
// one previous token
CSVUtils.Token preToken = null;

do {
List<String> line = new ArrayList<String>();

while ((token = tokenizer.token()) != null
&& !(token.type == TT.EOF || token.type == TT.CRLF
|| token.type == TT.CR || token.type == TT.LF)) {
// check empty field.
if ((preToken == null || preToken.type == TT.COMMA)
&& token.type == TT.COMMA) {
line.add("");// empty field...
preToken = token;
continue;
}

if (token.type == TT.COMMA) {
preToken = token;
continue;// skip comma
}
line.add(token.val.toString());
preToken = token;
}

// ignore empty line
if (preToken == null && token.type == TT.EOF) {
break;
}

// check empty field.
if ((preToken != null && preToken.type == TT.COMMA)
&& (token.type == TT.EOF || token.type == TT.CRLF
|| token.type == TT.CR || token.type == TT.LF)) {
line.add("");// empty field...
}

executor.exec(row++, line);
preToken = null;
} while (token != null && token.type != TT.EOF);
} finally {
executor.post();
}

return row;
}

public static long parse(InputStream inputStream, IExecutor executor)
throws IOException {
return parse(inputStream, executor, System.getProperty("file.encoding"));
}

public static long parse(String s, IExecutor executor) throws IOException {

InputStream inputStream = new ByteArrayInputStream(s.getBytes("utf-8"));

return parse(inputStream, executor, "utf-8");
}

}

いまだにCSVです。 2010/09/17

Javaです。いまだにCSVです。
以前つくりかけていたものが、なんかいろいろだめだったので少しずつですが、テストして試してます。
あと、RFCだけに対応させるとCSVのパーサーとしては使いづらいものになってしまうかなと考えてたりしてます。
あと、osx上のエクセルでcsvで保存するとCRLFでは保存されていないことに気がついて....

とりあえず、コミット。



以下、ちょっと工夫してます。
以前から実装したいアイデアがあって、まあ単純にCSVの行ごとに処理をしやすいようにしたいということなのですが、
まあ、なんとなく実装できてるかなと。
手書きのパーサで、依存するものを極力少なくしておいて、ソースをひとつにしておくと、個人で使う場合に便利なことが多いので、ひとつのソースにまとめてます。
package quicklunch.e2.goodies.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PushbackReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

public abstract class CSVUtils {

public interface IExecutor {
public void pre();

public void exec(List<String> line);

public void post();
}

abstract static public class AbstractExecutor implements IExecutor {
public void pre() {
}

public void exec(List<String> line) {
}

public void post() {
}
}

// ===================

public enum TT {
EOF("EOF"), FIELD("FIELD"), COMMA("COMMA"), CRLF("CRLF"), CR("CR"), LF(
"LF");

String s;

TT(String s) {
this.s = s;
}

public String toString() {
return s;
}
}

public static class Token {
TT type;
public StringBuilder val = new StringBuilder();

public Token build(TT type) {
this.type = type;
return this;
}

public void append(int ch) {
this.val.append((char) ch);
}

public void append(String s) {
this.val.append(s);
}

public String toString() {
return "T:[" + type + "] V:[" + val + "]";
}
}

public static class CSVTokenizer {

PushbackReader reader;

static final int DQUOTE = '"';
static final int QUOTE = '\'';
static final int COMMA = ',';
static final int EOF = -1;
static final int CR = '\r';
static final int LF = '\n';

/* STATE */
static final int ST_nonescaped = 1;
static final int ST_escaped = 2;
static final int ST_escaped_single_quote = 3;

public CSVTokenizer(String s) {
this.reader = new PushbackReader(new BufferedReader(
new StringReader(s)));
}

public CSVTokenizer(InputStream inputStream) {
this.reader = new PushbackReader(new BufferedReader(
new InputStreamReader(inputStream)));
}

public Token token() throws IOException {

int state = 0;

Token token = new Token();
loop: while (true) {
int ch = read();

switch (state) {
case 0:
/*
* -- START --
*/
if (ch == EOF) {
return token.build(TT.EOF);
}

// dpuble quote
if (ch == DQUOTE) {
state = ST_escaped;
token.type = TT.FIELD;
break;
}

// single quote
if (ch == QUOTE) {
state = ST_escaped_single_quote;
token.type = TT.FIELD;
break;
}

if (ch == COMMA) {
// empty field
token.append(ch);
return token.build(TT.COMMA);
}

if (ch == CR) {
ch = read();
if (ch == LF) {
// default CRLF
return token.build(TT.CRLF);
}

// suport CR
unread(ch);
return token.build(TT.CR);
}

// suport LF
if (ch == LF) {
return token.build(TT.LF);
}

state = ST_nonescaped;
token.type = TT.FIELD;
case ST_nonescaped:
/*
* -- non-escaped --
*/
if (ch == EOF || ch == CR || ch == LF || ch == DQUOTE) {
unread(ch);
return token;
}

if (!isTextdata(ch)) {
unread(ch);
return token;
}

token.append(ch);
break;
case ST_escaped:
/*
* -- escaped(double quote) --
*/

if (ch == EOF) {
return token.build(TT.FIELD);
}

// 2DQUOTE
if (ch == DQUOTE) {
ch = read();
if (ch == DQUOTE) {
token.append("\"");
state = ST_escaped;
break;
}
unread(ch);
return token;
}

token.append(ch);
break;

case ST_escaped_single_quote:
/*
* -- escaped(single quote) --
*/
if (ch == EOF) {
return token.build(TT.FIELD);
}

// 2DQUOTE
if (ch == QUOTE) {
ch = read();
if (ch == QUOTE) {
token.append("\'");
state = ST_escaped_single_quote;
break;
}
unread(ch);
return token;
}

token.append(ch);
break;

default:
break loop;
}
}

return token;
}

boolean isTextdata(int ch) {
if (notEq(ch, '\r') && notEq(ch, '\n') && notEq(ch, '"')
&& notEq(ch, ',')) {
return true;
}
return false;
}

int read() throws IOException {
if (reader != null)
return reader.read();
return -1;
}

boolean notEq(int l, int r) {
return (l != r);
}

void unread(int ch) throws IOException {
if (reader != null && ch != -1) {
reader.unread(ch);
}
}

public void close() {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
}
}

/**
*
*
* @param inputStream
* @return
*/
public static CSVTokenizer tokenizer(InputStream inputStream) {
return new CSVTokenizer(inputStream);
}

public static IExecutor tokenize(InputStream inputStream,
IExecutor executor) throws IOException {
executor.pre();
try {
CSVTokenizer tokenizer = new CSVTokenizer(inputStream);
CSVUtils.Token token = null;
do {
List<String> line = new ArrayList<String>();

while ((token = tokenizer.token()) != null
&& !(token.type == CSVUtils.TT.EOF || token.type == CSVUtils.TT.CRLF
|| token.type == CSVUtils.TT.CR || token.type == TT.LF)) {
if (token.type == TT.COMMA)
continue;// skip comma
line.add(token.val.toString());
}

executor.exec(line);

} while (token != null && token.type != TT.EOF);
} finally {
executor.post();
}

return executor;
}
}

けっていひょうの読み方がわかりません。 2010/09/12



決定表を調べていて、みつけたのが上記の質問。デンジョンテーブルとなっているのがおもしろいなと。
デンジョンじゃなくてデシジョンだけど。
頭の整理をするついでにエクセルでつくってみたけど、ほんとは機械的にリストをつくってそこからいろいろレイアウトを変えてみたい。

結論は(休日前 AND スキー期間)が料金が高い。

ひとつめは横で


つぎに



そして
Nを消してみると


さらにスリムにしてみると



ここまでやっても何かもやもやが残るのは何故だろう...
途中で、(平日・ 休日|休前日)であることがカテゴライズされてないからもやもやするんだと思ったりしたけど。

で、さらに、勝手に分類してしまって


もうやめておこう...

readLine - 自分用のu.Utilsの実装 2010/09/11

Java用です。自分用のu.Utilsの実装です。
ファイルを読み込むコードを毎回書くのは結構苦痛だったりしてます。
巨大なファイルを想定して一気に読んで一気に吐き出すというふうにしてません。
ファイルを一行づつ読んで処理するためのユーティリティメソッドです。
どこからでも利用できるように、svnにあげときます。



EclipseとJavaがあれば、とりあえずどんなプラットフォーム(Windows,osx,Linux)でもなんとなくやっていけるなーとよく思います。

で、コード
実装はお手軽BufferedReaderのreadLineを使ってます。
package u;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public abstract class Utils {

public interface IExecutor {
public void pre();
public void exec(String line);
public void post();
}

abstract static public class AbstractExcutor implements IExecutor{
public void pre(){}
public void exec(String line){}
public void post(){}
}
/**
* implement
* use BufferedReader
*
* @param file
* @param executor
* @return
* @throws IOException
*/
public static IExecutor readLine(File file, IExecutor executor)
throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(file));

try {
executor.pre();
String line = null;
while ((line = reader.readLine()) != null) {
executor.exec(line);
}

} finally {
try {
reader.close();
} finally {
executor.post();
}

}

return executor;
}
}



使い方
package u;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;

public class UsageUtils {

public static void main(String[] args) throws IOException,
URISyntaxException {
readLine();
}

static void readLine() throws IOException, URISyntaxException {
/*
* 1.
*/
Utils.readLine(
new File(UsageUtils.class.getResource(
"doc-files/日本語/日本語TEST_SJIS.txt").toURI()),
new Utils.IExecutor() {
int total = 0;

public void pre() {
System.out.println("*** pre");
}

public void post() {
System.out.println("*** post total[" + total + "]");
}

public void exec(String line) {
total++;
System.out.println("[" + line + "]");
}
});

/*
* 2.
*/
Utils.readLine(
new File(UsageUtils.class.getResource("doc-files/TEST.txt")
.toURI()), new Utils.AbstractExcutor(){
int total = 0;
public void exec(String line) {
total++;
System.out.println("[" + line + "]");
}
});

}
}

cocos2dで音をだしたい。 2010/09/09

cocos2dです。音をだしたいわけです。
うーん、簡単だ。
コード

#import "SimpleAudioEngine.h"

SimpleAudioEngine *audioEngine = [SimpleAudioEngine sharedEngine];
[audioEngine playEffect:@"motorbike_start.aif"];


現在のライセンスは、
ライセンスはcocos2dと同じMITライセンス
cocosdenshion:license - cocos2d for iPhone
CocosDenshion License

CocosDenshion is released under the MIT license the same as cocos2d.

The intention is that it can be used without restriction.



参考
A-Liaison BLOG: cocos2d細かいところメモ

SQLCODEが100ならば 2010/09/08

COBOLです。
SQLCODEが100ならば、該当行がないということのようです。
0は正常に終了しました。
このふたつだ判定してそれ以外はエラーってするのが一般的?

なんか、わざわざ、他の言語使って書き直すより、COBOLでいいじゃんと思ってる人って多かったりして。。。。

$で絶対参照 - エクセル 2010/09/06

エクセルです。忘れるのでメモ。
エクセルでセルを選んでしたにぴーと動かして、値を増やしていくことをよくやります。
セルの式を入れたときにこの機能が働いてくれて、いいときもありますが、よくないときも多々あります。



参照する値に$をつければ問題は解決。
B2というセルの値を固定して参照したいときは、$B$2とすればよいわけです。

わかりづらいけど...

=OFFSET(INDIRECT(ADDRESS(ROW(),COLUMN())), 0, -1)+$B$2




エクセルで考えることになれちゃうとエクセル脳になっちゃうよと思う今日この頃です。

CFAttributedStringSetAttributeで、フォントを変更、アラインの変更などなど 2010/09/03

CGContextRefにいろいろ描画していて、さらに文字列を表示しようとしていろいろ四苦八苦。
表示する分には簡単に調べてできたけど、中央に表示したいと思い、やりはじめるといろいろはまったのでした。
とりあえず、iphone sdk4.0がターゲットです。

(1)iphoneだと、文字がひっくりかえるの防ぐ


CGAffineTransform transform = CGAffineTransformMake(1.0, 0.0, 0.0, -1.0, 0.0, 0.0);
CGContextSetTextMatrix(context, transform);


(2)フォントを変更。
※CTFontCreateWithNameって、フォントによっては時間がかかってるようにみえた.....

CTFontRef font = CTFontCreateWithName(CFSTR("Helvetica"), 48., NULL);// これでも日本語okだった.....
CFAttributedStringSetAttribute(attrString, CFRangeMake(0,[str length]), kCTFontAttributeName, font);
CFRelease(font);


(3)真ん中にそろえる

CTTextAlignment alignment = kCTCenterTextAlignment;// kCTJustifiedTextAlignment
CTParagraphStyleSetting _settings[] = { {kCTParagraphStyleSpecifierAlignment, sizeof(alignment), &alignment} };
CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(_settings, sizeof(_settings) / sizeof(_settings[0]));

CFAttributedStringSetAttribute(attrString, CFRangeMake(0, CFAttributedStringGetLength(attrString)), kCTParagraphStyleAttributeName, paragraphStyle);
CFRelease(paragraphStyle);


特に、このサイトの記事によるものです。

ここのスライドショー


参考


コード自分用
{ // このコードがないとひっくりかえるよ
CGAffineTransform transform = CGAffineTransformMake(1.0, 0.0, 0.0, -1.0, 0.0, 0.0);
CGContextSetTextMatrix(context, transform);
}

CGMutablePathRef path = CGPathCreateMutable();
CGRect bounds = CGRectMake(0.0, 10.0, 320, 200.0);
CGPathAddRect(path, NULL, bounds);
CFStringRef string = (CFStringRef)str;// CFSTR("test");
CFMutableAttributedStringRef attrString = CFAttributedStringCreateMutable(kCFAllocatorDefault, 0);
CFAttributedStringReplaceString (attrString, CFRangeMake(0, 0), string);

{ // フォントを変更
CTFontRef font = CTFontCreateWithName(CFSTR("Helvetica"), 48., NULL);// これでも日本語okだった.....
CFAttributedStringSetAttribute(attrString, CFRangeMake(0,[str length]), kCTFontAttributeName, font);
CFRelease(font);
}


{ // アラインを変更
CTTextAlignment alignment = kCTCenterTextAlignment;// kCTJustifiedTextAlignment
CTParagraphStyleSetting _settings[] = { {kCTParagraphStyleSpecifierAlignment, sizeof(alignment), &alignment} };
CTParagraphStyleRef paragraphStyle = CTParagraphStyleCreate(_settings, sizeof(_settings) / sizeof(_settings[0]));

CFAttributedStringSetAttribute(attrString, CFRangeMake(0, CFAttributedStringGetLength(attrString)), kCTParagraphStyleAttributeName, paragraphStyle);
CFRelease(paragraphStyle);
}

CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString(attrString);
CTFrameRef frame = CTFramesetterCreateFrame(framesetter,CFRangeMake(0, 0), path, NULL);

CFRelease(attrString);
CFRelease(framesetter);
CTFrameDraw(frame, context);
CFRelease(frame);

NSStringからCFStringRefにしたいのさ 2010/09/03

Objective-Cです。CoreFoundationです。NSStringをCFStringRefに変換して使いたいわけですが、はて、どうしたものか。
CFStringRefでキャストするだけ...

CFStringRef cfString = (CFStringRef)@"test";


参考

文字列からセレクター 引数がある場合 - NSSelectorFromString 2010/09/02

Objective-Cです。NSSelectorFromStringです。
文字列からセレクターを作成して利用します。その際に、呼び出すメソッドに引数がある場合についてです。
一時間ぐらいはまったのでメモ。
ようはコロン(:)を忘れずにです。

プログラマメモ2: 文字列からセレクターを作成する - NSSelectorFromString

以下サンプルコードです。

#import <Foundation/NSString.h>
#import <Foundation/NSAutoreleasePool.h>

@interface MyObj : NSObject {

}
- a1:(id)arg;
- a2:(id)arg;
- a3:(id)arg;
@end

@implementation MyObj

- a1:(id)arg;
{
NSLog(@"** a1[%d]", [arg intValue]);
}
- a2:(id)arg
{
NSLog(@"** a2[%d]", [arg intValue]);
}
- a3:(id)arg
{
NSLog(@"** a3[%d]",[arg intValue]);
}
@end

int main(){

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

id myObj = [MyObj alloc];

// NSSelectorFromStringを使ってるよ
// 引数がある場合は:を付ける!!
SEL sel1 = NSSelectorFromString(@"a1:");
// performSelectorを使ってるよ
//(1) SELを使ってます
[myObj performSelector:sel1 withObject:(id)nil];
//(2)@selectorを使ってます
[myObj performSelector:@selector(a2:) withObject:[NSNumber numberWithInt:2]];
//(3)直にNSSelectorFromStringを使ってます
[myObj performSelector:NSSelectorFromString(@"a3:") withObject:[NSNumber numberWithInt:3]];

[pool drain];
return 0;
}

再度、wikipedia apiを使ってみたい。- Java + axis2 2010/09/01

プログラマメモ2: wikipedia apiを使ってみたい。- Java + axis2

Javaです。二年前の記事ですが、もう一度チャレンジです。
僕の環境はmac osxでJava1.6です。Eclipseベースで行ってます。

workspaceに、空のJavaプロジェクトを作成して、libフォルダを作成して、Axis2を解凍しておいておきます。
今回使ったのは、1.5.1です。



Apache Axis2 -


ついでにaxis2のlibにあるjarをとりあえず全部、buildpathにaddしておきます。
ほんとは、必要なものだけで選んでおきたいけど...



プロジェクト内にworkフォルダを用意してそこでWSDLからJavaのソースコード生成します.

ターミナル(windowsならコマンドプロンプト?)で、下の命令を実行

../lib/axis2-1.5.1/bin/wsdl2java.sh -uri http://dev.wikipedia-lab.org/WikipediaOntologyAPIv3/Service.asmx?WSDL -p wikipediaapi


-p指定で、wikipediaapiとします。
今回はパッケージをwikipediaapiとしてみました。
あと環境変数JAVA_HOMEは設定してないといけないです。

あと、ワーニングがでてきますが、気にしないで、前にすすみます。



eclipseでみると下のような感じ

できたソースをeclipseのビルドパスに含めてしまいます。
で、下の感じ。

これで生成できたので、あとは利用するだけです。
ちょっとしたtipsですが、生成されたソースフォルダと自分で作成するソースのフォルダをeclipseで別々にしておくと、
いろいろあとから変更しやすくなります。

サンプルコード

package wikipediaapi;

import java.rmi.RemoteException;

import org.apache.axis2.databinding.ADBException;
import org.apache.axis2.databinding.types.UnsignedInt;

import wikipediaapi.ServiceStub.GetThesaurusDS;
import wikipediaapi.ServiceStub.GetThesaurusDSResponse;
import wikipediaapi.ServiceStub.GetTopCandidateIDFromKeyword;
import wikipediaapi.ServiceStub.GetTopCandidateIDFromKeywordResponse;

public class Test {

public static void main(String[] args) throws RemoteException, ADBException {

String[] keywords = { "侍", "apple", "google", "o_o!" };
for (String k : keywords) {
System.out.println(b(a(k)));
}
}

static int a(String skeyword) throws RemoteException {
ServiceStub serviceStub = new ServiceStub();

GetTopCandidateIDFromKeyword keyword = new GetTopCandidateIDFromKeyword();
keyword.setKeyword(skeyword);
keyword.setLanguage("Japanese");

GetTopCandidateIDFromKeywordResponse response = serviceStub
.getTopCandidateIDFromKeyword(keyword);

return response.getGetTopCandidateIDFromKeywordResult().intValue();
}

static String b(int i) throws RemoteException {

ServiceStub serviceStub = new ServiceStub();

GetThesaurusDS getThesaurusDS = new GetThesaurusDS();
getThesaurusDS.setLanguage("Japanese");
getThesaurusDS.setIFrom(new UnsignedInt(i));

GetThesaurusDSResponse response = serviceStub
.getThesaurusDS(getThesaurusDS);

return "" + response.localGetThesaurusDSResult.localExtraElement;
}

}