SyntaxHighlighter

2013-11-12

Access 内でVBAでReportをプレビューで呼び出し

DoCmd.OpenReport "レポート名", View:=acViewPreview, WhereCondition:=条件

AccessからExcelに出力

参考資料:Export from ACCESS to Excel using VBA

AccessからVBAでExcelに出力は次のようなコードで実行できる。
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "tbl_lookup_ird", "c:\temp.xls", True


似ている方法で、Excelオブジェクトを作成してからそこに出力を書き込む方法もある。
Public Sub QueryToExcel(ExcelFile As String)
Dim db As Database
Dim qdf As QueryDef

Dim qryCount As Integer
Dim SheetName As String

Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet

    Set xlApp = CreateObject("Excel.Application")
    Set xlBook = xlApp.Workbooks.Add
    Set xlSheet = xlBook.Worksheets(1)

    'Make the worksheet visible.
    xlSheet.Application.Visible = True

    Set db = CurrentDb()

    With db
        qryCount = 0
        For Each qdf In .QueryDefs
            qryCount = qryCount + 1
            ' Output qryCount, .Name and .SQL to the next line
            ' in a sheet in the Excel file
            With xlSheet.Cells(qryCount, 1)
                .Value = Str(qryCount)
                .Font.Size = 12
                .Font.Bold = True
            End With
            With xlSheet.Cells(qryCount, 2)
                .Value = qdf.Name
                .Font.Size = 12
                .Font.Bold = True
            End With
            With xlSheet.Cells(qryCount, 3)
                .Value = qdf.SQL
                .Font.Size = 10
            End With
        Next qdf
    End With

    'Save the new worksheet, close Excel and clear the object variable.
    xlSheet.SaveAs ExcelFile
    xlSheet.Application.Quit
    Set xlSheet = Nothing

    ' Create new sheets in the newly created Excel file for
    ' the results of each of the queries
    With db
        qryCount = 0
        For Each qdf In .QueryDefs
            With qdf
                qryCount = qryCount + 1
                SheetName = "Query" & Trim(Str(qryCount))

                ' Create a new sheet in the specified Excel file with
                ' the output of the named query.
                ' If there is a pre-existing one with the same name
                ' the new sheet will have a "1" appended to its name.

                ' Problems or issues:
                ' 1. Invalid queries will error out
                ' 2. Action queries will error out
                ' 3. Queries with parameters will require user input

                DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, _
                    .Name, ExcelFile, , SheetName
            End With
        Next qdf
        .Close
    End With

End Sub


あるいは次のように
Dim appExcel As Excel.Application
    Dim wbk As Excel.Workbook
    Dim wks As Excel.Worksheet
    Dim rng As Excel.Range
    
    Dim fileName As String

    Set appExcel = Excel.Application
    appExcel.Visible = True
    Set wbk = appExcel.Workbooks.Add
    Set wks = wbk.Worksheets(1)
    Set rng = wks.Range("A2:I4001")
    wks.Cells(1, 1).Value = "Generating data..."
    
    Set rst = CurrentDb.OpenRecordset(customQuery)
    If (rst.RecordCount > 0) Then
        cnt = 1
        For Each fld In rst.Fields
            wks.Cells(1, cnt).Value = fld.Name
            cnt = cnt + 1
        Next fld
        Call rng.CopyFromRecordset(rst, 4000, 26)
    End If
    
    fileName = ExportDir & "\Molenproductie" & DateTimeFrom & "-" & DateTimeTo & ".xls"
    wks.SaveAs (fileName)
    
    rst.Close
    Set rst = Nothing


ところで、AccessからExcelに出力してからPivot Tableを作成するという手法がある。
但し、次のコードはExcelから直接にAccessのデータベースへ接続してデータを取り出しているようです。

Sub DAOCopyFromRecordSet(DBFullName As String, TableName As String, _
    FieldName As String, TargetRange As Range)
' Example: DAOCopyFromRecordSet "C:\FolderName\DataBaseName.mdb", _
    "TableName", "FieldName", Range("C1")
Dim db As Database, rs As Recordset
Dim intColIndex As Integer
    Set TargetRange = TargetRange.Cells(1, 1)
    Set db = OpenDatabase(DBFullName)
    Set rs = db.OpenRecordset(TableName, dbOpenTable) ' all records
    'Set rs = db.OpenRecordset("SELECT * FROM " & TableName & _
        " WHERE " & FieldName & _
        " = 'MyCriteria'", dbReadOnly) ' filter records
    ' write field names
    For intColIndex = 0 To rs.Fields.Count - 1
        TargetRange.Offset(0, intColIndex).Value = rs.Fields(intColIndex).Name
    Next
    ' write recordset
    TargetRange.Offset(1, 0).CopyFromRecordset rs
    Set rs = Nothing
    db.Close
    Set db = Nothing
End Sub




2013-11-06

Access在VBA中執行SQL

在Access中執行後台SQL
可在VBA中使用下面的程式來執行sql文

strSQL = "INSERT INTO table (column1, column2) VALUES (v1,v2)"
CurrentDb.Execute strSQL

easy?

Access 2010データベースファイルを2003にダウングレードする方法

Access 2010の環境で開発する際、新しいファイル(ACCDB)は古いAccessでは使えないため、旧形式のMDBファイルに変換する必要性がある。 但し、変換されたファイルに、VBAコードはうまく変換できない/VBAコードが削除されることが多々ある。

故に、次のステップで変換すると、無事(?)に変換できる。

1. VBAのエクスポート

Accessファイルに書き込まれているVBAコードを、全てのフォーム、レポート、標準モジュールを含めて、すべて別々にエクスポートして保存しておいてください。

やり方は簡単。AccessのVBA Editorを開いて、プロジェクトエクスプローラの中にあるそれぞれフォーム名に右クリックして、「ファイルのエクスポート(E)...」をクリックして、コードを.clsファイルにエクスポートする。無論、標準モジュールも同様。

※標準モジュールはバックアップする必要ないかもしれないが、一応…

2. コード保持設定の変更

Accessの編集画面に戻り、それぞれフォームとレポートのプロパティの「コード保持」を「いいえ」に変更する。

上記の設定をすると、保存する時にVBAコードが削除されるので、ステップ1のVBAコードエクスポートをちゃんと確認してから進めなさい。

3. 2003形式ファイルに保存

別名で保存をして、「Access 2002-2003形式(MDB)」に保存する。

4. Access 2003でVBA再導入

Access 2003で先保存したMDBファイルを開ける。そして、VBA Editorでステップ1でエクスポートしたコードファイル(cls)をそれぞれのフォームやレポートにインポートする。

フォームやレポートも同じようにインポートできますが、もし、できない場合はエクスポートしたプログラムはエディタ(メモ帳や秀丸など)で開くことができるので、そのままコピー&ペーストを行えばいいでしょう。先頭に「VERSION 1.0 CLASS」や「BEGIN」~「END」、「Attribute VB_~」などが書かれているので削除してしまいましょう。
とか言われたので、入れる時に注意する必要があるかもしれない。

参考URL: Access 2010から2003へ下位バージョンへ変換する方法
 

あと書き

Access 2010で開発が大丈夫の場合、最悪Access 2007/2010 Runtime Libraryをインストールすれば実行できる…但し編集できないので、最低限Access 2010を所有するPCが1台必要だ。もし実行の方で細かくプログラムの改正や編集する必要がない場合、Runtime Libraryだけで十分と思います。

2013-10-28

SyntaxHighlighter

Official Site: http://alexgorbatchev.com/SyntaxHighlighter/

for on-line offer http://alexgorbatchev.com/SyntaxHighlighter/hosting.html

Add the below codes into template's HEAD tag

<link type="text/css" rel="stylesheet" href="http://alexgorbatchev.com/pub/sh/current/styles/shCore.css"/>
<link type="text/css" rel="stylesheet" href="http://alexgorbatchev.com/pub/sh/3.0.83/styles/shThemeDefault.css" />
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js"></script>
<!-- Add Brush Here -->
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushAS3.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushBash.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushColdFusion.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCSharp.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCpp.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCss.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushDelphi.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushDiff.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushErlang.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushGroovy.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJScript.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJava.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJavaFX.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPerl.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPhp.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPlain.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPowerShell.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPython.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushRuby.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushScala.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushSql.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushVb.js"></script>
<script type="text/javascript" src="http://alexgorbatchev.com/pub/sh/current/scripts/shBrushXml.js"></script>
   
<script type="text/javascript"> 
  SyntaxHighlighter.all();
</script>

Usage:
<pre class="brush:csharp"> int a=2;</pre>

will be show as:
 int a=2; 


