Python抓取网页内容

1、BeautifulSoup解析网页

'''
Created on 20150203
@author: Hansen
'''

import urllib2
import sys
import io
from bs4 import BeautifulSoup

#Fetch HTML from URL
def fecth_html(index,url,keepHtml,resultFile):
    req = urllib2.Request(url)
    req.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.2; rv:16.0) Gecko/20100101 Firefox/16.0')
    rsp = urllib2.urlopen(req)
    content = rsp.read()
    #receive_header = rsp.info()
    #print(sys.getfilesystemencoding())
    #content = content.decode('utf-8','replace')
    
    if keepHtml:
        fileinfo = open(str(index)+'.html','w')
        fileinfo.write(content)
        print("save file "+ str(index)+'.html:    ok')
        
    parse_html(content,resultFile)
    
#Parse HTML
def parse_html(html,resultFile):
    soup = BeautifulSoup(html,fromEncoding="utf8")
    lis = soup.select('div.shop-all-list li')
    print(len(lis))
    for li in lis:
        szTitle = (li.select('div:nth-of-type(2) div:nth-of-type(1) a h4'))[0].get_text()
        szTitle = szTitle.replace("\r\n", "-").replace(" ","");
        szStar = (li.select('div:nth-of-type(2) div:nth-of-type(3) span'))[0]['title']
        szReviewNum = (li.select('div:nth-of-type(2) div:nth-of-type(3) a:nth-of-type(1)'))[0].get_text()
        szReviewNum = szReviewNum.replace("\n", "").replace(" ","");
        szMeanPrice = (li.select('div:nth-of-type(2) div:nth-of-type(3) a:nth-of-type(2)'))[0].get_text()
        szMeanPrice = szMeanPrice.replace("\n", "").replace(" ","");
        szCategory = (li.select('div:nth-of-type(2) div:nth-of-type(4) a:nth-of-type(1)'))[0].get_text()
        szAddressA = (li.select('div:nth-of-type(2) div:nth-of-type(4) a:nth-of-type(2)'))[0].get_text()
        szAddressB = (li.select('div:nth-of-type(2) div:nth-of-type(4) span:nth-of-type(3)'))[0].get_text()
        szAddress = (szAddressA+"-"+szAddressB).replace("\r\n", "-").replace(" ","");
        szTaste = (li.select('div:nth-of-type(2) span:nth-of-type(5) span:nth-of-type(1)'))[0].get_text()
        szEvn = (li.select('div:nth-of-type(2) span:nth-of-type(5) span:nth-of-type(2)'))[0].get_text()
        szService = (li.select('div:nth-of-type(2) span:nth-of-type(5) span:nth-of-type(3)'))[0].get_text()
        
        fileinfo = io.open(resultFile,'a',encoding='utf_16')
        fileinfo.write(szTitle+","+szStar+","+szReviewNum+","+szMeanPrice+","+szCategory+"," +szAddress+","+szTaste+","+szEvn+","+szService+"\n")

2、PyQuery解析网页

'''
Created on 20150203
@author: Hansen
'''

import urllib2
import sys
import io
from pyquery import PyQuery

#Fetch HTML from URL
def fecth_html(index,url,keepHtml,resultFile):
    req = urllib2.Request(url)
    req.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.2; rv:16.0) Gecko/20100101 Firefox/16.0')
    rsp = urllib2.urlopen(req)
    content = rsp.read()
    #receive_header = rsp.info()
    #print(sys.getfilesystemencoding())
    #content = content.decode('utf-8','replace')
    
    if keepHtml:
        fileinfo = open(str(index)+'.html','w')
        fileinfo.write(content)
        print("save file "+ str(index)+'.html:    ok')
        
    parse_html(content,resultFile)
    
