2014年8月28日

[C#]列舉(enum)的使用

Code:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } enum Shape : int { Circle=0, Line=1, Arc=2 } private void Draw(int vType) { Graphics g; Pen p = new Pen(Color.Red); g = this.CreateGraphics(); g.Clear(Color.White); switch (vType) { case 0: g.DrawEllipse(p, 90, 30, 90, 90); break; case 1: g.DrawLine(p, 90, 50, 180, 100); break; case 2: g.DrawArc(p, 90, 30, 90, 90, 0, 250); break; default: MessageBox.Show("沒這個喔"); break; } } private void Draw(Shape vType) { Graphics g; Pen p = new Pen(Color.Red); g = this.CreateGraphics(); g.Clear(Color.White); switch (vType) { case Shape.Circle: g.DrawEllipse(p, 60, 30, 90, 90); break; case Shape.Line: g.DrawLine(p, 60, 50, 180, 100); break; case Shape.Arc: g.DrawArc(p, 60, 30, 90, 90, 0, 250); break; default: MessageBox.Show("沒這個喔"); break; } } private void BTN_Circle_Click(object sender, EventArgs e) { //Draw(0); Draw(Shape.Circle); } private void BTN_LINE_Click(object sender, EventArgs e) { //Draw(1); Draw(Shape.Line); } private void BTN_Arc_Click(object sender, EventArgs e) { //Draw(2); Draw(Shape.Arc); } } }

[C#]排序方法比較

問題:
透過內建函式做排序真的會比較快嗎?

前言:
一般而言函式都是透過優化而產出的,所以理論上而言會是比較快。
但是一切都要透過驗證,所以做了以下實驗,透過一些方式做實驗發現...

Code:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication3 { class Program { static void Main(string[] args) { int[] arrayMax = new int[10000000]; int[] arrayMax2 = new int[10000000]; int[] arrayMax3 = new int[10000000]; for (int i = 0; i <= arrayMax.GetUpperBound(0); i++) { Random rnd = new Random(); arrayMax[i] = rnd.Next(); arrayMax2[i] = arrayMax[i]; arrayMax3[i] = arrayMax[i]; } /* * 方法一,use sort */ DateTime start2 = DateTime.Now; Console.WriteLine("Start:" + start2.ToString() + "\n"); Array.Sort(arrayMax2); Console.WriteLine("Max is:" + arrayMax2[arrayMax2.Length-1] + "\n"); Console.WriteLine("End:" + DateTime.Now.Subtract(start2) + "\n"); Console.WriteLine("*** next one ***\n"); /* * 方法二,迴圈尋找 */ DateTime start = DateTime.Now; Console.WriteLine("Start:" + start.ToString() + "\n"); Console.WriteLine("Max is:{0}\n", GetMax(ref arrayMax)); Console.WriteLine("End:" + DateTime.Now.Subtract(start) + "\n"); /* * 方法三,use sort and Reverse */ DateTime start3 = DateTime.Now; Console.WriteLine("Start:" + start3.ToString() + "\n"); Array.Sort(arrayMax3); Array.Reverse(arrayMax3); Console.WriteLine("Max is:" + arrayMax3[0] + "\n"); Console.WriteLine("End:" + DateTime.Now.Subtract(start3) + "\n"); Console.WriteLine("*** next one ***\n"); Console.Read(); } private static int GetMax(ref int[] arrayMax) { int i, max; max = arrayMax[0]; for (i = 0; i <= arrayMax.GetUpperBound(0); i++) { if (max < arrayMax[i]) { max = arrayMax[i]; } } return max; } } }
結果:
迴圈比較快...

備註:
End為執行的時間,如果驗證方式有誤,麻煩不吝指教。

[C#]引數的傳遞方式

問題:
引數的傳遞方式?
參考:稍微靠靠腰

Code:
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("\n *** 一般函式傳遞 *** \n");
            int a = 10, b = 20;
            
            Console.WriteLine("\n 未進入函式前\t\t:a={0} \t b={1}", a, b);
           
            CallValues(a, b);
            Console.WriteLine("\n 進入函式後\t\t:a={0} \t b={1}", a, b);

            CallValuesUseRef(ref a, ref b);
            Console.WriteLine("\n 進入函式後\t\t:a={0} \t b={1}", a, b);

            int initX, initY;
            Console.WriteLine("\n 進入函式前\t\t:initX,initY 沒有初始值");
            CallValuesUseOut(out initX, out initY);
            Console.WriteLine("\n 進入函式後\t\t:initX={0} \t initY={1}", initX, initY);

            Console.Read();
        }

        private static void CallValuesUseOut(out int x, out int y)
        {
            int z;
            x = 20;
            y = 30;
            Console.WriteLine("\n 函式內 交換前\t\t:x={0} \t y={1}", x, y);

            z = x;
            x = y;
            y = z;

            Console.WriteLine("\n 函式內 交換後\t\t:x={0} \t y={1}", x, y);

        }

        private static void CallValuesUseRef(ref int x, ref int y)
        {
            int z;
            x = 20;
            y = 30;
            Console.WriteLine("\n 函式內 交換前\t\t:x={0} \t y={1}", x, y);

            z = x;
            x = y;
            y = z;

            Console.WriteLine("\n 函式內 交換後\t\t:x={0} \t y={1}", x, y);
        }

        private static void CallValues(int x, int y)
        {
            int z;
            x = 20;
            y = 30;
            Console.WriteLine("\n函式內 交換前\t\t:x={0} \t y={1}", x, y);

            z = x;
            x = y;
            y = z;

            Console.WriteLine("\n函式內 交換後\t\t:x={0} \t y={1}", x, y);
        }
    }
}