[C#]Centering a Message Box on the Active Window

There are 2 way to centering the default MessageBox
or said, 1 only way, and 2 kind of Invoking.

1. Make a new WindowForm who has centerParent Location, then copy it's location to the MessageBox by "Hook" the system dialog's location.
2. Just Hook the system dialog's location and set it before call MessageBox.Show()

Way 1: CenterWinDialog by Hans Passant

There's the code(class CenterWinDialog):
using System;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;

class CenterWinDialog : IDisposable {
    private int mTries = 0;
    private Form mOwner;

    public CenterWinDialog(Form owner) {
        mOwner = owner;
        owner.BeginInvoke(new MethodInvoker(findDialog));
    }

    private void findDialog() {
        // Enumerate windows to find the message box
        if (mTries < 0) return;
        EnumThreadWndProc callback = new EnumThreadWndProc(checkWindow);
        if (EnumThreadWindows(GetCurrentThreadId(), callback, IntPtr.Zero)) {
            if (++mTries < 10) mOwner.BeginInvoke(new MethodInvoker(findDialog));
        }
    }
    private bool checkWindow(IntPtr hWnd, IntPtr lp) {
        // Checks if <hwnd> is a dialog
        StringBuilder sb = new StringBuilder(260);
        GetClassName(hWnd, sb, sb.Capacity);
        if (sb.ToString() != "#32770") return true;
        // Got it
        Rectangle frmRect = new Rectangle(mOwner.Location, mOwner.Size);
        RECT dlgRect;
        GetWindowRect(hWnd, out dlgRect);
        MoveWindow(hWnd,
            frmRect.Left + (frmRect.Width - dlgRect.Right + dlgRect.Left) / 2,
            frmRect.Top + (frmRect.Height - dlgRect.Bottom + dlgRect.Top) / 2,
            dlgRect.Right - dlgRect.Left,
            dlgRect.Bottom - dlgRect.Top, true);
        return false;
    }
    public void Dispose() {
        mTries = -1;
    }

    // P/Invoke declarations
    private delegate bool EnumThreadWndProc(IntPtr hWnd, IntPtr lp);
    [DllImport("user32.dll")]
    private static extern bool EnumThreadWindows(int tid, EnumThreadWndProc callback, IntPtr lp);
    [DllImport("kernel32.dll")]
    private static extern int GetCurrentThreadId();
    [DllImport("user32.dll")]
    private static extern int GetClassName(IntPtr hWnd, StringBuilder buffer, int buflen);
    [DllImport("user32.dll")]
    private static extern bool GetWindowRect(IntPtr hWnd, out RECT rc);
    [DllImport("user32.dll")]
    private static extern bool MoveWindow(IntPtr hWnd, int x, int y, int w, int h, bool repaint);
    private struct RECT { public int Left; public int Top; public int Right; public int Bottom; }
}

Usage:
    private void button1_Click(object sender, EventArgs e) {
        using (new CenterWinDialog(this)) {
            MessageBox.Show("Nobugz waz here");
        }
    }


Way 2: MessageBoxHelper by Jason Carr

There's the code(class MessageBoxHelper):
using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;

internal static class MessageBoxHelper
{
    internal static void PrepToCenterMessageBoxOnForm(Form form)
    {
        MessageBoxCenterHelper helper = new MessageBoxCenterHelper();
        helper.Prep(form);
    }

    private class MessageBoxCenterHelper
    {
        private int messageHook;
        private IntPtr parentFormHandle;

        public void Prep(Form form)
        {
            NativeMethods.CenterMessageCallBackDelegate callBackDelegate = new NativeMethods.CenterMessageCallBackDelegate(CenterMessageCallBack);
            GCHandle.Alloc(callBackDelegate);

            parentFormHandle = form.Handle;
            messageHook = NativeMethods.SetWindowsHookEx(5, callBackDelegate, new IntPtr(NativeMethods.GetWindowLong(parentFormHandle, -6)), NativeMethods.GetCurrentThreadId()).ToInt32();
        }

        private int CenterMessageCallBack(int message, int wParam, int lParam)
        {
            NativeMethods.RECT formRect;
            NativeMethods.RECT messageBoxRect;
            int xPos;
            int yPos;

            if (message == 5)
            {
                NativeMethods.GetWindowRect(parentFormHandle, out formRect);
                NativeMethods.GetWindowRect(new IntPtr(wParam), out messageBoxRect);

                xPos = (int)((formRect.Left + (formRect.Right - formRect.Left) / 2) - ((messageBoxRect.Right - messageBoxRect.Left) / 2));
                yPos = (int)((formRect.Top + (formRect.Bottom - formRect.Top) / 2) - ((messageBoxRect.Bottom - messageBoxRect.Top) / 2));

                NativeMethods.SetWindowPos(wParam, 0, xPos, yPos, 0, 0, 0x1 | 0x4 | 0x10);
                NativeMethods.UnhookWindowsHookEx(messageHook);
            }

            return 0;
        }
    }

    private static class NativeMethods
    {
        internal struct RECT
        {
            public int Left;
            public int Top;
            public int Right;
            public int Bottom;
        }

        internal delegate int CenterMessageCallBackDelegate(int message, int wParam, int lParam);

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool UnhookWindowsHookEx(int hhk);

        [DllImport("user32.dll", SetLastError = true)]
        internal static extern int GetWindowLong(IntPtr hWnd, int nIndex);

        [DllImport("kernel32.dll")]
        internal static extern int GetCurrentThreadId();

        [DllImport("user32.dll", SetLastError = true)]
        internal static extern IntPtr SetWindowsHookEx(int hook, CenterMessageCallBackDelegate callback, IntPtr hMod, int dwThreadId);

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool SetWindowPos(int hWnd, int hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags);

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        internal static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
    }
}


Usage:
    private void button1_Click(object sender, EventArgs e)
    {
        MessageBoxHelper.PrepToCenterMessageBoxOnForm(this);
        MessageBox.Show("Hello!", "Hello!", MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, 0);
    }

[C#] Custom Dialog Form and Control the DialogResult's value

You can customize any windows form to be a dialog form, with setting the below properties:
Property NameValueNote
FormBorderStyleFixed Dialog
MinimizeBoxFalse
MaximizeBoxFalse
ControlBoxFalse
TopmostTrueOption. To set it if you want the dialog be the most top one even there is other windows programs. Maybe you will like to return it off in most time.
ShowIconFalseWhen use this option, remember to sets ShowInTaskbar to false,too.
As Tod's advice, he leave this true and topmost to false, so the user can switches to another program and get back to this from taskbar.
ShowInTaskbarFalseTo 'hidden' the program from Taskbar.
CancelButtonThe Button object's nameAnd the Button object's property DialogResult will be set to Cancel, too.
StartPositionCenterParent




For set the dialog's DialogResult, you can set it into a button's action or a custom method with
this.DialogResult = System.Windows.Forms.DialogResult.Cancel;

or just set the button's DialogResult property to the value you want to return.

REMEMBER to call the form with ShowDialog() not Show().

2013-10-25

[C#]Force DataGridView Save Current Row's Data to Backyard.

Usually we edit the table data with DataGridView.

I do it, too. and I get problem when I try to get the changed DataTable.

It happened if you try to save data just after editing it.


There is the situation:

I have a 3x3 DataTable dt, and I link it to a DataGridView dgv
dgv.DataSource = dt;

then I edited the content with row 3 column 3.
I can move cursor to column 1 or column 2, but before i move cursor to the other row, the changing of row 3 will not be set to DataTable.

It's not good. I want it be saved after click SAVE or Ctrl-S.

So, there is a solution: DataGridView.EndEdit().
but, the row's data didn't change with only DataGridView.EndEdit().
The CurrentRow must lose focus to save the data.
Hmm... Here is a member called CurrentCell
and Someone set CurrentCell to null, then the data is stored.

I tried it, and it works good!
so, if you want to save the current row's data.
run the below 2 statement:

dgv.EndEdit();
dgv.CurrentCell = null;

then the current row's change will be saved in to DataTable, too.


[C#]Get DataTable from Database, Update DataTable to Database

just take a note.

When we want to update database with a list, as you know, there will be 3 kinds of operation: insert(for new rows), update(for changed rows), delete(for deleted rows)

for a single record, it will be easy. But for a list of data, it will be a nightmare.

use the .NET DataAdapter, we can make it easier.
for base, we have sqlConnectString for default connection, and we try to access all columns of demoTable. There is a global DataTable named dt.

to make the example for common case, I will type it for SQL server.

1. to get DataTable from Database
string sql = @"SELECT * FROM demoTable;";
using(var conn = new SQLConnection(sqlConnectString))
{
    conn.Open();
    using(var cmd = new SQLCommand(conn))
    {
        cmd.CommandText = sql;
        var reader = cmd.ExecuteReader();
        dt.Load(reader);
    }
}
2. to update DataTable's data to Database
string sql = @"SELECT * FROM demoTable;";
using(var conn = new SQLConnection(sqlConnectString))
{
    conn.Open();
    var adp = new SQLDataAdapter(sql, conn);
    var cmb = new SQLCommandBuilder(adp);
    adp.Update(dt);
}

to speed up the database access, can add transaction commands. Begin the transaction before update, and commit the transaction after update.

2013-10-07

444句實用英語

1. I see.我明白了
2. I quit! 我不干了!
3. Let go! 放手!
4. Me too.我也是。
5. My god! 天哪!
6. No way! 不行!
7. Come on.來吧(趕快)
8. Hold on.等一等。
9. I agree。我同意。
10. Not bad.還不錯。
11. Not yet.還沒。
12. See you.再見。
13. Shut up! 閉嘴!
14. So long.再見。
15. Why not? 好呀! (為什麼不呢?)
16. Allow me.讓我來。
17. Be quiet! 安靜點!
18. Cheer up! 振作起來!
19. Good job! 做得好!
20. Have fun! 玩得開心!
21. How much? 多少錢?
22. I'm full.我飽了。
23. I'm home.我回來了。
24. I'm lost.我迷路了。
25. My treat.我請客。
26. So do I.我也一樣。
27. This way。這邊請。
28. After you.您先。
29. Bless you! 祝福你!
30. Follow me.跟我來。
31. Forget it! 休想! (算了!)
32. Good luck! 祝好運!
33. I decline! 我拒絕!
34. I promise.我保證。
35. Of course! 當然了!
36. Slow down! 慢點!
37. Take care! 保重!
38. They hurt. (傷口)疼。
39. Try again.再試試。
40. Watch out! 當心。
41. What's up? 有什麼事嗎?
42. Be careful! 注意!
43. Bottoms up! 乾杯(見底)!
44. Don't move! 不許動!
45. Guess what? 猜猜看?
46. I doubt it 我懷疑。
47. I think so.我也這麼想。
48. I'm single.我是單身貴族。
49. Keep it up! 堅持下去!
50. Let me see.讓我想想。
51. Never mind.不要緊。
52. No problem! 沒問題!
53. That's all! 就這樣!
54. Time is up.時間快到了。
55. What's new? 有什麼新鮮事嗎?
56. Count me on 算上我。
57. Don't worry.別擔心。
58. Feel better? 好點了嗎?
59. I love you! 我愛你!
60. I'm his fan。我是他的影迷。
61. Is it yours? 這是你的嗎?
62. That's neat.這很好。
63. Are you sure? 你肯定嗎?
64. Do l have to 非做不可嗎?
65. He is my age.他和我同歲。
66. Here you are.給你。
67. No one knows . 沒有人知道。
68. Take it easy.別緊張。
69. What a pity! 太遺憾了!
70. Any thing else? 還要別的嗎?
71. To be careful! 一定要小心!
72. Do me a favor? 幫個忙,好嗎?
73. Help yourself.別客氣。
74. I'm on a diet.我在節食。
75. Keep in Touch.保持聯絡。
76. Time is money.時間就是金錢。
77. Who's calling? 是哪一位?
78. You did right.你做得對。
79. You set me up! 你出賣我!
80. Can I help you? 我能幫你嗎?
81. Enjoy yourself! 祝你玩得開心!
82. Excuse me,Sir.先生,對不起。
83. Give me a hand! 幫幫我!
84. How's it going? 怎麼樣?
85. I have no idea.我沒有頭緒。
86. I just made it! 我做到了!
87. I'll see to it 我會留意的。
88. I'm in a hurry! 我在趕時間!
89. It's her field.這是她的本行。
90. It's up to you.由你決定。
91. Just wonderful! 簡直太棒了!
92. What about you? 你呢?
93. You owe me one.你欠我一個人情。
94. You're welcome.不客氣。
95. Any day will do.哪一天都行夕
96. Are you kidding? 你在開玩笑吧!
97. Congratulations! 祝賀你!
98. T can't help it. 我情不自禁。
99. I don't mean it. 我不是故意的。
100. I'll fix you Up.我會幫你打點的
101. It sounds great!.聽起來很不錯。
102. It's a fine day。今天是個好天。
103. So far,So good.目前還不錯。
104. What time is it? 幾點了?
105. You can make it! 你能做到!
106. Control yourself! 克制一下!
107. He came by train.他乘火車來。
108. He is ill in bed.他臥病在床。
109. He lacks courage.他缺乏勇氣。
110. How's everything? 一切還好吧?
111. I have no choice.我別無選擇。
112. I like ice-cream.我喜歡吃冰淇淋。
113. I love this game.我鍾愛這項運動。
114. I'll try my best.我盡力而為。
115. I'm On your side.我全力支持你。
116. Long time no see! 好久不見!
117. No pain,no gain.不勞無獲。
118. Well,it depends 噢,這得看情況。
119. We're all for it.我們全都同意。
120. What a good deal! 真便宜!
121. What should I do? 我該怎麼辦?
122. You asked for it! 你自討苦吃!
123. You have my word.我保證。
124. Believe it or not! 信不信由你!
125. Don't count on me.別指望我。
126. Don't fall for it! 別上當!
127. Don't let me down.別讓我失望。
128. Easy come easy go.來得容易,去得快。
129. I beg your pardon.請你原諒。
130. I beg your pardon? 請您再說一遍(我沒有聽清)。
131. I'll be back soon.我馬上回來。
132. I'll check it out.我去查查看。
133. It’s a long story.說來話長。
134. It’s Sunday today.今天是星期天。
135. Just wait and see! 等著瞧!
136. Make up your mind.做個決定吧。
137. That's all I need.我就要這些。
138. The view is great.景色多麼漂亮!
139. The wall has ears.隔牆有耳。
140. There comes a bus.汽車來了。
141. What day is today? 今天星期幾?
142. What do you think? 你怎麼認為?
143. Who told you that? 誰告訴你的?
144. Who's kicking off? 現在是誰在開球?
145. Yes,I suppose So.是的,我也這麼認為。
146. You can't miss it 你一定能找到的。
147. Any messages for me? 有我的留言嗎?
148. Don't be so modest.別謙虛了。
149. Don't give me that! 少來這套!
150. He is a smart boy.他是個小機靈鬼。
151. He is just a child.他只是個孩子。
152. I can't follow you.我不懂你說的。
153. I felt sort of ill. 我感覺有點不適。
154. I have a good idea! 我有一個好主意。
155. It is growing cool.天氣漸漸涼爽起來。
156. It seems all right.看來這沒問題。
157. It's going too far.太離譜了。
158. May I use your pen? 我可以用你的筆嗎?
159. She had a bad cold.她患了重感冒。
160. That's a good idea.這個主意真不錯。
161. The answer is zero.白忙了。
162. What does she like? 她喜歡什麼?
163. As soon as possible! 越快越好!
164. He can hardly speak.他幾乎說不出話來。
165. He always talks big.他總是吹牛。
166. He won an election.他在選舉中獲勝。
167. I am a football fan.我是個足球迷。
168. If only I could fly.要是我能飛就好了。
169. I'll be right there.我馬上就到。
170. I'll see you at six.我六點鐘見你。
171. IS it true or false? 這是對的還是錯的?
172. Just read it for me.就讀給我聽好了。
173. Knowledge is power.知識就是力量。
174. Move out of my way! 讓開!
175. Time is running out.沒時間了。
176. We are good friends.我們是好朋友。
177. What's your trouble? 你哪兒不舒服?
178. You did fairly well! 你幹得相當不錯1
179. Clothes make the man.人要衣裝。
180. Did you miss the bus? 你錯過公共汽車了?
181. Don't lose your head。不要驚慌失措。
182. He can't take a joke.他開不得玩笑。
183. He owes my uncle $100.他欠我叔叔100美元。
184. How are things going? 事情進展得怎樣?
185. How are you recently? 最近怎麼樣?
186. I know all about it.我知道有關它的一切。
187. It really takes time.這樣太耽誤時間了。
188. It's against the law.這是違法的。
189. Love me,love my dog. (諺語)愛屋及烏。
190. My mouth is watering.我要流口水了。
191. Speak louder,please.說話請大聲點兒。
192. This boy has no job.這個男孩沒有工作。
193. This house is my own.這所房子是我自己的。
194. What happened to you? 你怎麼了?
195. You are just in time. 你來得正是時候。
196. You need to workout.你需要去運動鍛煉一下。
197. Your hand feels cold.你的手摸起來很冷。 。
198. Don't be so childish. 別這麼孩子氣。
199. Don't trust to chance! 不要碰運氣。
200. Fasten your seat belt.係好你的安全帶。
201. He has a large income. 他有很高的收入。
202. He looks very healthy.他看來很健康。
203. He paused for a reply.他停下來等著·回答。
204. He repaired his house.他修理了他的房子。
205. He suggested a picnic. 他建議搞一次野餐。
206. Here's a gift for you.這裡有個禮物送給你。
207. How much does it cost? 多少錢?
208. I caught the last bus. 我趕上了最後一班車。
209. I could hardly speak.我簡直說不出話來。
210. I'll have to try that.我得試試這麼做。
211. I'm very proud of you.我為你感到非常驕傲。
212. It doesn't make sense. 這沒有意義(不合常理)。
213. Make yourself at home.請不要拘禮。
214. My car needs washing.我的車需要洗一洗。
215. None of your business! 與你無關!
216. Not a sound was heard. 一點聲音也沒有。
217. That's always the case.習以為常了。
218. The road divides here. 這條路在這里分岔。
219. Those are watermelons.那些是西瓜。
220. What a nice day it is! 今天天氣真好!
221. What's wrong with you? 你哪裡不對勁?
222. You are a chicken.你是個膽小鬼。
223. A lovely day,isn't it? 好天氣,是嗎?
224. He is collecting money.他在籌集資金。
225. He was born in New York.他出生在紐約。
226. He was not a bit tired.他一點也不累。
227. I will be more careful.我會小心一些的,
228. I will never forget it.我會記著的。
229. It is Just what I need.這正是我所需要的。
230. It rather surprised me.那事使我頗感驚訝。
231. Just around the comer.就在附近。
232. Just for entertainment.只是為了消遣一下。
233. Let bygones be bygones.過去的,就讓它過去吧。
234. Mother doesn't make up.媽媽不化妝。
235. Oh,you are kidding me.哦,你別拿我開玩笑了。
236. She has been to school. 她上學去了。
237. Skating is interesting.滑冰很有趣。
238. Supper is ready at six.晚餐六點鐘就好了。
239. That's a terrific idea! 真是好主意!
240. What horrible weather! 這鬼天氣!
241. Which would you prefer? 你要選哪個?
242. Does she like ice-cream? 她喜歡吃冰淇淋嗎?
243. First come first served.先到先得。
244. Great minds think alike.英雄所見略同。
245. He has a sense of humor.他有幽默感。
246. He is acting an old man.他正扮演一個老人。
247. He is looking for a job.他正在找工作。
248. He doesn't care about me.他並不在乎我。
249. I develop films myself.我自己沖洗照片。
250. I felt no regret for it.對這件事我不覺得後悔。
251. I get up at six o'clock.我六點起床。
252. I meet the boss himself.我見到了老闆本人。
253. I owe you for my dinner. 我欠你晚餐的錢。
254. I really enjoyed myself.我玩得很開心。
255. I'm fed up with my work! 我對工作煩死了!
256. It's no use complaining. 發牢騷沒什麼用。
257. She's under the weather.她心情·不好。
258. The child sobbed sadly.小孩傷心地抽泣著。
259. The rumor had no basis.那謠言沒有·根據。
260. They praised him highly.他們大大地表揚了他。
261. Winter is a cold season. 冬天是一個,寒冷的季節。
262. You can call me any time.你可以隨時打電話給我。
263. 15 divided by 3 equals 5. 15除以3等於5。
264. All for one,one for all.我為人人,人人為我。
265. East,west,home is best.金窩,銀窩,不如自己的草窩。
266. He grasped both my hands. 他緊握住我的雙手。
267. He is physically mature.他身體己發育成熟。
268. I am so sorry about this. 對此我非常抱歉(遺憾)。
269. I can't afford a new car.我買不起一部新車。
270. I do want to see him now.我現在確實很想去見他。
271. I have the right to know. 我有權知道。
272. I heard some one laughing. 我聽見有人在笑。
273. I suppose you dance much.我想你常常跳舞吧。
274. I walked across the park.我穿過了公園。
275. I'll just play it by ear.我到時隨機應變。
276. I'm not sure I can do it.恐怕這事我幹不了。
277. I'm not used to drinking.我不習慣喝酒。
278. Is the cut still painful? 傷口還在痛嗎?
279. It's too good to be true! 好得難以置信。
280. Jean is a blue-eyed girl.珍是個藍眼睛的女孩。
281. Let's not waste our time.咱們別浪費時間了。
282. May I ask some questions? 我可以問幾個問題嗎?
283. Money is not everything.金錢不是一切。
284. Neither of the men spoke.兩個人都沒說過話。
285. Stop making such a noise.別吵了。
286. That makes no difference.沒什麼區別。
287. The price is reasonable.價格還算合理。
288. They crowned him king.他們擁立他為國王。
289. They're in red and white. 他們穿著紅白相間的衣服。
290. We all desire happiness. 我們都想要幸福。
291. We just caught the plane 我們剛好趕上了飛機。
292. What shall we do tonight? 我們今天晚上去干點兒什麼呢?
293. What's your goal in life 你的人生目標是什麼?
294. When was the house built? 這幢房子是什麼時候建造的?
295. Why did you stay at home? 為什麼呆在家裡?
296. Would you like some help? 需要幫忙嗎?
297. You mustn't aim too high 你不可好高騖遠。
298. You're really killing me! 真是笑死我了!
299. You've got a point there.你說得挺有道理的。
300. Bein
g criticized is awful! 被人批評真是痛苦
301. Did you enter the contest? 你參加比賽了嗎?
302. Do you accept credit cards? 你們收信用卡嗎?
303. Don't cry over split milk.不要做無益的後悔。
304. Don't let chances pass by.不要讓機遇從我們身邊溜走。
305. He owned himself defeated.他承認自己失敗了。
306. He seems at little nervous.他顯得有點緊張。
307. He strolls about the town.他在鎮上四處遛達。
308. Her tooth ached all night. 她牙疼了一整夜。
309. How about a drink tonight? 今晚喝一杯怎樣?
310. I can do nothing but that. 我只會做那件事。
311. I get hold of you at last.我終於找到你了。
312. I have a surprise for you.我有一個意想不到的東西給你看。
313. I like all kinds of fruit.我喜歡各種各樣的水果。
314. I saw it with my own eyes.我親眼所見。
315. I will arrange everything.我會安排一切的。
316. I wish I knew my neighbor.我很想認識我的鄰居。
317. I would like to check out.我想結帳。
318. It has be come much cooler.天氣變得涼爽多了。
319. It's time you went to bed.你早就該睡覺了。
320. No spitting on the street.禁止在大街上吐痰。
321. She was totally exhausted.她累垮了。
322. Show your tickets,please.請出示你的票。
323. Thank you for your advice.謝謝你的建議。
324. That's the latest fashion.這是最流行的款式。
325. The train arrived on time.火車準時到達。
326. There go the house lights.劇院的燈光滅了。
327. They are paid by the hour.他們按時取酬。
328. Things are getting better.情況正在好轉。
329. Wake me up at five thirty.請在五點半叫醒我。
330. We are all busy with work.我們都忙於工作。
331. Where do you want to meet? 你想在哪兒見面?
332. You can get what you want.你能得到你想要的。
333. A barking dog doesn't bite! 吠犬不咬人。
334. Are you free this Saturday? 你這個星期六有空嗎?
335. Be careful not to fall ill.注意不要生病了。
336. Being a mother is not easy.做一個母親是不容易的。
337. Brevity is the soul of wit.簡潔是智慧的精華。
338. Cancer is a deadly disease.癌症是一種致命的疾病。
339. Did you fight with others? 你又和別人打架了嗎?
340. Don't dream away your time.不要虛度光陰。
341. Don't keep me waiting long.不要讓我等得太久。
342. He has a remarkable memory.他有驚人的記憶力。
343. He has completed the task.他完成了這個任務。
344. He has quite a few friends.他有不少的朋友。
345. He is capable of any crime.他什麼樣的壞事都能幹得出來。
346. He walks with a quick pace.他快步走路。
347. He was not a little tired.他很累。
348. His looks are always funny.他的樣子總是滑稽可笑。
349. How about going to a movie? 去看場電影怎麼樣?
350. I think I've caught a cold.我想我得了感冒。
351. I was taking care of Sally. 我在照顧薩莉。
352. I wish I lived in NEWYORK.我希望住在紐約。
353. I'm very glad to hear that.很高興聽你這樣說。
354. I'm your lucky fellow then. 我就是你的幸運舞伴啦!
355. It's none of your business! 這不關你的事兒!
356. No littering on the campus.在校園內不准亂丟廢物。
357. She is a good-looking girl. 她是一個漂亮女孩。
358. She mended the broken doll.她修補了破了的洋娃娃。
359. So I just take what I want.那麼我只拿我所需要的東西。
360. Spring is a pretty season, 春天是一個好季節。
361. The figure seems all Right.數目看起來是對的。
362. The stars are too far away.星星太遙遠了。
363. The whole world knows that.全世界都知道。
364. Tomorrow will be a holiday.明天放假。
365. We walk on the garden path.我們走在花園小徑上。
366. What you need is just rest.你需要的就是休息。
367. What's your favorite steps? 你最喜歡跳什麼舞?
368. You'd better let her alone.你們最好是讓她一個人呆會兒。
369. A lost chance never returns.錯過的機會永不再來。
370. Don't let this get you down.不要為此灰心喪氣。
371. He shot the lion with a gun. 他用槍把獅子打死了。
372. I don't think you are right.我認為你是不對的。
373. I have never seen the movie.我從未看過那部電影。
374. I haven't seen you for ages.我好久沒見到你了。
375. I was alone,but not lonely.我獨自一人,但並不覺得寂寞。
376. I went there three days ago.我三天前去過那兒。
377. It's a friendly competition.這是一場友誼賽。
378. It's very thoughtful of you.你想得真周到。
379. May I speak to Lora,please? 我能和勞拉說話嗎?
380. Mr.Wang is fixing his bike.王先生在修他的自行車。
381. My brother is seeking a job.我弟弟正在找工作。
382. Nancy will retire next year.南希明年就退休了。
383. Neither you nor he is wrong.你沒錯,他也沒錯。
384. Opportunity knocks but once.機不可失,時不再來。
385. She dressed herself hastily.她匆忙穿上衣服。
386. She hired a car by the hour.她租了一輛按鐘點計費的汽車。
387. Someone is ringing the bell.有人在按門鈴。
388. The Smiths are my neighbors. 史密斯一家是我的鄰居。
389. These shoes don't fit right.這雙鞋不太合適。
390. This is only the first half.這才是上半場呢。
391. This pen doesn't write well.這鋼筆不好寫。
392. Would you like a cup of tea? 你想喝杯茶嗎?
393. You really look sharp today.你今天真漂亮。
394. Another cat came to my house.又有一隻貓來到我家了。
395. Check your answers with mine.把你的答案跟我的核對一下。
396. Don't keep the truth from me.別瞞著我事實真相。
397. Everything has its beginning.凡事都有開端。
398. He came to the point at once.他一下子就說到了點子上。
399. He fell behind with his work.他工作落後了。
400. He is the happiest man alive. 他是世界上最快樂的人
401. He neither smokes nor drinks.他既不抽煙也不喝酒。
402. He ran his horse up the hill.他策馬跑上小山。
403. He reminds me of his brother. 他使我想起了他的弟弟。
404. He was efficient in his work.他工作效率高。
405. He will do anything but work.只要不是乾活,他幹什麼都行。
406. His father runs a restaurant.他的父親經營一家餐館。
407. I have something to tell you.我有事要告訴你。
408. I smelled a smell of cooking.我聞到了燒菜做飯的味道。
409. I want to see the film again.我真想再看一遍。
410. I've got too much work to do.我要做的工作太多了。
411. Let's go for a walk,shall we? 咱們出去走走,好嗎?
412. Please let me check the bill.請讓我核對一下帳單。
413. Plenty of sleep is healthful.充足的睡眠有益於健康。
414. The sun comes up in the east.太陽從東方升起。
415. This is because we feel pain.這是因為我們能感到疼痛。
416. What do you desire me to do? 你想要我做什麼?
417. What you said was quite true. 你所說的完全符合事實。
418. You can either stay or leave.你或者留下或者離開。
419. Your life is your own affair.你的生活是你自己的事。
420. All that glitters is not gold.發閃光的不全是黃金。
421. Are you going to have a party? 你要舉行聚會嗎?
422. Aren't you concerned about it? 難道你不擔心嗎?
423. Don't forget to keep in touch.別忘了保持聯繫。
424. He broke his words once again. 他又一次違背了諾言。
425. He is in his everyday clothes.他穿著平常的衣服。
426. He is taller than I by ahead.他比我高一頭。
427. He led them down the mountain.他帶他們下山。
428. He was trained to be a lawyer.他被培養成一名律師。
429. I am afraid that l have to go.我要走了。
430. I don't have any cash with me.我身上沒帶現金。
431. I have been putting on weight.我開始發胖了。
432. I have just finished the book.我剛剛讀完這本書。
433. I was late for work yesterday, 我昨天上班遲到了。
434. It appears to be a true story.這故事似乎是真的。
435. I've got to start working out.我必須開始做健身運動了。
436. Japan is to the east of China.日本在中國的東部。
437. John asked Grace to marry him, 約翰向格雷斯求婚。
438. My watch is faster than yours.我的表比你的表快。
439. New China was founded in 1949. 1949年新中國成立。
440. Thanks for your flattering me.多謝你的誇獎。
441. They charged the fault on him.他們把過失歸咎於他。
442. This car is in good condition.這車性能很好。
443. This work itself is very easy.這件工作本身很容易。
444. Truth is the daughter of time.時間見真理。

2013-10-01

UVa 516 Solution

#include <iostream>
#include <vector>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <sstream>
using namespace std;

const int N = 32767;
bool sieve[N];
int prime_time[N][2];

void eratosthenes() {
    // 0 和 1 是質數
    sieve[0] = true;
    sieve[1] = true;

    int sqrt_value = sqrt(N);

    // 找下一個未被刪掉的數字
    for (int i = 2; i <= sqrt_value; i++)
        if (!sieve[i]) {
            // k是倍數,j是質數i的倍數。
            // 由大到小判斷,當sieve[k]成立時,
            // k才能涵蓋所有「大於等於i的質數,其倍數」倍。
            for (int k = (N - 1) / i, j = i * k; k >= i; k--, j -= i)
                if (!sieve[k])
                    sieve[j] = true;
            // 運用小範圍的sieve[k],避免存取大範圍的sieve[j],
            // 大幅減少cache miss。
        }


}

int main(int argc, char** argv){
    int a,b,total;
    
    eratosthenes();
    
    // 製作質數表
    vector<int> prime;
    for (int i = 1; i < N; i++) {
        if (!sieve[i])
            prime.push_back(i);
    }
  
    string s;

    while(1){
        getline(cin,s);
        
        total=1;
        // check the first number
        // if the first number is 0, get break;
        if(s[0] == '0') {
            break;
        }
        stringstream ss;
        ss.str(s);
        
        while(ss >> a >> b){
            //printf("DEBUG: A=%d, B=%d\n",a,b);
            for(int i=0;i<b;i++){
                total*=a;
            }
            
        }
        
        total -= 1;
        
        //printf("DEBUG:total:%d\n",total);
        
        int hit=0;
        
        bool first=true;
        // 從最大的質數開始找
        int index = prime.size()-1;
        //printf("DEBUG: index initial: %d\n",index);
        while(total < prime[index] && index >= 1) {index--;}
        //printf("DEBUG2: index initial: %d\n",index);
        
        while(index >= 0){
            if(total % prime[index] == 0){
                // if hit, add the hits
                total /= prime[index];
                if(hit == 0) {
                    if(first){
                        first=false;
                    }else{
                        cout << " ";
                    }
                    cout << prime[index];
                }
                hit += 1;
            }else{
                index--;
                if(hit > 0){
                    cout << " " << hit;
                    hit=0;
                }
            }
        }
        cout<<"\n";
         
    }
}

UVa 406 Solution

#include <iostream>
#include <vector>
#include <cmath>
#include <cstdio>
using namespace std;

const int N = 1000;
bool sieve[N];

void eratosthenes() {
    // 0 和 1 是質數
    sieve[0] = true;
    sieve[1] = true;

    int sqrt_value = sqrt(N);

    // 找下一個未被刪掉的數字
    for (int i = 2; i <= sqrt_value; i++)
        if (!sieve[i]) {
            // k是倍數,j是質數i的倍數。
            // 由大到小判斷,當sieve[k]成立時,
            // k才能涵蓋所有「大於等於i的質數,其倍數」倍。
            for (int k = (N - 1) / i, j = i * k; k >= i; k--, j -= i)
                if (!sieve[k])
                    sieve[j] = true;
            // 運用小範圍的sieve[k],避免存取大範圍的sieve[j],
            // 大幅減少cache miss。
        }


}

int main(int argc, char** argv){
    int iN, iC;
    
    eratosthenes();
    
    // 製作質數表
    vector<int> prime;
    for (int i = 1; i < N; i++) {
        if (!sieve[i])
            prime.push_back(i);
    }

    while(cin>>iN>>iC){
        //scanf("%d %d",&iN,&iC);
        printf("%d %d:",iN,iC);
        
        int doubleC = 2 * iC;
        int i,c;
        
        vector<int> output_prime;
  output_prime.clear();
        //get the primes < N
  output_prime.push_back(1);
        for(i=0;i<prime.size();i++){
            if(prime[i]<=iN) output_prime.push_back(prime[i]);
        }
        int index = output_prime.size();
        
        if (index % 2) {
            c = (iC * 2) - 1;
            i = (long) (ceil(index/2) - floor(c/2));
 
            if (i <= 0) {
                for (i = 0; i < index; i++)
                    printf(" %d", output_prime [i]);
            }
 
            else {
                while (i <= (ceil(index/2) + floor(c/2))) 
                    printf(" %d", output_prime [i++]);
            }
        }
 
        else {
            c = iC * 2;
            i = ((index/2)+1) - (c/2) - 1;
 
            if (i <= 0) {
                for (i = 0; i < index; i++)
                    printf(" %d", output_prime [i]);
            }
 
            else {
                while (i < ((index/2) + (c/2)))
                    printf(" %d", output_prime [i++]);
            }
        }
        printf ("\n\n");
    }
}

2013-09-30

演算法筆記

一個台灣的演算法介紹的網站。
最近又開始解UVa的題目。想找個質因數分解的最佳演算法,Google到的前幾名的網站就是這個網站。十分不錯。

但是我會建議站長把內容copy一份起來。因為站長是把網站架在台灣的大學內部。
Anyway, 我會在我的網路硬碟上copy一份XD, maybe

http://www.csie.ntnu.edu.tw/~u91029/index.html

Khan Academy

中文翻作可汗學院。日文稱作カーンアカデミー。

一個網路的免費學術機構,以YouTube提供免費的網路課程教學。內容包含了各種高等教育專題。由於影片公佈在YouTube上,各國有志者利用YouTube的字幕旁白功能,為他加入了各國的翻譯。
官方網站有提供簡體中文翻譯,但沒有日文版本。

相關連結:


2013年9月底為止,提供以下的主題
  • 數學 Math
    • 算術與準代數Arithmetic and pre-algebra
    • 代數學 Algebra
    • 幾何學 Geometry
    • 三角函數與準微積分 Trigonometry and precalculus
    • 微積分 Calculus
    • 機率與統計 Probability and statistics
    • 微分方程 Differential equations
    • 線性代數 Linear algebra
    • 應用數學 Applied math
    • 娛樂數學 Recreational math
    • 考試準備Test prep
    • 數學競賽 Math contests
  • 科學 Science
    • 生物學 Biology
    • 物理學 Physics
    • 化學 Chemistry
    • 有機化學 Organic chemistry
    • 宇宙與天文學 Cosmology and astronomy
    • Python programming
    • 健康與醫藥 Healthcare and medicine
    • 發現與計劃 Discoveries and Projects
  • 經濟學與金融學 Economics and finance
    • 個體經濟 Microeconomics
    • 宏觀經濟 Macroeconomics
    • 金融與市場Finance and capital markets
    • 創業 Entrepreneurship
  • 人類學 Humanities
    • 世界史 World history
    • 美術史 Art history
    • 美國市民 American Civics
  • 協力者內容 Partner Content
    • Standford School of Medicine
    • MIT+K12
    • LeBron asks
    • Crash Course

2013-09-21

Enable/Disable the FTP Server service on MacOSX 10.8

In MacOSX 10.8, you cannot find the easy switch for enable/disable FTP server.

To Enable FTP Server:
sudo -s launchctl load -w /System/Library/LaunchDaemons/ftp.plist

To Disable FTP Server:
sudo -s launchctl unload -w /System/Library/LaunchDaemons/ftp.plist

2013-08-22

Start / Stop / Restart Apache HTTP Service in MAC

START:
sudo apachectl start
STOP:
sudo apachectl stop
RESTART(unload service and load the service again):
sudo apachectl restart
RESTART but not disconnect all the linked connection(reload the config file)
sudo apachectl graceful

In fact, it calls the /usr/sbin/httpd, so you should set option -k before start|stop|restart|graceful|graceful-stop

for more information, try man apachectl or apachectl -h

2013-08-10

Draftsightで線の太さをグラフィック領域で表示させることに

ノート程度:

線の太さを画面に反映させる
Win:ツール>オプション でオプションウィンドを開き
作図スタイル>アクティブな作図スタイル>線のフォント で
[グラフィック領域で太さを表示]にチェックを入れる。

Mac:
System Menu  設定 / 形式→寸法スタイル でオプションウィンドを開き
その他はWinと同じ

2013-07-24

MACのSCREEN CAPTURE

Save as a png file(on desktop)
1) Command + Shift + 3 Capture Whole Screen 
2) Command + Shift + 4 Capture Part of Screen 
3) Command + Shift + 4 and press Space Bar Capture Objects (Icon, Dock, Menu, Submenu, etc)

Save in clipboard
1) Command + Shift + Control + 3 Capture Whole Screen 
2) Command + Shift + Control + 4 Capture Part of Screen 
3) Command + Shift + Control + 4 and press Space Bar Capture Objects

