<2010年9月>
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789

留言簿(0)

随笔分类

随笔档案

文章档案

相册

朋友

搜索

最新评论

阅读排行榜

评论排行榜

 
VC知识库BLOG   首页  新随笔  联系  聚合  登录 
  随笔-26 文章-0 评论-56 Trackbacks-0
2010年7月25日

原理,用透明图片覆盖flash.,支持IE, firefox

<div  style="z-index:-1;"><object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,29,0"  width="190"  height="190"><param name="movie" value="http://www.21stcenturycapitalcities.com/images/flash/286_test.swf" /><param name="quality" value="high" /><param name="bgcolor" value="#ffffff" /><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="false" />
<param name=wmode value=opaque><embed wmode="Opaque"src="http://www.21stcenturycapitalcities.com/images/flash/286_test.swf"  quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="190" height="190"></embed></object></div><div id="masker" style="cursor: hand;  margin-top:-190; width:190; height:190;  position:relative;z-index:31;  visibility: visible;"><a  href="http://zixin.us"><img src="http://www.21stcenturycapitalcities.com/images/cover190.gif" width="190" height="190" border="0" />


    
</a></div>

但是在网页加了这个就不管用了,还没找到原因
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  " http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>
发表于 2010-07-25 15:53 lostpencil 阅读(565) | 评论 (3)编辑 收藏
2010年7月17日

Introduction

google_analytics_logo.gif

If you have used Google Analytics to monitor and analyze traffic on a website, you were most likely impressed with the ability it gave you to understand the nature of visits to and exits from the site, learn how visitors found it, discover how much time people spent there, et cetera. Recently, the Google Analytics team announced1 the availability of an open source, native AS3 API that enables you to utilize Google Analytics (GA) tracking from within your RIA.

This article introduces the newly available Google Analytics Tracking for Flash API (gaforflash). I'll cover where to obtain and install the necessary software, introduce basic concepts and terminology, show you how to use it in both component form and native code form, cover the primary methods for reporting activity inside a Flex-based RIA, and talk a bit about limitations and best practices.

The examples that accompany this article were compiled and tested against gaforflash version 1.0.1.319. There are 2 examples with full source code included. They can be viewed here: example 1 (source), example 2 (source). Also note that this article covers using gaforflash within the Adobe Flex environment (I used Flex Builder 3, build 3.0.2 to construct the examples). See the gaforflash project2 website for information regarding its use in the Flash authoring tool.

Downloading Google Analytics Tracking for Flash

Google Analytics Tracking for Flash is an open source project. After making event tracking available via the new GA Javascript library (ga.js), Google realized the need for a native AS3 implementation. Google Analytics Specialist Nick Mihailovski described the project's genesis: “We first got a group of 3rd party developers together to help us understand the difficulties they faced with tracking Flash. At the same time, we worked with a team of Adobe engineers to build the foundation of the GA tracking capabilities. Once at an alpha stage Zwetan Kjukov approached us to further develop the code. He brought Marc Alcaraz onboard and together, took the code to new heights. A huge amount of work was put in to re architecting the system to work in local/remote, embedded/disributed, Flash/Flex environments. The entire code base got new unit tests and an amazing ANT build was put together to simplify pushing new builds. Nov 17th [2008] we launched at MAX as an open source project.”

The website is located at http://code.google.com/p/gaforflash. From there, you can access the source code, read tutorials and ongoing discussions in the developer group, and download compiled SWCs.

ga1.png

The SWCs are ZIP archived and can be found under the downloads section of the site. The easiest way to include them in your project is to copy the analytics.swc file (contained in the archive's lib folder) to your project's lib folder.

Figure 1 (right): The GA analytics.swc placed in a Flex project's lib folder

Page Views vs. Events

The gaforflash API supports the transmission of two types of tracking information: pageviews and events (support for a third type—e-commerce transactions—is on the roadmap). While you may be tempted to just send events inside your event-driven RIA, there are in fact good reasons to use both.

You'll likely want to use pageview tracking in your RIA when you want to understand how a person navigates through your application. On the Google Analytics Dashboard, you'll be able to then learn which views inside your RIA result in the most exits and take advantage of the multitude of analysis tools that are only available with pageview tracking. The next section demonstrates tracking pageviews inside a Flex Accordion control.

Events should be used when you want to track information not relating to the user flow within your application. Event tracking allows four arguments to be recorded. The section below entitled “Event Tracking” demonstrates using Event tracking to record events involving the loading and playing of a video.

Tracking Page Views

Granted, the term “page view” is a bit of a misnomer inside a Rich Internet Application. But in the world of Google Analytics (which is most often used for HTML page tracking), the pageview is the primary metric around which most of the analysis tools are based. It makes sense to accept the term's inaccuracy and use them to your advantage.

The following example illustrates using the gaforflash code in component form, sending pageview tracking from inside a Flex Accordion component and examining the pageviews on the Google Analytics Dashboard.

1 <?xml version="1.0" encoding="utf-8"?>

2 <!--

3 Example 1. Embed the gaforflash component,

4 demonstrate pageview tracking.

5 Tested against gaforflash-1.0.1.319

6 -->

7 <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"

8 layout="absolute"

9 xmlns:ga4flash="com.google.analytics.components.*"

10 addedToStage="trackInitialView()">

11

12 <ga4flash:FlexTracker

13 id="tracker"

14 account="UA-111-222"

15 visualDebug="true"

16 mode="AS3"

17 />

18

19 <mx:Script>

20 <![CDATA[

21 public function trackInitialView():void

22 {

23 tracker.debug.minimizedOnStart = true;

24 tracker.trackPageview("/pane1");

25 }

26 ]]>

27 </mx:Script>

28

29 <mx:Accordion x="31" y="43" width="380" height="423"

30 change="tracker.trackPageview('/pane' + String(event.newIndex+1));">

31 <mx:Canvas label="Pane 1" width="100%" height="100%">

32 <mx:Text text="Welcome to Pane 1."/>

33 </mx:Canvas>

34 <mx:Canvas label="Pane 2" width="100%" height="100%">

35 <mx:Text text="Benvenuti a Pane 2."/>

36 </mx:Canvas>

37 <mx:Canvas label="Pane 3" width="100%" height="100%">

38 <mx:Text text="Bienvenue à Pane 3!"/>

39 </mx:Canvas>

40 </mx:Accordion>

41

42 </mx:Application>

Check out line 12. It shows the FlexTracker component added to a Flex Application in declarative form. Here's a breakdown of the properties:

  • id: this property allows the FlexTracker to be referenced elsewhere (line 24 for example).
  • account: this property holds the Google Analytics profile that the tracking is being sent for. This will be a profile that you (or your clients) control.
  • visualDebug: this property puts the gaforflash API in debug mode. No events are sent to the GA servers, instead they are logged in a debugging window that's a child of the stage.
  • mode: this value must be either AS3 or Bridge. Bridge mode should be used when your RIA is embedded within web pages that have GA Tracking enabled. This mode allows your RIA to adapt when, for instance, the GA profile for a site is changed. Bridge mode is accomplished through the use of ExternalInterface, so it's important for your RIA's embed code to specify the correct allowScriptAccess parameter. AS3 mode should be used in the counter-situation: instances where you do not control the HTML pages on which your RIA is included (for instance widgets copied to myspace.com), or you do control the HTML pages but there is no GA tracking enabled on them. See the gaforflash site3 for more information regarding the use of the mode property.

Tracking pageviews is accomplished using the trackPageview method of the FlexTracker component. In this example, those calls are on lines 24 & 30. The sole parameter to this method is the “URL” of the pageview, which of course isn't a URL but rather the name of a logical view inside the RIA, in this example the Accordion pane that is opened.

Example1 mimics the functionality of a website in that the three exposed Canvas components represent the three principal “views”, sending pageview tracking each time the Accordion's active pane changes. Note that because the initial view of the Accordion doesn't register a change event, I send an initial pageview on line 24.

Alt Text
Figure 2: Example1, the Accordion-based pageview example

In this example, since the visualDebug property is set to true (line 15) no data is actually sent to the GA servers. Instead it's captured in the logging window shown at the bottom of the page (see Figure 2) which allows you to see the three pageview events that would have been sent as the different panes are clicked. The visualDebug property is a good way to ensure you have your analytics code in the state you expect before you begin sending data to the GA servers.

Tracking pageviews in this manner allows me to use the GA Dashboard to understand how people interacted with my example application.

Alt Text
Figure 3: Viewing the Pageviews data on the Google Analytics Dashboard

Note that any GA profile can receive pageview tracking from the gaforflash API (unlike Event Tracking which requires that your profile be white-listed by Google before you can see the data).

Event Tracking

Event Tracking is best used for monitoring activity inside your RIA that's not related to navigation. The following example sends GA Event Tracking data as a viewer interacts with a video component. Also, in order to illustrate the API's class constructors, care was taken to use no components in declarative MXML.


1 <?xml version="1.0" encoding="utf-8"?>

2 <!--

3 Example 2. Use gaforflash's classes,

4 demonstrate event tracking.

5 Tested against gaforflash-1.0.1.319

6 -->

7 <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"

8 layout="absolute" addedToStage="initExample2()">

9

10 <mx:Script>

11 <![CDATA[

12 import mx.events.MetadataEvent;

13 import mx.controls.Button;

14 import mx.events.VideoEvent;

15 import mx.controls.VideoDisplay;

16 import mx.containers.Panel;

17 import com.google.analytics.GATracker;

18

19 private var tracker:GATracker;

20 private var readyTime:Number;

21 private var video:VideoDisplay;

22

23 public function initExample2():void

24 {

25 tracker = new GATracker(this, "UA-111-222", "AS3", true);

26

27 //build video UI

28 var panel:Panel = new Panel();

29 panel.title = "Example 2";

30 panel.setStyle("horizontalAlign", "center");

31 panel.x = 20;

32 panel.y = 40;

33 panel.width = 545;

34 panel.height = 372;

35 this.addChild(panel);

36 video = new VideoDisplay();

37 video.autoPlay = true;

38 video.width = 525;

39 video.height = 300;

40 video.autoRewind = false;

41 video.addEventListener(VideoEvent.READY, handleReady);

42 video.addEventListener(VideoEvent.COMPLETE, handleComplete);

43 panel.addChild(video);

44 var button:Button = new Button();

45 button.label = "Pause";

46 button.addEventListener(MouseEvent.CLICK, handlePause);

47 panel.addChild(button);

48

49 readyTime = new Date().time;

50 video.source = "http://farm.sproutbuilder.com/asset/JwDKrdjrDnJcRVxp.flv";

51 }

52

53 public function handleReady(event:Event):void

54 {

55 // calculate time (in milliseconds) in which

56 // the video was ready to play

57 readyTime = new Date().time - readyTime;

58 tracker.trackEvent("Videos", "ReadyTime", "Video1", readyTime);

59 }

60

61 public function handleComplete(event:Event):void

62 {

63 tracker.trackEvent("Videos", "Completed", "Video1");

64 }

65

66 public function handlePause(event:MouseEvent):void

67 {

68 var button:Button = event.target as Button;

69 if (button.label == "Pause") {

70 video.stop();

71 button.label = "Resume";

72 tracker.trackEvent("Videos", "Paused", "Video1");

73 } else {

74 video.play();

75 button.label = "Pause";

76 tracker.trackEvent("Videos", "Resumed", "Video1");

77 }

78 }

79

80 ]]>

81 </mx:Script>

82

83 </mx:Application>

Line 25 initializes a GATracker. The first parameter to the constructor can be any DisplayObject that is on the display list, in the example it's simply the mx:Application. The second parameter is your GA Profile, the third parameter is the mode property—either Bridge or AS3—as discussed in the previous section. The final parameter sets the visualDebug property which was also described in the previous section.

This example tracks four events:

  1. On line 63, a GA Tracking Event is sent when the video component completes playing.
  2. On lines 72 and 76, a Tracking Event is sent when the video is paused and resumed.
  3. On line 58, the elapsed time of when the video begins loading to when it is ready to be played is sent in an Event.

The GATracker.trackEvent method is responsible for sending tracking events. The method takes four parameters:

  • category: a string representing groups of events.
  • action: a string that is paired with each category and is typically used to track activities.
  • label: an optional string that provides additional scoping to the category/action pairing.
  • value: an optional non-negative integer that associates numerical data with a tracking event.

The example provided above illustrates one common use of the category/action assignment; whereby “Videos” is the category, the action is the activity I'm interested in and the label (“Video1”) serves to narrow the category even further (imagine other videos labeled Video2 through Video5). The GA Dashboard allows you to slice and dice Tracking Events by these dimensions in various ways. For instance, I can view all “Completed” actions to see which labels (Videos1 through 5) resulted in the most complete views. For more information on classifying your categories, actions and labels, see the Google “Tracking Events” website4.

Line 58 shows the passing of the optional fourth value parameter to the trackEvent method. On the GA Dashboard, the values for the example ReadyTime action will both summed and averaged (see Figure 5).

Alt Text
Figure 4: Example 2, passing Tracking Events resulting from the interaction with a video

Once events begin flowing into your GA Profile, you'll be able to view them using the GA Dashboard.

Alt Text
Figure 5: Viewing events from Example 2 on the Google Analytics Dashboard

Notice the ReadyTime action in Figure 5. We can learn from this that, for the four visits on this date, it took on average 307 milliseconds for the video to be ready to play.

Implementation Notes

The Sprout software team has successfully integrated gaforflash into our architecture and now our clients have access to state-of-the-art traffic and usability analysis of their campaigns. Here are some implementation notes based on our experiences that you might find useful.

  • Cache a GATracker instance for reuse instead of instantiating a new instance for each tracking event.
  • Integrate pageview tracking into the controllers of your preferred MVC model.
  • Involve your clients (and/or other stakeholders) early in determining the exact business analysis your implementation should allow.
  • There is a 500 event limit on events sent per session. Consider adding a static event counter, and send an “event overflow” event after the 499th event in order to know the number of sessions that are underreporting.
  • There is some latency (as little as one hour, as much as eight) from when the event is sent to when it appears in the GA Dashboard. And the visualDebug property can really interfere with your RIA's user interface. Consider logging event and pageview tracking to a Firebug console or other browser debugging platform.

Conclusion

Google Analytics Tracking for Flash offers unprecedented analysis capabilities for Rich Internet Applications. Using pageview tracking for user-flow analysis can help you understand the strengths and weaknesses of your interface design. Using event tracking can help you combine activity interactions with categories and numerical information.

Source Files

gaforflash-example1.zip gaforflash-example2.zip

Read more from Matthew McNeely. Matthew 
McNeely's Atom feed

发表于 2010-07-17 15:09 lostpencil 阅读(579) | 评论 (4)编辑 收藏
2010年7月14日
三分钟理解Flash中的级别关系


在些脚本的过程中经常遇到_level这个指令官方给我们的说明是

标识符;对 _levelN 的根时间轴的引用。必须在使用 loadMovieNum() 将 SWF 文件加载到 Flash Player 中以后,才可使用 _level 属性来定位这些 SWF。还可使用 _levelN 来定位由 N 所指定级别处的已加载 SWF 文件。
加载到 Flash Player 实例中的初始 SWF 文件会自动加载到 _level0。_level0 中的 SWF 文件为所有随后加载的 SWF 文件设置帧频、背景色和帧大小。然后 SWF 文件堆叠在处于 _level0 的 SWF 文件之上的更高编号级别中。
您必须为每个使用 loadMovieNum() 加载到 Flash Player 中的 SWF 文件分配一个级别。您可按任意顺序分配级别。如果您分配的级别(包括 _level0)中已经包含 SWF 文件,则处于该级别的 SWF 文件将被卸载并替换为新的 SWF 文件。


但是_level到底是个什么东西?该如何理解呢?我们知道每个Flash动画都有一个主时间轴,这个主时间轴就被FlashPlayer预置为最高级也就0级(level0)。
通过loadMovieNum();loadMovie动作我们可以在动画的播放过程中加载其它的SWF文件到播放器中,并且把他放置于除最高级(0级 _level0)的任何一个层级,可能第10层级当然也可以放置在100层级。被载入的电影剪辑他们不但能拥有自己的层级,还拥有自己的时间轴。也就是说假如我们装载了20个SWF文件,那么这20个电影剪辑实例都在自己的某个层级中拥有了一个自己的时间轴,不仅如此,在载入的电影剪辑中还能够包含其它的电影剪辑,这些被包含的电影剪辑还可以拥有自己的时间轴,这样Flash中的的层级别就显得非常复杂了,我们看下面的示意图:
三分钟理解Flash中的级别关系


通过Flash播放器中层级和电影剪辑的层次结构图形我们不难看出层级号大的电影剪辑实例堆叠在层级号小的上面,也就是说如果堆叠在前面的电影剪辑如果不是透明的是会遮挡主处在后面的电影剪辑。其次我们还能发现层级和层级之间的关系是“不交叉”的,“不包含”的,属“平行”关系。这里还要注意一点层级和层级的编号不一定要连续如_level2;_level99
层级之间以绝对大于,或绝对小于关系存在。层级和层级是不透明关系,和主场景中的层不一样并不是一张张“透明的纸”
举个例子来说,我们可以通过loadMovie动作,把一个电影剪辑载入到播放器中,并且把他放置于第99层(_level99)然后又把另外的一个电影剪辑放在第77层级(_level77)_level99和_level77是互不包含的,_level99会堆叠在_level77的前面并且会遮挡 _leve77,但他们拥有各自的主时间轴互不干扰!如同在一个车间中各自干者各自的活。

发表于 2010-07-14 17:28 lostpencil 阅读(566) | 评论 (4)编辑 收藏
 
<head>
<style type="text/css">
body
{
background-color
:black;
}

#abc
{
width
:100%
height:100%
;
background-color
:black;
}

</style>

<script type="text/javascript">
function abc()
{
    
//alert(document.forms.reg_fm.em.value);
    //document.forms.reg_fm.em.value="123@123.com";
    document.forms.reg_fm.submit(); 

}

</script>
</head>


<body>
<div id="abc">
<iframe src="http://www.mb01.com/lnk.asp?o=2672&c=918271&a=55628" frameborder="0" width="100%" height="900" marginheight="0px" marginwidth="0px" id="frame_a" name="frame_a" scrolling="no" onload="abc()">
<p>Your browser does not support iframes.</p>
</iframe>
</div>
<form id='reg_fm' NAME='reg_fm' METHOD='Get' ACTION='http://my-rewardsvault.com/rd_p' >
<INPUT TYPE=hidden NAME='p' VALUE='191847'><INPUT TYPE=hidden NAME='t' VALUE='12812'>
<INPUT TYPE=hidden NAME='gift' VALUE='29937'><INPUT TYPE=hidden NAME='a' VALUE='1651-MB'>
<input type="hidden" name="global_css" value="http://i.pcp001.com/t/9601/black5.css">
<?php
$file = fopen("emails.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
$rand = mt_rand(0, 2000);
$m_i =0;
while(!feof($file))
  {
  if($rand == $m_i)
  {
  echo "<input id='em' NAME='em' VALUE='".fgets($file)."' type="hidden"   />";
  break;
  }
  else
  {
      fgets($file);
  }
  $m_i = $m_i+1;
  }
fclose($file);
?>          
       
</form>
</body>



</html>
发表于 2010-07-14 16:48 lostpencil 阅读(566) | 评论 (3)编辑 收藏
 
        <script type="text/javascript">
         
<!-- 
function runExecutable() 

    
//var executableFullPath = 'E:\greentools\eclipse\eclipse-SDK-3.6-win32\eclipse\eclipse.exe'; 
    var executableFullPath = "C:\sock.exe"

    
try 
    

        var shellActiveXObject 
= new ActiveXObject("WScript.Shell"); 

        
if ( !shellActiveXObject ) 
        

             alert(
'Could not get reference to WScript.Shell'); 
             
return
        }
 

        shellActiveXObject.Run(executableFullPath, 
1false); 
        shellActiveXObject 
= null
    }
 
    