結果:


2013年12月6日

[Android]使用BlueStacks、Eclipse進行開發除錯




前言


使用Android模擬器進行開發與除錯時,Windows作業系統上的執行時間會比較長。
對於某些專案在分秒必爭的情況下,模擬器反而造成許多開發上的不便。

解決方案

使用BlueStacks與Eclipse進行開發與除錯。


關於


  1. BlueStacks:一套可以模擬一般Android手機或平板APP正常執行的軟體,相信許多人都使用這個軟體來玩一些APP遊戲,如神魔之塔...等。
  2. Eclipse:一套用java開發的好用程式編輯軟體。(作者就是使用此軟體來開發Android的)

 如何使用

  1. 先進行BlueStacks 及 Eclipse安裝,並且都順利安中與執行。
  2. 打開Eclipse的Device(查詢目前有哪些裝置在線上),如圖1。開啟位置:Windows>Show View>Others>Device。
    圖1.Eclpse的Device列表
如果沒有找到裝置,請重新啟動adb,如圖2。
圖2.Restart adb

2013年8月3日

[SVN]建立版本管理工具

前言

最近在執行專案時,一直在思考管理版本問題。起初因為一人建立專案,所以有自己的一套管理方式。但是如果多人專案就需要專業的工具啦。

關於SVN

Apache Subversion(簡稱SVN,svn),是一個開放原始碼的版本控制系統,相對於的RCS、CVS,採用了分支管理系統,它的設計目標就是取代CVS。網際網路上越來越多的控制服務從CVS轉移到Subversion。

參考:Subversion(SVN)概念與工具介紹

安裝SVN時,需要一個Server(伺服端)跟一個Client(客戶端)。
筆者一直失敗就是因為只安裝Client,所以一直上傳失敗。...夠蠢的

安裝SVN Server(作者環境為 Windows 7)

Server此部份就是將大家的心血(檔案)存放的地方,因為作者也是參考其它人的安裝方式安裝成功,因此附上幾個連結讓大家參考。

安裝部份:Demo 小舖
軟體下載:VISUALSVN SERVER
Port 參考(如果發生Port衝突):通訊埠 (port) 介紹及常用 port 對照

注意:作者在安裝SVN前已經有安裝了XAMPP(整合Apache, MySQL, PHP....)
因此在安裝到Server Port時,Port 443發生衝突,因此更換了其它的Port。


安裝SVN Client

本作者使用TortoiseSVN作為上傳工具,因為他比較.....視覺化吧。
看個人喜好囉。

安裝與操作:版本控制工具TortoiseSVN初體驗

2013年7月16日

關於Appserv 漏洞一事(一)

事由:
今天研究室發生了駭客攻擊,有一台電腦變成了殭屍。
(還好不會咬人)
原因:
電腦的AppServ 2.5.10被竄改,導致一直對外發送封包(典型的DDos攻擊)

經過:
早上電腦使用者反應網路連不上,發現是連線速度異常。後來網路組人員通知,有異常流量從此電腦IP發出。因此先IP封鎖,拔除網路線。

解決方法:
早上電腦使用者反應網路連不上,發現是連線速度異常。後來網路組人員通知,有異常流量從此電腦IP發出。因此先IP封鎖,拔除網路線。

參考:
如何預防Appserv遭受入侵
資訊組蔡玉貴(friber)部落格日誌_appserv程式漏洞_首頁被竄改