http://guides.macrumors.com/Taking_Screenshots_in_Mac_OS_X

2013-07-05

DraftSight - モデル空間とペーパー空間の切り替え

AutoCADではボタンで1クリック切り替えですけどね
DraftSightではややめんどくさい

印刷シート(シートタブ)内で、全空間(モデルタブ)の特定の場所だけ出力させたい時に、ペーパー空間(シート ワークスペース)よりモデル空間(モデル ワークスペース)へ切り替える必要がある。

やり方はコマンドにSHEETMODEを入力する。

逆にモデル空間に切り替えるときにはMODELMODEを入力するか、シート画面でダブルクリックする。

これで苦労していんた自分はやはり2D CADに慣れていないなぁ
Solidworksの簡単さにありがたい。

2013-06-29

台湾戸籍謄本の日本語訳

日本で結婚するときに、台湾の戸籍謄本の訳本が要る。
検索したら、いろいろ有用な先人たちの情報があります。



んで、一応訳してみました。
これで大丈夫でしょう(自称)

2013-06-20

Free 2D CAD - DraftSight

如果你像我一樣想找個免費的好用CAD
可以相容AutoCAD,開圖又不會跑掉
那你可以試試DraftSight

DraftSight是有名的3D CAD公司Dassault Systemes開發的免費2D CAD軟體。
同一家公司也出過有名的Solidworks以及CATIA。