#Parse HTML
def parse_html(html,resultFile):
    doc = PyQuery(html)
    lis = doc('div.shop-all-list li')
    print(len(lis))
    for li in lis:
        li_doc = PyQuery(li)
        szTitle = li_doc('li div div a h4').text()
        szTitle = szTitle.replace("\r\n", "-").replace(" ","");
        szStar = li_doc("li div div span").filter('.sml-rank-stars').attr('title')
        szReviewNum = li_doc('li div div a').filter('.review-num').text()
        szReviewNum = szReviewNum.replace("\n", "").replace(" ","");
        szMeanPrice = li_doc('li div div a').filter('.mean-price').text()
        szMeanPrice = szMeanPrice.replace("\n", "").replace(" ","");
        szCategory = li_doc('li div div a span').filter('.tag').eq(1).text()
        szAddressA = li_doc('li div div a span').filter('.tag').eq(1).text()
        szAddressB = li_doc('li div div span').filter('.addr').eq(0).text()
        szAddress = (szAddressA+"-"+szAddressB).replace("\r\n", "-").replace(" ","");
        szTaste = li_doc('li div span span').eq(0).text()
        szEvn = li_doc('li div span span').eq(1).text()
        szService = li_doc('li div span span').eq(2).text()
        
        fileinfo = io.open(resultFile,'a',encoding='utf_16')
        fileinfo.write(szTitle+","+szStar+","+szReviewNum+","+szMeanPrice+","+szCategory+"," +szAddress+","+szTaste+","+szEvn+","+szService+"\n")

从WIN ADT复制到MAC ADT

Android SDK超级大(我现在有26.5G),而连接Google的速度超级慢,一次下载要好久。

最近准备在MAC进行Android开发,别的都好下载,但Adroid SDK就有些太大了,于是考虑从WIN下直接复制到MAC。

Android SDK主要由下面几部分组成:

/add-ons:GoogleAPI,操作系统无关
/build-tools:构建工具,这个和操作系统相关的,要重新下载
/docs:文档,操作系统无关
/extras:扩展内容,是否需要重新下载与其功能有关
/extras/android:操作系统无关
/extras/google:操作系统无关
/extras/intel:intel的硬件加速驱动,操作系统相关,需重新下载
/platforms:android平台,早期操作系统相关,后期将操作系统相关内容放到了build-tools中,可以全部拷贝过去,系统相关内容会自动重新下载
/platform-tools:管理工具,这个和操作系统相关的,要重新下载
/samples:demo,操作系统无关
/sources:android源码,操作系统无关
/system-images:android系统映像,操作系统无关
/temp:下载缓存,不需要拷贝
/tools:管理工具,这个和操作系统相关的,要重新下载

MAC设置AndroidStudio初始环境

1、从Oracle下载MAC版本的JDK7

http://www.oracle.com/technetwork/java/javase/downloads/index.html

2、从Google下载MAC版本Android Studio和Android SDK Manager

http://developer.android.com/sdk/index.html

3、安装JDK7、Android Studio、Android SDK Manager,并下载需要版本的Android SDK

4、此时双击Android Studio会报错:

Android Studio was unable to find a valid JVM.

这是因为Android Studio默认使用JDK1.6.*的原因

在Finder中打开Application文件夹,在“Android Studio.app”上右键,显示程序包内容
编辑Content/Info.plist,修改属性JVMOptions->JVMVersion一行,从1.6.*修改为1.7.*

5、此时双击Android Studio会尝试从Google获取最新的Android SDK信息

Fetching Android SDK component information

当然你读不到啦,只好屏蔽初始化方法:

编辑Content/idea.properties/bin/idea.properties文件,添加一行
disable.android.first.run=true

6、现在Android Studio可以启动了,但是不能新建项目
需要告诉Android Studio,Android SDK在哪里:

主界面-》Configure-》Project Defaults-》Project Structure-》Android SDK location
填写Android SDK的绝对路径,保存,然后就能新建应用了

7、那就新建一个简单应用测试一下吧,当然先是虚拟机:

Starting emulator for AVD 'new'
emulator: ERROR: x86 emulation currently requires hardware acceleration!
Please ensure Intel HAXM is properly installed and usable.
CPU acceleration status: HAX kernel module is not installed!

这是因为HAXM模块没有安装,前往Android SDK根目录

安装下面的软件:
PATH_TO_SDK/extras/intel/Hardware_Accelerated_Execution_Manager/IntelHAXM_1.1.1_for_10_9_and_above.dmg

8、然后就是在设备上测试,Android SDK找不到我的设备