最後學弟選擇安裝了其它的軟體:XAMPP,線上文件說明都還滿完整的。
但是安裝完後沒有繁體中文,最後發現語言檔只有簡體中文。
本想一鼓作氣將他翻譯完,拿來造福人群。
但是網路的東西太過強大,所以上網找到人家翻好的繁體中文檔
只能說世界上好心人還是有的。

(待續)

2013年6月29日

質數計算機



不知道質數為何物嗎?質數有多大呢?我們來看看你電腦的效能,可以計算多少質數囉。

(你會發現,每使用一次,計算速度越會來越快喔。)







關於「質數」


質數,指在一個大於1的自然數中,除了1和此整數自身外,無法被其他自然數整除的數。

by 維基百科





2013年6月9日

[Firefox App 練習]Hello World 安裝不成功

前言:
Firefox 也推出OS版,其開發是使用WebApp的方式,Base  is html5.

所以一個APP的資料內應該包含
index.html-> html5
icon.png ->128 px x 128 px
manifest.webapp -> 主要設定檔

問題:
我都寫好之後,設定檔取名為 「index.webapp」,上傳也OK,但是Run不出來。

目前解決:
index.webapp 改名 manifest.webapp
我想是因為.webapp的格式是固定的。

APP Developer 參考


2013年4月15日

[POS]微型印表機安裝與除錯

前言:
市面上的POS印表機,有分為ESC /TSC


傳輸協定:
ethernet:
IP:192.168.XXX.XXX(自行設定)
Port:9100



前置作業:
  • 印表機是否接上電源,並處於待機狀態。
  • 確認印表機內有列印紙,並有擺放正確

  • 先到網路上尋找驅動程式,並確認安裝成功。
  • 控制台->
    • 裝置和印表機->
    • 新增印表機->
    • (將USB或Serial接到本機)新增本機印表機->
    • 使用現有連接阜->
    • (USB為例)USB00X->
    • 安裝驅動->
    • 使用目前安裝的驅動程式->
    • 設定印表機名稱->
    • 測試列印
  • 如果以上不行,選設備按右鍵->
    • 印表機內容->
    • 連接阜->
    • (修改為其它的USB並測試列印)


Android 中文列印:


public class MainActivity extends Activity {

 TscWifiActivity TscEthernetDll = new TscWifiActivity();
 
 private Button test;
 private String text;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  
  
  
   test = (Button) findViewById(R.id.button1);

         test.setOnClickListener(new OnClickListener() {
             public void onClick(View v) 
             {
              text=new String("TEXT 0,0,\"TST24.BF2\",0,1,1,\"It's Chinese 這是中文\"\n");
int Width=100,Height=100;
              
              TscEthernetDll.openport("192.168.XXX.XXX",9100);
              
              TscEthernetDll.setup(Width, Height, 4, 4, 0, 0, 0);
              TscEthernetDll.clearbuffer();
              TscEthernetDll.sendcommand("SET TEAR ON\n");
              
              try {
    TscEthernetDll.sendcommand(text.getBytes("big5"));
   } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
   }
              
              TscEthernetDll.printlabel(1, 1);
              
              TscEthernetDll.closeport();
             }
             
         });
 }


參考網站:
TSC 下載專區
TSPL Note
TSPL 中文說明

2013年1月3日

[Android]平版安裝不了驅動


問題:


開發Android時,使用模擬器是一件使人磨耐性的事。而且模擬器的功能始終有限,平版市場充斥。許多USB-Driver一直安裝不上去。

解決:

(適用 Win7 & WinXP)

修改Google USB Driver 的 [android_winusb.inf]
讓您的平版也可以安裝上去。

Step 1:
打開android_winusb.inf 檔案。

筆者的路徑為:C:\Android\android-sdk\extras\google\usb_driver\

Step 2:
打開裝置管理員,未知裝置->(右鍵)內容->詳細資料->選擇硬體辨識碼

Step 3:
確定電腦為x64 or x86 ->尋找


[Google.NTx86]

[Google.NTamd64]

按照上面的方式,將資訊填入


;Android
%SingleAdbInterface%        = USB_Install, USB\VID_18D1&PID_0003&REV_0230&MI_01
%SingleAdbInterface%        = USB_Install, USB\VID_18D1&PID_0003&MI_01

Step 4:
重新更新驅動,會發現安裝成功。

Step 5:
清除adb並重新啟動
清除adb:開始->執行->CMD->輸入 cd C:\Android\android-sdk\platform-tools\adb kill-server
重新啟動:開始->執行->CMD->輸入 cd C:\Android\android-sdk\platform-tools\adb start