DraftSight相容於AutoCAD,介面也跟AutoCAD非常的類似,熟悉AutoCAD的朋友應該馬上就可以上手。同時,他也公開了Windows/Mac/Linux等不同平台上的包裝,跨平台的幫助下,其實有機會可以建立一個完全免費的CAD環境(Ubuntu + DraftSight)

下載網址如下:
(日文版) http://www.3ds.com/jp/products/draftsight/free-cad-software/
(簡中版) http://www.3ds.com/cn/products/draftsight/download-draftsight/

* 免費只限於獨立版本,每年需要登記(但登記也是免費的!!)
** 撰寫時,版本編號V1R3.1

2013-06-18

Online LaTeX Equation Editor

這幾天為了打出好看的數學/化學方程式而煩惱...
做出來的東西是要放在網頁上,而不是要放在Word裡面(在Office裡面的話就直接用內建的方程式編輯器就好啦),偏偏公司的電腦又不給灌OOo(不然我就可以用OOo的方程式編輯器存成png檔了)

找了半天,原來有線上轉換器XD

基本上原理就是運用後台的LaTeX解析器轉換TeX文法,然後將生成出來的方程式文件轉換成圖像檔讓我們可以抓下來用

Codecogs: Online Latex Equation Editor - create, integrate and download

HostMath: http://www.hostmath.com/