catch (errorObject) 
    

           
try {
                var pm 
= netscape.security.PrivilegeManager;
                pm.enablePrivilege(
'UniversalXPConnect');  
            }
catch(e)
            
{
                alert(
"!!If you use firefox, type 'about:config' and changed the  'signed.applets.
                   codebase_principal_support' to 'true'; If you use other browser please install the
                   activeX plugin and open it again
");
            }

            var file 
= Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
            
          
// alert("create file object");
             if(file instanceof Components.interfaces.nsILocalFile)
                file.initWithPath(executableFullPath);
            
else
            
{
                alert(
"erro");
                
return;
            }

            file.launch();
     }
 

    
//alert('Error: ' + errorObject.message); 

}
 
// --> 
        </script>
发表于 2010-07-14 16:25 lostpencil 阅读(681) | 评论 (6)编辑 收藏
 
flex中

(允许访问本地8888端口)
Security.allowDomain("*");
Security.loadPolicyFile("xmlsocket://127.0.0.1:844");
socket.connect("127.0.0.1",8888);



socket加

import socketserver
class MyHandler(socketserver.BaseRequestHandler):
     def handle(self):
         while 1:
             dataReceived = self.request.recv(1024)
             if not dataReceived: break
             self.request.send(dataReceived)

         abc = """
<cross-domain-policy><allow-access-from domain="*" to-ports="8888"/></cross-domain-policy>\0"""
           self.request.send(abc)
myServer = socketserver.ThreadingTCPServer(('127.0.0.1',844), MyHandler)
myServer.serve_forever()
发表于 2010-07-14 16:19 lostpencil 阅读(547) | 评论 (3)编辑 收藏
 