#添加adb路径
echo "export PATH=${PATH}:/PATH_TO_SDK/android-sdk-macosx/platform-tools/">>~/.bash_profile
#然后刷新一下
source .bash_profile 
#添加设备厂商ID(我的是小米),可以在系统报告中看到设备厂商ID信息
echo"0x2717">>~/.android/adb_usb.ini
#杀掉adb服务
adb kill-server
#重启adb服务
adb sever
#PTP模式连上手机,当然要开启手机调试咯,这样就能看到设备了
adb devices

9、连上设备了,运行时报错:

Permission Denial: starting Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.neohope.testapp/.LoginActivity } from null (pid=29619, uid=2000) not exported from uid 10139

这个错误是因为Main Activity没有设置,在Manifest中对应的Activity中增加如下设置即可

<intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

C#命令行打印PDF文档

1、使用Windows命令行
BAT Code

print /D:"\\COMPUTERNAME\打印机名" "PDF文件路径"

C# Code

ProcessStartInfo psInfo = new ProcessStartInfo();
psInfo.Verb = "Print"; // or "PrintTo"
psInfo.FileName = pdfFileName;
psInfo.Arguments = String.Format("/p /h \"{0}\" \"{1}\"", pdfFileName, printerName);
psInfo.WindowStyle = ProcessWindowStyle.Hidden;
psInfo.CreateNoWindow = true;
psInfo.UseShellExecute = true;
Process process = Process.Start(psInfo);

2、使用adobe命令行
BAT Code

#发送到默认打印机
AcroRd32.exe /s /o /h /p “PDF文件路径”
#发送到指定打印机
AcroRd32.exe /s /o /h /t “PDF文件路径” “打印机名” “驱动” “端口”

C# Code

ProcessStartInfo psInfo = new ProcessStartInfo();
psInfo.FileName = @"C:\Program Files\Adobe\Reader 9.0\Reader\AcroRd32.exe";
psInfo.Arguments = String.Format("/s /o /h /p{0}", pdfFileName);
psInfo.WindowStyle = ProcessWindowStyle.Hidden;
psInfo.CreateNoWindow = true;
psInfo.UseShellExecute = true;

Process p= Process.Start(psInfo);
p.WaitForInputIdle();
System.Threading.Thread.Sleep(3000);
if (false == p.CloseMainWindow())p.Kill();

3、使用gostscript命令行
BAT Code

gswin32c.exe -dPrinted -dBATCH -dNOPAUSE -dNOSAFER -q -dNumCopies=1 -sDEVICE=ljet4 -sOutputFile="\\spool\打印机名称" "PDF文件路径"

C# Code

ProcessStartInfo psInfo = new ProcessStartInfo();
psInfo.Arguments = String.Format(" -dPrinted -dBATCH -dNOPAUSE -dNOSAFER -q -dNumCopies=1 -sDEVICE=ljet4 -sOutputFile=\"\\\\spool\\{0}\" \"{1}\"", printerName, pdfFileName);
psInfo.FileName = @"C:\Program Files\gs\gs8.70\bin\gswin32c.exe";
psInfo.UseShellExecute = false;

Process p= Process.Start(psInfo);
p.WaitForInputIdle();
System.Threading.Thread.Sleep(3000);
if (false == p.CloseMainWindow())p.Kill();

4、使用PrintDocument+第三方渲染插件(参考资料3)

PrintDocument pd = new PrintDocument();
pd.DocumentName = pdfName;
pd.PrinterSettings.PrinterName =printerName;
pd.PrinterSettings.PrintFileName = fileName;
pd.PrintController = new StandardPrintController();
pd.OriginAtMargins = false;
pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
pd.Print();

参考资料:
PDF: direct printing with .NET
How to Silently Print PDFs using Adobe Reader and C#
100% .NET component for rendering PDF documents

Windows服务程序访问NAS

由于服务程序授权与用户桌面授权互不影响,所以即使在用户桌面映射了NAS盘符,在Windows服务程序下仍然是不可以访问的。

一般来说有这样几种做法来访问NAS或共享盘:
1、加入域,通过“域用户认证”或“通过将NAS资源设置对某台计算机授权”来达到访问NAS的目的
2、不加域,在Windows中添加与NAS相同的用户名及密码,服务程序通过该用户名密码登录,可以访问NAS
3、不加域,通过调阅API的方式来获得访问NAS的权限
A、VC实现如下:

DWORD AcessNetDrtive(TCHAR* szRemotePath, TCHAR* szLocalDriver,  const TCHAR* szUsername, const TCHAR* szPassword)
{
	DWORD dwRetVal;
	DWORD dwFlags;

	NETRESOURCE nr;
	memset(&nr, 0, sizeof(NETRESOURCE));
	nr.dwScope = RESOURCE_GLOBALNET;
	nr.dwType = RESOURCETYPE_ANY;
	nr.lpLocalName = szLocalDriver;
	nr.lpRemoteName = szRemotePath;
	nr.lpProvider = NULL;

	//CONNECT_REDIRECT;CONNECT_UPDATE_PROFILE;
	dwFlags = 0;
	dwRetVal = WNetAddConnection2(&nr, szPassword, szUsername, dwFlags);

	retrun dwRetVal;
}

B、C#实现如下:

    public class NetworkDrive
    {
        public enum ResourceScope
        {
            RESOURCE_CONNECTED = 1,
            RESOURCE_GLOBALNET,
            RESOURCE_REMEMBERED,
            RESOURCE_RECENT,
            RESOURCE_CONTEXT
        }

        public enum ResourceType
        {
            RESOURCETYPE_ANY,
            RESOURCETYPE_DISK,
            RESOURCETYPE_PRINT,
            RESOURCETYPE_RESERVED
        }

        public enum ResourceUsage
        {
            RESOURCEUSAGE_CONNECTABLE = 0x00000001,
            RESOURCEUSAGE_CONTAINER = 0x00000002,
            RESOURCEUSAGE_NOLOCALDEVICE = 0x00000004,
            RESOURCEUSAGE_SIBLING = 0x00000008,
            RESOURCEUSAGE_ATTACHED = 0x00000010,
            RESOURCEUSAGE_ALL = (RESOURCEUSAGE_CONNECTABLE | RESOURCEUSAGE_CONTAINER | RESOURCEUSAGE_ATTACHED),
        }

        public enum ResourceDisplayType
        {
            RESOURCEDISPLAYTYPE_GENERIC,
            RESOURCEDISPLAYTYPE_DOMAIN,
            RESOURCEDISPLAYTYPE_SERVER,
            RESOURCEDISPLAYTYPE_SHARE,
            RESOURCEDISPLAYTYPE_FILE,
            RESOURCEDISPLAYTYPE_GROUP,
            RESOURCEDISPLAYTYPE_NETWORK,
            RESOURCEDISPLAYTYPE_ROOT,
            RESOURCEDISPLAYTYPE_SHAREADMIN,
            RESOURCEDISPLAYTYPE_DIRECTORY,
            RESOURCEDISPLAYTYPE_TREE,
            RESOURCEDISPLAYTYPE_NDSCONTAINER
        }

        [StructLayout(LayoutKind.Sequential)]
        private class NETRESOURCE
        {
            public ResourceScope dwScope = 0;
            public ResourceType dwType = 0;
            public ResourceDisplayType dwDisplayType = 0;
            public ResourceUsage dwUsage = 0;
            public string lpLocalName = null;
            public string lpRemoteName = null;
            public string lpComment = null;
            public string lpProvider = null;
        }

        [DllImport("mpr.dll")]
        private static extern int WNetAddConnection2(NETRESOURCE lpNetResource, string lpPassword, string lpUsername, int dwFlags);

        public static int MapNetworkDrive(string remotePath, string localDrive, string userName, string passWord)
        {
            NETRESOURCE myNetResource = new NETRESOURCE();
            myNetResource.lpLocalName = localDrive;
            myNetResource.lpRemoteName = remotePath;
            myNetResource.lpProvider = null;
            int result = WNetAddConnection2(myNetResource, passWord, userName, 0);
            return result;
        }
    }

IIS程序访问NAS

IIS程序访问NAS,一般有两种情况,加域和没加域
1、加域后,什么都好办,可以通过两种方式认证
A、采用域帐户认证
B、NAS资源可以直接授权给指定计算机访问