OK, 又解決一個問題

Enable Reference Extension for MediaWiki

在某些跟我一樣喜歡用MediaWiki形式撰寫內部資料的人來說,當你想要如同在Wikipedia裡面一樣用<ref>標籤來標示參考資料/腳註,你必須自己下載Cite外掛

安裝方法很簡單,
  1. 到Cite外掛的頁面,下載最新的安定版本
  2. 把內容解壓縮到你的MediaWiki目錄中的extensions\Cite
  3. 編輯你的MediaWiki目錄中的LocalSetting.php檔,加入下面語句:
    require_once("$IP/extensions/Cite/Cite.php");
使用的時候,加入下面的標籤到你的MediaWiki編輯頁(如果你有開啟進階編輯輔助器,就直接插入腳註就好XD)
<ref name="example">腳註內容</ref>

最後在參考文獻處打上<references /> ,MediaWiki就會自動把你之前打上的所有註解列在最後面囉。簡單吧XD

2013-06-09

3.5吋軟碟片FAT磁區解析-part 5. 資料區格式

本來應該是不需要寫到這裡的。但是實際上處理時遇上了一些問題,讓我寫在這裡吧。

第1個問題,EOF
當你分析整個sector,你會發現:要怎麼處理檔案結束(EOF)阿?
當讀取整個磁區時,它一定會是磁區的倍數(512的倍數)大小