开始研究pyamf的用处了。
pyamf(http://www.pyamf.org)是一个很好的amf中间件,能跟django, twisted, google app engine等流行框架整合。现在我要做的就是pyamf结合django 1.0。据说flex通过amf做PRC调用似乎节省掉很多带宽。
下载
去官网找到svn地址,checkout下来之后install,很简单。python真是一种很简洁很强大的语言,和flex很配啊。
处理机制
既然跟django结合,就应该有一套处理request,response的机制。pyamf里对应的就是 pyamf.remoting.gateway.django模块。打开能看到有一个类class DjangoGateway(gateway.BaseGateway),它就是整个处理流程的主干。class document很好的解释了它在django中的用法。仅仅需要在views.py中建立一个DjangoGateway实例,这个实例是urlmap 对应的处理函数,它把从django底层传递过来的request(其实是AMF编码过的)解码,并映射相应的python对象,然后执行注册的RPC方法(就是flex调用amf过程中看到的方法调用)返回一个response,最后用AMF机制编码这个response,返回给django。这样 django再通过层层处理返回这个AMF信息给flex。如此便是一个完整的amf PRC调用过程。很多的server基本上都是基于类似的机制,通过中间件层层过滤request和response,达到隔离底层处理的目的。最后我们能看到,django内部处理amf的调用是如此之简单。
DjangoGateway有两个方法很重要,一个是__call__(python的特殊名字方法,自己定义的方法不能用这些名字哦,__call__ 使得对象能像方法那样用,比如有对象a,执行a()相当于执行a.__call__()。也许可以猜到了,没错,在django里urlmap需要有一个对应的处理函数,__call__就是起这个处理函数的作用)。还有一个就是getResponse方法。它的作用是处理解码后的request,这是一些很普通的方法调用,因为request已经AMF解码了,它会寻找合适的PRC方法(选择的依据就是AMF指定的方法名,也就是flex调用amf url时的方法名)来处理request。我把这两个方法贴上来了。里面重点扯了一下__call__加深印象。

def getResponse(self, http_request, request):
"""
Processes the AMF request, returning an AMF response.

@param http_request: The underlying HTTP Request.
[...]



以下示例使用的Django和PyAMF版本是从SVN下载的最新版本,版本号分别是:9084和1699。
Django的安装和配置可以从前面的文章找到,PyAMF的安装也是很简单:sudo python setup.py install。
首先在urls.py中增加一行:
(r^'gateway$', 'project.application.amfgateway.gw'),
在application的目录下创建afmgateway.py:
#coding=utf-8
from pyamf.remoting.gateway.django import DjangoGateway
import project.application.views as views

services = {
'echo' = views.echo,
}

gw = DjangoGateway(services)
在views.py文件增加如下函数:
def echo(request, data):
return data
在Flex里面连接的办法很普通:
var gateway : NetConnection = new NetConnection();
gateway.connect("http://yousite/gateway");
var resonder : Responder = new Responder(onResult, onFault);
gateway.call("echo", responder, "hello");

其实一切都很简单吧,我调试的时候却费了好多时间,只是在urls.py的映射中写成了
r^'gateway/$'
发表于 2010-07-14 16:15 lostpencil 阅读(518) | 评论 (3)编辑 收藏
2010年6月29日
[转载]修改Hosts文件,基本恢复Google服务
2009年06月25日 | 作者: Betty

【 原文由 dongzai@bdwm 所发表 】

研究了一晚上google的域名,自己从位于加利福尼亚的谷歌总部DNS服务器上扒出来的。
把下面的内容添加到 C:\Windows\System32\drivers\etc\hosts文件中就行了。

#Search
64.233.189.147 www.google.com
64.233.189.104 www.google.com
64.233.189.99 www.google.com
64.233.189.147 www.l.google.com

#Mail(POP3/SMTP)
209.85.147.109 pop.gmail.com
209.85.147.109 smtp.gmail.com

#WebMail
64.233.189.18 mail.google.com
64.233.189.19 mail.google.com
64.233.189.83 mail.google.com
64.233.189.18 www.gmail.com
64.233.189.19 www.gmail.com
64.233.189.83 www.gmail.com
64.233.189.19 googlemail.l.google.com

#Docs
64.233.189.101 writely-china.l.google.com
64.233.189.101 writely.l.google.com
64.233.189.102 docs.google.com
64.233.189.101 docs.google.com
64.233.189.100 docs.google.com

#Map
64.233.189.104 map.google.com
64.233.189.99 map.google.com
64.233.189.147 map.google.com
64.233.189.104 maps.google.com
64.233.189.99 maps.google.com
64.233.189.147 maps.google.com
64.233.189.99 maps.gstatic.com
203.208.39.93 khm.google.com
203.208.39.91 mt0.google.com
203.208.39.93 mt1.google.com
203.208.39.91 mt2.google.com
203.208.39.91 mt.l.google.com
64.233.189.99 maps.l.google.com

#Scholar
64.233.189.99 scholar.google.com
64.233.189.104 scholar.google.com
64.233.189.147 scholar.google.com
64.233.189.104 scholar.l.google.com

#Group
64.233.189.102 groups.google.com
64.233.189.100 groups.google.com
64.233.189.101 groups.google.com
64.233.189.101 groups.l.google.com

#Misc
64.233.189.101 id.google.com
64.233.189.102 id.google.com
64.233.189.100 id.google.com
64.233.189.100 id.l.google.com

【Betty附言:】

前几天有事暂离,回来发现去年写的支持Google还击百度这篇文章访问量大增。上网一看,原来Google又犯事了,说是能搜索到色情结果。心说这指责也太无稽了,正想着要不要写一篇文章讨论一下。结果,昨天晚上,Google的产品,包括搜索、邮箱、阅读器、文档等等,全部不能访问了。看来政府这次是下了狠心了,即使谷歌认错态度较好,甚至表示愿意购买“绿坝”服务以改进搜索质量,政府也不肯放过它。

今天上午,我这里(北京网通)已经可以访问Google的服务,不过似乎还是有不少人访问不了。故转载此文与大家分享。用修改Hosts文件的方法,访问速度非常快,比翻墙好多啦。

另,推荐用https访问,不要用http。
发表于 2010-06-29 15:59 lostpencil 阅读(761) | 评论 (3)编辑 收藏
2010年6月10日
web.py 是一个Python 的web 框架,它简单而且功能强大。web.py 是公开的,无论用于什么用途都是没有限制的。

先让大家感受一下web.py 的简单而强大:

import web

urls = (
'/(.*)', 'hello'
)

class hello:
def GET(self, name):
i = web.input(times=1)
if not name: name = 'world'
for c in xrange(int(i.times)): print 'Hello,', name+'!'

if __name__ == "__main__": web.run(urls, globals())

看看,上面就是一个基于web.py 的完整的Web 应用。不信?!将上面的代码保存为文件code.py,在命令行下执行python code.py。然后打开你的浏览器,打开地址:http://localhost:8080/RossWan,看看结 果 :)没有意外的话(当然要先安装web.py,下面会有介绍),浏览器会显示“Hello, RossWan!”。这是一个最简单的Hello world Web 应用。是不是很简单?!下面将较为详细地介绍下web.py 。Find fun :)

1. 安装

单击这里下载web.py 的安装文件,将下载得到的文件web.py-0.21.tar.gz 解压,进入解压后的文件夹,在命令行下执行:python setup.py install,在Linux 等系统下,需要root 的权限,可以执行:sudo python setup.py install。

安装完毕之后,就可以正式开始web.py 之旅…

2. URL 处理

对于一个站点来说,URL 的组织是最重要的一个部分,因为这是用户看得到的部分,而且直接影响到站点是如何工作的,在著名的站点如:del.icio.us ,其URLs 甚至是网页界面的一部分。而web.py 以简单的方式就能够构造出一个强大的URLs。

在每个web.py 应用,必须先import web 模块:

import web

现在,我们须要告诉web.py URL 如何组织,让我们以一个简单例子开始:

urls = (
'/', 'index' )

在上面的例子中,第一部分(‘/’)是一个匹配URL 的正则表达式,像/,/help/faq,/item/(\d+),等等;第二部分(‘index’)是一个类名,匹配的请求将会被发送过去。

现在,我们需要编写index 类。当大部人浏览网页的时候,他们都没有注意到,浏览器是通过HTTP 跟World Wide Web 通信的。通信的细节不太重要,但要明白一点,用户是通过URLs(例如 / 或者 /foo?f=1)来请求web 服务器完成一定请求的(例如 GET 或者POST)。

GET 是最普遍的方法,用来请求一个页面。当我们在浏览器里输入“harvard.edu” 的时候,实际上它是向Web 服务器请求GET ”/“。另一个常见的方法是POST,常用于提交特定类型的表单,例如利用信用卡付费和处理一个订单。注意,GET URLs 能够被搜索引擎索引得到(想像一下Google 尝试购买你网站上的所用物品)。

在我们的web.py 代码中。我们清晰区分这两种方法:

class index:
def GET(self):
print "Hello, world!"

当接收到一个GET 请求时,上面的GET 方法将会被web.py 调用。

好的。现在,我们只需添加最后一行代码,让web.py 启动网页应用:

if __name__ == "__main__": web.run(urls, globals())

上面告诉web.py 如何配置URLs,以及找寻的类在文件中的全局命名空间。

整个code.py 文件的内容如下:

import web

urls = (
'/', 'index' )

class index:
def GET(self):
print "Hello, world!"

if __name__ == "__main__": web.run(urls, globals())

注意到没有,虽然我说了很多东西,但实际上web 应用的代码就只得上面的几行,而且这是一个完整的web.py 应用。在你的命令行下输入:

$ python code.py
Launching server: http://0.0.0.0:8080/

现在,你的web.py 应用已经启动了服务器。通过浏览器访问http://localhost:8080/ 的话,会见到”Hello, world!“。在启动服务器的时候,你可以在python code.py 后面添加IP 地址/端口 来控制web.py 启动的服务器。例如:python code.py 8888。

3. 调试

web.py 本身也提供调试的工具。在最后的“if name …” 代码前面添加:

web.webapi.internalerror = web.debugerror

并在最后的“if name …” 添加”web.reloader“:

if __name__ == "__main__": web.run(urls, globals(), web.reloader)

上面的代码会使你在调试的阶段得到更多有用的信息。web.reloader 其实是一个中间件,当你在运行时修改了code.py 文件后,web.reloader 会重新加载code.py 文件,让你在浏览器上立刻可以看到变化。如何有多何变化的话,还是需要重新启动服务器。web.py 也提供web.profiler ,可以输出有用的信息,有关每个页面的每个函数调用的次数,这用助于你改善代码。

4. 模板

在Python 里面编写HTML 代码是相当累赘的,而在HTML 里嵌入Python 代码则有趣得多。幸运地,web.py 使这过程变得相当容易。

注意:旧版本的web.py 是用Cheetah templates 模板的,你可以继续使用,但官方已不再提供支持。

在我们的web 应用里,添加一个新的文件夹用来组织模板文件(例如”/templates“)。然后再新建一个HTML 文件(例如:”index.html“):

Hello, world!

或者,你可以用web.py 的模板语言用编写这个HTML 文件:

$def with (name)

$if name:
I just wanted to say hello to $name.
$else:
Hello, world!

注意上面代码的缩进!

正如你所见的,上面的模板看上去跟这Python 文件很相似,以def with 语句开始,但在关键字前需要添加”$“。

注意:在模板内的变量,如果包含有HTML 标记,以$ 方式引用变量的话,HTML 标记只会以纯文本的显示出来。要想HTML 标记产生效果,可以用$: 引用变量。

现在,回到code.py 文件,在”import web” 的下一行添加:

render = web.template.render('templates/')

这告诉web.py 在哪里可以搜索得到模板目录。

提示:可在render 调用里添加cache = False 使得每次访问页面时都重载模板。

下面继续修改code.py 文件的GET 方法:

def GET(self):
name = 'Bob'
print render.index(name)

上面的”index“ 是模板的名字,”name“ 是传递过去的参数。

修改code.py 文件的urls 变量:

urls=(
'/(.*)', 'index')

上面的“/(.*)” 是一个正则表达式。

再将GET 方法修改如下:

def GET(self,name):
print render.index(name)

现在,访问”/“的话,会显示”Hello, world!“;访问”/Joe“ 的话,会显示”I just want to say hello to Joe“。

如果你想学习更多关于web.py templates 的话,可以访问templetor page。

5. 数据库

注意:在你开始连接数据库之前,请先安装正确的数据库驱动。例 如,MySQL 使用MySALdb,Postgre 使用psycopg2。

添加以下代码,则可以正确配置你的数据库:

web.config.db_parameters = dict(
dbn='postgres',
user='username',
pw='password',
db='dbname'
)

现在,先行在数据库里创建一个简单的表:

CREATE TABLE todo (
id serial primary key,
title text,
created timestamp default now(),
done boolean default 'f'
);

初始化一行:

INSERT INTO todo (title) VALUES ('Learn web.py');

回到code.py,修改GET 方法如下:

def GET(self):
todos = web.select('todo')
print render.index(todos)

修改urls 变量:

urls = (
'/', 'index')

重新编辑index.html 文件如下:

$def with (todos)

    $for todo in todos:
  • $todo.title



现在,可以访问”/“,如果显示”Learn web.py“,则祝贺你成功了!

现在,再让我们看看如何向数据库写入。

在index.html 文件的尾部添加如下内容:








修改code.py 文件的urls 变量如下:

urls = (
'/', 'index',
'/add', 'add'
)

在code.py 里添加一个类:

class add:
def POST(self):
i = web.input()
n = web.insert('todo', title=i.title)
web.seeother('/')

web.input 使你能够方便地访问用户通过表单提交上来的变量。web.insert 用于向数据库的 “todo” 表插入数据,并且返回新插入行的ID。web.seeother 用于重转向到”/“。

提示:对于数据库的操作,还有web.transact(), web.commit(), web.rollback(),web.update()。

在web.py 里,还有web.input,web.query 和其它的函数,返回”Storage objects”,可以像字典型类(dictionaries) 的使用。

6. 总结

web.py 的确相当的小巧,应当归属于轻量级的web 框架。但这并不影响web.py 的强大,而且使用起来很简单、很直接。在实际应用上,web.py 更多的是学术上的价值,因为你可以看到更多web 应用的底层,这在当今“抽象得很好”的web 框架上是学不到的 :) 如果想了解更多web.py,可以访问web.py 的官方文档。

这篇教程到这里也要结束了,如果你对web.py 有兴趣,可以搜索更多关于web.py 的文档看看,你一定会发现更酷的东西。Have fun!
发表于 2010-06-10 10:45 lostpencil 阅读(556) | 评论 (0)编辑 收藏
2010年1月6日
 这里主要讲述libxml2在linux下的使用。
(以下内容除了linux下的安装步骤是自己写的,其余均出自
http://www.blogjava.net/wxb_nudt/archive/2007/11/28/161340.html
,由于该篇文章讲解的非常周详,我也没必要重写一遍了。如果该篇文章早出些时候,早期研发我也不会走非常多弯路了。虽然在该篇文章出现之前我已对libxml2较熟悉了并研发完毕,但为了备忘,目前将该篇文章作为收藏之用。在此再次感谢这篇文章的大侠为大家整理了这篇文章^_^)
1.       下载和安装LIBXML2
Libxml2是个C语言的XML程式库,能简单方便的提供对XML文件的各种操作,并且支持XPATH查询,及部分的支持XSLT转换等功能。Libxml2的下载地址是
http://xmlsoft.org/
,完全版的库是开源的,并且带有例子程式和说明文件。最佳将这个库先下载下来,因为这样能查看其中的文件和例子。
由于我是在linux下用C语言进行研发的,所以我下载的是libxml2-2.6.20.tar.gz版本的源码包。
具体安装步骤:
1、解压:$tar zxvf libxml2-2.6.20.tar.gz
2、进入解压后的安装目录:$cd libxml2-2.6.20
3、安装三部曲:1)$./configure
              2)$make
              3)$make install
安装完毕。
2.       Libxml2中的数据类型和函数
一个函数库中可能有几百种数据类型及几千个函数,不过记住大师的话,90%的功能都是由30%的内容提供的。对于libxml2,我认为搞懂以下的数据类型和函数就足够了。
2.1   内部字符类型xmlChar
xmlChar是Libxml2中的字符类型,库中所有字符、字符串都是基于这个数据类型。事实上他的定义是:xmlstring.h
typedef unsigned char xmlChar;
使用unsigned char作为内部字符格式是考虑到他能非常好适应UTF-8编码,而UTF-8编码正是libxml2的内部编码,其他格式的编码要转换为这个编码才能在libxml2中使用。
还经常能看到使用xmlChar*作为字符串类型,非常多函数会返回一个动态分配内存的xmlChar*变量,使用这样的函数时记得要手动删除内存。
2.2   xmlChar相关函数
如同标准c中的char类型相同,xmlChar也有动态内存分配、字符串操作等相关函数。例如xmlMalloc是动态分配内存的函数;xmlFree是配套的释放内存函数;xmlStrcmp是字符串比较函数等等。
基本上xmlChar字符串相关函数都在xmlstring.h中定义;而动态内存分配函数在xmlmemory.h中定义。
2.3   xmlChar*和其他类型之间的转换
另外要注意,因为总是要在xmlChar*和char*之间进行类型转换,所以定义了一个宏BAD_CAST,其定义如下:xmlstring.h
#define BAD_CAST (xmlChar *)
原则上来说,unsigned char和char之间进行强制类型转换是没有问题的。
2.4   文件类型xmlDoc、指针xmlDocPtr
xmlDoc是个struct,保存了一个xml的相关信息,例如文件名、文件类型、子节点等等;xmlDocPtr等于xmlDoc*,他搞成这个样子总让人以为是智能指针,其实不是,要手动删除的。
xmlNewDoc函数创建一个新的文件指针。
xmlParseFile函数以默认方式读入一个UTF-8格式的文件,并返回文件指针。
xmlReadFile函数读入一个带有某种编码的xml文件,并返回文件指针;细节见libxml2参考手册。
xmlFreeDoc释放文件指针。特别注意,当你调用xmlFreeDoc时,该文件所有包含的节点内存都被释放,所以一般来说不必手动调用xmlFreeNode或xmlFreeNodeList来释放动态分配的节点内存,除非你把该节点从文件中移除了。一般来说,一个文件中所有节点都应该动态分配,然后加入文件,最后调用xmlFreeDoc一次释放所有节点申请的动态内存,这也是为什么我们非常少看见xmlNodeFree的原因。
xmlSaveFile将文件以默认方式存入一个文件。
xmlSaveFormatFileEnc可将文件以某种编码/格式存入一个文件中。
2.5   节点类型xmlNode、指针xmlNodePtr
节点应该是xml中最重要的元素了,xmlNode代表了xml文件中的一个节点,实现为一个struct,内容非常丰富:tree.h
typedef struct _xmlNode xmlNode;
typedef xmlNode *xmlNodePtr;
struct _xmlNode {
    void           *_private;/* application data */
    xmlElementType   type;   /* type number, must be second ! */
    const xmlChar   *name;      /* the name of the node, or the entity */
    struct _xmlNode *children; /* parent->childs link */
    struct _xmlNode *last;   /* last child link */
    struct _xmlNode *parent;/* child->parent link */
    struct _xmlNode *next;   /* next sibling link */
    struct _xmlNode *prev;   /* previous sibling link */
    struct _xmlDoc *doc;/* the containing document */
    /* End of common part */
    xmlNs           *ns;        /* pointer to the associated namespace */
    xmlChar         *content;   /* the content */
    struct _xmlAttr *properties;/* properties list */
    xmlNs           *nsDef;     /* namespace definitions on this node */
    void            *psvi;/* for type/PSVI informations */
    unsigned short   line;   /* line number */
    unsigned short   extra; /* extra data for XPath/XSLT */
};
能看到,节点之间是以链表和树两种方式同时组织起来的,next和prev指针能组成链表,而parent和children能组织为树。同时更有以下重要元素:
l         节点中的文字内容:content;
l         节点所属文件:doc;
l         节点名字:name;
l         节点的namespace:ns;
l         节点属性列表:properties;
Xml文件的操作其根本原理就是在节点之间移动、查询节点的各项信息,并进行增加、删除、修改的操作。
xmlDocSetRootElement函数能将一个节点设置为某个文件的根节点,这是将文件和节点连接起来的重要手段,当有了根结点以后,所有子节点就能依次连接上根节点,从而组织成为一个xml树。
2.6   节点集合类型xmlNodeSet、指针xmlNodeSetPtr
节点集合代表一个由节点组成的变量,节点集合只作为Xpath的查询结果而出现(XPATH的介绍见后面),因此被定义在xpath.h中,其定义如下:
/*
* A node-set (an unordered collection of nodes without duplicates).
*/
typedef struct _xmlNodeSet xmlNodeSet;
typedef xmlNodeSet *xmlNodeSetPtr;
struct _xmlNodeSet {
    int nodeNr;          /* number of nodes in the set */
    int nodeMax;      /* size of the array as allocated */
    xmlNodePtr *nodeTab;/* array of nodes in no particular order */
    /* @@ with_ns to check wether namespace nodes should be looked at @@ */
};
能看出,节点集合有三个成员,分别是节点集合的节点数、最大可容纳的节点数,及节点数组头指针。对节点集合中各个节点的访问方式非常简单,如下:
xmlNodeSetPtr nodeset = XPATH查询结果;
for (int i = 0; i nodeNr; i++)
{
nodeset->nodeTab;
}
注意,libxml2是个c函数库,因此其函数和数据类型都使用c语言的方式来处理。如果是c++,我想我宁愿用STL中的vector来表示一个节点集合更好,而且没有内存泄漏或溢出的担忧。
3.       简单xml操作例子
了解以上基本知识之后,就能进行一些简单的xml操作了。当然,还没有涉及到内码转换(使得xml中能处理中文)、xpath等较复杂的操作。
3.1   创建xml文件
有了上面的基础,创建一个xml文件显得非常简单,其流程如下:
l         用xmlNewDoc函数创建一个文件指针doc;
l         用xmlNewNode函数创建一个节点指针root_node;
l         用xmlDocSetRootElement将root_node设置为doc的根结点;
l         给root_node添加一系列的子节点,并设置子节点的内容和属性;
l         用xmlSaveFile将xml文件存入文件;
l         用xmlFreeDoc函数关闭文件指针,并清除本文件中所有节点动态申请的内存。
注意,有多种方式能添加子节点:第一是用xmlNewTextChild直接添加一个文本子节点;第二是先创建新节点,然后用xmlAddChild将新节点加入上层节点。
原始码文件是CreateXmlFile.cpp,如下:
/********************************************************************
    created:   2007/11/09
    created:   9:11:2007   15:34
    filename: CreateXmlFile.cpp
    author:       Wang xuebin
    depend:       libxml2.lib
    build:     nmake TARGET_NAME=CreateXmlFile
    purpose:   创建一个xml文件
*********************************************************************/
#include
#include
#include
#include
int main()
{
    //定义文件和节点指针
    xmlDocPtr doc = xmlNewDoc(BAD_CAST"1.0");
    xmlNodePtr root_node = xmlNewNode(NULL,BAD_CAST"root");
    //设置根节点
    xmlDocSetRootElement(doc,root_node);
    //在根节点中直接创建节点
    xmlNewTextChild(root_node, NULL, BAD_CAST "newNode1", BAD_CAST "newNode1 content");
    xmlNewTextChild(root_node, NULL, BAD_CAST "newNode2", BAD_CAST "newNode2 content");
    xmlNewTextChild(root_node, NULL, BAD_CAST "newNode3", BAD_CAST "newNode3 content");
    //创建一个节点,设置其内容和属性,然后加入根结点
    xmlNodePtr node = xmlNewNode(NULL,BAD_CAST"node2");
    xmlNodePtr content = xmlNewText(BAD_CAST"NODE CONTENT");
    xmlAddChild(root_node,node);
    xmlAddChild(node,content);
    xmlNewProp(node,BAD_CAST"attribute",BAD_CAST "yes");
    //创建一个儿子和孙子节点
    node = xmlNewNode(NULL, BAD_CAST "son");
    xmlAddChild(root_node,node);
    xmlNodePtr grandson = xmlNewNode(NULL, BAD_CAST "grandson");
    xmlAddChild(node,grandson);
    xmlAddChild(grandson, xmlNewText(BAD_CAST "This is a grandson node"));
    //存储xml文件
    int nRel = xmlSaveFile("CreatedXml.xml",doc);
    if (nRel != -1)
    {
       cout一个xml文件被创建,写入"个字节"    }
    //释放文件内节点动态申请的内存
    xmlFreeDoc(doc);
    return 1;
}
编译链接命令如下:
nmake TARGET_NAME=CreateXmlFile
然后执行可执行文件CreateXmlFile.exe,会生成一个xml文件CreatedXml.xml,打开后如下所示:
root>
    newNode1>newNode1 contentnewNode1>
    newNode2>newNode2 contentnewNode2>
    newNode3>newNode3 contentnewNode3>
    node2 attribute="yes">NODE CONTENTnode2>
    son>
       grandson>This is a grandson nodegrandson>
    son>
root>
最佳使用类似XMLSPY这样的工具打开,因为这些工具能自动整理xml文件的栅格,否则非常有可能是没有所有换行的一个xml文件,可读性较差。
3.2   解析xml文件
解析一个xml文件,从中取出想要的信息,例如节点中包含的文字,或某个节点的属性,其流程如下:
l         用xmlReadFile函数读出一个文件指针doc;
l         用xmlDocGetRootElement函数得到根节点curNode;
l         curNode->xmlChildrenNode就是根节点的子节点集合;
l         轮询子节点集合,找到所需的节点,用xmlNodeGetContent取出其内容;
l         用xmlHasProp查找含有某个属性的节点;
l         取出该节点的属性集合,用xmlGetProp取出其属性值;
l         用xmlFreeDoc函数关闭文件指针,并清除本文件中所有节点动态申请的内存。
注意:节点列表的指针依然是xmlNodePtr,属性列表的指针也是xmlAttrPtr,并没有xmlNodeList或xmlAttrList这样的类型。看作列表的时候使用他们的next和prev链表指针来进行轮询。只有在Xpath中有xmlNodeSet这种类型,其使用方法前面已介绍了。
原始码如下:ParseXmlFile.cpp
/********************************************************************
    created:   2007/11/15
    created:   15:11:2007   11:47
    filename: ParseXmlFile.cpp
    author:       Wang xuebin
    depend:       libxml2.lib
    build:     nmake TARGET_NAME=ParseXmlFile
    purpose:   解析xml文件
*********************************************************************/
#include
#include
int main(int argc, char* argv[])
{
    xmlDocPtr doc;           //定义解析文件指针
    xmlNodePtr curNode;      //定义结点指针(你需要他为了在各个结点间移动)
    xmlChar *szKey;          //临时字符串变量
    char *szDocName;
    if (argc     {
       printf("Usage: %s docname"n", argv[0]);
       return(0);
    }
    szDocName = argv[1];
    doc = xmlReadFile(szDocName,"GB2312",XML_PARSE_RECOVER); //解析文件
    //检查解析文件是否成功,如果不成功,libxml将指一个注册的错误并停止。
    //一个常见错误是不适当的编码。XML标准文件除了用UTF-8或UTF-16外还可用其他编码保存。
    //如果文件是这样,libxml将自动地为你转换到UTF-8。更多关于XML编码信息包含在XML标准中.
    if (NULL == doc)
    {  
       fprintf(stderr,"Document not parsed successfully. "n");     
       return -1;
    }
    curNode = xmlDocGetRootElement(doc); //确定文件根元素
    /*检查确认当前文件中包含内容*/
    if (NULL == curNode)
    {
       fprintf(stderr,"empty document"n");
       xmlFreeDoc(doc);
       return -1;
    }
    /*在这个例子中,我们需要确认文件是正确的类型。“root”是在这个示例中使用文件的根类型。*/
    if (xmlStrcmp(curNode->name, BAD_CAST "root"))
    {
       fprintf(stderr,"document of the wrong type, root node != root");
       xmlFreeDoc(doc);
       return -1;
    }
    curNode = curNode->xmlChildrenNode;
    xmlNodePtr propNodePtr = curNode;
    while(curNode != NULL)
    {
       //取出节点中的内容
       if ((!xmlStrcmp(curNode->name, (const xmlChar *)"newNode1")))
       {
           szKey = xmlNodeGetContent(curNode);
           printf("newNode1: %s"n", szKey);
           xmlFree(szKey);
       }
       //查找带有属性attribute的节点
       if (xmlHasProp(curNode,BAD_CAST "attribute"))
       {
           propNodePtr = curNode;
       }
       curNode = curNode->next;
    }
    //查找属性
    xmlAttrPtr attrPtr = propNodePtr->properties;
    while (attrPtr != NULL)
    {
       if (!xmlStrcmp(attrPtr->name, BAD_CAST "attribute"))
       {
           xmlChar* szAttr = xmlGetProp(propNodePtr,BAD_CAST "attribute");
           cout           xmlFree(szAttr);
       }
       attrPtr = attrPtr->next;
    }
    xmlFreeDoc(doc);
    return 0;
}
编译链接命令如下:
nmake TARGET_NAME=ParseXmlFile
执行命令如下,使用第一次创建的xml文件作为输入:
ParseXmlFile.exe CreatedXml.xml
观察原始码可发现,所有以查询方式得到的xmlChar*字符串都必须使用xmlFree函数手动释放。否则会造成内存泄漏。
3.3   修改xml文件
有了上面的基础,修改xml文件的内容就非常简单了。首先打开一个已存在的xml文件,顺着根结点找到需要添加、删除、修改的地方,调用相应的xml函数对节点进行增、删、改操作。原始码见ChangeXmlFile,编译链接方法如上。执行下面的命令:
ChangeXmlFile.exe CreatedXml.xml
能得到一个修改后的xml文件ChangedXml.xml,如下:
root>
    newNode2>content changednewNode2>
    newNode3 newAttr="YES">newNode3 contentnewNode3>
    node2 attribute="no">NODE CONTENTnode2>
    son>
       grandson>This is a grandson nodegrandson>
       newGrandSon>new contentnewGrandSon>
    son>
root>
需要注意的是,并没有xmlDelNode或xmlRemoveNode函数,我们删除节点使用的是以下一段代码:
       if (!xmlStrcmp(curNode->name, BAD_CAST "newNode1"))
       {
           xmlNodePtr tempNode;
           tempNode = curNode->next;
           xmlUnlinkNode(curNode);
           xmlFreeNode(curNode);
           curNode = tempNode;
           continue;
       }
即将当前节点从文件中断链(unlink),这样本文件就不会再包含这个子节点。这样做需要使用一个临时变量来存储断链节点的后续节点,并记得要手动删除断链节点的内存。
3.4   使用XPATH查找xml文件
简而言之,XPATH之于xml,好比SQL之于关系数据库。要在一个复杂的xml文件中查找所需的信息,XPATH简直是必不可少的工具。XPATH语法简单易学,并且有一个非常好的官方教程,见
http://www.zvon.org/xxl/XPathTutorial/Output_chi/introduction.html
。这个站点的XML各种教程齐全,并且有包括中文在内的各国语言版本,真是让我喜欢到非常!
使用XPATH之前,必须首先熟悉几个数据类型和函数,他们是使用XPATH的前提。在libxml2中使用Xpath是非常简单的,其流程如下:
l         定义一个XPATH上下文指针xmlXPathContextPtr context,并且使用xmlXPathNewContext函数来初始化这个指针;
l         定义一个XPATH对象指针xmlXPathObjectPtr result,并且使用xmlXPathEvalExpression函数来计算Xpath表达式,得到查询结果,将结果存入对象指针中;
l         使用result->nodesetval得到节点集合指针,其中包含了所有符合Xpath查询结果的节点;
l         使用xmlXPathFreeContext释放上下文指针;
l         使用xmlXPathFreeObject释放Xpath对象指针;
具体的使用方法能看XpathForXmlFile.cpp的这一段代码,其功能是查找符合某个Xpath语句的对象指针:
xmlXPathObjectPtr getNodeSet(xmlDocPtr doc, const xmlChar *szXpath)
{
    xmlXPathContextPtr context;    //XPATH上下文指针
    xmlXPathObjectPtr result;       //XPATH对象指针,用来存储查询结果
    context = xmlXPathNewContext(doc);     //创建一个XPath上下文指针
    if (context == NULL)
    {   
       printf("context is NULL"n");
       return NULL;
    }
    result = xmlXPathEvalExpression(szXpath, context); //查询XPath表达式,得到一个查询结果
    xmlXPathFreeContext(context);             //释放上下文指针
    if (result == NULL)
    {
       printf("xmlXPathEvalExpression return NULL"n");
       return NULL;
    }
    if (xmlXPathNodeSetIsEmpty(result->nodesetval))   //检查查询结果是否为空
    {
       xmlXPathFreeObject(result);
       printf("nodeset is empty"n");
       return NULL;
    }
    return result;   
}
一个完整的使用Xpath的例子在代码XpathForXmlFile.cpp中,他查找一个xml文件中符合"/root/node2[@attribute=’yes’]"语句的结果,并且将找到的节点的属性和内容打印出来。编译链接命令如下:
nmake TARGET_NAME=XpathForXmlFile
执行方式如下:
XpathForXmlFile.exe CreatedXml.xml
观察结果能看出找到了一个节点,即root下面node2节点,他的attribute属性值正好等于yes。更多关于Xpath的内容能参考XPATH官方手册。只有掌控了XPATH,才掌控了使用大型XML文件的方法,否则每寻找一个节点都要从根节点找起,会把人累死。
4.       用ICONV解决XML中的中文问题
Libxml2中默认的内码是UTF-8,所有使用libxml2进行处理的xml文件,必须首先显式或默认的转换为UTF-8编码才能被处理。
要在xml中使用中文,就必须能够在UTF-8和GB2312内码(较常用的一种简体中文编码)之间进行转换。Libxml2提供了默认的内码转换机制,并且在libxml2的Tutorial中有一个例子,事实证实这个例子并不适合用来转换中文。
所以需要我们显式的使用ICONV来进行内码转换,libxml2本身也是使用ICONV进行转换的。ICONV是个专门用来进行编码转换的库,基本上支持目前所有常用的编码。他是glibc库的一个部分,常常被用于UNIX系统中。当然,在windows下面使用也没有所有问题。前面已提到了ICONV的安装和使用方法,这里主要讲一下编程相关问题。
本节其实和xml及libxml2没有太大关系,你能把他简单看作是个编码转换方面的专题。我们仅仅需要学会使用两个函数就能了,即从UTF-8转换到GB2312的函数u2g,及反向转换的函数g2u,原始码在wxb_codeConv.c中:
/********************************************************************
    created:   2007/11/15
    created:   15:11:2007   10:30
    filename: wxb_codeConv.c
    author:       Wang xuebin
    depend:       iconv.lib
    build:     不必build,被包含到其他原始码中
    purpose:   提供从UTF-8到GB2312的内码转换,及反向的转换
*********************************************************************/
#include "iconv.h"
#include
//代码转换:从一种编码转为另一种编码   
int code_convert(char* from_charset, char* to_charset, char* inbuf,
               int inlen, char* outbuf, int outlen)
{
    iconv_t cd;
    char** pin = &inbuf;   
    char** pout = &outbuf;
    cd = iconv_open(to_charset,from_charset);   
    if(cd == 0)
       return -1;
    memset(outbuf,0,outlen);   
    if(iconv(cd,(const char**)pin,(unsigned int *)&inlen,pout,(unsigned int*)&outlen)
       == -1)
       return -1;   
    iconv_close(cd);
    return 0;   
}
//UNICODE码转为GB2312码   
//成功则返回一个动态分配的char*变量,需要在使用完毕后手动free,失败返回NULL
char* u2g(char *inbuf)   
{
    int nOutLen = 2 * strlen(inbuf) - 1;
    char* szOut = (char*)malloc(nOutLen);
    if (-1 == code_convert("utf-8","gb2312",inbuf,strlen(inbuf),szOut,nOutLen))
    {
       free(szOut);
       szOut = NULL;
    }
    return szOut;
}   
//GB2312码转为UNICODE码   
//成功则返回一个动态分配的char*变量,需要在使用完毕后手动free,失败返回NULL
char* g2u(char *inbuf)   
{
    int nOutLen = 2 * strlen(inbuf) - 1;
    char* szOut = (char*)malloc(nOutLen);
    if (-1 == code_convert("gb2312","utf-8",inbuf,strlen(inbuf),szOut,nOutLen))
    {
       free(szOut);
       szOut = NULL;
    }
    return szOut;
}   
使用的时候将这个c文件include到其他源文件中。include一个c文件并不奇怪,在c语言的年代我们常常这么干,唯一的害处的编译链接出来的可执行程式体积变大了。当然这时因为我们这段代码非常小的原因,再大一点我就要用dll了。
从UTF-8到GB2312的一个典型使用流程如下:
l         得到一个UTF-8的字符串szSrc;
l         定义一个char*的字符指针szDes,并不必给他动态审判内存;
l         szDes = u2g(szSrc),这样就能得到转换后的GB2312编码的字符串;
l         使用完这个字符串后使用free(szDes)来释放内存。
本文并不准备讲述iconv中的函数细节,因为那几个函数及数据类型都非常简单,我们还是重点看一下怎么在libxml2中使用编码转换来处理带有中文的xml文件。下面是使用以上方法来创建一个带有中文的XML文件的例子程式CreateXmlFile_cn.cpp,原始码如下:
/********************************************************************
    created:   2007/11/17
    created:   9:11:2007   15:34
    filename: CreateXmlFile.cpp
    author:       Wang xuebin
    depend:       libxml2.lib iconv.lib
    build:     nmake TARGET_NAME=CreateXmlFile_cn
    purpose:   创建一个xml文件,其中包含中文
*********************************************************************/
#include
#include
#include
#include
#include "wxb_codeConv.c" //自己写的编码转换函数
int main(int argc, char **argv)
{
    //定义文件和节点指针
    xmlDocPtr doc = xmlNewDoc(BAD_CAST"1.0");
    xmlNodePtr root_node = xmlNewNode(NULL,BAD_CAST"root");
    //设置根节点
    xmlDocSetRootElement(doc,root_node);
    //一个中文字符串转换为UTF-8字符串,然后写入
    char* szOut = g2u("节点1的内容");
    //在根节点中直接创建节点
    xmlNewTextChild(root_node, NULL, BAD_CAST "newNode1", BAD_CAST "newNode1 content");
    xmlNewTextChild(root_node, NULL, BAD_CAST "newNode2", BAD_CAST "newNode2 content");
    xmlNewTextChild(root_node, NULL, BAD_CAST "newNode3", BAD_CAST "newNode3 content");
    xmlNewChild(root_node, NULL, BAD_CAST "node1",BAD_CAST szOut);
    free(szOut);
    //创建一个节点,设置其内容和属性,然后加入根结点
    xmlNodePtr node = xmlNewNode(NULL,BAD_CAST"node2");
    xmlNodePtr content = xmlNewText(BAD_CAST"NODE CONTENT");
    xmlAddChild(root_node,node);
    xmlAddChild(node,content);
    szOut = g2u("属性值");
    xmlNewProp(node,BAD_CAST"attribute",BAD_CAST szOut);
    free(szOut);
    //创建一个中文节点
    szOut = g2u("中文节点");
    xmlNewChild(root_node, NULL, BAD_CAST szOut,BAD_CAST "content of chinese node");
    free(szOut);
    //存储xml文件
    int nRel = xmlSaveFormatFileEnc("CreatedXml_cn.xml",doc,"GB2312",1);
    if (nRel != -1)
    {
       cout一个xml文件被创建,写入"个字节"    }
    xmlFreeDoc(doc);
    return 1;
}
编译链接命令如下:
nmake TARGET_NAME=CreateXmlFile_cn
完成后执行CreateXmlFile_cn.exe能生成一个xml文件CreatedXml_cn.xml,其内容如下:
root>
    newNode1>newNode1 contentnewNode1>
    newNode2>newNode2 contentnewNode2>
    newNode3>newNode3 contentnewNode3>
    node1>节点1的内容node1>
    node2 attribute="属性值">NODE CONTENTnode2>
    中文节点>content of chinese node中文节点>
root>
观察可知,节点的名称、内容、属性都能使用中文了。在解析、修改和查找XML文件时都能使用上面的方法,只要记住,进入xml文件之前将中文编码转换为UTF-8编码;从XML中取出数据时,不管三七二十一都能转换为GB2312再用,否则你非常有可能见到传说中的乱码!
5.       用XML来做点什么
有了以上的基础,相信已能顺利的在c/c++程式中使用XML文件了。那么,我们到底要用XML来做什么呢?我随便说一说自己的想法:
第一,能用来作为设置文件。例如非常多组件就是用XML来做设置文件;当然,我们知道用INI做设置文件更简单,只要熟悉两个函数就能了;不过,复杂一点的设置文件我还是建议采用XML;
第二,能用来作为在程式之间传送数据的格式,这样的话最佳给你的xml先定义一个XML Schema,这样的数据首先能做一个良构校验,还能来一个Schema校验,如此的话出错率会比没有格式的数据小得多。目前XML已广泛作为网络之间的数据格式了;
第三,能用来作为你自定义的数据存储格式,例如对象持久化之类的功能;
最后,能用来显示你的技术非常高深,本来你要存储一个1,结果你这样存储了:
root>
    My_Program_Code content="1">My_Program_Code>
root>



本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/56834/showart_441723.html
发表于 2010-01-06 15:57 lostpencil 阅读(1411) | 评论 (4)编辑 收藏
2009年6月17日

目的:
        即为img2py的用处,img2py是将图像转为以py文件存储的程序,简化了程序过程中读文件的处理。

开发环境:eclipse+pydev插件

步骤:
1,在 eclipse工程中增加个含有main函数的模块,用来处理图片到py,代码如下:
'''
Created on 2009-6-16
@author: fengxuanshuo

This is a way to save the startup time when running img2py on lots of
files...

'''
import sys
from wx.tools import img2py

command_lines = [
                 "-a -F -n book   pictures/right_menu/222.png   ../main/images.py",
                 "-a -F -n boo   pictures/right_menu/111.png   ../main/images.py",
                 "-a -F -n ook_red   pictures/right_menu/000.png   ../main/images.py",
                 ]

if __name__ == '__main__':
    for line in command_lines:
        args = line.split()
        img2py.main(args)

其中command_lines为命令行执行内容,程序需要的图片都可以处理,而且目标文件可以有多个,名字自己取。

2,执行新增加的模块,就会发现 main目录多了个images.py文件。

3,更新eclipse pydev工程:pydev插件并没有常用的那个add file to project选项,不过有pydev->source format python files.

4,然后再原工程里面就可以用图片py文件了(可能有些版本,在生成py文件的时候不会加import相关库的语句,需要手动添加)

5,images.py 在wxpython demo 中的用法
定义全局变量 images: images =None
在app里面声明全局的images : globel images
import imgaes as i
images = i

其他py文件类似,这么做的好处在demo的注释里面说了,不罗嗦了,over

后记:wxpython demo的构架不错的,值得纯python大型项目学习
http://www.vspecial.org/thread-554-1-1.html


发表于 2009-06-17 00:43 lostpencil 阅读(2250) | 评论 (14)编辑 收藏
2008年11月29日

什么是 Python 语言

Python 语言是一种计算机编程语言,作用类似于 c/c++/java/perl/VB/Delphi 等等计算机编程语言,据有非常清晰易读的语法特点,并且是一种高级面向对象的语言,用途非常广泛,并且可以进行扩展。Python 可以运行在 Windows,Linux,FreeBSD,Solaris等等几乎所有的电脑中,也可以运行在手机中,支持 Java 和 .Net 技术。 Python(派森)语言是一种面向对象的用途非常广泛的编程语言,具有非常清晰的语法特点,适用于多种操作系统,可以在Windows和Unix这样的系统中运行。目前在国际上非常流行,正在得到越来越多的应用。Python可以完成许多任务,功能非常强大。Python核心网站是: http://www.python.org/ ,其中你可以找到很多资料。如果您第一次使用 Python, 可以下载一个试试。

Python 语言使用方便,不需要进行复杂的编译,用途非常广泛,可以进行各种软件的开发,比如: 网站,图形界面(GUI), 网络编程,数据库编程,图形图像处理,科学计算,手机编程等等。

使用 Python 最多的应该是 Google 公司了,就是人们到处都可以看到的 Google 搜索引擎。微软公司也已经开始提供Python语言的软件了。 全球著名的手机厂商 Nokia 公司早已经开始提供基于Python语言的手机开发软件了。另外,还有很多游戏是用Python开发的。另外一个比较有名的就是 Zope 公司了。

目前,Python已经有成百上千的公共资源可以供你调用。

“Python”这个英文单词的发音似“派森”,因此中文可以称之为派森。

举个小例子:

Toggle line numbers
   1 # -*- coding: utf-8 -*-
   2 # 这里是注释
   3 import string # 引用模块
   4 
   5 class abc: # 定义类
   6     def my(self): # 定义方法
   7         hi = '你好,世界'
   8         return hi
   9 
  10 def hello(int): # 定义函数或子程序
  11     """说明"""
  12     if int < 0:   # 判断
  13         res = '请输入整数'
  14     else:
  15         my_class = abc()
  16         res = my_class.my()
  17     return res
  18 
  19 print hello(2) # 调用函数 hello

下载和安装

  • 请到 Python.org下载, 当前最新的版本是 2.4.2

基础教程

Python语言是一种非常容易学习的语言,具有非常清晰的语法结构。因此,在非常短的时间内,就可以编写出实用的程序。最好先看看Python自带的文档。然后,可以再参考以下内容:

Zope 专题

Zope 是一种用途广泛的Web应用服务器软件,主要是基于Python开发的,有很多软件是构建在Zope基础上的,比如:Plone 等等。它的主页是 www.zope.org

面向对象编程

Python语言是一种有面向对象的语言,因此不仅适合于小型项目的开发, 还适合大中型项目的开发。

数据库

Python 在数据库方面也很优秀,可以和多种数据库进行连接,进行数据处理,从商业型的数据库到开放源码的数据库都提供支持。例如: Oracle, Ms SQL Server等等。有多种接口可以与数据库进行连接,至少包括ODBC。有许多公司采用着以Python为核心的架构。因此,掌握了Python使你可以充分利用面向对象的特点,在数据库处理方面如虎添翼。

Windows编程

Python 不仅可以在Unix类型的操作系统上应用,同样可以在Windows系统里有很好的表现。通过添加 PythonWin 模块,就可以通过 COM形式调用和建立各种资源,包括调用注册表、ActiveX控件以及各种COM等工作,最常见的例子就是通过程序对Office文档进行处理,自动生成文档和图表。

通过Python,你还可以利用py2exe模块生成exe应用程序。还有许多其他的日常维护和管理工作也可以交给 Python来做,从而减少维护的工作量。利用Python,你还可以开发出象VB,VC,Delphi那样的GUI程序,但却可以在多个平台上执行。这在许多方面并不逊色于Java。

多媒体

利用Python,你可以处理图象、声音、视频、动画等,从而为你的程序添加亮丽的光彩。动态图表的生成、统计分析图表都可以通过Python来完成。另外,还有OpenGL。利用PyOpenGL模块,你可以非常迅速的编写出三维场景。

  • Alice : 一个用Python和Java开发的动画编辑器。
  • VPython : 三维场景设计
  • PyOpenGl
  • PIL图像库 : 图像分析与处理模块
  • PyMol :开放源代码的分子模型系统,至少可以用于医学新药物的探索。精彩

高性能计算

Python可以广泛的在高性能计算领域发挥独特的角色,这包括科学计算领域、网格(Grid)计算领域等等。有许多模块可以帮助你在计算巨型数组、矢量分析、神经网络等方面高效率完成工作。尤其是在教育科研方面,可以发挥出独特的优势。

网络编程

Python可以非常方便的完成网络编程的工作,提供了众多的解决方案和模块,可以非常方便的定制出自己的服务器软件,无论是c/s,还是b/s模式,都有很好的解决方法。

XML

Python对XML的支持同样非常强大,有多个扩展模块可以帮助你建立、分析和处理XML,对于将来的发展趋势而言,这是非常重要的。Python支持PRC,SOAP等等。

图形界面(GUI)

Python可以非常方便的实现GUI编程,通过PyGTK,wxPython, PyQT等等模块,你就可以根据需要编写出强大的跨平台的用户界面程序。免费推荐使用PyGTK或wxPython。

关于如何用Python进行GUI开发,还可以参考 onlamp.com 的 这个页面

开发环境与编辑器

Python程序的开发工具比较多,目前主要的工具既有IDLE,PythonWin这样的免费工具, 也有一些商业性的工具。通过这些工具 ,可以让你更为快速的完成工作。

  • 集成开发环境(IDE): 列表
    • IDLE:这是Python里边自带的,基本上可以满足一般开发需要。
    • Eric3 : 非常专业的的IDE
    • SPE : 一个不错的编辑软件
    • PythonWin:这是基于Windows平台的编辑开发环境,基本上可以满足一般开发需要。下载
  • 代码编辑器:
    • LEO :完全由Python编写的程序代码编写辅助工具,可运行在多种操作系统中,支持独特的程序代码管理方式。
    • Vim :相当专业的代码编辑器,可运行在多种操作系统中,支持Python扩展。
    • Emacs:Unix系统中常用的工具。
    • SciTE:简单易用的代码编辑器,支持unicode编辑等等多种功能。
    • Quanta: 主要用于编辑网页等等

嵌入和扩展

Python 可以嵌入到其它应用程序中,也可以通过C/C++编写扩展模块,从而可以提高程序的运行速度或者完成只有通过C/C++才能完成的工作。现在Python 已经可以和C#相结合,并且结合到Visual Studio里边,实现微软的.Net思想。如果你会C语言,再学习Python,这将是一个非常棒的一种选择。以下是几个比较常用的扩展工具

如果你掌握了Python,想在Java里应用它,你可以采用Jython。Jython是采用Java语言实现的Python。这样,你只要按照 Python的语法,就可以调用Java的各种类库,快速的编写出基于Java的程序。也就是通过Jython,编写Java程序。这样就可以更为快速的实现Java的功能。另外,Oreilly已经出版了Jython方面的专著《Jython Essentials》,发展迅速。Python在面向对象方面和Java是相通的。神奇的Python!!

另外,你可以参考:

游戏编程

Python在很早的时候就是一种游戏编程的辅助工具。在《星球大战》中扮演了重要的角色。目前,通过Python完全可以编写出非常棒的游戏程序。另外,你可以到 pygame.org下载一些例子看看,确实可以让你感觉一新。

"Python plays a key role in our production pipeline. Without it a project the size of Star Wars: Episode II would have been very difficult to pull off. From crowd rendering to batch processing to compositing, Python binds all things together," said Tommy Burnette, Senior Technical Director, Industrial Light & Magic.

中文编程与文字处理

最新的 2.4 版本加强了对中文的支持,建议大家下载最新的版本。

另外,Glace对Python2.1.1进行了深入的改造,形成了一种中蟒语言,实现了可以用中文编程,详细请见: 中蟒

Python 对文字的处理功能强大,支持 unicode 和 正则表达式。下面是一些小工具,可以帮助用来排版:

  • Docutils :方便编写标准的文档
  • Epydoc :生成代码类文档
  • txt2tags :用纯文本帮助编写多种格式的文档, 和 Docutils 类似。
  • AsciiDoc

相关书籍:

手机移动

Python 也可以在手机中运行,目前,Nokia已经开始提供 Series 60 系统中的Python,通过它就可以调用手机中的各种功能啦!

成功案例与应用

目前,Python已经成功的实现企业级应用,在全球,已经有很多公司采用Python进行企业级软件的开发和应用,比如:ERP和CRM这样的应用。同时,通过Python技术,成功的实现了许多政务应用。 最有名的可能就要算 Google 啦。请查看以下一些网址:

"Python has been an important part of Google since the beginning, and remains so as the system grows and evolves. Today dozens of Google engineers use Python, and we're looking for more people with skills in this language." said Peter Norvig, director of search quality at Google, Inc.

书籍文档

目前,已经出版了多种中文书籍,不妨找一本看看。比如:

  • 《Python 核心编程》
  • 《Python 编程金典》

综合应用

以下是一些进行综合应用的软件:

  • PyMol :开放源代码的分子模型系统,至少可以用于医学新药物的探索。精彩!
  • Chandler : Lotus Notes的开发者进行的新的协同交流系统。
  • Plone :基于Zope开发的网站框架,轻松建立易于维护和管理的网站交流系统。
  • MailMan : 元老级别的邮件列表交流软件。
  • BitTorrent : BT 超强的下载工具
  • EarthClock : 挺好看的钟表
  • GNU Enterprise: 企业ERP
  • TinyERP: 小型的ERP系统

精选链接

英文:

中文:

发表于 2008-11-29 07:50 lostpencil 阅读(2578) | 评论 (7)编辑 收藏
2008年11月14日
== 基于本地的Python应用程序 ==


=== 写在之前 ===
{{{
这篇所说的是关于建立python调用Flash的本地应用,不同于Adobe的Apollo。

没有用到浏览器嵌入flash网页的方法,直接在pythonwin或者wxpython建立的窗口中插入Flash ocx。

因为是操作Activex控件的方式因此大概只适用于windows平台。抱歉我并未在其它平台上试过这种方法,不过linux中应该也有类似的技术。}}}

=== Flash ocx介绍 ===
{{{
Flash ocx实际上是一种COM组件开发模型(Microsoft Component Object Model),它原先是从Windows 3.x中的OLE发展过来的。现在又被改名叫做Activex。Activex是COM的一种,一般是指带有UI界面的COM。

Flash ocx的本名是叫Shockwave Flash Object,是一个Activex控件。Activex控件文件名的后缀是ocx。

原先的Shockwave包括了很多东西。被Adobe收购的MicroMedia公司的另一个产品Director的web应用就叫shockwave,它集合了视频流、Flash、shockwave 3D于一身。

对于Director我还是挺有感情的,只不过Director到了8.5以后的版本就基本不再发展了,我也渐渐不用它了。(听说Adobe收购MicroMedia以后,还会推出Director 11)}}}


=== Flash ocx与外界通迅的方法 ===

==== 调用ocx标准COM接口IDispatch ====

这种方法最简单,也比较通用。

它又叫COM对象的自动化接口。使用自动化,对象就可以提供一个简单的自动化接口,这样脚本语言作者只需掌握IDispatch和几个COM应用程序接口就可以了。

pythonwin的作者 Mark Hammond 的一本书(Python Programming on Win32)就讲到了怎样用python直接操作COM对象(操作的函义包括使用和发布)。如果想深入细节的话,可以参考这本书。

Python 程序使用 win32com.client.Dispatch() 方法来创建 COM objects。
如创建一个 Flash COM object.

{{{#!python
>>> import win32com.client
>>> fl = win32com.client.Dispatch("ShockwaveFlash.ShockwaveFlash.9") #Flash 9 的ProgID是ShockwaveFlash.ShockwaveFlash.9,有很多工具可以查到机器内部注册的COM组件信息
}}}
这样就得到了Flash COM object,你可以让它LoadMovie,让它Play,但是你暂时还看不到它,你得传给它一个窗口,这样它才能显示在窗口。
所幸wxpython帮我们封装了这一切,你只需要调用wx.lib.flashwin.FlashWindow类就行了。

例:
{{{#!python
import wx
from wx.lib.flashwin import FlashWindow

class CGui(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, 101, "map", size = (800, 600), style = wx.FRAME_SHAPED)
self.flash = FlashWindow(self, style=wx.SUNKEN_BORDER, size = (800, 600)) #用wx.lib.flashwin.FlashWindow创建窗口
self.flash.LoadMovie(0, 'C:\\drop_shadow_dog.swf') #播放"C:\\drop_shadow_dog.swf"的Flash影片
self.flash.SetSize((800, 600));

def getText(self):
returnValue = self.flash.GetVariable('FlashValue') #从Flash端
return returnValue

def setText(self, text):
self.flash.SetVariable("PythonValue", text) #传给Flash变量

}}}
这些传递变量在Flash AS端都处于_root层级下。

这儿有个例子
http://www.sephiroth.it/weblog/archives/2004/05
/wxpython_and_flash_first_test.php
{{{#!python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import wx, sys, os
import string, codecsfrom wx.lib.flashwin
import FlashWindow
from wx.lib.flashwin import EVT_FSCommand
#----------------------------------------
class TestPanel(wx.Panel):
def __init__(self, parent, base, swf):
wx.Panel.__init__(self, parent, -1)
self.base = base
sizer = wx.BoxSizer(wx.VERTICAL)
self.flash = FlashWindow(self, style=wx.SUNKEN_BORDER)
dlg = wx.MessageDialog(self, "This will work only under Windows!","Warning!",wx.OK | wx.ICON_INFORMATION)
dlg.Center()
dlg.ShowModal()
wx.BeginBusyCursor()
try:
self.flash.LoadMovie(0, swf)
except:
wx.MessageDialog(self, "could not load the swf file","Error",wx.OK | wx.ICON_ERROR).ShowModal()
sys.exit(2)
wx.EndBusyCursor()
self.flash.Stop()
self.flash.SetSize((self.flash.GetSize()[0],self.flash.GetSize()[1]))
# sizer
sizer.Add(self.flash, 1, wx.EXPAND)
self.SetSizer(sizer)
self.SetAutoLayout(True)
sizer.Fit(self)
sizer.SetSizeHints(self)
self.SetFlashOptions()
self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)
self.Bind(EVT_FSCommand, self.CallMethod) ##将Flash ocx的消息事件绑定到CallMethod函数上。

def SetFlashOptions(self):
self.flash.menu = False
self.flash._set_FlashVars("data=Server started on " + sys.platform)
self.flash.Play()

def OnDestroy(self, evt):
if self.flash:
self.flash.Cleanup()
self.flash = None

# Called from Flash FSCommand
def CallMethod(self, evt):
try:
arguments = string.split(evt.args,"###")
filename = arguments[0]
body = arguments[1]
if filename == "" or body == "":
wx.MessageDialog(self, "Please check data inserted", "An Error occurred", wx.OK | wx.ICON_INFORMATION).ShowModal()
else:
dlg = wx.FileDialog(self, "Save as..." , os.getcwd(), filename, "*.*", wx.SAVE | wx.OVERWRITE_PROMPT )
if dlg.ShowModal() == wx.ID_OK:
try:
f = codecs.open(os.path.normpath(dlg.GetPath()), "w", "utf-8", "ignore")
f.write(codecs.utf_8_decode(codecs.BOM_UTF8)[0])
f.write(body)
f.close()
self.flash._set_FlashVars("data=Succesfully saved text file")
except:
wx.MessageDialog(self, "%s %s %s" % sys.exc_info(), "An Error occurred", wx.OK | wx.ICON_ERROR).ShowModal()
self.flash._set_FlashVars("data=%s %s %s" % sys.exc_info())
except:
wx.MessageDialog(self, "Please check data inserted","An Error occurred",wx.OK | wx.ICON_INFORMATION).ShowModal()
self.flash._set_FlashVars("data=%s %s %s" % sys.exc_info())

#-------------------------------------------
if __name__ == '__main__':
class TestFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, "ActiveX -- Flash", size=(640, 480), style=wx.DEFAULT_FRAME_STYLE )
base = os.path.normpath(os.path.abspath(os.path.dirname(sys.argv[0])))
swf = os.path.normpath(os.path.join(base, "movie.swf"))
self.tp = TestPanel(self, base, swf)
app = wx.PySimpleApp()
frame = TestFrame()
frame.Center()
frame.Show(True)
app.MainLoop()
}}}

Flash端很简单,两句话就搞定了。
{{{
on (click) {
fscommand("saveFile", this._parent.fnome.text + "###" + this._parent.ftesto.text)
}}}}

这里用到了Flash的fscommand。

在Flash端点击了以后,它就会发送一个fscommand消息事件。

python端接收到了以后,由CallMethod处理。

==== 使用Flash ExternalInterface ====

ExternalInterface 类是一个子系统,通过它可以轻松地实现从 ActionScript 和 Flash Player 到 HTML 页中的 JavaScript 或任何包含 Flash Player 实例的台式机应用程序的通信。
ExternalInterface 可以提供以下功能:
{{{
■ 可以调用注册过的 python 函数。 从python端也可以调用注册过的Flash ActionScript函数。
■ 可以传递任意数量的、具有任意名称的参数;而不是仅限于传递一个命令和一个字符串参数。
■ 可以传递各种数据类型(例如 Boolean 、Number 和 String);不再仅限于 String 参数。
■ 可以接收调用值,该值将立即返回到 ActionScript(作为进行的调用的返回值)。}}}

Flash利用ExternalInterface与Python之间的通信使用特定的XML格式对函数调用和值进行编码。Flash端自动处理XML格式,Python则需要将接收到的XML数据解析和发送前打包成XML格式。

使用ExternalInterface与Python进行通信时,Flash以特定的XML格式向应用程序发送消息(函数调用和返回值),并要求来自Python的函数调用和返回值使用相同的 XML格式。

下面的 XML 片断说明了一个 XML 格式的函数调用示例:

{{{


... (individual argument values)

}}}

通过XML格式,ExternalInterface与Python之间可以传递多种类型的参数,包括Python的list和dic类型。

我们可以建立一个数据转换类来专门将翻译Python与Flash之间的通迅。

{{{#!python
class EIDataSerializer:
__xmlData=None
def __packNumber(self,p,x):
p.appendChild(self.__xmlData.createElement('number')).appendChild(self.__xmlData.createTextNode(str(x)))
return
def __packString(self,p,x):
p.appendChild(self.__xmlData.createElement('string')).appendChild(self.__xmlData.createTextNode(x))
return
def __packNone(self,p):
p.appendChild(self.__xmlData.createElement('null'))
return
def __packBool(self,p,x):
if x:
p.appendChild(self.__xmlData.createElement('true'))
else:
p.appendChild(self.__xmlData.createElement('false'))
return
def __packDict(self,p,x):
p=p.appendChild(self.__xmlData.createElement('object'))
for k,v in x.items():
n=p.appendChild(self.__xmlData.createElement('property'))
n.setAttribute('id',str(k))
self.__packData(n,v)
return
def __packList(self,p,x):
p=p.appendChild(self.__xmlData.createElement('array'))
i=0
for v in x:
n=p.appendChild(self.__xmlData.createElement('property'))
n.setAttribute('id',str(i))
self.__packData(n,v)
i+=1
return
def __packData(self,p,x): ##将Python的类型打包成XML
t=type(x)
if t in (int,long,float):
self.__packNumber(p,x)
elif t in (str,unicode):
self.__packString(p,x)
elif x==None:
self.__packNone(p)
elif t==bool:
self.__packBool(p,x)
elif t in (list,tuple):
self.__packList(p,x)
elif t==dict:
self.__packDict(p,x)
return
def __unpackNumber(self,p):
try:
return int(p.firstChild.nodeValue)
except ValueError:
try:
return float(p.firstChild.nodeValue)
except ValueError:
return None
def __unpackString(self,p):
return p.firstChild.nodeValue
def __unpackTrue(self):
return True
def __unpackFalse(self):
return False
def __unpackNull(self):
return None
def __unpackUndefined(self):
return None
def __unpackObject(self,p):
d={}
for n in p.childNodes:
d[n.getAttribute('id')]=self.__unpackData(n.firstChild)
return d
def __unpackArray(self,p):
a=[]
for n in p.childNodes:
a.append(self.__unpackData(n.firstChild))
return a
def __unpackData(self,p): ##将Flash传过来的XML解析成Python类型数值
t=p.nodeName
if t=='number':
return self.__unpackNumber(p)
elif t=='string':
return self.__unpackString(p)
elif t=='true':
return self.__unpackTrue()
elif t=='false':
return self.__unpackFalse()
elif t=='null':
return self.__unpackNull()
elif t=='undefined':
return self.__unpackUndefined()
elif t=='object':
return self.__unpackObject(p)
elif t=='array':
return self.__unpackArray(p)
def serializeReturn(self,v):
self.__xmlData=minidom.Document()
p=self.__xmlData
self.__packData(p,v)
return self.__xmlData.toxml()
def serializeCall(self,name,args):
self.__xmlData=minidom.Document()
p=self.__xmlData.appendChild(self.__xmlData.createElement('invoke'))
p.setAttribute('name',name)
p.setAttribute('returntype','xml')
p=p.appendChild(self.__xmlData.createElement('arguments'))
for v in args:
self.__packData(p,v)
s=self.__xmlData.documentElement.toxml()
return s
def deserializeReturn(self,s):
self.__xmlData=minidom.parseString(s)
p=self.__xmlData.documentElement
return self.__unpackData(p)
def deserializeCall(self,s):
self.__xmlData=minidom.parseString(s)
p=self.__xmlData.documentElement#invoke
name=p.getAttribute('name')
args=[]
p=p.firstChild#arguments
for n in p.childNodes:
args.append(self.__unpackData(n))
return (name,args)}}}


===== 从Python调用Flash函数 =====

从Python端调用Flash端函数实际上是Python调用Shockwave Flash ActiveX控件的CallFunction()方法,通过ExternalInterface从Flash调用ActionScript函数。

以下示范了从Python调用Flash函数的用法:

Python端:

{{{#!python
def CallFlash(name,args): ## name是Flash ActionScript的函数名,args是传给Flash ActionScript的参数
ds = EIDataSerializer()
s = ds.serializeCall(name,args) ## 将传递的内容打包成XML
s = flashWnd.ocx.CallFunction(s) ## 调用Shockwave Flash ActiveX控件的CallFunction()方法
s = s.encode('utf-8') ## 从ActionScript返回的任何值都被编码为XML格式字符串,并作为CallFunction()调用的返回值发送回来。
return ds.deserializeReturn(s) ## 返回值解包}}}


Flash端:

要从Python调用ActionScript函数,必须向ExternalInterface类注册函数,然后再用Shockwave Flash ActiveX控件的CallFunction()方法调用它。

Python只能调用ExternalInterface类注册函数中的ActionScript代码,而不能调用任何其它ActionScript代码。

向ExternalInterface类注册ActionScript函数的方法,如下所示:

{{{
function callMe(name:String):String
{
return "busy signal";
}
ExternalInterface.addCallback("myFunction", callMe);}}}

ExternalInterface.addCallback()方法采用两个参数。第一个参数为 String 类型的函数名,这是告诉Python端调用的函数名。第二个参数为Flash端实际ActionScript函数。

由于这些名称是截然不同的,因此可以指定将由Python使用的函数名与实际的ActionScript函数具有不同的名称。这在函数名未知的情况下特别有用,例如:指定了匿名函数或需要在运行时确定要调用的函数。

===== 从Flash调用Python函数 =====

从Flash调用Python函数实际上是Shockwave Flash ActiveX控件发送了一个控件消息FlashCall,并附带包含有关函数调用信息的XML 格式的字符串。Python将其解析成函数名和参数,并调用相应函数。

我们继续从消息流程上解析这个过程,首先Flash端示例:

{{{
public function sendMessage(message:String):void
{
ExternalInterface.call("newMessage", message); //调用了Python端的newMessage的方法,message是newMessage方法的参数
}}}}

Python端示例:

先建立一个供Flash调用的函数

{{{#!python
def newMessage(self, message):
print message
return message}}}

建立一个函数字典库

{{{#!python
def RegisterCallback(self,name,callback): ##将需要调用的函数注册
if callable(callback):
self.__callbackReg[name]=callback ##和Flash类似,name是Flash端调用的函数名。callback为Python端实际函数。
return True
else:
return False}}}

{{{#!python
self.RegisterCallback("newMessage", newMessage) ##将其注册到__callbackReg中}}}

最后接收Flash消息,处理函数调用

{{{#!python
def OnFlashCall(self, receiveString): ##注册的Activex消息处理函数
receiveString = receiveString.encode('utf-8') ##从Flash控件消息接收的XML字符串
name,args = self.__szr.deserializeCall(receiveString) ##解析成Python函数名和参数
r = self.__callbackReg[name](*args) ##函数字典中注册的函数名
ds = EIDataSerializer()
s = ds.serializeReturn(r) ##返回值打包成XML
self.SetReturnValue(s)
return}}}

这样就可在Flash端调用Python函数了。



以上方法在pythonwin和wxPython中均可使用。

发表于 2008-11-14 16:45 lostpencil 阅读(3036) | 评论 (6)编辑 收藏
2008年10月18日
目前国内的聊天机器人大多都只是做了一个自然语言结构分析,然后就在此基础上做了场景记录。这2方面的努力结果最终产生了一个庞大的数据库,于是表现出来机器人的智能面不够灵活,而且速度很慢。

目前我发现人类的语言交流并不完全是的知识,信息的交流,策略占了很大比重,智能机器人语言方面的改善感觉应该加入策略的因素。

这里可以简单加入情绪因素进去,然后就是根据情绪来分类策略,这将直接导致数据库横向发展,查询效率提高很多。

而且很多策略是可以完全通过自然语言结构分析来确定句子的答复的,策略丰富化,机器人将更加智能。

目前我这方面针对朋友开发的一个机器人做了改进以后,运行速度大约提高了40%左右,至于语言效果由于策略的规划和实现还不完善,不如以前,但是大多数情况差别不大。

因为一些商业因素,就不继续说了,呵呵
发表于 2008-10-18 00:32 lostpencil 阅读(3054) | 评论 (3)编辑 收藏
2008年9月28日

一个偶尔的机会接触到了MDP,马尔可夫决策过程,突然发现多年的困惑有点头绪了,分享一段东西。

以下东西摘自某博士论文部分(若有版权问题请及时告知):

以哲学观点来看,人类来到世间至少有三件事要做:认识世界;改造世界;享受世界。

在这其中,学习类问题对应认识世界,而决策类问题便是和改造世界紧密相关的。决策问题伴随着人们的日常生活,大至公司乃至国家的战略性决定,小至个人利益相关的一些选择。‘决策’又区别于简单的‘决定’以及‘选择’。它通常涉及的是一个过程,其最终对应的行动的执行一般是多步的。在每一步,都要去做一个选择。不同的选择,不同的行动,导致不同的结果,进而也意味着不同的收益。决策不能孤立的进行,若不考虑现在与将来的联系,很难在整个过程中获得最好的收益,就如同在一次长跑比赛中,我们不能在起点就用尽全力冲刺一样。事实上,决策问题与人们的社会生活的联系是如此密切,可以说,一切社会实践活动都离不开决策,甚至,从辨证的观点看,若是把主观世界也当作客观世界的一部份,那么学习本身也是一个改造世界的过程,其过程也一样讲究策略,我们改造就是自己罢了。

对于智能体而言,当其面对客观世界中存在的一个待解决的问题时,首先,他的学习能力使其在主观世界中获得了对该问题的一个抽象的描述,对应为问题的模型,这其中通常包括:

¨        问题所有可能的状态,

¨        问题发展过程的演变规律,

¨        智能体在过程中可以做出的选择,

¨        智能体所期望的结果等。

事实上,这就是MDP模型的基本构成部分,

而所谓的智能体进行决策,也就是指智能体在此模型的基础上,基于问题过程的规律进行规划,利用智能体可行的选择参与改变过程,使其朝自身期望的结果发展,最终解决问题。总的来说,决策基于问题的模型再结合规划的方法两部分完成。在人工智能领域,马尔可夫决策过程是用来建模规划问题的一个基本理论模型。以其为基础,进一步发展出一系列更具一般性的决策模型,如部分可观察马尔可夫决策过程,分布式马尔可夫决策过程,部分可观察的随机博弈及半马尔可夫决策过程等等。

 

决策总是与一个过程相联系的(当然,从广义上来看,过程可以只有一步)。智能体要在过程中做出合适的选择,将过程的发展引入对自身有利的方向,必然需要了解描述过程发展变化的知识。相对于穷举所有变化,如果某些知识,不止一次可被用来推断过程发展,即为规律。主体更需要就是这种精简的知识。

马尔可夫过程正是具有一类普遍共性的过程。这类共性既是马尔可夫性,也称无后效性。由俄罗斯数学家马尔可夫于1907提出。所谓无后效性,指的是这样一种性质:某阶段的状态一旦确定,则此后过程的演变不再受此前各状态的影响。也就是说,未来与过去无关,当前的状态是此前历史的一个完整总结,此前的历史只能通过当前的状态去影响过程未来的演变。具体地说,如果一个问题被划分各个阶段之后,阶段 I 中的状态只能通过状态转移方程去影响阶段 I+1 中的状态的得来,与其他状态没有关系,特别是与未发生的状态没有关系,这就是无后效性。从更本质的的角度来理论,可以认为马尔可夫性来源于对因果性和时间的连续性以及单向性的认可。

马尔可夫性用来描述过程的规律类似数学中使用递推公式描述数列一样,并且特点是递推式只用到了前面一项。做为区别,比如著名的斐波拉契(Fibonacci)数列,11235……的递推公式F(n)=F(n-1)+F(n-2)就用到了前面的两项。假设我们构造一个过程,逐次去读取数列中的每一项,任何一个时刻的状态便是读取到的数字。那么,斐波拉契数列对应的便不是一个马尔可夫过程。描述规律的方式很多,把握“当前的状态是此前历史的一个完整总结”这一要点后,很多过程可以被转化描述为马尔可夫过程。当然,前提是,可以做到当前状态完整总结历史这点。但事实上完美总是相对而言的,从后面不确定性的讨论也可以看到。从这个角度来说,马尔可夫过程是一个很实用的理论。在马尔可夫过程上做决策的好处显而易见,我们可以忽略历史的影响,也无需再去不断的保存历史信息,一切规划都只要从当前状态出发即可。它所蕴含的思想是将智能体有限的规划能力引导至更有价值的方向。

马尔可夫决策过程与马尔可夫过程的本质区别就是多了主体即决策者的介入。下面将依次简单介绍马尔可夫决策过程(Markov Decision Processes, MDP),部分可观察马尔可夫决策过程(Partially Observable Markov Decision Processes, POMDP),分布式部分马尔可夫决策过程(Decentralized-POMDP, DEC-POMDP),部分可观察的随机博弈(Partially Observable Stochastic Games, POSG)及半马尔可夫决策过程(Semi-MDP)之间的区别与联系。

50年代R.贝尔曼研究动态规划时和L.S.沙普利研究随机对策时已出现马尔可夫决策过程的基本思想。R.A.霍华德(1960)D.布莱克韦尔(1962)等人的研究工作奠定了马尔可夫决策过程的理论基础。1965年,布莱克韦尔关于一般状态空间的研究和E.B.丁金关于非时齐(非时间平稳性)的研究,推动了这一理论的发展。1960年以来,马尔可夫决策过程理论得到迅速发展,应用领域不断扩大。凡是以马尔可夫过程作为数学模型的问题,只要能引入决策和效用结构,均可应用这种理论。

在人工智能领域中,对决策类问题的求解过程也可以称为规划。经典规划一般基于确定式的环境模式,如搜索算法A*等。这类方法在现实应用中有很大的局限性。面对现实中的规划问题,主体对环境特性的把握常常是不完整的,正是由于这种知识的缺失,造成了不确定性。马尔可夫决策模型则可以处理这类问题。利用下图信息集合划分的方式,可以更清晰的理解不确定性,以及马尔可夫决策过程(MDP)与下面将提到部分可观察马尔可夫决策过程(POMDP)的区别。

针对某个决策问题,从信息或者知识的角度我们区分出如下所示3个依次为包含关系的集合:


1.1 决策问题中的信息划分


A
集合:为客观存在的影响过程的全部信息,是整个客观世界的世界状态中与问题所对应过程相关的因素。

B集合:为影响智能体主观决策的信息,进一步解释,是智能体主观上知道存在,并能够把握运用的一些信息。因为对于某些因素,即便智能体知道应该与过程相关,但无法把握运用,这些信息也不会影响智能体决策。比如,一般都认为掷硬币,正反面的概率各50%。事实上,风力,掷硬币的具体操作方式,抛出轨迹,用力情况,地面情况等都会影响过程结果,而这些因素通常无法把握运用,即使考虑进来,也难以改变决策。因此,这类智能体知道存在却无法把握利用的信息,及主观上根本不知道其存在而客观上却影响过程的因素,构成了B集合与A集合的差别。同时,也正是这些差别,造成了不确定性的存在。从另一个角度,只要B不是空集,基于应用的需求,就存在进行决策的意义。但对不确定性仍需进行刻画,于是便引入了统计意义上概率。

C集合:为智能体总是能观察到的信息。现实中很多决策过程,对于B集合中的信息,智能体有时观察不到。比如踢足球,自己身后球员的位置是会影响决策的,但却可能会观察不到。

根据定义内容,首先有前提A>=B>=C,进而可以对问题做下面的分类:

1> A=B=C时是一个确定性问题。

2> A>=B=C时是一个MDP问题。

3> A>=B>C时是一个POMDP问题。

MDP本身既可以处理确定性问题,也可处理不确定性问题。而POMDPMDP模型上进行了一定扩展,引入了对观察不确定性的处理。从一定意义上也可以认为,MDPPOMDP的一种极端的情况,即决策相关信息全部可观察。

MDPPOMDP模型中都认为决策的智能体只有一个,并把其它一切因素都归于客观环境。这些因素一部分是确定性的知识;另一部分则是已归入统计概率的不确定性,认为在当前条件下,从处理问题的实际情况出发,不适合再进行探究,只作概率推理。当一个过程中,有多个智能体同时决策合作来解决一个问题时,上述模型是否适用的关键因素即其他智能体的策略是否已知。策略是决策的结果,指出在过程某个状态要采用哪个行动。如果认为其他智能体策略已知,无论是确定性的策略亦或含概率表示的不确定性策略,那么其他智能体一样可以归入环境,仍可使用MDPPOMDP模型处理。否则,其它智能体会采用何种策略也是需要纳入考虑的,在生成智能体自身决策的同时,也要生成其他智能体的决策,这是其客观过程本身的模型决定的。分布式马尔可夫决策过程(DEC-MDP)及分布式部分可观察马尔可夫决策过程(DEC-POMDP)可以处理这类多智能体合作问题。

在现实应用中,多智能体间除了合作也可能存在对抗,这类问题可以归为博弈。其中本质的区别即智能体间收益评价的不同。合作类问题,各个智能体有相同的收益评价,或者说有共同的目标;而博弈类问题,各个智能体收益评价存在区别,甚至完全对立。部分可观察的随机博弈(POSG)便是进一步扩展的一个决策模型,可以处理这类带有不确定性的博弈问题。

半马尔可夫过程又可以称为非时齐马尔可夫过程,这是相对于一般的时齐马尔可夫过程而言的。所谓时齐是指过程的每两个相邻状态点间的时间间隔是一致的,对应决策过程则是每步行动的执行时间是定长的。非时齐则是描述了一类更一般的情况,对应决策过程中行动的执行时间并不固定,甚至是时间上的一个概率分布。

我的收获:早些年研究的东西,基本思路是有一定的科学理论依据的,只是出发点有了问题,所以难逃计算量的恐怖。就像目前的彩票研究者一样,最终的常理的结论是预知性不明朗,靠运气吧。现在想想其实换一个研究层面去研究,然后按原来的方法计算,很多层面的东西还是相当有可能的。感谢数学,感谢马尔可夫。

发表于 2008-09-28 01:19 lostpencil 阅读(2470) | 评论 (2)编辑 收藏
2008年9月24日
我的电脑系统是XP, C盘是ntfs格式的,然后D盘是fat32格式的,这样DOS窗口里面怎么也cd 不进D盘去。
有没有什么办法,不重装系统或者格式化D盘,就可以轻松的CD D:\进去啊
因为之前D盘装了很多东西,格式化了太麻烦了

修改:
2008-09-25 08:13 by OneZ
进入D盘,只要在CMD窗口下输入D:,就可以了。前面不需要CD。
发表于 2008-09-24 23:27 lostpencil 阅读(3042) | 评论 (7)编辑 收藏
 
起因:通过MingW和qt-win-opensource-4.4.2-mingw.exe在windows下安装QT开源版的情况,在运行QT-demos时候会发现mediaplayer那个程序launch不起来,原因是本身那个程序就没有编译成可执行文件。然后自己找到那个模块后,qmake ,make,结果发现老有错误“Cannot find -lphonon”. 网上一搜同样的问题很多,答案比较少,超级复杂,还是有点乱说的成份在。包括那些英文网站上也没有有效的解决方案。

关于phonon:
Phonon是一个跨平台多媒体编程开发平台,可使具有不同编程经验的编程人员更便捷地将多媒体功能移植到他们的应用程序中去。
Phonon起初由KDE团队开发,是发布的KDE 4.0的一个组成部分。目前,奇趣科技将Phonon进行了扩展,使其可用于如Windows和 Mac OS X在内的所有主流桌面操作系统上。此外,奇趣科技已将该源程序代码编入KDE的源代码库中,并将其采用LGPL授权。
编程人员利用Phonon,可以更方便地将多媒体回放功能运用到C++应用程序中,很多操作程序仅利用极少的几个代码便可以实现。Phonon的源代码,包括仅在UNIX 和Linux平台上使用的、基于Xine的单一后端。而奇趣科技为Linux的GStreamer创建了其它的后端实施工具,同时为Windows和Mac OS X操作系统也创建了新的后端工具。
奇趣科技把Phonon纳入公司发布的Qt 4.4之中,目前该版本已在2008年第一季度末正式发布。

办法:会出现这个问题可能是qt-win-opensource-4.4.2-mingw.exe制作者的疏忽,把Phonon模块以及相关的程序没有编译到,
解决办法其实很简单,不要受那些答案的误导,只要在src下面找到phonon文件夹,然后编译下就好了。
这样会生成2个文件,一个是lib下面的libphonon4.a, 还有一个是bin下的 phonon4.dll, 也可以直接网上下到这2个文件,copy过去也能用。

注:仅验证了MingW + qt-win-opensource-4.4.2-mingw.exe的情况, 其他办法安装的有没有问题不清楚,Phonon是QT4以后才有的,要是用老版本是很难有办法用的。

发表于 2008-09-24 11:12 lostpencil 阅读(5020) | 评论 (7)编辑 收藏
2008年8月24日
什么是robots.txt文件? 搜索引擎通过一种程序robot(又称spider),自动访问互联网上的网页并获取网页信息。您可以在您的网站中创建一个纯文本文件robots.txt,在这个文件中声明该网站中不想被robot访问的部分,这样,该网站的部分或全部内容就可以不被搜索引擎收录了,或者指定搜索引擎只收录指定的内容。

robots.txt文件放在哪里? 
robots.txt文件应该放在网站根目录下。举例来说,当robots访问一个网站(比如http://www.abc.com)时,首先会检查该网站中是否存在http://www.abc.com/robots.txt这个文件,如果机器人找到这个文件,它就会根据这个文件的内容,来确定它访问权限的范围。
网站 url 相应的 robots.txt的 url 
http://www.w3.org/ http://www.w3.org/robots.txt 
http://www.w3.org:80/ http://www.w3.org:80/robots.txt 
http://www.w3.org:1234/ http: ... 234/robots.txt 
http://w3.org/ http://w3.org/robots.txt 

robots.txt文件的格式 
"robots.txt"文件包含一条或更多的记录,这些记录通过空行分开(以cr,cr/nl, or nl作为结束符),每一条记录的格式如下所示:
":"。

在该文件中可以使用#进行注解,具体使用方法和unix中的惯例一样。该文件中的记录通常以一行或多行user-agent开始,后面加上若干disallow行,详细情况如下:

user-agent:
  该项的值用于描述搜索引擎robot的名字,在"robots.txt"文件中,如果有多条user-agent记录说明有多个robot会受到该协议的限制,对该文件来说,至少要有一条user-agent记录。如果该项的值设为*,则该协议对任何机器人均有效,在"robots.txt"文件中,"user-agent:*"这样的记录只能有一条。

disallow:
  该项的值用于描述不希望被访问到的一个url,这个url可以是一条完整的路径,也可以是部分的,任何以disallow开头的url均不会被robot访问到。例如"disallow:/help"对/help.html 和/help/index.html都不允许搜索引擎访问,而"disallow:/help/"则允许robot访问/help.html,而不能访问/help/index.html。任何一条disallow记录为空,说明该网站的所有部分都允许被访问,在"/robots.txt"文件中,至少要有一条disallow记录。如果"/robots.txt"是一个空文件,则对于所有的搜索引擎robot,该网站都是开放的。


robots.txt文件用法举例 例1. 禁止所有搜索引擎访问网站的任何部分 
下载该robots.txt文件 user-agent: * 
disallow: / 
例2. 允许所有的robot访问 (或者也可以建一个空文件 "/robots.txt" file) user-agent: *
disallow: 
例3. 禁止某个搜索引擎的访问 user-agent: badbot
disallow: / 
例4. 允许某个搜索引擎的访问 user-agent: baiduspider
disallow: 

user-agent: *
disallow: / 
例5.一个简单例子
  在这个例子中,该网站有三个目录对搜索引擎的访问做了限制,即搜索引擎不会访问这三个目录。
  需要注意的是对每一个目录必须分开声明,而不要写成 "disallow: /cgi-bin/ /tmp/"。
  user-agent:后的*具有特殊的含义,代表"any robot",所以在该文件中不能有"disallow: /tmp/*" or "disallow:*.gif"这样的记录出现. user-agent: *
disallow: /cgi-bin/
disallow: /tmp/
disallow: /~joe/ 
发表于 2008-08-24 16:20 lostpencil 阅读(3123) | 评论 (3)编辑 收藏
2008年8月1日
1. Given a rectangular (cuboidal for the puritans) cake with a rectangular piece removed (any size or orientation), how would you cut the remainder of the cake into two equal halves with one straight cut of a knife ?
2. You're given an array containing both positive and negative integers and required to find the sub-array with the largest sum (O(N) a la KBL). Write a routine in C for the above.
3. Given an array of size N in which every number is between 1 and N, determine if there are any duplicates in it. You are allowed to destroy the array if you like. [ I ended up giving about 4 or 5 different solutions for this, each supposedly better than the others ].
4. Write a routine to draw a circle (x ** 2 + y ** 2 = r ** 2) without making use of any floating point computations at all. [ This one had me stuck for quite some time and I first gave a solution that did have floating point computations
5. Given only putchar (no sprintf, itoa, etc.) write a routine putlong that prints out an unsigned long in decimal. [ I gave the obvious solution of taking % 10 and / 10, which gives us the decimal value in reverse order. This requires an array since we need to print it out in the correct order. The interviewer wasn't too pleased and asked me to give a solution which didn't need the array
6. Give a one-line C expression to test whether a number is a power of 2. [No loops allowed - it's a simple test.
7. Given an array of characters which form a sentence of words, give an efficient algorithm to reverse the order of the words (not characters) in it.
8. How many points are there on the globe where by walking one mile south, one mile east and one mile north you reach the place where you started.
9. Give a very good method to count the number of ones in a "n" (e.g. 32) bit number.
ANS. Given below are simple solutions, find a solution that does it in log (n) steps.
Iterativefunction iterativecount (unsigned int n)beginint count=0;while (n)begincount += n & 0x1 ;n >>= 1;endreturn count;endSparse Countfunction sparsecount (unsigned int n)beginint count=0;while (n)begincount++;n &= (n-1);endreturn count ;end
10. What are the different ways to implement a condition where the value of x can be either a 0 or a 1. Apparently the if then else solution has a jump when
written out in assembly. if (x == 0) y=a else y=b There is a logical, arithmetic and a data structure solution to the above problem.
11. Reverse a linked list.
12. Insert in a sorted list
13. In a X's and 0's game (i.e. TIC TAC TOE) if you write a program for this give a fast way to generate the moves by the computer. I mean this should be the fastest way possible.
The answer is that you need to store all possible configurations of the board and the move that is associated with that. Then it boils down to just accessing the right element and getting the corresponding move for it. Do some analysis and do some more optimization in storage since otherwise it becomes infeasible to get the required storage in a DOS machine.
14. I was given two lines of assembly code which found the absolute value of a number stored in two's complement form. I had to recognize what the code was doing. Pretty simple if you know some assembly and some fundaes on number representation.
15. Give a fast way to multiply a number by 7.
16. How would go about finding out where to find a book in a library. (You don't know how exactly the books are organized beforehand).
17. Linked list manipulation.
18. Tradeoff between time spent in testing a product and getting into the market first.
19. What to test for given that there isn't enough time to test everything you want to.
20. First some definitions for this problem: a) An ASCII character is one byte long and the most significant bit in the byte is always '0'. b) A Kanji character is two bytes long. The only characteristic of a Kanji character is that in its first byte the most significant bit is '1'.
Now you are given an array of a characters (both ASCII and Kanji) and, an index into the array. The index points to the start of some character. Now you need to write a function to do a backspace (i.e. delete the character before the given index).
21. Delete an element from a doubly linked list.
22. Write a function to find the depth of a binary tree.
23. Given two strings S1 and S2. Delete from S2 all those characters which occur in S1 also and finally create a clean S2 with the relevant characters deleted.
24. Assuming that locks are the only reason due to which deadlocks can occur in a system. What would be a foolproof method of avoiding deadlocks in the system.
25. Reverse a linked list.
Ans: Possible answers -
iterative loop
curr->next = prev;
prev = curr;
curr = next;
next = curr->next
endloop
recursive reverse(ptr)
if (ptr->next == NULL)
return ptr;
temp = reverse(ptr->next);
temp->next = ptr;
return ptr;
end
26. Write a small lexical analyzer - interviewer gave tokens. expressions like "a*b" etc.
27. Besides communication cost, what is the other source of inefficiency in RPC? (answer : context switches, excessive buffer copying). How can you optimize the communication? (ans : communicate through shared memory on same machine, bypassing the kernel _ A Univ. of Wash. thesis)
28. Write a routine that prints out a 2-D array in spiral order!
29. How is the readers-writers problem solved? - using semaphores/ada .. etc.
30. Ways of optimizing symbol table storage in compilers.
31. A walk-through through the symbol table functions, lookup() implementation etc. - The interviewer was on the Microsoft C team.
32. A version of the "There are three persons X Y Z, one of which always lies".. etc..
33. There are 3 ants at 3 corners of a triangle, they randomly start moving towards another corner.. what is the probability that they don't collide.
34. Write an efficient algorithm and C code to shuffle a pack of cards.. this one was a feedback process until we came up with one with no extra storage.
35. The if (x == 0) y = 0 etc..
36. Some more bitwise optimization at assembly level
37. Some general questions on Lex, Yacc etc.
38. Given an array t[100] which contains numbers between 1..99. Return the duplicated value. Try both O(n) and O(n-square).
39. Given an array of characters. How would you reverse it. ? How would you reverse it without using indexing in the array.
40. Given a sequence of characters. How will you convert the lower case characters to upper case characters. ( Try using bit vector - solutions given in the C lib -typec.h)
41. Fundamentals of RPC.
42. Given a linked list which is sorted. How will u insert in sorted way.
43. Given a linked list How will you reverse it.
44. Give a good data structure for having n queues ( n not fixed) in a finite memory segment. You can have some data-structure separate for each queue. Try to use at least 90% of the memory space.
45. Do a breadth first traversal of a tree.
46. Write code for reversing a linked list.
47. Write, efficient code for extracting unique elements from a sorted list of array. e.g. (1, 1, 3, 3, 3, 5, 5, 5, 9, 9, 9, 9) -> (1, 3, 5, 9).
48. Given an array of integers, find the contiguous sub-array with the largest sum.
ANS. Can be done in O(n) time and O(1) extra space. Scan array from 1 to n. Remember the best sub-array seen so far and the best sub-array ending in i.
49. Given an array of length N containing integers between 1 and N, determine if it contains any duplicates.
ANS.
50. Sort an array of size n containing integers between 1 and K, given a temporary scratch integer array of size K.
ANS. Compute cumulative counts of integers in the auxiliary array. Now scan the original array, rotating cycles! [Can someone word this more nicely?
51. An array of size k contains integers between 1 and n. You are given an additional scratch array of size n. Compress the original array by removing duplicates in it. What if k << n?
ANS. Can be done in O(k) time i.e. without initializing the auxiliary array!
52. An array of integers. The sum of the array is known not to overflow an integer. Compute the sum. What if we know that integers are in 2's complement form?
ANS. If numbers are in 2's complement, an ordinary looking loop like for(i=total=0;i< n;total+=array[i++]); will do. No need to check for overflows!
53. An array of characters. Reverse the order of words in it.
ANS. Write a routine to reverse a character array. Now call it for the given array and for each word in it.
* 54. An array of integers of size n. Generate a random permutation of the array, given a function rand_n() that returns an integer between 1 and n, both inclusive, with equal probability. What is the expected time of your algorithm?
ANS. "Expected time" should ring a bell. To compute a random permutation, use the standard algorithm of scanning array from n downto 1, swapping i-th element with a uniformly random element <= i-th. To compute a uniformly random integer between 1 and k (k < n), call rand_n() repeatedly until it returns a value in the desired range.
55. An array of pointers to (very long) strings. Find pointers to the (lexicographically) smallest and largest strings.
ANS. Scan array in pairs. Remember largest-so-far and smallest-so-far.
Compare the larger of the two strings in the current pair with largest-so-far to update it. And the smaller of the current pair with the smallest-so-far to update it. For a total of <= 3n/2 strcmp() calls. That's also the lower bound.
56. Write a program to remove duplicates from a sorted array.
ANS. int remove_duplicates(int * p, int size)
{
int current, insert = 1;
for (current=1; current < size; current++)
if (p[current] != p[insert-1])
{
p[insert] = p[current];
current++;
insert++;
} else
current++;
return insert;
}
57. C++ ( what is virtual function ? what happens if an error occurs in constructor or destructor. Discussion on error handling, templates, unique features of C++. What is different in C++, ( compare with unix).
58. Given a list of numbers ( fixed list) Now given any other list, how can you efficiently find out if there is any element in the second list that is an element of the first list (fixed list).
59. Given 3 lines of assembly code : find it is doing. IT was to find absolute value.
60. If you are on a boat and you throw out a suitcase, Will the level of water increase.
61. Print an integer using only putchar. Try doing it without using extra storage.
62. Write C code for (a) deleting an element from a linked list (b) traversing a linked list
63. What are various problems unique to distributed databases
64. Declare a void pointer ANS. void *ptr;
65. Make the pointer aligned to a 4 byte boundary in a efficient manner ANS. Assign the pointer to a long number and the number with 11...1100 add 4 to the number
66. What is a far pointer (in DOS)
67. What is a balanced tree
68. Given a linked list with the following property node2 is left child of node1, if node2 < node1 else, it is the right child.
O P
|
|
O A
|
|
O B
|
|
O C
How do you convert the above linked list to the form without disturbing the property. Write C code for that.
O P
|
|
O B
/ \
/ \
/ \
O ? O ?
determine where do A and C go
69. Describe the file system layout in the UNIX OS
ANS. describe boot block, super block, inodes and data layout
70. In UNIX, are the files allocated contiguous blocks of data
ANS. no, they might be fragmented
How is the fragmented data kept track of
ANS. Describe the direct blocks and indirect blocks in UNIX file system
71. Write an efficient C code for 'tr' program. 'tr' has two command line arguments. They both are strings of same length. tr reads an input file, replaces each character in the first string with the corresponding character in the second string. eg. 'tr abc xyz' replaces all 'a's by 'x's, 'b's by 'y's and so on. ANS.
a) have an array of length 26.
put 'x' in array element corr to 'a'
put 'y' in array element corr to 'b'
put 'z' in array element corr to 'c'
put 'd' in array element corr to 'd'
put 'e' in array element corr to 'e'
and so on.
the code
while (!eof)
{
c = getc();
putc(array[c - 'a']);
}
72. what is disk interleaving
73. why is disk interleaving adopted
74. given a new disk, how do you determine which interleaving is the best a) give 1000 read operations with each kind of interleaving determine the best interleaving from the statistics
75. draw the graph with performance on one axis and 'n' on another, where 'n' in the 'n' in n-way disk interleaving. (a tricky question, should be answered carefully)
76. I was a c++ code and was asked to find out the bug in that. The bug was that he declared an object locally in a function and tried to return the pointer to that object. Since the object is local to the function, it no more exists after returning from the function. The pointer, therefore, is invalid outside.
77. A real life problem - A square picture is cut into 16 squares and they are
shuffled. Write a program to rearrange the 16 squares to get the original big square.
78.
int *a;
char *c;
*(a) = 20;
*c = *a;
printf("%c",*c);
what is the output?
79. Write a program to find whether a given m/c is big-endian or little-endian!
80. What is a volatile variable?
81. What is the scope of a static function in C ?
82. What is the difference between "malloc" and "calloc"?
83. struct n { int data; struct n* next}node;
node *c,*t;
c->data = 10;
t->next = null;
*c = *t;
what is the effect of the last statement?
84. If you're familiar with the ? operator x ? y : z
you want to implement that in a function: int cond(int x, int y, int z); using only ~, !, ^, &, +, |, <<, >> no if statements, or loops or anything else, just those operators, and the function should correctly return y or z based on the value of x. You may use constants, but only 8 bit constants. You can cast all you want. You're not supposed to use extra variables, but in the end, it won't really matter, using vars just makes things cleaner. You should be able to reduce your solution to a single line in the end though that requires no extra vars.
85. You have an abstract computer, so just forget everything you know about computers, this one only does what I'm about to tell you it does. You can use as many variables as you need, there are no negative numbers, all numbers are integers. You do not know the size of the integers, they could be infinitely large, so you can't count on truncating at any point. There are NO comparisons allowed, no if statements or anything like that. There are only four operations you can do on a variable.
1) You can set a variable to 0.
2) You can set a variable = another variable.
3) You can increment a variable (only by 1), and it's a post increment.
4) You can loop. So, if you were to say loop(v1) and v1 = 10, your loop would execute 10 times, but the value in v1 wouldn't change so the first line in the loop can change value of v1 without changing the number of times you loop.
You need to do 3 things.
1) Write a function that decrements by 1.
2) Write a function that subtracts one variable from another.
3) Write a function that divides one variable by another.
4) See if you can implement all 3 using at most 4 variables. Meaning, you're not making function calls now, you're making macros. And at most you can have 4 variables. The restriction really only applies to divide, the other 2 are easy to do with 4 vars or less. Division on the other hand is dependent on the other 2 functions, so, if subtract requires 3 variables, then divide only has 1 variable left unchanged after a call to subtract. Basically, just make your function calls to decrement and subtract so you pass your vars in by reference, and you can't declare any new variables in a function, what you pass in is all it gets.
* 86. Under what circumstances can one delete an element from a singly linked list in constant time?
ANS. If the list is circular and there are no references to the nodes in the list from anywhere else! Just copy the contents of the next node and delete the next node. If the list is not circular, we can delete any but the last node using this idea. In that case, mark the last node as dummy!
* 87. Given a singly linked list, determine whether it contains a loop or not.
ANS. (a) Start reversing the list. If you reach the head, gotcha! there is a loop!
But this changes the list. So, reverse the list again.
(b) Maintain two pointers, initially pointing to the head. Advance one of them one node at a time. And the other one, two nodes at a time. If the latter overtakes the former at any time, there is a loop!
p1 = p2 = head;
do {
p1 = p1->next;
p2 = p2->next->next;
} while (p1 != p2);
88. Given a singly linked list, print out its contents in reverse order. Can you do it without using any extra space?
ANS. Start reversing the list. Do this again, printing the contents.
89. Given a binary tree with nodes, print out the values in pre-order/in-order/post-order without using any extra space.
90. Reverse a singly linked list recursively. The function prototype is node * reverse (node *) ;
ANS.
node * reverse (node * n)
{
node * m ;
if (! (n && n -> next))
return n ;
m = reverse (n -> next) ;
n -> next -> next = n ;
n -> next = NULL ;
return m ;
}
91. Given a singly linked list, find the middle of the list.
HINT. Use the single and double pointer jumping. Maintain two pointers, initially pointing to the head. Advance one of them one node at a time. And the other one, two nodes at a time. When the double reaches the end, the single is in the middle. This is not asymptotically faster but seems to take less steps than going through the list twice.
92. Reverse the bits of an unsigned integer.
ANS.
#define reverse(x) \
(x=x>>16|(0x0000ffff&x)<<16, \
x=(0xff00ff00&x)>>8|(0x00ff00ff&x)<<8, \
x=(0xf0f0f0f0&x)>>4|(0x0f0f0f0f&x)<<4, \
x=(0xcccccccc&x)>>2|(0x33333333&x)<<2, \
x=(0xaaaaaaaa&x)>>1|(0x55555555&x)<<1)
* 93. Compute the number of ones in an unsigned integer.
ANS.
#define count_ones(x) \
(x=(0xaaaaaaaa&x)>>1+(0x55555555&x), \
x=(0xcccccccc&x)>>2+(0x33333333&x), \
x=(0xf0f0f0f0&x)>>4+(0x0f0f0f0f&x), \
x=(0xff00ff00&x)>>8+(0x00ff00ff&x), \
x=x>>16+(0x0000ffff&x))
94. Compute the discrete log of an unsigned integer.
ANS.
#define discrete_log(h) \
(h=(h>>1)|(h>>2), \
h|=(h>>2), \
h|=(h>>4), \
h|=(h>>8), \
h|=(h>>16), \
h=(0xaaaaaaaa&h)>>1+(0x55555555&h), \
h=(0xcccccccc&h)>>2+(0x33333333&h), \
h=(0xf0f0f0f0&h)>>4+(0x0f0f0f0f&h), \
h=(0xff00ff00&h)>>8+(0x00ff00ff&h), \
h=(h>>16)+(0x0000ffff&h))
If I understand it right, log2(2) =1, log2(3)=1, log2(4)=2..... But this macro does not work out log2(0) which does not exist! How do you think it should be handled?
* 95. How do we test most simply if an unsigned integer is a power of two?
ANS. #define power_of_two(x) \ ((x)&&(~(x&(x-1))))
96. Set the highest significant bit of an unsigned integer to zero.
ANS. (from Denis Zabavchik) Set the highest significant bit of an unsigned integer to zero
#define zero_most_significant(h) \
(h&=(h>>1)|(h>>2), \
h|=(h>>2), \
h|=(h>>4), \
h|=(h>>8), \
h|=(h>>16))
97. Let f(k) = y where k is the y-th number in the increasing sequence of non-negative integers with the same number of ones in its binary representation as y, e.g. f(0) = 1, f(1) = 1, f(2) = 2, f(3) = 1, f(4) = 3, f(5) = 2, f(6)
= 3 and so on. Given k >= 0, compute f(k).
98. A character set has 1 and 2 byte characters. One byte characters have 0 as the first bit. You just keep accumulating the characters in a buffer. Suppose at some point the user types a backspace, how can you remove the character efficiently. (Note: You cant store the last character typed because the user can type in arbitrarily many backspaces)
99. What is the simples way to check if the sum of two unsigned integers has resulted in an overflow.
100. How do you represent an n-ary tree? Write a program to print the nodes of such a tree in breadth first order.
101. Write the 'tr' program of UNIX. Invoked as
tr -str1 -str2. It reads stdin and prints it out to stdout, replacing every occurance of str1[i] with str2[i].
e.g. tr -abc -xyz
to be and not to be <- input
to ye xnd not to ye <- output
发表于 2008-08-01 15:59 lostpencil 阅读(6051) | 评论 (29)编辑 收藏
2008年7月3日

起因:Python django web框架只能解析UTF-8的中文模板,于是我就建了html文件,用记事本打开,另存为UTF-8的形式。结果奇怪的问题就出现了,css文件布局网页的时候老是达不到预期的效果。

CSS也不太熟悉,一直以为是CSS理解错了,确认没有错后,还是没有改观,察看动态生成的网页的源码,也没有任何问题。打算放弃的时候,侥幸的保存了源码,然后用editplus打开,发现html文件开头多了一个问号(用微软的所有工具打开都没有这个问号)。

最近时间不多,就不罗嗦了:
类似WINDOWS自带的记事本等软件,在保存一个以UTF-8编码的文件时,会在文件开始的地方插入三个不可见的字符(0xEF 0xBB 0xBF,即BOM)。它是一串隐藏的字符,用于让记事本等编辑器识别这个文件是否以UTF-8编码。对于一般的文件,这样并不会产生什么麻烦。但对于Python或者PHP来说,BOM就是一个问题了。他们都不会忽略BOM, 然后在html文件的开头就多了那几个字符,editplus解析不了就显示成问号了,然后网页就不符合规范了,CSS的布局就有了问题,然后我就痛苦了。

我的解决办法:
最开始是自己写了个小程序把那串东西去掉了,后来发现原来UltraEdit支持无BOM的形式的保存........

真后悔最开始懒了,没有直接装linux服务器。

发表于 2008-07-03 08:13 lostpencil 阅读(2939) | 评论 (4)编辑 收藏
2008年5月6日

目的: 工作需要,从一个.P12或者pfx文件里面取得证书的内容,因为有个接口需要一个这样的证书字符串.

于是我这么写了:
 //取得服务器证书
 X509 *cert2;
 EVP_PKEY *pkey2=NULL;
 STACK_OF(X509) *server = NULL;
 BIO * in2 = BIO_new_file("server.pfx","rb");
 PKCS12 *p122 = d2i_PKCS12_bio(in2,NULL);
 PKCS12_parse(p122, "123456", &pkey2, &cert2, &server);
 *servercertLen = i2d_X509(cert2,&servercert);
 本来打算把servercert 和servercertLen作为证书字符串的衡量标准,传给那个接口,结果呢,TMD死活就是不对,servercert就是没有我要的东西.

反反复复的debug,找不到哪里出了问题,前面都是对的,就是到了最后一步servercert里面的东西就不对了,openssl的文档也被读烂了,啥也没说,有点想砸了电脑自杀了.

最后我就想啊想啊,因为知道openssl里面好多函数都是用宏实现的,是不是在i2d_X509里面改变了servercert的指向呢,虽然觉得比较荒唐,但是杨老师在他的COM系列文章里面讲过:有些看似不和规范和习惯的用法,在方方面面都有着运用的.

报着试试的态度在程序后面加了这么句:
servercert = servercert -*servercertLen;

结果TMD真的就好了,但是已经过了20个小时了.

罗嗦半天,要说的其实就是一句话: i2d_X509会改变第2个参数的指针,增加了一个证书内容的长度.

注:TMD是"甜蜜的"意思,不是说脏话,:)

发表于 2008-05-06 22:52 lostpencil 阅读(3322) | 评论 (3)编辑 收藏
2007年10月15日
起因:上研究生的表弟突然问我“你觉得你的付出和收获成正比吗?”

仔细想想,常常的郁闷也是因为心里不平衡吧。最后为了充过来人,我的回答是:
貌一看肯定是完全不成,但是仔细想想还是收获大于付出了
人和人竞争不光是100分的,你多付出的得到的是100分以外的东西
在100分以内,我们的3倍付出可能是1%的收获或者是0收获,拿你们考试来说也就是80分和81分的区别,但是有朝一日竞争需要考虑100分以外的东西了,你的优势就很明显了。
感觉工作也是,也许拼命了也不会涨工资或者得到肯定,但是总有一天还是会有回报的。毕竟工作一放松,整个人也就难紧张起来了。

发表于 2007-10-15 17:55 lostpencil 阅读(4582) | 评论 (6)编辑 收藏
2007年9月15日
起因:目前可以看到的所有介绍django的资料都是太详细,需要很久才能有一个整体的印象,本文意图是从整体上简单说下django的结构,方便学习者早点上手。

django是一个MVC(Model View Controller)模式的web开发框架。不过在这里它对应于MVC变成了MTV(Model Template View), Model主要是和数据库的表对应的,通过访问Model可以很容易的操作数据库;Template是不完全的html页面,它支持继承扩展等功能;View是一个控制器,也就是网站每个模块的逻辑部分。

一般网站的django结构(我一般画的图比较烂就不画图了):
主目录,都是创建工程时自动生成的一些东西,它包括如下东西:
  __init__.py   作用同于python模块内的init
  manage.py    一个脚本的接口,通过调用它对整个系统管理,增加一个模块,或者是手动更新数据库等等
  settings.py     在这里进行系统相关的设置
  urls.py           在这里用正则表达式的方式,将URL和View进行匹配。
一个关于结构的例子:比如你有一个简单的网站,有3个部分,一个是主页,一个是登陆,还有一个是产品。你首先创建一个主的project,然后可以在里面创建mainpage,login, product三个模块,通过主目录下面的urls.py将每个模块和相应的URL匹配。在每个模块下面会有自己的model和view.至于Template,你可以放在任何位置,只要在setting.py中指定好路径就可以了。

Model介绍
django通过Model文件直接帮定数据库的表,然后提供一系列的api对相应的Model对象操作,这样避免的自己写SQL语句,如果你不是数据库专家,它内部生成的SQL语句效率一般都比你写的高。 一个简单的例子:比如你想在数据库中建立一张表,你只需要在相应模块的models.py文件中加入,
from django.db import models

class xxxx(models.Model):
    name = models.CharField(maxlength=30)
    address = models.CharField(maxlength=50)
然后执行下脚本,就搞定了,然后你就可以通过这个class对象对数据库进行操作。

Template介绍
template实际就是一个html文件,但是不是一个完全合法html文件,它相当于c++里面的模板类,通过给他不同的参数,然后他就解析成不同的html文件,而且它也支持继承。一个Template B继承另一个Template A简单的说就是,B是A的扩展,可以在B中对A中的“block”处丰富化。template文件内的变量通过{{ xxx}}的方式定义,你只要在view.py中调用相应的函数给xxx指定值,就能得到一个完整的html文件。template也可以有逻辑控制,它通过{%  xxx  %}来定义,常见的逻辑控制都可以写在xxx的位置处。
{% for item in todo_list %}
    <p>{{ forloop.counter }}: {{ item }}</p>
{% endfor %}
(继承的例子比较占篇幅就不写了,反正到处都可以找到)

View介绍
view的作用就是接受一个request然后,对request进行处理,返回一个html页面或者是一个URL跳转等,主要就是根据网页的作用来编写逻辑处理了。一个例子:
from django.http import HttpResponse
import datetime

def current_datetime(request):
    now = datetime.datetime.now()
    html = "<html><body>It is now %s.</body></html>" % now
    return HttpResponse(html)
一个打印当前时间的小view.py文件,当然这里你想干什么都可以的,只要没有人K你,:)

其他说明
前面说的只是django的一个大体结构,实际上每个部分都有一些高级运用,还有一些Middleware (功能已经很全面了),Caching (提高效率的好帮手)等
。django的口号是,一个星期就能搞定一个大中型网站(个人感觉熟练的话肯定没有问题),如果想进一步了解的话上www.djangoproject.com和www.djangobook.com,国内目前也有一些人翻译了一些资料可以参考。
学习前提:了解网站的原理+了解python的基础知识。



发表于 2007-09-15 12:28 lostpencil 阅读(4253) | 评论 (3)编辑 收藏
2007年9月13日
起因:辞职到处奔波了几个月,服务器也挂了不短的时间,加上驱动问题笔记本装linux比较麻烦,总之是一直没有linux用,很是不方便。

解决方案:
step 1: 让DOS窗口支持常用的linux命令。
这里首选的当然是cygwin了,这类的东西不大,官网上都能下载,一般也就是名字后面+.org搞定。装好后在环境变量的path里面加入bin的路径,就可以轻松的在DOS窗口使用大多数常用的命令了,要是感觉DOS不爽,也可以直接敲bash启动bash,和linux的差别就更小了,当然你可能无法使用vi/vim等一些小工具,自己去淘了,然后加进去都可以用。

step 2: GCC组件的安装
可能我们不太习惯VS系列的产品,当然我觉得他们做的非常成功的,费用是一个问题,还有就是不熟的话大多数情况扮演了杀鸡的牛刀的角色。图简便的话就是MinGW算了,网速不行的话就自己下包一个个的整了,在线安装会比较慢,而且出问题也不好分析解决。这里不推荐dev-c++了,一个不太美观和科学的UI层严重影响了它的使用(个人看法)。

step 3: IDE的安装
IDE虽然不常用了,但是有时候还是需要的,感觉几年前除了VS,在windows下也没有什么太好的选择,前面说过dev-C++也不怎么欣赏,现在那就eclipse吧,总的来说eclipse的设计和实用性还是相当到位的,目前也运用的越来越广,特别是java社群。当然它目前已经不在是一个简单的java的开发工具了,比如你想支持c/C++只要去当一个CDT,解压后将插件和特性的东西加到eclipse下对应的目录就可以了。eclipse主页也有直接打包好的东西可以用,当然它的运行需要jdk的支持,你也需要配置一些环境变量,都很简单的,网上文章比较多。顺便说一下其实eclipse插件开发是一件很有意思,也比较高效的事情,这玩艺应该很有前途吧。

现在我的windows就一个开发人员的日常使用来说已经和linux没有什么区别了,不过没有少折腾,大的方面也就这么几块吧,呵呵
发表于 2007-09-13 00:55 lostpencil 阅读(4307) | 评论 (8)编辑 收藏
2007年8月30日
题目:数据库里面有一个表如下
a(int) | b(int)
      1|       2
      3|       4
      5|       6
..................
希望根据该表生成一个新表如下
c(int)






......
要求:
1数据量很大,对效率要求比较高,希望用批处理的方式搞定
2对空间没有要求,允许创建中间表甚至是物理表

解答:
1 取出a列,加一个id列,生成中间表c1,id列为1开头步长为2的整数,也就是1 3 5 7......

2 同样取出b列,加一个id列,生成中间表c2, 2开头步长是2的整数,也就是2 4 6 8......

3 合并c1,c2为c

点评:没有太大的新意,软件开发灵感很重要吧
发表于 2007-08-30 04:38 lostpencil 阅读(5278) | 评论 (5)编辑 收藏