2、不加域,那一般有三种方式设置访问权限
A、通过指定程序的用户名和密码访问(这里指定的不是本地的用户名和密码,而是NAS的用户名和密码)
B、不指定用户名和密码,直接通过pass-through authentication方式访问,其规则为:
首先通过用户的真实id进行验证
如果用户没有授权,会尝试使用应用池的账户进行验证
如果应用池账号为NetworkService或LocalSystem,将使用计算机账号进行验证
采取这样的方式IIS会提出警告,因为IIS只有在运行之后,才知道能否访问NAS
C、通过代码实现

    //NAS访问封装类
    public class NetworkDrive
    {
        public enum ResourceScope
        {
            RESOURCE_CONNECTED = 1,
            RESOURCE_GLOBALNET,
            RESOURCE_REMEMBERED,
            RESOURCE_RECENT,
            RESOURCE_CONTEXT
        }

        public enum ResourceType
        {
            RESOURCETYPE_ANY,
            RESOURCETYPE_DISK,
            RESOURCETYPE_PRINT,
            RESOURCETYPE_RESERVED
        }

        public enum ResourceUsage
        {
            RESOURCEUSAGE_CONNECTABLE = 0x00000001,
            RESOURCEUSAGE_CONTAINER = 0x00000002,
            RESOURCEUSAGE_NOLOCALDEVICE = 0x00000004,
            RESOURCEUSAGE_SIBLING = 0x00000008,
            RESOURCEUSAGE_ATTACHED = 0x00000010,
            RESOURCEUSAGE_ALL = (RESOURCEUSAGE_CONNECTABLE | RESOURCEUSAGE_CONTAINER | RESOURCEUSAGE_ATTACHED),
        }

        public enum ResourceDisplayType
        {
            RESOURCEDISPLAYTYPE_GENERIC,
            RESOURCEDISPLAYTYPE_DOMAIN,
            RESOURCEDISPLAYTYPE_SERVER,
            RESOURCEDISPLAYTYPE_SHARE,
            RESOURCEDISPLAYTYPE_FILE,
            RESOURCEDISPLAYTYPE_GROUP,
            RESOURCEDISPLAYTYPE_NETWORK,
            RESOURCEDISPLAYTYPE_ROOT,
            RESOURCEDISPLAYTYPE_SHAREADMIN,
            RESOURCEDISPLAYTYPE_DIRECTORY,
            RESOURCEDISPLAYTYPE_TREE,
            RESOURCEDISPLAYTYPE_NDSCONTAINER
        }

        [StructLayout(LayoutKind.Sequential)]
        private class NETRESOURCE
        {
            public ResourceScope dwScope = 0;
            public ResourceType dwType = 0;
            public ResourceDisplayType dwDisplayType = 0;
            public ResourceUsage dwUsage = 0;
            public string lpLocalName = null;
            public string lpRemoteName = null;
            public string lpComment = null;
            public string lpProvider = null;
        }

        [DllImport("mpr.dll")]
        private static extern int WNetAddConnection2(NETRESOURCE lpNetResource, string lpPassword, string lpUsername, int dwFlags);

        public static int MapNetworkDrive(string remotePath, string localDrive, string userName, string passWord)
        {
            NETRESOURCE myNetResource = new NETRESOURCE();
            myNetResource.lpLocalName = localDrive;
            myNetResource.lpRemoteName = remotePath;
            myNetResource.lpProvider = null;
            int result = WNetAddConnection2(myNetResource, passWord, userName, 0);
            return result;
        }
    }

    //调用示例
    NetworkDrive.MapNetworkDrive("NAS paht with ip", "Local Driver Letter", "user", "password");

参考资料:
What is “pass-through authentication” in IIS 7?

不支持一个STA线程上针对多个句柄的WaitAll

最近项目中用了COM控件,同时也用了多线程,在等待线程退出的地方,使用了

AutoResetEvent[] tEevents;
//...
WaitHandle.WaitAll(tEevents);

程序运行到这里,就会报错:

不支持一个STA线程上针对多个句柄的WaitAll

当时事情很急,将其调整为

AutoResetEvent[] tEevents;
//...
foreach(var tEvent in tEevents)
{
    tEvent.WaitOne();
}

就将这个问题绕了过去。

