python,ruby中时间类型的萃取

jeremy.chen 发表于 2008-09-16 13:04:48

ruby中
strTime= '2008-8-26A23:47:42'
strTime= '2008-8-26 23:47:42'
postTime = (Time.parse(strTime) + 60*2).strftime("%Y-%m-%d %H:%M:%S")
#dosomething

python中
import datetime
strTime = '2008-8-26 23:47:42'
pdate= datetime.datetime.strptime(strTime, '%Y-%m-%da%H:%M:%S') + datetime.timedelta(minutes = 2)
postTime =pdate.strftime("%Y-%m-%d %H:%M:%S")
#dosomething
-------------------------

嘿嘿,这个ruby灵活,时间对象直接和整数运算了,省略了把整数timedelta成对象那步.
ruby强制类型转换难道比python要弱?
关键词(Tag): gp
收藏: QQ书签 del.icio.us 订阅: Google 抓虾

myspace+fsharp=?

jeremy.chen 发表于 2008-09-16 12:47:11

fackbook在协同并发上用了Erlang,而google应用了自己开发的函数式映射模块MapReduce。
自傲的M$应该不会用别人的东东,估计.Net开发的Myspace在等Fsharp吧,好拿来验证它的新语言,^_^!
关键词(Tag): fp
收藏: QQ书签 del.icio.us 订阅: Google 抓虾

Test Round Robin Database (python 存根)

jeremy.chen 发表于 2008-09-16 12:28:01

//test draw graph with rrttool
import os

os.chdir("C:/rrdtool")

##13KB
c = 'rrdtool.exe "create" "C:/topic.rrd" "--step" "300" \
"--start" "1167019200" "DS:visits:COUNTER:600:U:U" \
"DS:replys:COUNTER:600:0:U" "DS:focuses:GAUGE:600:U:U" \
"RRA:AVERAGE:0.5:1:24" \
"RRA:AVERAGE:0.5:12:48" \
"RRA:AVERAGE:0.5:12*24:400" \
'
s1 = os.popen(c)

u1 = 'rrdtool.exe "update" "C:/topic.rrd" "1167019500:110:1:1000" "1167019800:320:3:1700"'
u2 = 'rrdtool.exe "update" "C:/topic.rrd" "1167020100:340:3:2500" "1167020400:405:5:2500"'
u3 = 'rrdtool.exe "update" "C:/topic.rrd" "1167020700:650:7:3400" "1167021000:810:8:5900"'
u4 = 'rrdtool.exe "update" "C:/topic.rrd" "1167021300:920:9:6200" "1167021600:1000:10:1100"'
u5 = 'rrdtool.exe "update" "C:/topic.rrd" "1167021900:1150:11:3500" "1167022200:1600:15:5800"'
u6 = 'rrdtool.exe "update" "C:/topic.rrd" "1167022500:1800:17:6000" "1167022800:2100:20:7000"'
u7 = 'rrdtool.exe "update" "C:/topic.rrd" "1167023100:2100:22:7800" "1167023400:2400:25:9500"'
os.popen(u1)
os.popen(u2)
os.popen(u3)
os.popen(u4)
os.popen(u5)
os.popen(u6)
os.popen(u7)

g = 'rrdtool.exe "graph" "C:/clickRate1.png" "--start" "1167019200" "--end" "1167023700" \
"-t" "change of topic" "-v" "tianya" \
"-c" "BACK#C3D0FF" "-c" "SHADEB#0075BE" \
"-n" "TITLE:12" "-n" "AXIS:10" "-n" "UNIT:20" \
"DEF:visit=C\:/topic.rrd:visits:AVERAGE" \
"DEF:reply=C\:/topic.rrd:replys:AVERAGE" \
"DEF:focus=C\:/topic.rrd:focuses:AVERAGE" \
"CDEF:myvisit=visit,6,*" \
"CDEF:myreply=reply,300,*" \
"CDEF:myfocus=focus,1000,/" \
"LINE1:myvisit#FF0000:"visits"" \
"LINE1:myreply#00FF00:"replys"" \
"LINE1:myfocus#0000FF:"focuses"" \
'
s2 = os.popen(g)
print s2.read()