但是,實際上一個檔案並不一定會佔滿整個磁區。或者說,很小的機率下檔案會是剛好一個磁區大小。

於是,還是需要讀到EOF來結束實際上的二次元檔案輸出

但是,EOF是C裡面的處理符號,當使用C#之類的語言的時候要怎麼處理呢?

答案是,讀到0x1A就是EOF!!

又但是...這個論點只限於處理文字檔案,不適合處理一般的binary檔案
那要怎麼決定檔案結束呢?

很簡單,記不記得在讀取根目錄結構的時候有個參數是"檔案大小"?
對,讀到應讀取的檔案大小之後就可以停止了。這樣就可以避免誤讀0x1A了

以上,結束 XD


3.5吋軟碟片FAT磁區解析-part.4 根目錄

位於根目錄區域和子目錄區域的目錄條目都是下面的格式:
位元組偏移長度描述
0x008DOS檔名(附加空格)
第一個位元組可以是下面的特殊數值:
0x00這個條目有用並且後面沒有被佔用條目
0x05最初字元確實是0xE5
0x2E'點'條目;'.'或者'..'
0xE5這個條目曾經被刪除不再有用。取消刪除檔案工具作為取消刪除的一步必須使用一個正常的字元取代它。
0x083DOS副檔名(空格補齊)
0x0b1檔案內容
第一個位元組可以是下面一些特殊值:
掩碼描述
00x01唯讀
10x02隱藏
20x04系統
30x08卷標
40x10子目錄
50x20檔案
60x40裝置(內部使用,磁碟上看不到)
70x80沒有使用