后来,在Stackoverflow上面,查了STA和MTA的区别。COM线程模型称为Apartment模型,分为STA和MTA两种。
STA(Single Thread Apartment)
STA是非线程安全的,常用于UI界面,其他线程要访问STA模式的COM组件,需要通过STA线程进行访问(其实就变成了单线程调用)
MTA(Multi Thread Apartment)
MTA是线程安全的,COM的程序员自己处理了并发的问题,其他线程可以直接访问COM组件

参考资料:
Could you explain STA and MTA?

CS进程单例模式

1、SingletonExeController.cs

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;

namespace SingletonExeTest
{
    //通过检测Mutex,确认只会启用一个进程
    //第一个进程,会启用Tcp监听,接收参数
    //后续进程,通过TcpChannel,将参数传递给第一个进程
    //使用前,必须先调用InitSingleton,使用后必须调用UninitSingleton
    class SingletonExeController : MarshalByRefObject
    {
        private static Mutex m_Mutex = null;
        private static TcpChannel m_TCPChannel = null;
        
        //初始化
        public static void InitSingleton()
        {
            string assemblyName = System.Reflection.Assembly.GetExecutingAssembly().GetName(false).CodeBase;
            string uniqueIdentifier = assemblyName.Replace("\\", "_");
            m_Mutex = new Mutex(false, uniqueIdentifier);
        }

        //回收资源
        public static void UninitSingleton()
        {
            if (m_Mutex != null)
            {
                m_Mutex.Close();
            }
            m_Mutex = null;

            if (m_TCPChannel != null)
            {
                m_TCPChannel.StopListening(null);
            }
            m_TCPChannel = null;
        }

        //判断是否为第一个进程
        public static bool FirstProcToRun(int tcpPort,String serviceName)
        {
            if (m_Mutex.WaitOne(1, true))
            {
                CreateTCPChannel(tcpPort,serviceName);
                return true;
            }
            else
            {
                m_Mutex.Close();
                m_Mutex = null;
                return false;
            }
        }

        //创建TCP监听
        private static void CreateTCPChannel(int tcpPort,String serviceName)
        {
            try
            {
                m_TCPChannel = new TcpChannel(tcpPort);
                ChannelServices.RegisterChannel(m_TCPChannel, false);
                RemotingConfiguration.RegisterWellKnownServiceType(typeof(SingletonExeController), serviceName, WellKnownObjectMode.SingleCall);
            }
            catch(Exception ex)
            {
                //Fix me...
                //port in use
                MessageBox.Show(ex.Message);
            }
        }

        //后续进程,向第一个进程发送自己的参数
        public static void Send(int port,String serviceName, string[] s)
        {
            try
            {
                SingletonExeController ctrl;
                TcpChannel channel = new TcpChannel();
                ChannelServices.RegisterChannel(channel, false);
                try
                {
                    String address = "tcp://localhost:" + port + "/" + serviceName;
                    ctrl = (SingletonExeController)Activator.GetObject(typeof(SingletonExeController), address);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception: " + e.Message);
                    throw;
                }
                ctrl.Receive(s);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        //第一个进程,接收传入参数
        public void Receive(string[] s)
        {
            //Do something here
            //...

            //Test Code
            MessageBox.Show(s[0]);
        }

        //查找第一个进程
        public static Process findMainProcess()
        {
            Process currentProcess = Process.GetCurrentProcess();
            string processName = currentProcess.ProcessName;

            Process mainProcess = null;
            Process[] allProcesses = Process.GetProcessesByName(processName);
            if (allProcesses != null)
            {
                foreach (Process p in allProcesses)
                {
                    if (p.Id != currentProcess.Id)
                    {
                        if (p.MainWindowHandle != null)
                        {
                            mainProcess = p;
                            break;
                        }
                    }
                }
            }

            return mainProcess;
        }

        //查找第一个进程的主窗口
        public static IntPtr findMainWnd()
        {
            IntPtr mainWnd = IntPtr.Zero;
            Process p = findMainProcess();
            if(p!=null && p.MainWindowHandle != null)
            {
                mainWnd=p.MainWindowHandle;
            }

            return mainWnd;
        }
    }
}

2、Program.cs

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;

namespace SingletonExeTest
{
    static class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            //Debugger.Launch();
            //Debugger.Break();

            int tcpPort = 9999;
            String serviceName = "MyTestService";

            SingletonExeController.InitSingleton();