关键词(Tag): database
收藏: QQ书签 del.icio.us 订阅: Google 抓虾

获取visa仪器屏幕截图(C#,存根)

jeremy.chen 发表于 2008-09-16 12:14:41

//***************************IVSIA.cs*************************************

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;

namespace GetSnapOfInstrument
{
    // Abstract:
    //    Import System API
    class SysAPI
    {
        /************************************************************************/
        /* API for reading & writing .ini file                                  */
        /************************************************************************/
        [DllImport("kernel32.dll", EntryPoint = "WritePrivateProfileString", CharSet = CharSet.Auto)]
        public static extern long WritePrivateProfileString(string section,
            string key, string val, string filePath);

        [DllImport("kernel32.dll", EntryPoint = "GetPrivateProfileString", CharSet = CharSet.Auto)]
        public static extern int GetPrivateProfileString(string section,
            string key, string def, StringBuilder retVal, int size, string filePath);

        [DllImport("kernel32.dll", EntryPoint = "GetPrivateProfileInt", CharSet = CharSet.Auto)]
        public static extern uint GetPrivateProfileInt(string section, string key, int def, string filePath);

        /************************************************************************/
        /* API for sending & receiving window message between windows           */
        /************************************************************************/
        [DllImport("user32.dll", EntryPoint = "SendMessageA", SetLastError = true)]
        public static extern int SendMessage(IntPtr hwnd, uint wMsg, IntPtr wParam, IntPtr lParam);

        [DllImport("user32.dll", EntryPoint = "SendMessageA", SetLastError = true)]
        public static extern int SendMessage(IntPtr hwnd, uint wMsg, int wParam, int lParam);

        [DllImport("user32.dll", EntryPoint = "PostMessage", SetLastError = true)]
        public static extern bool PostMessage(IntPtr hwnd, uint wMsg, int wParam, int lParam);

        [DllImport("user32.dll", EntryPoint = "PostMessage", SetLastError = true)]
        public static extern bool PostMessage(IntPtr hwnd, uint wMsg, IntPtr wParam, IntPtr lParam);

        [DllImport("User32.dll ", EntryPoint = "FindWindow")]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
    }
    //
    // Abstract:
    //    Import VISA Driver's API Functions
    class VISAAPI
    {
        [DllImport("visa32.dll", EntryPoint = "viOpenDefaultRM", CharSet = CharSet.Auto)]
        public static extern int viOpenDefaultRM(ref UInt32 sesn);

        [DllImport("visa32.dll", EntryPoint = "viOpen", CharSet = CharSet.Ansi)]
        public static extern int viOpen(UInt32 session, string strcomd, UInt32 vinull, UInt32 vinul, ref UInt32 instrr);

        [DllImport("visa32.dll", EntryPoint = "viWrite", CharSet = CharSet.Ansi)]
        public static extern int viWrite(UInt32 instr, string outStr, Int32 strLen, ref UInt32 count);

        [DllImport("visa32.dll", EntryPoint = "viRead", CharSet = CharSet.Ansi)]
        public static extern int viRead(UInt32 instr, [Out]StringBuilder outStr, UInt32 strLen, ref UInt32 count);

        [DllImport("visa32.dll", EntryPoint = "viRead", CharSet = CharSet.Ansi)]
        public static extern int viRead(UInt32 instr, [Out]byte[] outStr, UInt32 strLen, ref UInt32 count);

        [DllImport("visa32.dll", EntryPoint = "viClose", CharSet = CharSet.Ansi)]
        public static extern int viClose(UInt32 session);

        [DllImport("visa32.dll", EntryPoint = "viFlush", CharSet = CharSet.Ansi)]
        public static extern int viFlush([In]UInt32 session, [In]UInt16 mask);

        [DllImport("visa32.dll", EntryPoint = "viGetAttribute", CharSet = CharSet.Ansi)]
        public static extern int viGetAttribute([In]UInt32 session, [In]UInt32 attribute, ref Int32 attrState);

        [DllImport("visa32.dll", EntryPoint = "viGetAttribute", CharSet = CharSet.Ansi)]
        public static extern int viGetAttribute(UInt32 session, UInt32 attribute, [Out]StringBuilder attrState);

        [DllImport("visa32.dll", EntryPoint = "viFindRsrc", CharSet = CharSet.Ansi)]
        public static extern int viFindRsrc(UInt32 session, string expr, ref UInt32 findList, ref UInt32 retCnt, [Out]StringBuilder desc);

        [DllImport("visa32.dll", EntryPoint = "viQueryf", CharSet = CharSet.Ansi)]
        public static extern int viQueryf(UInt32 session, string writeIn, string readOut, [Out]StringBuilder result);
    }
}

//***************************Form1.cs*************************************

namespace GetSnapOfInstrument
{
    public partial class Form1 : Form
    {
        private UInt32 uDefaultRM;
        private UInt32 uSessionIns;
        private string SACommStr = "TCPIP::{0:S}::INSTR";

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int result = 0;
            StringBuilder strRet = new StringBuilder(100);

            result = VISAAPI.viOpenDefaultRM(ref uDefaultRM);
            if (result < 0)
                return;
            string strCmd = string.Format(SACommStr, "192.168.0.2");
            result = VISAAPI.viOpen(uDefaultRM, strCmd, 0, 0, ref uSessionIns);
            if (result < 0)
                return;
            if (!GetScreenSnap())
                MessageBox.Show("Snap can't be captured!");
        }

        private bool GetScreenSnap()
        {
            int result;
            UInt32 retSize = 0;
            const UInt32 bufSize = 1024 * 1024;
            byte[] strRet = new byte[bufSize];

            IxVisaWrite("HCOP:DEV:LANG BMP");         // Define file format
            IxVisaWrite("HCOP:DEST1 'MMEM'");         // Select output medium
            IxVisaWrite("MMEM:NAME 'C:/snap/temp'");  // Define the file name
            IxVisaWrite("HCOP:IMM");                  // Start a hard-copy output

            result = IxVisaWrite("MMEM:DATA? 'C:/snap/temp.bmp'");    // Data transfer from instrument to control computer.
            if (result < 0)
                return false;

            result = VISAAPI.viRead(uDefaultRM, strRet, bufSize, ref retSize);
            if (result < 0)
                return false;

            Byte xLen = Byte.Parse(ASCIIEncoding.ASCII.GetString(strRet, 1, 1));
            Byte[] newData = new Byte[retSize];
            Array.Copy(strRet, xLen + 2, newData, 0, retSize - xLen - 2);

            MemoryStream ms = new MemoryStream(newData);
            Image img = Image.FromStream(ms);
            //redefine the image size
            Image myImg = img.GetThumbnailImage(800, 600, null, IntPtr.Zero);
            this.pictureBox1.Image = myImg;
            //save the image to file
            MemoryStream ms1 = new MemoryStream();
            myImg.Save(ms1, ImageFormat.Bmp);
            File.WriteAllBytes(Application.StartupPath + @"\" + DateTime.Now.ToString("yyyyMMdd.HHmmss") + ".bmp", ms1.ToArray());
           
            return true;
        }

        public int IxVisaWrite(string outStr)
        {
            int iRetStatus = -1;
            UInt32 outCnt = 0;
            iRetStatus = VISAAPI.viWrite(uDefaultRM, outStr, outStr.Length, ref outCnt);
            return iRetStatus;
        }

        public string IxVisaRead()
        {
            uint iRdSize = 100;
            StringBuilder strRet = new StringBuilder((int)iRdSize);
            int iRetStatus = -1;
            UInt32 uCount = 0; // 实际读出的字节数

            iRetStatus = VISAAPI.viRead(uDefaultRM, strRet, iRdSize, ref uCount);

            if (strRet.Length > uCount)
                strRet.Remove((int)uCount, (int)(strRet.Length - uCount)); // 清除无效字符
            if (iRetStatus < 0)
            {
                return strRet.ToString();
            }
            return strRet.ToString();
        }
    }
}


关键词(Tag): .net
收藏: QQ书签 del.icio.us 订阅: Google 抓虾

handle IE's win32ole(ruby,存根)

jeremy.chen 发表于 2008-09-16 12:06:41

//**********************************************HTMLClass.rb*****************************************

if (#CONTENT# != __FILE__)
  curpath = File.expand_path(File.dirname(__FILE__))
  if ($LOAD_PATH.include?(curpath) == false)
    $LOAD_PATH << curpath
  end
end
require 'win32ole'

class DOMObject
  def name
    @name
  end
 
  def id
    @id
  end
 
  def initialize(_name, _id)
    @name = _name
    @id = _id
  end
end

class IE
  READYSTATE_COMPLETE = 4
  FAST_SLEEP_TIME = 0.01
  LOW_SLEEP_TIME = 0.1
 
  attr_reader :m_down_load_time
  attr_reader :m_ie
 
  def initialize()
    @m_ie = WIN32OLE.new('InternetExplorer.Application')
    @m_url_list = []
    @m_defaultSleepTime = FAST_SLEEP_TIME
  end
 
  def goto( _url )
    @m_ie.navigate( _url )
    wait()
    sleep 0.2
    return @m_down_load_time
  end
 
  def setHtml( _htmlfile )
    #~ _htmlfile = Func.getFullpath(_htmlfile)
    goto( _htmlfile )
  end
 
  def close
    @m_ie.quit
  end
 
  def document
    return @m_ie.document
  end
 
  def activeElement
    return @m_ie.document.activeElement
  end
 
  def focus
    @m_ie.document.activeElement.blur
    @m_ie.document.focus
  end
 
  def rect( _width, _height, _fullscreen=false )
    @m_ie.menubar = false
    @m_ie.addressbar = false
    @m_ie.toolbar = false
    @m_ie.statusbar = false
    @m_ie.resizable = true
    @m_ie.fullscreen = _fullscreen
    @m_ie.width = _width
    @m_ie.height = _height
    @m_ie.left = (@m_ie.document.parentwindow.screen.availwidth-@m_ie.width)/2
    @m_ie.top = (@m_ie.document.parentwindow.screen.availheight-@m_ie.height)/2
  end
 
  def url
    return @m_ie.LocationURL
  end
 
  def html
    return @m_ie.document.body.outerHTML
  end
 
  def text
    return @m_ie.document.body.innerText.strip
  end
 
  def wait( _noSleep=false )
    begin
      @m_down_load_time = 0
      pageLoadStart = Time.now
      @m_pageHasReloaded = false
     
      until @m_ie.readyState == READYSTATE_COMPLETE
        @m_pageHasReloaded = true
        sleep 0.02
      end
      sleep 0.02
     
      until @m_ie.document.readyState == "complete"
        sleep 0.02
      end
     
      if @m_ie.document.frames.length > 1
        begin
          0.upto @m_ie.document.frames.length-1 do |i|
            until @m_ie.document.frames[i.to_s].document.readyState == 'complete'
                sleep 0.02
            end
            @m_url_list << @m_ie.document.frames[i.to_s].document.url unless @m_url_list.include?(@m_ie.document.frames[i.to_s].document.url)
          end
        rescue=>e
            puts 'frame error in wait'   + e.to_s + "\n" + e.backtrace.join("\n")
        end
      else
          @m_url_list << @m_ie.document.url unless @m_url_list.include?(@m_ie.document.url)
      end
      @m_down_load_time = Time.now - pageLoadStart
    rescue WIN32OLERuntimeError => e
      puts "runtime error in wait: #{e}\n#{e.backtrace.join("\\n")}"
    end
    sleep 0.01
    sleep @m_defaultSleepTime unless _noSleep == true
  end

  def stopMsgLoop
    puts 'Now Stop IE...'
    @m_ie_loop = false
  end

  def show
    @m_ie.visible = true
   
    ev = WIN32OLE_EVENT.new( @m_ie, 'DWebBrowserEvents' )
    ev.on_event('Quit') {|*args| stopMsgLoop}
    @m_ie_loop = true
    while (@m_ie_loop)
      sleep 0.005
      WIN32OLE_EVENT.message_loop
    end
  end
 
  def msgBox( _message )
    @m_ie.document.parentwindow.alert( _message )
    #bConfirmed = @m_ie.document.parentwindow.confirm( _message )
    #vTextData = @m_ie.document.parentwindow.prompt( _message, _defaultValue )
  end
 
  def getElementById( _id )
    return @m_ie.document.getElementById( _id )
  end
 
  #~ def getAllIDObjects()
    #~ @m_ie.document.all.each do |n|
      #~ id = n.invoke( 'id' )
      #~ if ( id.to_s!='' )
        #~ tag = n.invoke( 'tagname' )
        #~ if ( tag=='INPUT' )
          #~ t = n.invoke( 'type' ).upcase
          #~ tag = tag + ' ' + t
        #~ end
        #~ s = tag + ': id='+ id
        #~ @m_DOMlist.add( NElement.new(tag, id) ) #( DOMObject.new(tag, id) )
        #~ puts s
      #~ end
    #~ end
  #~ end

  def newObject( _type, _id, _value, _parent=nil )
    case _type
      when 'Button'
        type_text = "<INPUT TYPE='button'>"
      when 'Text'
        type_text = "<INPUT TYPE='text'>"
      when 'A'
        type_text = "A"
      else
        type_text = _type
    end
    obj = @m_ie.document.createElement( "#{type_text}" )
    obj.setAttribute( "id", "#{_id}" )
    obj.setAttribute( "value", "#{_value}" )
    if _parent == nil
      @m_ie.document.body.insertBefore( obj )
    else
      @m_ie.document.getElementById("#{_parent}").appendChild( obj )
    end
  end
 
  def deleteTr(_table_id, _tr_id)
    tr = @m_ie.document.getElementById(_table_id).childNodes(0)
    tr.removeChild(tr.childNodes(_tr_id))
  end

  def deleteTbody(_tbody)
    if (_tbody.hasChildNodes())
      begin
        (_tbody.childNodes.length-1).downto 0 do |i|
          _tbody.removeChild(_tbody.childNodes(i))
        end
      rescue
        p 'You have already removed the body element.'
      end
    end
  end

end

 //**********************************************test.html*****************************************

<body>
<div>input URL:<input type="text" id="url_location" style='width:80%' value='http://cache.tianya.cn/publicforum/ArticlesList/0/poem.shtml'>
<!--<br><INPUT type=radio name="type" id='type_forum' CHECKED>Forum
<INPUT type=radio name="type" id='type_thread'>Thread
<input  id='url_button'   style="width:50;visibility:hidden" type="button" value="ok" >
</br>-->
<input  id='filter_button'   style="width:50" type="button" value="filter">
</div>

<!--<IFRAME id='frame' FRAMEBORDER=1 style='width:99%;height:70%' ></IFRAME>-->

<div id='main'>
</div>

<div id='result'></div>

</body>

//***********************************************test.rb***************************************

#~ require 'net/http'
#~ require 'open-uri'
#~ require 'hpricot'
#require 'simpleTianyaParser.rb'
require 'HTMLClass.rb'


def handle_filter
   
    url = $window.document.getElementById('url_location').value
    p url
    tp = SimpleTianyaParser.new
   
   
    p tp.checkType?(url)
    begin
      type,result = tp.parseHTML(url)
    rescue Exception => e  
      p e
      result = e
      type = 'exception'
    end
    if type=='forum'
      s = '<p>'
      s += result
      s += '</p>'
       $window.document.getElementById('result').innerHTML += "#{s}<br>----------------<br>"  
    elsif type=='thread'
      s ='<p>'
      s += result
      s +='</p>'
      $window.document.getElementById('result').innerHTML += "<br>#{s}<br>----------------<br>"           
    elsif type=='exception'
      $window.document.getElementById('result').innerHTML += "Exception Occur:<br>#{result}<br>"                         
    else #not supported
      $window.document.getElementById('result').innerHTML += "The following URL is not supported:<br>#{url}<br>"                   
    end
  
end

htmlroot = File.expand_path(File.dirname(__FILE__))
htmlfile = 'test.html'

$window = IE.new
$window.setHtml(htmlroot+'/'+htmlfile  )
$window.rect( 800, 600 )

$window.document.getElementById('filter_button').onclick = method(:handle_filter)

$window.show()

 

 
关键词(Tag): dom
收藏: QQ书签 del.icio.us 订阅: Google 抓虾