內容值0x0F用來表示長檔名條目。
0x0c1保留,NT使用(參見後面)
0x0d1建立時間,最小時間解析度:10ms單位,數值從0到199。
0x0e2建立時間。小時、分鐘和秒根據後面的圖示描述進行編碼:
描述
15-11小時(0-23)
10-5分鐘(0-59)
4-0秒/2(0-29)
注意只保存了2秒的解析度。更細解析度的檔案建立時間在偏移0x0d處。
0x102建立日期。年、月和日根據後面的圖示編碼:
描述
15-9年(0 = 1980, 127 = 2107)
8-5月(1 = 1月,12 = 12月)
4-0日(1 - 31)
0x122最近存取時間;參見偏移0x0e處的描述。
0x142FAT12和FAT16中的EA-Index(OS/2和NT使用),FAT32中第一個叢集的兩個高位元組
0x162最後更改時間;參見偏移0x0e處的描述。
0x182最後更改日期; 參見偏移0x10處的描述。
0x1a2FAT12和FAT16中的第一個叢集。FAT32中第一個叢集的兩個低位元組。
0x1c4檔案大小
長檔名(LFN)使用一個技巧儲存在FAT檔案系統上——在目錄表中添加假的條目。這些條目使用一個普通檔案無法使用的卷標內容標識,普通檔案無法使用是由於它們被大多數舊的MS-DOS程式忽略。很顯然,一個只包含卷標的目錄被當作空卷,這樣就允許刪除;使用長檔名建立的檔案在從普通的DOS刪除就會發生這樣的情形。

當是長檔名的時候,將會用下面表中的格式來登錄。

位元組偏移長度描述
0x001序列號
0x0110名稱字元(5個UTF-16字元)
0x0b1內容(永遠是0x0F)
0x0c1保留(永遠是0x00)
0x0d1DOS檔名校驗和
0x0e12名稱字元(6個UTF-16字元)
0x1a2第一個叢集(永遠是0x0000)
0x1c4名稱字元(兩個UTF-16字元)

最後須注意的是,舊型的系統因為不支援長檔名,所以通常讀到叢集數是0x0000的時候,就可以直接忽略掉它了


3.5吋軟碟片FAT磁區解析-part.3 檔案分割表

第三章 檔案分割表File Allocation Table (FAT)

基本上,在我整理的這一系列文章裡面,主要討論的目標是FAT12
為什麼叫FAT12呢?
對檔案系統有點認識的人,就知道除了FAT12之外,最常聽到的FAT格式就是FAT16跟FAT32

12/16/32是在說什麼呢?他是指一個FAT佔了多少位元(bit)
沒錯,你沒看錯,是位元而不是位元組
而大家都知道,一個位元組佔了8位元
也就是說,除了FAT12以外,其他的FAT都可以直接讀取/寫入整個位元組來確認磁區位置,只有FAT12這傢伙很難處理



在這裡,要先說明FAT格式下如何取得檔案內容
Step1. 前往根目錄磁區取得檔案的第一磁簇位置
Step2. 取得被標示在第一磁簇位置的二次元檔案內容
Step3. 前往FAT確認下一個磁簇位置
Step4. 取得下一個磁簇位置的二次元內容
Step5. 重覆Step3~4,直到下一個磁簇位置被標示為檔案結尾

由於FAT12用12bit來表示一個磁簇位置,所以通常一個磁簇的內容會是下表的其中一個內容
entry content說明
0x000空白
0x001內部用途保留。由於通常資料都是由第二磁簇開始的,應該是不會用到1號磁簇。
0x002-0xFEF下一個磁簇的位置
0xFF7損壞磁簇
0xFF8-0xFFF檔案結束
未列出的就是保留用的。


很好,你看到了Step3的地方要到FAT取得下一個磁簇位置。
我們調用某個磁碟的第一FAT的前32byte(16 Chars)如下
00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
F0 FF FF 03 40 00 05 60 00 07 80 00 09 A0 00 0B
前12bit 它是0xf0 + 0xf。表示它是2HD的1440KiB的軟碟。12bit的餘下4bit通常會被填入1 第二組,必須是0xfff。
這裡,你想調用第二磁簇的位置,你看到了下一個byte。
什麼鬼?0x034?
喔,不對不對,它是0x003。因為一般的86機是little-endian,所以下面的byte要放到上面來。如果你用的程式剛好可以讀寫一個bit,那當然沒問題
問題在於,通常的程式都是一次讀寫一個byte,也就是說,你一定會讀到8的倍數的bit數
像是這個部分,你必須讀出六個byte分成上下兩部分,分別是0xff,0x0f跟0xf0,0xff
因為他們的bit剛好是 11111111 | 11110000 跟 00001111 | 11111111

...我寫到這裡已經很火大了,因為取得一個簇的時候要分成奇偶數
當是偶數的時候,起始byte位置(從0開始) = 想取得簇數cluster * 3 / 2
當是奇數的時候,起始byte位置(從0開始) = (想取得簇數cluster * 3 - 1) / 2

讀取的時候還好,只需要取得起始位置開始2byte, 然後依照奇偶數進行交集(AND)位元運算。
偶數時,0xff 0x0f
奇數時,0xf0 0xff

寫入的時候就痛苦了,必須先讀出原始位置中重覆的那一個byte,把原始的4bit寫進將要寫入的byte上,然後再寫回FAT表...
好慘...我要寫個慘字

3.5吋軟碟片FAT磁區解析-part.2 啟動磁區


第二章 啟動磁區Boot Sector

對於一般的2HD, 2DD來說、啟動磁區都佔有磁區的前512KiB
啟動磁區的大小,一般的5吋跟3.5吋都是512KiB,只有某些舊式的8吋磁碟會有其他的大小
所以基本上,先讀512KB進來分析就對了!!

雖然最近的系統裡都會定義這個部分,但是某些舊式的系統(像是MSX-DOS 1.0,還有MOTOMAN的軟碟片)會直接跳過這部分,而讀取FAT磁區的第一byte來確認磁碟格式。
當系統讀不出磁碟內容的時候,絕對是Boot Sector被跳過了!!