            if (SingletonExeController.FirstProcToRun(tcpPort, serviceName))
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                //Do something here
                //...

                //Test Code
                Application.Run(new MainForm());
            }
            else
            {
                IntPtr mainWnd = SingletonExeController.findMainWnd();
                Win32Utils.ShowWindow(mainWnd, Win32Utils.SW_RESTORE);
                //Real Code
                //SingletonExeController.Send(tcpPort, serviceName, args);

                //Test Code
                String[] msgs = {"hi","hello","good"};
                SingletonExeController.Send(tcpPort, serviceName, msgs);
            }

            SingletonExeController.UninitSingleton();
        }
    }
}

R从文本文件读取矩阵

1、数据文件
1.1、InA.txt

1,2,3
4,5,6
7,8,9

1.2、InB.txt

1
2
3
4
5
6
7
8
9

1.3、InC.csv

col1,col2,col3
1,2,3
4,5,6
7,8,9

3、数据读取
3.1读行取文本转为矩阵

filename="C:\\TestData\\InA.txt"
matrixA <- as.matrix(read.table(filename, header=FALSE, sep = ",",as.is=TRUE))

3.2按Cell读取文本转为矩阵

filename="C:\\TestData\\InB.txt"
matrixB <- matrix(scan(filename),ncol=3,byrow=TRUE)

3.3直接读取CSV

filename="C:\\TestData\\InC.csv"
matrixC =read.csv(filename,header=FALSE)

4、数据输出
4.1输出为文本文件

filename="C:\\TestData\\resultA.txt"
write.table(resultA, file = resultA, row.names = F, quote = F)

4.2输出为CSV文件

filename="C:\\TestData\\resultB.csv"
write.csv(matrixResult,filename)

5、设置工作路径

setwd("C:\\TestData")

R语言矩阵运算

1向量
1.1定义向量

##定义向量,下面两种方式结果相同
##c(..., recursive = FALSE) 
x=1:12
x=c(1,2,3,4,5,6,7,b,9.10)

1.2向量与数字四则运算

##+-×/
x=1:12
y=10
z=x*y

1.3向量的内积

##%*% crossprod
x=1:5
y=1:5
z=x%*%y
z1=crossprod(x)
z2=crossprod(x,y)

1.4向量的外积

##x%o%y tcrossprod
x=1:5
y=1:5
z=x%o%y
z1=tcrossprod(x)
z2=tcrossprod(x,y)
z3=outer(x,y)

1.5矩阵转向量