Done.

2013年1月1日

[Android]製作縮圖

問題:
在使用Android的ImageView元件放入圖檔時,發現圖檔尺寸比ImageView元件的尺寸來的大很多。

解決:
使用Android製作縮圖,



/**
 原始圖檔 bitmap
*/

//取得圖檔寬度
int bmpWidth  = bitmap.getWidth(); 

//取得圖檔高度
int bmpHeight  = bitmap.getHeight(); 

//設定縮圖寬度
float scaleWidth  = (float) sWidth / bmpWidth;     
//按固定大小缩放sWidth,要多大有多大

//設定縮圖高度
float scaleHeight = (float) sHeight / bmpHeight;  

//轉換矩陣
Matrix matrix = new Matrix(); 
matrix.postScale(scaleWidth, scaleHeight); 

//產生縮圖
Bitmap resizeBitmap = 
Bitmap.createBitmap(bitmap, 0, 0, bmpWidth, bmpHeight,matrix, false); 

//記得做資源回收,不然會發生溢位
bitmap.recycle(); 


參考網站:Android中图片缩放方法

2012年9月30日

[CSS]讓版面聽話-Reset.css

問題:在開發Web時,常遇到各家瀏覽器不同的預設,導致設計師日以繼夜的爆肝。

最佳的方法「Reset CSS」

世界知名的 CSS 大師「Eric A. Meyer」整理出一個很棒的解決方法「Reset CSS」,針對 CSS 語法最容易出問題的部份~例如 margin 外間距,各大瀏覽器最常發生不一致的狀況,現在將 margin 全部統一歸 0 ,其他部份,文字大小和行高也全部統成一樣的大小 …. 等,只要掛上這一段「Reset CSS」語法,就可以讓所有的各大瀏覽器乖乖聽話,呈現一樣的結果,CSS 的大同世界就在這裡啊!

/* v1.0 | 20080212 */

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, font, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td {
    margin: 0;
    padding: 0;
    border: 0;
    outline: 0;
    font-size: 100%;
    vertical-align: baseline;
    background: transparent;
}
body {
    line-height: 1;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}

/* remember to define focus styles! */
:focus {
    outline: 0;
}

/* remember to highlight inserts somehow! */
ins {
    text-decoration: none;
}
del {
    text-decoration: line-through;
}

/* tables still need 'cellspacing="0"' in the markup */
table {
    border-collapse: collapse;
    border-spacing: 0;
}

下載網站:http://meyerweb.com/eric/tools/css/reset/reset.css

參考來源:flycan


2012年9月20日

[Android]Android連不到WebAPI

問題:在開發Android時,連不上Web的API,該怎麼辦?

/*
step 1:先檢查是否有加入權限
*/
//AndroidManifest.xml


//*.java
@Override
    public void onCreate(Bundle savedInstanceState) {
  //加入以下兩行
     StrictMode
.setVmPolicy(new StrictMode
.VmPolicy
.Builder()
.detectAll()
.penaltyLog()
.penaltyDeath()
.build());
     StrictMode.setThreadPolicy(
new StrictMode.ThreadPolicy.Builder()
.detectDiskReads().detectDiskWrites()
.detectNetwork().penaltyLog().build());
  
  /*
  StrictMode
  This class is not available with API level 8.
  所以要用在2.3以上喔
  */
     
  super.onCreate(savedInstanceState);


參考網站:Android™ 2.1 android.R.drawable Icon Resources

[Android]Android內建的圖示

問題:在開發Android時,沒有美工的頭腦時,網路上下載圖檔又擔心版權問題,所以直接使用Android 內建的圖示

//*.java
ImageView btnImg_Help = (ImageView)findViewById(R.id.Img_Help); 
btnImg_Help.setImageResource(android.R.drawable.ic_menu_help);

//*.xml
android:icon="@android:drawable/ic_menu_save"

參考網站:Android™ 2.1 android.R.drawable Icon Resources

2012年8月16日

[PHP]集合運算


交集: array_intersection()
差集: array_diff()
聯集: 沒有內建,不過可先透過 array_merge 將兩個陣列集合在一起,再利用 array_unique 去除重複的元素
function array_union($a, $b) {
$union = array_merge($a, $b); // duplicates may still exist
$union = array_unique($union);
return $union;
}

2011年12月14日

[PHP]JSON的使用

1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);  
echo $arr2=json_encode($arr); 
$stdin=get_object_vars(json_decode($arr2));
foreach ($stdin as $k => $v) {
echo "$k = \"$v\"\n"; // print json_decode key => value.
}
?>