這512KiB中,資料依照以下內容排列:
Sector
Offset
磁區偏移
BPB
Offser
length
長度
說明
0x000 3 Jump instruction.
跳轉指令(跳過開頭一段區域)
0x003 8 OEM Name (padded with spaces 0x20).
OEM名稱(空白0x20補齊)
0x00B 0x00 2 Bytes per logical sector
磁區位元組數
0x00D 0x02 1 Logical sectors per cluster.
每叢集磁區數
0x00E 0x03 2 Reserved logical sectors
保留磁區數(包括啟動磁區)
0x010 0x05 1 Number of File Allocation Tables.
檔案分配表數目
0x011 0x06 2 Maximum number of FAT12 or FAT16 root directory entries.
根目錄磁區最大登錄數
0x013 0x08 2 Total logical sectors.
總磁區數.
0x015 0x0A 1 Media Descriptor
介質描述。常用0xF0: 2HD144, 0xF9: 2DD720, 0xFB: 2DD640
0x016 0x0B 2 Logical sectors per File Allocation Table for FAT12/FAT16.
每個檔案分配表的邏輯磁區數
0x018 0x0D 2 Physical sectors per track for disks with INT 13h CHS geometry.
磁軌磁區數
0x01A 0x0F 2 Number of heads for disks with INT 13h CHS geometry
磁頭數
0x01C 0x11 4 Count of hidden sectors preceding the partition that contains this FAT volume.
隱藏磁區數
0x020 0x15 4 Total logical sectors(FAT16)
總磁區數。當大於65535時(0xffff)。FAT12下是通常不會用到…
0x026 0x1B 1 Extended boot signature(0x29)
延伸啟動磁區記號。通常為0x29
0x027 0x1C 4 Volume ID(serial number)
磁碟ID。"xxxx-xxxx"  通常是系統時間與系統日期的綜合。至於位元組內容可以參考根目錄磁區的檔案時間與日期
0x02B 0x20 11 Partition Volume Label, padded with blanks(0x20).
分割區標籤。
0x036 0x2B 8 File system type, padded with blanks(0x20).
檔案系統格式。e.g., "FAT12   ","FAT16   ", "FAT     "
0x1FE 2 Boot sector signature (0x55 0xAA)
磁區結束符

為了快速查詢各種參數,請看下面的表(出自英文版的Wikipedia。中文翻譯則以中文維基百科為主)
Media Descriptor
界質描述
0xF0 0xF9 0xFA 0xFB 0xFC 0xFD 0xFE 0xFF
DISC Size
物理磁碟尺寸
3.5" 5.25" 3.5" 3.5"
5.25"
3.5"
5.25"
5.25" 5.25" 5.25" 5.25"
Density
磁碟密度
HD HD DD DD DD DD DD
Modulation
調變
MFM MFM MFM MFM MFM MFM MFM MFM MFM
Formatted Capacity(KiB)
格式化磁碟容量
1440 1200 720 320 640 180 360 160 320
Cylinders(CHS)
磁柱數
80 80 80 80 80 40 40 40 40
Physical sertors/track
磁軌磁區數[0x18]
18 15 9 8 8 9 9 8 8
Number of heads
磁頭數[0x1A]
2 2 2 1 2 1 2 1 2
Bytes/Logical sector
邏輯磁區位元組數[0x0B]
512 512 512 512 512 512 512 512 512
Logical sectors/cluster
每個簇的邏輯磁區數[0x0D]
1 1 2 1 2 1 2 1 2
Reserved Logical Sectors
保留磁區數[0x0E]
1 1 1(2) 1 1 1 1 1 1
Number of FATs
FAT數[0x10]
2 2 2 2 2 2 2 2 2
Root directory entries
根目錄條目數[0x11]
224 224 112 64 112 64 112 64 112
Total logical sectors
總磁區數
2880 2400 1440 640 1280 360 720 320 640
logical sectors/FAT
FAT磁區數
9 7 3 2 2 2 2 1 1
Hidden sectors
隱藏磁區數
0 0 0 0 0 0 0 0 0

2013-06-08

3.5吋軟碟片FAT磁區解析-part.1 磁碟結構

前言

因為XP以後的作業系統把1.44MiB 3.5吋軟碟以外的支援拿掉了
於是其他格式的舊磁片的內容就不能備份到一般電腦內
換句話說,在一般的電腦裡就不能編修軟碟內容...這東西非常棘手

對於某些舊式MC以及機器人(像是MOTOMAN),沒有了新式周圍機器的支援,他們只會輸出2DD型式的內容,於是XP讀不出來他們的內容(對,很機車)。
另外,對於某些舊式的程式來說,他們不會輸出Boot Sector,所以就算裡面資料是正確的,在一般的磁碟分析工具裡面也是讀不出他們的內容的(這點可以用暴力法強迫讀出...請參照FAT一章)

雖然說套用工具去直接控制BIOS可以讓我們直接對磁碟片進行HARD-COPY(就是說完整copy磁片內容,包括所有有用/無用的磁區),但是其實我們還是想看看程式內容寫了些什麼,這樣我們才能分析自己的程式到底跑了些什麼內容。

以下提供主要的三種類3.5吋磁片的內容分析

  1. 2HD, 1.44MiB
  2. 2DD, 720KiB
  3. 2DD, 640KiB

其他的磁片種類,請看英文Wikipedia FAT12的分析(非常詳細,只是很難看懂)

第一章:磁碟結構


要寫的東西有點多,我就簡單的整理一下就好

一般的FAT12/16格式,磁碟結構內容都是照下面的順序排列

名稱英文磁區大小(sector數)
啟動磁區Boot Sector保留sector大小。一般是512KB(1 sector)
檔案分配表#1File Allocation Table #1FAT磁區大小
檔案分配表#2File Allocation Table #2FAT磁區大小
根目錄Directory table(根目錄保存檔案上限*32)/(Sector Byte數)
資料區Data Region剩餘磁區


2013-06-05

Call Win32 DLL from C#

參考網址:

Win32 APIやDLL関数を呼び出すには? - http://www.atmarkit.co.jp/fdotnet/dotnettips/024w32api/w32api.html

C# Win32 API および DLL の利用
http://typea.info/tips/wiki.cgi?page=C%23+Win32+API+%A4%AA%A4%E8%A4%D3+DLL+%A4%CE%CD%F8%CD%D1

[C#] 使用 Win32 API 來進行控制其他程式視窗行為表現
http://www.dotblogs.com.tw/nobel12/archive/2009/10/05/10915.aspx

(筆記) 如何使用C#使用Win32 DLL? (.NET) (C#) (Windows Form)
http://www.cnblogs.com/oomusou/archive/2011/02/13/cs_pinvoke.html

Floppy Raw Read Driver for Windows


fdrawcmd.sys

請到下面網址抓取相關工具
http://simonowen.com/fdrawcmd/


有了Driver,你也可以順便抓取其他工具來讀寫資料
推薦下面兩個:


SAMdisk - http://simonowen.com/samdisk/
跟上面的驅動是同一個作者,簡單的讀寫還沒問題,至於想要看讀寫出來的東西的內容...還是看下面另一個吧


HxC Floppy Emulator - http://hxc2001.free.fr/floppy_drive_emulator/
這傢伙可強大了,不止可以讀寫磁碟機,還可以幫你搞定裡面的檔案內容
但是有點小問題...他不會幫你搞定Boot Sector
所以原始磁碟的Boot Sector沒有資料但是其實裡面有東西的時候...
自己做個同樣大小的假磁碟然後把Boot Sector拷貝過去,那東西就讀的出來了XD

2013-06-04

ASCII String/Char to Byte

String -> Byte

string sTest = "TEST"
byte[] bTest = Encoding.ASCII.GetBytes(sTest);


Char -> Byte

Char cTest = 'A'
byte bTest = Convert.toByte(cTest);


Convert BitArray to Byte

byte ConvertToByte(BitArray bits) 
{
	if (bits.Count != 8) { throw new ArgumentException("bits"); }     
	byte[] bytes = new byte[1];     
	bits.CopyTo(bytes, 0);     
	return bytes[0]; 
}

[C#]string,char,byteの相互変換


文字を表現する各種データ型の変換方法です。
Stringから他の型に変換する場合は、文字コードの指定が必要となります。

string -> char

string str = "hello world";
 
//文字列をcharの配列に変換する
char[] charArray = str.ToCharArray();
 
//文字列を、1文字づつcharとして処理する
foreach (char c in str) {
    Console.WriteLine( c );
}
 
//文字列のn文字目をcharとして取得する
int n = 5;
char c = str[n];


char -> string

char c = "あ";
string s = c.ToString();


string -> byte

byte[] bytesArray = xxx;
 
// SJISのbyte配列をstringに変換
str = System.Text.Encoding.GetEncoding( 932 ).GetString( bytesArray );
 
// UTF-8のbyte配列をstringに変換
str = System.Text.Encoding.UTF8.GetString( bytesArray );



byte -> string

string str = "hello world";
byte[] bytesArray;
 
// stringをSJISのbyte配列に変換
byte[] bytesArray = System.Text.Encoding.GetEncoding( 932 ).GetBytes( str );
 
// stringをUTF-8のbyte配列に変換
byte[] bytesArray = System.Text.Encoding.UTF8.GetBytes( str );



byte -> char

byte[] bytesArray = ...;
char[] charArray  = System.Text.Encoding.GetEncoding( 932 ).GetString( bytesArray ).ToCharArray();



char -> byte

char c = "あ";
byte b = Convert.ToByte( c );

人気の投稿