vec<-function (x){
          t(t(as.vector(x)))
}
vech<-function (x){
          t(x&#91;lower.tri(x,diag=T)&#93;)
}
x=matrix(1:16,nrow=4,ncol=4,byrow=TRUE)
vec(x)
vech(x)
&#91;/code&#93;

1.6生成滞后序列
&#91;code lang="R"&#93;
library(fMultivar)
x=1:20
tslag(x,1:4,trim=F)
tslag(x,1:4,trim=T)
&#91;/code&#93;

<strong>2数组</strong>
2.1定义数组
[code lang="R"]
##向量转数组,按列转
##dim(x)
dim(x)=c(3,4);
##或者直接定义多维数组
x=array(1:12,dim=c(3,4))

3矩阵
3.1定义矩阵

##matrix(data=NA,nrow=1,ncol=1,byrow=FALSE,dimnames=NULL)
##data项为必要的矩阵元素,nrow为行数,ncol为列数,nrow与ncol的乘积应为矩阵元素个数,byrow项控制排列元素时是否按行进行,dimnames给定行和列的名称
x=matrix(1:16,nrow=4,ncol=4,byrow=TRUE)
##行数
nrow(x)
##列数
ncol(x)
##上三角阵
C=x
C[lower.tri(A)]=0
##下三角阵
C=x
C[upper.tri(A)]=0
##元素的行与列
row(x)
col(x)
D=x
D[row(x)<col(x)&#93;=0
D=x
D&#91;row(x)>col(x)]=0

3.2定义对角矩阵

##diag
A=c(1:5)
##对角阵
B=diag(A)
##获取对角元素
C=diag(B)
##生成单位对角阵
D=diag(5)

3.3矩阵与数字四则运算

##+-*/
A=matrix(1:9,nrow=3,ncol=3,byrow=TRUE)
B=10
C=A+B
D=A-B
E=A*B
F=A/B
##行和
rowSums(A)
apply(A,1,sum)
##行平均值
rowMeans(A)
apply(A,1,mean)
##行方差
apply(A,1,var)
##列和
colSums(A)
apply(A,2,sum)
##列平均值
colMeans(A)
apply(A,2,mean)
##列方差
apply(A,2,var)

3.4矩阵与矩阵加减法

##+-
A=matrix(1:9,nrow=3,ncol=3,byrow=TRUE)
B=matrix(10:18,nrow=3,ncol=3,byrow=TRUE)
C=A+B
D=A-B

3.5矩阵与矩阵乘法

##%*%
A=matrix(1:9,nrow=3,ncol=3,byrow=TRUE)
B=matrix(10:18,nrow=3,ncol=3,byrow=TRUE)
C=A%*%B
##t(A)%*%B;
C1=crossprod(A,B)
##A%*%t(B)
C2=tcrossprod(A,B)
##Hadamard积
D=A*A

3.6矩阵转置

##t(x)
A=matrix(1:6,nrow=2);
B=t(A)

3.7矩阵行列式

##det(x, ...)
A=matrix(1:9,nrow=3);
B=det(A)

3.8矩阵求逆

##solve
A=matrix(c(1,2,3,2,2,1,3,4,3),nrow=3,byrow=TRUE);
B=det(A)
C=solve(A)

##需要strucchange包,A'A的逆
library(strucchange)
C1=solveCrossprod(A,method="qr")
C2=solveCrossprod(A,method="chol")
C3=solveCrossprod(A,method="solve")
C4=solve(crossprod(A,A))

3.9求解线性方程

##solve
A=matrix(c(1,2,3,2,2,1,3,4,3),nrow=3,byrow=TRUE);
B=c(1,2,8)
C=solve(A,B)

##对于系数为三角阵的情况,可以用 backsolve及fowardsolve函数求解
##这一段有些错误,时间不够了,下次修复
A=matrix(1:9,3,3)
V=c(1,2,3)
B=A
B[upper.tri(B)]=0
backsolve(A,V,upper.tri=F,transpose=F)
forwardsolve(A,V,upper.tri=F,transpose=F)
##why not the same?
##something is wrong
solve(B,V)

3.10特征值及特征向量

##eigen
A=matrix(c(1,-2,2,-2,-2,4,2,4,-2),nrow=3,byrow=TRUE);
B=eigen(A)
##结果应该为对角阵
C=solve(B$vectors)%*%A%*%B$vectors

4.矩阵分解
4.1奇异值分解

##A=U%*%D%*%t(V),其中U, V是正交阵,D为对角阵,也就是矩阵A的奇异值
##svd
A=matrix(c(1,0,1,0,0,1),nrow=3,byrow=TRUE);
B=svd(A)
C=B$u%*%diag(B$d)%*%t(B$v)

4.2QR分解

##设A为m*n矩阵,如果存在m*m酉矩阵Q(即Q(H)Q=QQ(H)=I)和m*n阶梯形矩阵R,使得A=QR,那么此分解称为QR分解
##qr
A=matrix(c(1,1,1,2,-1,-1,2,-4,5),nrow=3,byrow=TRUE);
B=qr(A)
Q=qr.Q(B)
R=qr.R(B)
C=Q%*%R

4.3Schur分解

##A=USU(H),其中U是标准的正交矩阵(即满足UU(H)=I),S为上三角矩阵,并且对角线上的元素为A的特征值。
##Schur
library(Matrix);
A=matrix(c(1,1,1,2,-1,-1,2,-4,5),nrow=3,byrow=TRUE);
B=Schur(A, vectors=TRUE);
C=B$Q%*%B$T%*%t(B$Q)

4.4Cholesky分解

##对任意的正定矩阵A,存在上三角矩阵R,使A=t(R)%*%R,则称为A的Cholesky分解
##chol
A=matrix(c(4,-1,1,-1,4.25,2.75,1,2.75,3.5),nrow=3,byrow=TRUE);
B=chol(A);
C=t(B)%*%B;
##求行列式
D=prod(diag(chol(A))^2)
##求逆
E=chol2inv(chol(A))