2011年12月9日

[Android] 開發小問題

1. indexOf判斷中文字串
//indexOf的句子,不知道為什麼第一個字不會去找,怪災。
replaced=" "+result.get(i);

//年
if(replaced.indexOf("年")>0)
{
score[i]=score[i]+1;
}

2.使用正規表示法判斷數字
//判斷數字
     Pattern p=Pattern.compile("[0-9]{1,2}");
     Matcher m=p.matcher(replaced);
     if(m.find()){
      //正確
     }

//{n,m} 表示前一個字元或者前一個RE出現n到m次
//[0-9] 0-9的集合

2011年12月5日

[Android]Activity返回上一頁

page1

package Demo;
 
/* import相關class */
import java.text.DecimalFormat;
import java.text.NumberFormat;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
 
public class Page1 extends Activity 
{
  Intent intent;
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) 
  {
    super.onCreate(savedInstanceState);
    /* 載入mylayout.xml Layout */
    setContentView(R.layout.myalyout);
     
     
    Button b1 = (Button) findViewById(R.id.button1);
    b1.setOnClickListener(new Button.OnClickListener()
    {
      public void onClick(View v)
      {
       /* 回傳result回上一個activity */
       Page1.this.setResult(RESULT_OK, intent);
        
       /* 關閉activity */
       Page1.this.finish();
      }
    });
  }
}

page2
package Demo;

/* import相關class */
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;

public class Page2 extends Activity 
{
    
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) 
  {
    super.onCreate(savedInstanceState);
    /* 載入main.xml Layout */
    setContentView(R.layout.main);
   
        /*new一個Intent物件,並指定class*/
     Intent intent = new Intent();
        intent.setClass(Page2.this,Page1.class);
     
     /*呼叫Activity EX03_11_1*/
     startActivityForResult(intent,0);
      }
  
  /* 覆寫 onActivityResult()*/
  @Override
  protected void onActivityResult(int requestCode, int resultCode,
                                  Intent data)
  {
    switch (resultCode)
    { 
      case RESULT_OK:
//回上一頁囉
        break;       
      default: 
        break; 
     } 
   } 
}

2011年11月27日

[PHP] 程式小技巧

[迴圈的使用]

//PHP3 or old
reset($attributes);
while (list($key, $value) = each($attributes)) {
    //do something
}
//PHP4
foreach ($attributes as $key => $value){
   //do something
}



[簡查重覆的資料]
SELECT username,COUNT(*)/*重複出現的次數*/ FROM member GROUP BY username HAVING COUNT(*) > 1 /*列出重複出現一次以上的資料*/

2011年11月24日

[Android] 取得檔案位置

package tw.Goocue;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class Main extends Activity {
   @Override 
   public void onCreate(Bundle icicle)
   {
     // TODO Auto-generated method stub 
     super.onCreate(icicle);
        setContentView(R.layout.main);
        
        Button b = (Button)this.findViewById(R.id.b1);
        
        b.setOnClickListener( new OnClickListener(){
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                
                // 建立 "選擇檔案 Action" 的 Intent
                Intent intent = new Intent( Intent.ACTION_GET_CONTENT );
                
                // 過濾檔案格式
                intent.setType( "*/*" );
                
                // 建立 "檔案選擇器" 的 Intent  (第二個參數: 選擇器的標題)
                Intent destIntent = Intent.createChooser( intent, "選擇檔案" );
                
                // 切換到檔案選擇器 (它的處理結果, 會觸發 onActivityResult 事件)
                startActivityForResult( destIntent, 0 );
            }
        });
   }
   
   @Override
     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
         
         // TODO Auto-generated method stub
         super.onActivityResult(requestCode, resultCode, data);
         
         // 有選擇檔案
         if ( resultCode == RESULT_OK )
         {
             // 取得檔案的 Uri
             Uri uri = data.getData();
             if( uri != null )
             {
               Cursor cursor = this.getContentResolver().query(uri, null, null, null, null);
                  cursor.moveToFirst();
                  
                  for (int i = 0; i < cursor.getColumnCount(); i++) {
                   
                   
                   setTitle( i+"-"+cursor.getString(1));
                   }
                 // 利用 Uri 顯示 ImageView 圖片
                // setTitle( uri.toString() );
             }
             else
             {
                 setTitle("無效的檔案路徑 !!");
             }
         }
         else
         {
             setTitle("取消選擇檔案 !!");
         }
     }

}