ASPECT ORIENTED PROGRAMMING IN.NET. BASED ON ATTRIBUTES

合集下载

AOP

AOP
),元数据就是在静态或是运 (4)元数据(metadata),元数据就是在静态或是运 )元数据( ), 行的时间绑定到一个类的附加信息,更强大的一方面, 行的时间绑定到一个类的附加信息,更强大的一方面, 能够动态的绑定元数据到一个给定的对象实例. 能够动态的绑定元数据到一个给定的对象实例.当我 们在编写能够应用任何对象的一般方面时, 们在编写能够应用任何对象的一般方面时,而逻辑需 要知道制定类的信息时,元数据就显得非常强大. 要知道制定类的信息时,元数据就显得非常强大.
AOP实现方式
1 横切点实现方式
AOP中横切关注点的实现方式是这样的, 中横切关注点的实现方式是这样的, 中横切关注点的实现方式是这样的 函数是advice 实现并封装在 实现并封装在Aspect中,编 函数是 中 织器将advice的调用语句无缝的织入到其它 织器将 的调用语句无缝的织入到其它 的模块中.编程者只需要在aspect中通过 的模块中.编程者只需要在 中通过 pointcut- designator定义需要织入的位 定义需要织入的位 以及定义advice的功能,剩下就让编织 的功能, 置,以及定义 的功能 器来完成就可以了. 器来完成就可以了 2 AspectJ的编织器的实现方式 的编织器的实现方式 目前, 的实现方式主要有两种: 目前,AOP的实现方式主要有两种:动态织 的实现方式主要有两种 入和静态织入. 入和静态织入.
AOP背景
AOP设计并不是万能的,它是在oop设计的发 设计并不是万能的,它是在 设计并不是万能的 设计的发 展过程中诞生的, 认为: 展过程中诞生的,Gregor Kiczales 认为:"我们 并没有也不想把一切推倒重来, 并没有也不想把一切推倒重来,我们提供的只是一种 15%的解决方案".通过对比 的解决方案" 通过对比AOP和OOP的技术实 的解决方案 和 的技术实 在对象之间的横向连接不是很频繁的情况下, 现,在对象之间的横向连接不是很频繁的情况下, AOP并不比 并不比OOP有多大的优势,所以,AOP 是对 有多大的优势, 并不比 有多大的优势 所以, OOP在某些应用场合的补充.AOP就是分离横切关注 在某些应用场合的补充. 在某些应用场合的补充 就是分离横切关注 点来实现软件的模块之间的松散耦合, 点来实现软件的模块之间的松散耦合,从而提高软件 的可维护性和可复用性. 的可维护性和可复用性.

Java语言程序设计基础篇英文版第十版课程设计

Java语言程序设计基础篇英文版第十版课程设计

Java Programming Fundamentals, 10th Edition CourseDesign (English Version)IntroductionJava Programming Fundamentals is a comprehensive course that covers the basic concepts and principles of Java programming. In this course, students will learn to design, code, and test Java programs while developing a strong foundation in programming logic and object-oriented programming concepts. This course is designed for students who are new to programming and want to learn Java programming from scratch.Course ObjectivesThe mn objective of this course is to provide students with a solid foundation in programming using the Java language. Upon completion of this course, students will be able to:•Understand the basic syntax and structure of the Java programming language•Design, code, and test simple Java programs•Use decision structures and loops in Java programming•Work with arrays and arraylists•Understand object-oriented programming concepts•Implement inheritance and polymorphism in Java programming•Understand Java class libraries and use them in Java programming•Develop event-driven programs using graphical user interfacesCourse OutlineThe course is divided into several chapters, each covering adifferent aspect of Java programming fundamentals. The following is a detled outline of the course:Chapter 1: Getting Started with Java•Introduction to Java programming language•Understanding the basic structure of a Java program•Writing and running a Java program•Understanding variables, data types, and constants•Basic Input/Output operationsChapter 2: Control Structures•Understanding decision structures•Using if statement, if-else statement, and nested if statements•Understanding loops and using while, do-while, and for loops•Understanding break and continue statements•Using switch statementChapter 3: Arrays and Arraylists•Understanding arrays•Declaring and initializing arrays•Multidimensional arrays•Understanding arraylist•Using arraylist class methodsChapter 4: Object-Oriented Programming Concepts•Introduction to object-oriented programming•Understanding classes and objects•Encapsulation: Access modifiers, getters, and setters•Constructors and overloading•Methods and method overloadingChapter 5: Inheritance and Polymorphism•Understanding inheritance•Using superclass and subclass•Polymorphism: Method overloading and overriding•Casting objects•Abstract classes and interfacesChapter 6: Java Class Libraries•Understanding Java class libraries•Using the String class•Using the Math class•Using the Date class•Using the File classChapter 7: Graphical User Interfaces•Understanding event-driven programming•Using the Swing library•Designing a user interface using JFrame, JDialog, and JPanel •Using event listeners•Designing a GUI-based applicationCourse Requirements•Basic computer skills•Basic understanding of programming concepts is helpful but not required•Java Development Kit (JDK) version 8 or later•Integrated Development Environment (IDE) such as Eclipse or NetBeansGrading PolicyThe final grade for this course will be calculated based on the following components:•Assignments (50%)•Midterm Exam (20%)•Final Exam (30%)ConclusionJava Programming Fundamentals, 10th Edition course is designed to provide students with a solid foundation in Java programming language and object-oriented programming concepts. By the end of this course, students will be able to write simple Java programs, use decision constructs and loops, work with arrays and arraylists, implement inheritance and polymorphism, understand Java class libraries, and develop graphical user interfaces. This course is intended for anyone who is interested in learning Java programming from scratch.。

面向方面(aspect)的程序设计方法

面向方面(aspect)的程序设计方法

面向方面(aspect)的程序设计方法程虎摘要 面向方面的程序设计(Aspect—Oriented Programming, AOP)是一种很有前途的新型程序设计方法,它是面向过程、面向对象方法的进一步发展。

通过引入方面概念,改进关注点的分离(separation of concerns),减少代码缠结(code tangling)解决横切关注点(cross cutting concerns)的问题,提高软件质量和效率。

自1997年AOP以来的7年间,全球已开展大量有关研究与开发工作,并自2002年起每年召开专门的国际学术会议(International conf .on Aspect-Oriented Software Development,AOSD)探讨问题,交流取得的成果。

关键词 方面,面向方面的程序设计(AOP),关注点,横切关注点,面向方面的软件开发(AOSD)。

1引言计算机软件包括程序及其文档。

程序设计包括设计、编制和调试程序的方法与过程。

程序设计方法涉及用于指导程序设计工作的原理和原则,以及基于这些原理和原则的设计方法和技术。

数十年来,经历公式翻译、过程式程序设计、结构化程序设计、逻辑式程序设计、函数式程序设计以及面向对象程序设计等。

程序设计方法学可以对程序设计人员选用具体的程序设计方法起指导作用,而具体的程序设计方法对象程序设计工作的质量以及所设计出来的程序(即软件)的质量影响巨大。

世间事物总是在不断发展变化,螺旋式上升。

程序设计方法也如此,近年来流行面向对象程序设计方法。

面向对象的方法起源于面向对象的编程语言,可以追溯到20世纪60年代后期的Simula67语言。

到20世纪末,面向对象方法已逐步发展成为一类完整的方法学和系统化的技术体系。

它不仅指导编程设计,还指导开发操作系统、数据库、网络和编译系统等。

使用面向对象语言来实现面向对象设计相对而言比较容易,用非面向对象语言也可实现面向对象设计。

面向方面编程中必要语义约束的研究

面向方面编程中必要语义约束的研究

面向方面编程中必要语义约束的研究1杨剑青,杨宗源,谢瑾奎华东师范大学计算机科学技术系,上海 (200062)E-mail:learwwj@摘要:面向方面编程(AOP)可以很好地解决非功能性关注点(Non-Functional Concern)的封装问题,但是目前的AOP技术过于灵活,甚至会不恰当地破坏原有对象的封装性,以及代码正确性。

本文讨论了在软件设计或者编程实现过程中,对于AOP应该加以适当约束,具体包括常量性质的约束,单件(Singleton)类型的约束等等,在各个不同的具体应用领域中,还可以相应有不同的约束,通过这些约束,AOP才能更好地为软件开发所服务。

关键词:AOP;约束;软件开发;软件工程中图分类号:TP3111.引言面向方面编程(Aspect Oriented Programming,以下称为AOP)可以用来解决软件开发中,对于系统级关注点实现的代码纠缠和难以管理等问题。

但是对其任意使用可能在某些情况下,造成对原有面向对象模型语义的破坏,本文提出了在现有的AOP实现机制上,添加适当的约束来解决这一问题,并且刻画出了所提出约束的设计模式。

2.AOP简介面向对象方法已经在软件工业界取得了巨大的成功。

面向对象方法通过把不同大小级别的功能单元封装在类中,来提高软件的开发效率。

但是,对于一些系统级别的,非功能性的关注点(Non-Functional Concern),比如操作同步,资源的互斥,数据加密解密,数据的压缩解压缩等等,面向对象技术的解决方案却会引入一系列的问题,比如代码纠缠(Code Tangling)和难以管理[2]。

所谓代码纠缠,就是指相同的代码反复地出现在不同的类中,而没有办法使用面向对象方法(比如继承)加以消除;而难以管理主要指的是面向对象技术只提供了封装功能关注点的单元,而没有提供封装横切关注点(Cross-Cutting Concern)的单元,导致这些关注点的修改十分困难。

基于ASP_NET的MVC框架的应用研究

基于ASP_NET的MVC框架的应用研究
MVC 的缺点是由于它没有明确的定义,所以完全理解 MVC 并不是很容易。使用 MVC 需要精心的计划,由于它的内部原理比较 复杂,所以需要花费一些时间去思考。 根据开发者经验,由于开发者将一个应用程序分成了三个部件,所以使用 MVC 同时也意味着 将要管理比以前更多的文件。MVC 并不适合小型甚至中等规模的应用程序,花费大量时间将 MVC 应用到规模并不是很大的应用程 序通常会得不偿失。
就是说模型与数据格式无关,这样一个模型能为多个视图提供数据。 由于应用于模型的代码只需写一次就可以被多个视图重用,所
以减少了代码的重复性。
2.2 View 角色
即视图角色,根据 Model 数据进行内容展示的组件,是用户看到并与之交互的界面。 对老式的 Web 应用程序来说,视图就是由 HTML 元素组成的界面,在新式的 Web 应用程 序 中 ,HTML 依 旧 在 视 图 中 扮 演 着 重 要 的 角 色 ,但 一 些 新 的 技 术 已 层 出 不 穷 ,它 们 包 括 Macromedia Flash 和像 XHTML,XML/XSL,WML 等一些标识语言和 Web services 等, 因此如何处理应用程序的界面变 得 越 来 越 有挑战性。MVC 一个的优点是能为应用程序处理很多不同的视图。在视图中其实没有真正的处理发生,不管这些数据是联机存储的 还是一个雇员列表,作为视图来讲,它只是作为一种输出数据并允许用户操纵的方式。
第 5 卷第 7 期 (2009 年 3 月)
成用户的需求。所以当单击 Web 页面中的超链接和发送 HTML 表单时,控制器本身不输出任何东西和做任何处理。它只是接收请求 并决定调用哪个模型构件去处理请求,然后确定用哪个视图来显示模型处理返回的数据。
2.4 优缺点分析

计算机专业英语考试试题及答案

计算机专业英语考试试题及答案

计算机专业英语考试试题及答案一、选择题1. Which of the following is NOT a programming language?A. JavaB. PythonC. HTMLD. CSS2. What does the acronym "SQL" stand for?A. Structured Query LanguageB. Simple Query LanguageC. Script Query LanguageD. Secure Query Language3. Which protocol is commonly used for sending and receiving emails?A. FTPB. HTTPC. SMTPD. TCP4. What does the term "CPU" refer to?A. Central Processing UnitB. Computer Processing UnitC. Central Program UnitD. Computer Program Unit5. Which of the following is NOT a type of network topology?A. StarB. RingC. MeshD. Scroll二、填空题1. HTML stands for Hypertext Markup Language, which is used for ____________.2. The process of converting source code into machine code is called ____________.3. IP address stands for ____________.4. The act of copying files from a remote server to a local computer is known as ____________.5. The programming language developed by Apple Inc. for iOS and macOS is ____________.三、简答题1. What is the difference between a compiler and an interpreter? Provide examples of programming languages that use each of these methods.2. Explain the concept of object-oriented programming (OOP) and provide an example of a programming language that utilizes this paradigm.3. Describe the client-server model and provide an example of a commonly used protocol within this model.四、论述题Discuss the impact of artificial intelligence (AI) on various industries. Provide examples of how AI is being used in fields such as healthcare, finance, and transportation. Analyze the potential benefits and challenges of implementing AI in these industries.答案:一、选择题1. C. HTML2. A. Structured Query Language3. C. SMTP4. A. Central Processing Unit5. D. Scroll二、填空题1. creating and structuring the content of a webpage2. compilation3. Internet Protocol4. downloading5. Swift三、简答题1. A compiler translates the entire source code into machine code before the program is executed. Examples of languages that use compilers are C, C++, and Java. On the other hand, an interpreter translates and executes the source code line by line. Python and Ruby are examples of languages that use interpreters.2. Object-oriented programming (OOP) is a programming paradigm that organizes data and functions into reusable objects. It focuses on the concept of classes and objects, allowing for code reuse and encapsulation. An example of a programming language that uses OOP is Java, where objects are instances of classes and can interact with each other through methods and attributes.3. The client-server model is a distributed computing architecture wherea server provides services or resources to multiple clients. The clients request and receive these resources through the network. An example of a commonly used protocol within this model is the Hypertext Transfer Protocol (HTTP), which is used for communication between web browsers (clients) and web servers.四、论述题Artificial intelligence (AI) has had a significant impact on various industries. In healthcare, AI is being used for diagnoses and treatments, analyzing medical images, and personalized medicine. For example, AI-powered algorithms can help detect diseases like cancer at an early stage, leading to better treatment outcomes. In finance, AI is utilized for fraud detection, algorithmic trading, and customer service. AI algorithms can analyze large amounts of financial data to identify patterns and make accurate predictions. In transportation, AI is being employed for autonomous vehicles, traffic management, and logistics optimization. Self-driving cars, for instance, use AI algorithms to navigate and make decisions on the road.The implementation of AI in these industries brings about many benefits, such as increased efficiency, improved accuracy, and cost savings. AI systems can process and analyze vast amounts of data much faster than humans, leading to faster and more accurate results. However, there are also challenges to consider. Privacy and security concerns arise as AI systems handle sensitive information. There is also the worry of job displacement, as AI automation may replace certain human tasks. Additionally, ethical considerations need to be addressed, such as bias in algorithms and the potential for AI to be used for malicious purposes.Overall, the impact of AI on various industries is undeniable. It has the potential to revolutionize healthcare, finance, transportation, and many other sectors. However, careful implementation and regulation are necessary to ensure its responsible and beneficial use.。

计算机专业英语 考试

计算机专业英语 考试

一、选择题1.What is the process of converting a high-level programming language into machine languagecalled?A.Debuggingpilation(正确答案)C.ExecutionD.Interpretation2.Which of the following is a programming paradigm that organizes software design around data,and the operations performed on that data?A.Object-oriented programming(正确答案)B.Procedural programmingC.Functional programmingD.Event-driven programming3.In computer networks, what does the term "protocol" refer to?A. A set of rules governing the exchange of information between devices(正确答案)B.The physical connection between devicesC.The speed of data transmissionD.The type of data being transmitted4.What is the term used to describe the process of dividing a complex problem into smaller, moremanageable parts?A.Modularization(正确答案)B.OptimizationC.EncapsulationD.Polymorphism5.In computer security, what is the term for unauthorized access to or modification of data?A.EncryptionB.DecryptionC.Hacking(正确答案)D.Firewall6.Which of the following is a type of software that allows two or more computers tocommunicate and share resources?A.Operating systemB.Database management systemwork operating system(正确答案)D.Word processing software7.What is the term used to describe the process of identifying and correcting errors in computerprograms?A.Debugging(正确答案)B.TestingC.Codingpilation8.In computer graphics, what is the term for the number of distinct pixels that can be displayedon a screen?A.Resolution(正确答案)B.Color depthC.Refresh rateD.Aspect ratio。

Spring的web框架-外文翻译

Spring的web框架-外文翻译

英文原文Spring contains a lot of functionality and features, which are well-organized in seven modules shown in the diagram below. This section discusses each the of modules in turn.The Core package is the most fundamental part of the framework and provides the Dependency Injection features allowing you to manage bean container functionality. The basic concept here is the BeanFactory, which provides a factory pattern removing the need for programmatic singletons and allowing you to decouple the configuration and specification of dependencies from your actual program logic.On top of the Core package sits the Context package, providing a way to access beans in a framework-style manner, somewhat resembling a JNDI-registry. The context package inherits its features from the beans package and adds support for text messaging using e.g. resource bundles, event-propagation, resource-loading and transparent creation of contexts by, for example, a servlet container.The DAO package provides a JDBC-abstraction layer that removes the need to do tedious JDBC coding and parsing of database-vendor specific error codes. Also, the JDBC package provides a way to do programmatic as well as declarative transaction management, not only for classes implementing special interfaces, but for all your POJOs (plain old java objects).The ORM package provides integration layers for popular object-relational mapping APIs, including JDO, Hibernate and iBatis. Using the ORM package you can use all those O/R-mappers in combination with all the other features Spring offers, like simple declarative transaction management mentioned before.Spring's AOP package provides an AOP Alliance compliant aspect-oriented programming implementation allowing you to define, for example, method-interceptors and pointcuts to cleanly decouple code implementing functionality that should logically speaking be separated. Using source-level metadata functionality you can incorporate all kinds of behavioral information into your code, a little like .NET attributes.Spring's Web package provides basic web-oriented integration features, such as multipart functionality, initialization of contexts using servlet listeners and a web-oriented application context. When using Spring together with WebWork or Struts, this is the package to integrate with.Spring's Web MVC package provides a Model-View-Controller implementation for web-applications. Spring's MVC implementation is not just any implementation, it provides a clean separation between domain model code and web forms and allows you to use all the other features of the Spring Framework like validation.Spring's web MVC framework is designed around a DispatcherServlet that dispatches requests to handlers, with configurable handler mappings, view resolution, locale and theme resolution as well as support for upload files. The default handler is a very simple Controller interface, just offering a ModelAndView handleRequest(request,response) method. This can already be used for application controllers, but you will prefer the included implementation hierarchy, consisting of, for example AbstractController, AbstractCommandController and SimpleFormController. Application controllers will typically be subclasses of those. Note that youcan choose an appropriate base class: If you don't have a form, you don't need a FormController. This is a major difference to Struts.You can use any object as a command or form object -there's no need to implement an interface or derive from a base class. Spring's data binding is highly flexible, for example, it treats type mismatches as validation errors that can be evaluated by the application, not as system errors. So you don't need to duplicate your business objects' properties as Strings in your form objects, just to be able to handle invalid submissions, or to convert the Strings properly. Instead, it is often preferable to bind directly to your business objects. This is another major difference to Struts which is built around required base classes like Action and ActionForm - for every type of action.Compared to WebWork, Spring has more differentiated object roles. It supports the notion of a Controller, an optional command or form object, and a model that gets passed to the view. The model will normally include the command or form object but also arbitrary reference data. Instead, a WebWork Action combines all those roles into one single object. WebWork does allow you to use existing business objects as part of your form, but only by making them bean properties of the respective Action class. Finally, the same Action instance that handles the request is used for evaluation and form population in the view. Thus, reference data needs to be modeled as bean properties of the Action too. These are arguably too many roles for one object.Spring's view resolution is extremely flexible. A Controller implementation can even write a view directly to the response, returning null as ModelAndView. In the normal case, a ModelAndView instance consists of a view name and a model Map, containing bean names and corresponding objects (like a command or form, containing reference data). View name resolution is highly configurable, either via bean names, via a properties file, or via your own ViewResolver implementation. The abstract model Map allows for complete abstraction of the view technology, without any hassle. Any renderer can be integrated directly, whether JSP, V elocity, or any other rendering technology. The model Map is simply transformed into an appropriate format, such as JSP request attributes or a Velocity template model..Pluggability of other MVC implementationsThere are several reasons why some projects will prefer to use other MVC implementations. Many teams expect to leverage their existing investment in skills and tools. In addition, there is a large body of knowledge and experience avalailable for the Struts framework. Thus, if you can live with Struts' architectural flaws, it can still be a viable choice for the web layer. The same applies to WebWork and other web MVC frameworks.If you don't want to use Spring's web MVC, but intend to leverage other solutions that Spring offers, you can integrate the web MVC framework of your choice with Spring easily. Simply start up a Spring root application context via its ContextLoaderListener, and access it via its ServletContext attribute (or Spring's respective helper method) from within a Struts or WebWork action. Note that there aren't any "plugins" involved, so no dedicated integration is necessary. From the web layer's point of view, you'll simply use Spring as a library, with the root application context instance as the entry point.All your registered beans and all of Spring's services can be at your fingertips even withoutSpring's web MVC. Spring doesn't compete with Struts or WebWork in this scenario, it just addresses the many areas that the pure web MVC frameworks don't, from bean configuration to data access and transaction handling. So you are able to enrich your application with a Spring middle tier and/or data access tier, even if you just want to use, for example, the transaction abstraction with JDBC or Hibernate.Features of Spring MVCSpring's web module provides a wealth of unique web support features, including:Clear separation of roles - controller, validator, command object, form object, model object, DispatcherServlet, handler mapping, view resolver, etc. Each role can be fulfilled by a specialized object.Powerful and straightforward configuration of both framework and application classes as JavaBeans, including easy referencing across contexts, such as from web controllers to business objects and validators.Adaptability, non-intrusiveness. Use whatever controller subclass you need (plain, command, form, wizard, multi-action, or a custom one) for a given scenario instead of deriving from a single controller for everything.Reusable business code - no need for duplication. You can use existing business objects as command or form objects instead of mirroring them in order to extend a particular framework base class.Customizable binding and validation - type mismatches as application-level validation errors that keep the offending value, localized date and number binding, etc instead of String-only form objects with manual parsing and conversion to business objects.Customizable handler mapping and view resolution - handler mapping and view resolution strategies range from simple URL-based configuration, to sophisticated, purpose-built resolution strategies. This is more flexible than some web MVC frameworks which mandate a particular technique.Flexible model transfer - model transfer via a name/value Map supports easy integration with any view technology.Customizable locale and theme resolution, support for JSPs with or without Spring tag library, support for JSTL, support for Velocity without the need for extra bridges, etc.A simple but powerful tag library that avoids HTML generation at any cost, allowing for maximum flexibility in terms of markup code.Data Access using O/R MappersSpring provides integration with Hibernate, JDO, Oracle TopLink, Apache OJB and iBATIS SQL Maps: in terms of resource management, DAO implementation support, and transaction strategies. For example for Hibernate, there is first-class support with lots of IoC convenience features, addressing many typical Hibernate integration issues. All of these support packages for O/R mappers comply with Spring's generic transaction and DAO exception hierarchies. There are usually two integration styles: either using Spring's DAO 'templates' or coding DAOs against plain Hibernate/JDO/TopLink/etc APIs. In both cases, DAOs can be configured through DependencyInjection and participate in Spring's resource and transaction management.Spring's adds significant support when using the O/R mapping layer of your choice to create data access applications. First of all, you should know that once you started using Spring's support for O/R mapping, you don't have to go all the way. No matter to what extent, you're invited to review and leverage the Spring approach, before deciding to take the effort and risk of building a similar infrastructure in-house. Much of the O/R mapping support, no matter what technology you're using may be used in a library style, as everything is designed as a set of reusable JavaBeans. Usage inside an ApplicationContext does provide additional benefits in terms of ease of configuration and deployment; as such, most examples in this section show configuration inside an ApplicationContext.Some of the the benefits of using Spring to create your O/R mapping DAOs include:Ease of testing. Spring's inversion of control approach makes it easy to swap the implementations and config locations of Hibernate SessionFactory instances, JDBC DataSources, transaction managers, and mapper object implementations (if needed). This makes it much easier to isolate and test each piece of persistence-related code in isolation.Common data access exceptions.Spring can wrap exceptions from you O/R mapping tool of choice, converting them from proprietary (potentially checked) exceptions to a common runtime DataAccessException hierarchy. This allows you to handle most persistence exceptions, which are non-recoverable, only in the appropriate layers, without annoying boilerplate catches/throws, and exception declarations. You can still trap and handle exceptions anywhere you need to. Remember that JDBC exceptions (including DB specific dialects) are also converted to the same hierarchy, meaning that you can perform some operations with JDBC within a consistent programming model.General resource management. Spring application contexts can handle the location and configuration of Hibernate SessionFactory instances, JDBC DataSources, iBATIS SQL Maps configuration objects, and other related resources. This makes these values easy to manage and change. Spring offers efficient, easy and safe handling of persistence resources. For example: Related code using Hibernate generally needs to use the same Hibernate Session for efficiency and proper transaction handling. Spring makes it easy to transparently create and bind a Session to the current thread, either by using an explicit 'template' wrapper class at the Java code level or by exposing a current Session through the Hibernate SessionFactory (for DAOs based on plain Hibernate3 API). Thus Spring solves many of the issues that repeatedly arise from typical Hibernate usage, for any transaction environment (local or JTA).Integrated transaction management. Spring allows you to wrap your O/R mapping code with either a declarative, AOP style method interceptor, or an explicit 'template' wrapper class at the Java code level. In either case, transaction semantics are handled for you, and proper transaction handling (rollback, etc) in case of exceptions is taken care of. As discussed below, you also get the benefit of being able to use and swap various transaction managers, without your Hibernate/JDO related code being affected: for example, between local transactions and JTA, with the same full services (such as declarative transactions) available in both scenarios. As an additional benefit,JDBC-related code can fully integrate transactionally with the code you use to do O/R mapping. This is useful for data access that's not suitable for O/R mapping, such as batch processing or streaming of BLOBs, which still needs to share common transactions with O/R mapping operations.To avoid vendor lock-in, and allow mix-and-match implementation strategies. While Hibernate is powerful, flexible, open source and free, it still uses a proprietary API. Furthermore one could argue that iBA TIS is a bit lightweight, although it's excellent for use in application that don't require complex O/R mapping strategies. Given the choice, it's usually desirable to implement major application functionality using standard or abstracted APIs, in case you need to switch to another implementation for reasons of functionality, performance, or any other concerns. For example, Spring's abstraction of Hibernate transactions and exceptions, along with its IoC approach which allows you to easily swap in mapper/DAO objects implementing data access functionality, makes it easy to isolate all Hibernate-specific code in one area of your application, without sacrificing any of the power of Hibernate. Higher level service code dealing with the DAOs has no need to know anything about their implementation. This approach has the additional benefit of making it easy to intentionally implement data access with a mix-and-match approach (i.e. some data access performed using Hibernate, and some using JDBC, others using iBATIS) in a non-intrusive fashion, potentially providing great benefits in terms of continuing to use legacy code or leveraging the strength of each technology.The Spring transaction abstractionSpring provides a consistent abstraction for transaction management. This abstraction is one of the most important of Spring's abstractions, and delivers the following benefits: Provides a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, iBA TIS Database Layer and JDO.Provides a simpler, easier to use, API for programmatic transaction management than most of these transaction APIsIntegrates with the Spring data access abstractionSupports Spring declarative transaction managementTraditionally, J2EE developers have had two choices for transaction management: to use global or local transactions. Global transactions are managed by the application server, using JTA. Local transactions are resource-specific: for example, a transaction associated with a JDBC connection. This choice had profound implications. Global transactions provide the ability to work with multiple transactional resources. (It's worth noting that most applications use a single transaction resource) With local transactions, the application server is not involved in transaction management, and cannot help ensure correctness across multiple resources.Global transactions have a significant downside. Code needs to use JTA: a cumbersome API to use (partly due to its exception model). Furthermore, a JTA UserTransaction normally needs to be obtained from JNDI: meaning that we need to use both JNDI and JTA to use JTA. Obviously all use of global transactions limits the reusability of application code, as JTA is normally only available in an application server environment.The preferred way to use global transactions was via EJB CMT (Container Managed Transaction): a form of declarative transaction management (as distinguished from programmatic transaction management). EJB CMT removes the need for transaction-related JNDI lookups--although of course the use of EJB itself necessitates the use of JNDI. It removes most--not all--need to write Java code to control transactions. The significant downside is that CMT is (obviously) tied to JTA and an application server environment; and that it's only available if we choose to implement business logic in EJBs, or at least behind a transactional EJB facade. The negatives around EJB in general are so great that this is not an attractive proposition, when there are alternatives for declarative transaction management.Local transactions may be easier to use, but also have significant disadvantages: They cannot work across multiple transactional resources, and tend to invade the programming model. For example, code that manages transactions using a JDBC connection cannot run within a global JTA transaction.Spring resolves these problems. It enables application developers to use a consistent programming model in any environment. You write your code once, and it can benefit from different transaction management strategies in different environments. Spring provides both declarative and programmatic transaction management. Declarative transaction management is preferred by most users, and recommended in most cases.With programmatic transaction management developers work with the Spring transaction abstraction, which can run over any underlying transaction infrastructure. With the preferred declarative model developers typically write little or no code related to transaction management, and hence don't depend on Spring's or any other transaction API.中文译文Core包是框架的最基础部分,并提供依赖注入(Dependency Injection)特性来使你可管理Bean容器功能。

车辆路径问题概念模型与算法五星推荐

车辆路径问题概念模型与算法五星推荐
CVRP的描述:设某中心车场有k辆车,每辆配送车的最 大载重量Q,需要对n个客户(节点)进行运输配送,每辆 车从中心车场出发给若干个客户送货,最终回到中心 车场,客户点i的货物需求量是qi (i=1,2,…,n),且qi<Q。 记配送中心编号为0,各客户编号为i(i=1,2 ,…,n), cij表 示客户i到客户j的距离。求满足车辆数最小,车辆行驶 总路程最短的运送方案。
模拟退火算法(Simulated Annealing)
模拟退火算法来源于固体退火原理,将固体加温至充 分高,再让其徐徐冷却,加温时,固体内部粒子随温
升变为无序状,内能增大,而徐徐冷却时粒子渐趋有
序,在每个温度都达到平衡态,最后在常温时达到基 态,内能减为最小。根据Metropolis准则,粒子在温度 T时趋于平衡的概率为e(-ΔE/(kT)),其中E为温度T时的 内能,ΔE为其改变量,k为Boltzmann常数。用固体退 火模拟组合优化问题,将内能E模拟为目标函数值f,温 度T演化成控制参数t,即得到解组合优化问题的模拟退 火算法:由初始解i和控制参数初值t开始,对当前解重 复“产生新解→计算目标函数差→接受或舍弃”的迭代, 并逐步衰减t值,算法终止时的当前解即为所得近似最 优解,这是基于蒙特卡罗迭代求解法的一种启发式随
总的说来,精确性算法基于严格的数学手段,在可以 求解的情况下,其解通常要优于人工智能算法。但由
于引入严格的数学方法,计算量一般随问题规模的增
大呈指数增长,因而无法避开指数爆炸问题,从而使 该类算法只能有效求解中小规模的确定性VRP,并且通 常这些算法都是针对某一特定问题设计的,适用能力较 差,因此在实际中其应用范围很有限。
(5) 相容性约束:引出相容性约束车辆路径问题 (VehicleRouting Problem with Compatibility Constraints, VRPCC)。

计算机专业英语(5)

计算机专业英语(5)

CoUnit 5 Programming Language·59·conversation.Jerry: Please have a seat, Tom. Tom: Thanks.Jerry: Well, Tom, what kind of education have you got?Tom: I studied computer science in Zhejiang University, and got a B. S. degree. Jerry: OK, what specialized courses did you take?Tom: The specialized courses I completed include computer science, operation systems, Java, OOA&OOD, software engineering, etc.Jerry: What kind of experience have you got for the job? Tom: I've been a computer programmer for more than two years. Jerry: What kind of software do you have a good command of? Tom: 、JS and Photoshop, etc. Jerry: Well, can you start next Monday? Tom: Sure.Jerry: That’s settled then.TASK II TEXT AIntroduction to ProgrammingLanguageFigure 5.1 Types of Programming Language计算机专业英语·60·instruction[in5strQkFEn ] n . 指令 symbolic[sim5bClik ] adj . 象征的,象征性的assembly language 汇编语言variable[5vAriEbl ] n . 变量higher-level language 高级语言 compiler[kEm5pailE ] n . 编译器abstract[5AbstrAkt ] adj . 抽象的 execution[7eksi5kju:FEn ] n . 执行source code 源代码utility[ju5tiliti ] n . 实用text editor 文本编辑器 notation[nEu5teiFEn ] n . 记号, 标记A programming language is a language used to write instructions for the computer. It lets the programmer express data processing in a symbolic manner without regard to machine-specific details.The difficulty of writing programs in the machine language of 0s and 1s led first to the development of assembly language , which allows programmers to use mnemonics for instructions and symbols for variables . Such programs are then translated by a program known as an assembler into the binary encoding used by the computer.Assembly language was found to be sufficiently inconvenient that higher-level languages (closer to natural languages) were invented in the 1950s for easier, faster programming; along with them came the need for compilers , programs that translate high-level language programs into machine code (See Figure 5.1).As programming languages became more powerful and abstract , building efficient compilers that create high-quality code in terms of execution speed and storage consumption became an interesting computer science problem in itself.A compiler is a computer program that translates source code into object code. Software engineers write source code using high-level programming languages that people can understand. Computers can’t directly execute source code, but need a compiler to translate these instructions into a low-level language called machine code.Software designers create new programs by using special applications programs, often called utility programs or development programs. A programmer uses another type of program called a text editor to write the new program in a special notation called a programming language. With the text editor, the programmer creates a text file, which is an ordered list of instructions, also called the program source file. The individual instructions that make up the program source file are called source code. At this point, a special applications program translates the source code into machine language, or object code —a format that the operating system will recognize as aUnit 5 Programming Language·61·set[set ] n . 集合separately[5sepEritli ] adv .分别地,单独地debugger[di:5bQ^E ] n . 调试器 detect[di5tekt ] v . 检测intermediate[7intE5mi:djEt ] adj .中间的interpreter[in5tE:pritE ] n . 解释器proper program and be able to execute.Programs are often written as a set of smaller pieces, with each piece representing some aspect of the overall application program. After each piece has been compiled separately , a program called a linker combines all of the translated pieces into a single executable program.Programs seldom work correctly the first time, so a program called a debugger is often used to help find problems called bugs. Debugging programs usually detect an event in the executing program and point the programmer back to the origin of the event in the program code.Recent programming systems, such as Java, use a combination of approaches to create and execute programs. A compiler takes a Java source program and translates it into an intermediate form. Such intermediate programs are then transferred over the Internet into computers where an interpreter program then executes the intermediate form as an application program.ExercisesI. March each of the following terms to its equivalent(s).II. Fill in the blanks with the information given in the text. 1.allows programmers to use mnemonics for instructions and symbols for .2.A compiler is a computer program that translates into .3. Software designers create new programs by using special applications programs, often called or .计算机专业英语·62·4. After each piece has been compiled separately, a program called a combines all of the translated pieces into a single program.5. Programs seldom work correctly the first time, so a program called a is often used to help find problems called bugs.III. Mark the following sentences with true or false according to the passage.1. The difficult of writing programs in the machine language of 0s and 1s led first to the development of high-level language.( ) 2. The machine language allows programmers to use mnemonics for instructions and symbols for variables. ( ) 3. Assembly language was invented in the 1950s for easier, faster programming, along with them came the need for compilers.( ) 4. Computers need a compiler to translate source code into a low-level language called machine code. A compiler is a computer program. ( ) 5. A programmer uses a text editor to write the new program in a special notation called aprogramming language.( )IV. Translate the following passage from English into Chinese.A computer program is a set of instructions that directs a computer to perform some processing function or combination of functions. For the instructions to be carried out, a computer must execute a program, that is, the computer reads the program, and then follows the steps encoded in the program in a precise order until completion. A program can be executed many different times, with each execution yielding a potentially different result depending upon the options and data that the user gives the computer.TASK III TEXT BBasics of Object-OrientedProgrammingFigure 5.2 Object-Oriented Programming (OOP)Unit 5 Programming Language·63·object-oriented 面向对象的inheritance[in5heritEns ] n . 继承package[5pAkidV ] n . 包state[steit ] n . 状态 behavior[bi5heivjE ] n . 行为 field [fi:ld ]n . 字段 method[5meWEd ] n . 方法instance[5instEns ] n .例子,实例definition[7defi5niFEn ] n . 定义gear[^iE ] n . 齿轮If you've never used an object-oriented programming language before, you'll need to learn a few basic concepts before you can begin writing any code. This lesson will introduce you to objects, class, inheritance, interface, and package (See Figure 5.2). Each discussion focuses on how these concepts relate to the real world.What Is an Object?An object is a software bundle of related state and behavior. Software objects are often used to model the real-world objects that you find in everyday life: your dog, your desk, your television set, your bicycle. They consist of state and related behavior. An object stores its state in fields (variables in some programming languages) and exposes its behavior through methods (functions in some programming languages).What Is a Class?In the real world, you'll often find many individual objects are of the same kind. There may be thousands of other bicycles in existence, all of the same make and model. Each bicycle was built from the same set of blueprints and therefore contains the same components. In object-oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles. A class is the blueprint from which individual objects are created.Class's definition can be divided into interface and impleme- ntation. Interface describes class as an abstraction, what client needs to know. Implementation is the internals, only used by implementer.What Is Inheritance?Different kinds of objects often have a certain amount in common with each other.Object-oriented programming allows classes to inherit commonly used state and behavior from other classes.Mountain bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles (current speed, current pedal cadence, and current gear). Yet each also defines additional features that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower gear ratio.What Is an Interface?An interface is a contract between a class and the outside world.计算机专业英语·64·publish[5pQbliF ] vt .&vi . 出版,公布namespace[5neim speis ] n .命名空间logical[5lCdVikEl ] adj . 逻辑的encapsulate[en5kApsE7leit ] vt .封装Polymorphism [pCli5mC:fizEm ] n .多态性When a class implements an interface, it promises to provide the behavior published by that interface.In its most common form, an interface is a group of related methods with empty bodies. A bicycle's behavior, if specified as an interface, might appear as follows:interface Bicycle {void changeCadence(int newValue); // wheel revolutions per minutevoid changeGear(int newValue); void speedUp(int increment); void applyBrakes(int decrement); }What Is a Package?A package is a namespace for organizing classes and interfaces in a logical manner. Placing your code into packages makes large software projects easier to manage.The features of object-oriented programming include: (1)encapsulation (data hiding).(2)inheritance (derived classes inherit attributes and methods from base classes).(3)polymorphism (meaning of a message depends on class of recipient).ExercisesI. March each of the following terms to its equivalent(s).Unit 5 Programming Language·65·II. Fill in the blanks with the information given in the text.1. The basic concepts of object-oriented programming include , class, , interface, and .2. An object stores its state in (variables in some programming languages) and exposes its behavior through (functions in some programming languages).3. Object-oriented programming allows classes to commonly used state and behavior from other classes.4.In its most common form, an interface is a group of related methods with empty . 5. A package is a(an) for organizing classes and interfaces in a manner. III. Mark the following sentences with true or false according to the passage.1. Software objects are often used to model the real-world objects that you find in everyday life: your desk, your classmates, your bicycle.( ) 2. In object-oriented terms, we say that your bicycle is a class of the instance of objects known as bicycles. A class is the blueprint from which individual objects are created. ( ) 3. Object-oriented programming allows classes to inherit commonly used state and behavior from other classes.( ) 4. A package is a namespace for organizing classes and interfaces in a logical manner. Placing code into packages can’t make large software projects easier to manage. ( ) 5. The features of object-oriented programming include encapsulation, inheritance, andpolymorphism.( )IV. Translate the following passage from English into Chinese.The Java platform provides an enormous class library (a set of packages) suitable for use in your own applications. This library is known as the "Application Programming Interface", or "API" for short. Its packages represent the tasks most commonly associated with general-purpose programming. For example, a String object contains state and behavior for character strings; a file object allows a programmer to easily create, delete, inspect, compare, or modify a file on the file system; various GUI objects control buttons and checkboxes and anything else related to graphical user interfaces. There are literally thousands of classes to choose from. This allows you, the programmer, to focus on the design of your particular application, rather than the infrastructure required to make it work.TASK IV Writing TrainingNotice通知是上级对下级,组织对个人发出通知、下达指示、提出要求的一种应用文体;启事是个人对公众、组织对公众发布信息的一种文件,在英文表述上大体一样。

zty翻译原文

zty翻译原文

1 ZAC:Access Control in JavaScriptRodolfo Toledo´Eric TanterPLEIAD LabComputer Science Department(DCC)University of ChileBlanco Encalada2120Santiago,Chile{rtoledo,etanter}@dcc.uchile.clAbstractZAC is a practical lightweight library for access control in JavaScript based on aspect orientation.The ZAC access control architecture is stack-based,very similar to the ones of Java and C#.However,ZAC integrates other interesting features for more expressive access control.First,access control policies can be enforced at the level of objects,which permits morefine-grained control over the access to resources.Second,policies in ZAC can base their decisions on the execution history of scripts,which permits to express policies that are impossible to define using other models,such as bounded-time execution.Index TermsD.3.3Language Constructs and Features,D.3.2Scripting languages,D.3.1SemanticsI.I NTRODUCTIONThird-party JavaScript code inclusion is a cornerstone of today’s Web-2.0applications.Without it,rich personalized start pages,like iGoogle and My Yahoo,would be unthinkable.Facebook would not be as rich as it is without external applications.Even targeted advertising,like Google AdSense,would be impossible.However,despite being very useful,including external code poses a threat to the hosting page: JavaScript can be used to modify both the layout and the functionality of a page to a potentially arbitrary degree.The questions are therefore:What are the rights of external code?Is it allowed to arbitrarily modify the host page layout or functionality?How can it be restricted to only certain actions?Can we make sure external code does not degrade the interactive user experience with the page?Other languages that also support dynamic loading of code,like Java and C#,have a powerful access control architecture,allowing developers to expressively specify the rights of code.While the most recent specification of JavaScript includes some basic access control features[10],external tools must be used for more advanced control over the access to sensitive resources;these tools rely on a variety of approaches,ranging from code analyses,code transformation,and runtime libraries.C URRENT A PPROACHES FOR A CCESS C ONTROL IN J AVA S CRIPTThe only way provided by the HTML standard to control the rights of external code is to use frames: including a script inside a frame gives full permissions to the script,but only over its enclosing frame. However,in the majority of cases,this option is not expressive enough,mainly because it is too coarse-grained.For instance,it is impossible to grant certain permissions to external code,like showing alert dialogs,while forbidding others,like accessing cookies.For this reason,several proposals have been presented for controlling the actions that scripts can perform within a web page(Figure1).AdSafe[1]limits the JavaScript features external code can use,leaving only a“secure”subset of the language that can be statically checked to ensure it does not perform potentially dangerous actions.FBJS[6]rewrites the code to replace references to standard objects with limited,but2Name Enforcement Based on Extensible/Specification Granularity AdSafe static static analysis no/-scriptFBJS static+dynamic object wrappers no/-pageBrowserShield dynamic program monitoring yes/blacklisting pageCaja static+dynamic object capabilities yes/whitelisting scriptZAC dynamic dynamic AOP yes/blacklisting objectFig.1.JavaScript proposals for access control.equivalent objects,preventing any potentially dangerous action.This is what Facebook uses for third-party applications.BrowserShield[13]is a moreflexible proposal that can be used in more scenarios. BrowserShield transforms code to make it trigger notifications of its own activity during execution.An observer entity then decides whether the activity of the code should be allowed or not.New policies can be specified as functions using the JavaScript language itself.Finally,Caja[2]is a more principled approach to access control based on the object-capability model.In this model,external code can access (and therefore use)references to other objects only if the host page provides them.If no reference is provided,the external code can still compute based on its own(harmless)references.Caja is used in iGoogle and My Yahoo.As depicted in Figure1,ZAC combines very interesting features:•Dynamic enforcement of policies enables the execution of programs that are safe but use unsafe constructs.For example,programs that use eval only to deserialize JSON objects from strings,and not to execute arbitrary code,are safe.However,because they use a potentially unsafe construct, such programs are rejected by systems like AdSafe.•Being based on dynamic aspect-oriented programming(AOP)[5],allows ZAC policies to reason about program execution in its entirety.For instance,it is possible to define a policy that preventsa script from never ending,or taking too much time for acceptable web interaction.This kind ofpolicy is impossible to express in the object-capability model because the property does not depend on object references,but rather on computation itself.•Extensible access control specifications is crucial considering that different usage scenarios imply different requirements.This is acknowledged by other proposals like BrowserShield and Caja.•Object-level granularity is a unique feature of ZAC.Allowing the coexistence of different policies for different scripts within a Web page is fundamental.Going beyond the script level down to the object level also enables a secure interaction among scripts:objects from one script can use objects from other scripts,possibly with different policies;the correct policy will be unequivocally enforced.This is not the case with capabilities,where an untrusted object that obtains a reference to a sensitive resource can use it without limitations.The principle of ZAC is that foreign code can use every feature of JavaScript,including eval,and also can access every reference to any object in the system.However,the access control policy assigned to the foreign code when loaded forbids dangerous actions before they happen at runtime.In other words,ZAC follows a blacklisting approach,which,despite being considered less safe than a whitelisting approach, is actually used in real systems for access control.Even more,it turns out to be equivalent to the access control architectures of widely-used languages such as Java[8]and C#[9](see Figure2for more details). Finally,ZAC also inherits the great expressive power of the underlying general-purpose library for aspect-oriented programming AspectScript[15],as will be shown later on in this article.II.ZAC IN A CTIONZAC is based on assigning access control policies to scripts when loaded.At runtime,the policy is enforced for every action performed by these scripts.3 Blacklisting v/s Whitelisting in PracticePolicies based on whitelisting specify what resources the entities in the system can access(erX can use the printer).Conversely,policies based on blacklisting specifies what resources cannotbe accessed(er Y cannot modify systemfiles).In general,whitelisting is considered a safer approach because access to resources can be granted gradually,minimizing the risk of inadvertently granting access to unneeded sensitive resources.This is not the case of blacklisting where it is possible to forget to restrict access to a resource.However,and despite the fact that whitelisting is superior from a conceptual point of view, blacklisting-equivalent approaches are successfully use in practice.A compelling proof of this comes from the widespread use of Java and C#.While their access control architectures appearto be based on whitelisting(because one declares permissions,not restrictions),they are in practice equivalent to blacklisting approaches.This stems from the fact that permission checkingin these architectures has to be explicitly triggered at each and every relevant place in the code (using SecurityManager.checkPermission(<Permission>)in Java and<IPermission>.Demand()in C#). This means that forgetting to add the permission check associated to a sensitive resource in Java/C#is just like forgetting to restrict the access to that resource in ZAC.The dependency on explicit checks implies that the set of permissions is known in advance,and therefore,the set of restrictions can be calculated as the complement of the permissions.This is what makes the architectures of Java and C#equivalent,in practice,to the blacklisting architecture of ZAC.Fig.2.A.Loading ScriptsEnforcing access control policies with ZAC is very easy through the use of a simple API.For example, to load a third-party script it is only necessary to use the ZAC.load method:ZAC.load(”http://w w w.e v i l s i t /e v i l.j s”,ZAC.newDefaultPolicy());Loading the evil.js script using load,its execution is automatically subject to the restrictions in the policy specified as the second argument.Policies in ZAC are sets of restrictions.Figure3shows the restrictions in the policy returned by ZAC.newDefaultPolicy(),targeted to restrict the access to common sensitive resources. For instance,the ZAC.R ALERT restriction forbids the use of alert dialogs.These dialogs are normally used to provide valuable information to the user,but they can also be used to turn a page(or even the whole browser)unusable by endlessly showing an alert dialog.Another example is ZAC.R LOCA TION,that forbids redirections of the page.This restriction prevents malicious scripts from sending the browser to potentially dangerous sites.B.Policy EnforcementWhen loaded using ZAC.load,a script is unable to bypass the specified access control policy,directly or indirectly.This means that the script itself will not be able to perform any action forbidden by the policy, and also that it will not be able to lead other(possibly trusted)code to do it on its behalf.The reason is that ZAC supports stack-based access control[7]similar to Java[8]and C#[9].The semantics of stack-based access control says that each time a sensitive action is about to be performed,the current stack of evaluation is inspected to determine whether all the participating entities(in the case of JavaScript,objects and functions)are allowed to perform the action.If one entity is not allowed,then the action is aborted, typically by throwing an exception.In order to diminish the performance overhead,ZAC does not inspect the stack every time a sensitive action occurs,but maintains the security state of the application at each necessary point(see Figure4for more details).Figure5shows three different attempts to call the alert function,all ending with an exception raised by the access control policy.Thefirst one is a direct call,the second one uses delegation:the untrusted code4Constant(ZAC.)DescriptionR ALERT prevents alert calls.R LOCATION prevents redirection of the browser.R C STYLES prevents calls to computedStyles().R INNER HTML sanitizes strings assigned to the innerHTML property.R COOKIES prevents access to cookies.R GLOBAL prevents access to properties of the global object.R EVAL prevents arbitrary use of eval(only JSON deserialization).R FUN prevents instantiations of Function objects.R STO SI prevents calls to setTimeout and setInterval with a string argument.R HTTP REQ prevents instantiations of XMLHttpRequest objects.R DEF PROTOS prevents modification of prototypes of default objects.R ARGS prevents access to the arguments property of other functions.R WATCH prevents calls to watch and unwatch.R UNENCR prevents calls to toSource and uneval.R ZAC POLICIES prevents access to ZAC policies.Fig.3.Restrictions in ZAC’s default access control policy.Constants are accessed as properties of the ZAC global property.ZAC Performance overheadThe main sources of performance overhead in ZAC are twofold:the overhead of event generation, and the overhead of the stack-inspection semantics for access control.We refer the reader to[15]for an overview of the optimization techniques for event generation.In order to diminish the performance overhead of access control,ZAC does not inspect the stack every time a sensitive action occurs.Instead,it uses a state-based approach in which the security stateof the application is kept up to date.This approach is similar to the optimization for controlflow pointcuts commonly used in the implementation of aspect-oriented languages[12],where determining whether an action is in the controlflow of another is a matter of testing a variable,avoiding the traversal of the stack.The technique used in ZAC can also be compared to security-passing style[16],in which an extra parameter representing the current security context is passed to all functions.As future work,other implementation approaches can be integrated,such as using continuation marks[4]. This permits to get rid of the dependency on the stack to reason about access control(maintaining the same semantics),and also enables very interesting optimizations[3].Fig.4.invokes the(trusted)info function,which in turn tries to call alert.All these attempts end with an exception because the stack contains an object whose policy does not permits calls to alert.The third attempt is interesting,because it uses eval.ZAC ensures that restrictions of the code that calls eval are inherited by the eval-ed code:therefore,this attempt also fails.The last attempt is more intricate:although ZAC’s policies are specified at the level of scripts(loading them using load),they are enforced at the level of individual objects.The consequence is that if an object is created during the execution of a script subject to a certain policy,that object’s execution will always be subject to that policy:wherever the object goes, the policy follows it.Therefore,in the example,the policy is present in the stack when the anonymous function calls info.This is the reason why the third attempt also ends with an exception.It is important to highlight that this kind of access control is impossible to achieve with any other proposal(Figure1).For example,in capability-based access control,if the anonymous function manages to get a reference to the info function,there are no means to prevent it from calling info to display an alert dialog.Once an object obtains a reference,it can use that reference at will,no matter which was the policy originally assigned5Fig.5.Policy enforcement in ZAC.All these attempts will fail with an exception raised by the access control policy.to it.C.Defining Custom PoliciesAs typical sets,policies in ZAC can be modified by adding or removing restrictions(using the add and remove methods respectively).There are several scenarios where this can be useful.For instance,it seems natural to specify different policies for different foreign scripts,depending on the level of confidence the host page has in each of them.Another scenario is when a policy must be constructed programmatically (e.g.according to the preferences of the user).The API of ZAC permit to modify policies even after using them to l oad a script.These modifications will affect all the scripts already loaded using the policy.In addition to default policies,empty policies can be created using ZAC.newPolicy().In the following piece of code,two policies are configured to enforce different restrictions in two different scripts:var softPolicy=ZAC.newPolicy();//fresh policy(no r e s t r i c t i o n s)//r e s t r i c t only page redirections and evaluation of code in notSoEvil.j ssoftPolicy.add(ZAC.R LOCATION,ZAC.R EVAL);ZAC.load(”http://e v i l s i t /notSoEvil.j s”,softPolicy);//get a default policy and remove only the R ALERT r e s t r i c t i o n for e v i l.j svar hardPolicy=ZAC.newDefaultPolicy();hardPolicy.remove(ZAC.R ALERT);ZAC.load(”http://e v i l s i t /e v i l.j s”,hardPolicy);III.E XTENDING ZACEach restriction in a policy is targeted to restrict the access to common sensitive resources.ZAC’s policies can be extended by adding new restrictions targeted to protect other resources.A.Defining RestrictionsA restriction is a JavaScript object with two properties,both of which are functions.A rule property is in charge of identifying the access to the resource,and an action property is in charge of specifying the action to take when the resource access occurs.For example,the ZAC.R ALERT restriction is implemented as follows:ZAC.R ALERT={rule:function(event){return event.isCall()&&event.fun===alert;},action:function(event){throw”Cannot c a l l a l e r t”;}};6Event Name Properties CommonpropertiesCommonmethodsNew fun,argsparent proceed(args), clone(),is<eventName>()Init target,fun,argsCall target,fun,args,context,reflectiveExec target,fun,argsPropRead target,namePropWrite target,name,valueFig.6.Properties and methods of events supported by ZAC.fun:the function being used as a constructor(New and Init),or being called/executed(Call and Exec).args:the arguments of the event.target:the target of the event.context:the object performing the call.reflective:whether the call was performed using call or apply.parent:the parent event(like a stack of execution).proceed: executes the event.clone:clones the event(useful to store a reference).is<eventName>():boolean-returning utility methods to identify the kind of event.The function bound to the rule property identifies calls to the alert function by returning true when such calls occur.It uses the event parameter,which is a representation of the event occurring in the script. Figure6shows the complete list of event types supported by ZAC,and the corresponding properties (fields and methods)in each case.The function bound to the action property simply throws an exception because invoking alert is completely forbidden.An alternative to simply throwing an exception is to provide,possibly under certain circumstances,an alternate“safe”behavior.For example,the eval function of JavaScript is widely considered dangerous because it permits to execute arbitrary,potentially malicious,code.However,eval has a very useful application:the deserialization of a JSON[11]object from a string.Because JSON object’s serialization format do not permit functions,no arbitrary code can be executed when eval uating a serialized object. In other words,using eval for deserializing JSON objects is safe.The code below shows the ZAC.R EVAL restriction that only forbids the eval uation of code that is not in JSON format:ZAC.R EVAL={rule:function(event){return event.isCall()&&event.fun===eval;},action:function(event){try{return JSON.parse(event.args[0]);}catch(e){throw”Eval can only be used to d e s e r i a l i z e JSON objects.”;}}};Just like in the ZAC.R ALERT restriction,the rule property identifies calls to a certain function,in this case, eval.The action property,instead of immediately throwing an exception,first tries to evaluate thefirst argument of eval(event.args[0])as a JSON string.If it effectively is a JSON string,the resulting object is returned.Otherwise,an exception is thrown by JSON.parse;the restriction action then throws an exception itself.B.Adding New RestrictionsZAC comes with a set of predefined restrictions(recall Figure3),which corresponds to common cases. It is possible to define whole new kinds of restrictions as well.Let us define a new restriction that limits the number of windows a script can open:function nWindowsRestriction(n){return{nWindows:0,7 rule:function(event){return event.isCall()&&event.fun===document.open;},action:function(event){i f(++this.nWindows>n){throw”Cannot open more than”+n+”windows.”;}return event.proceed();}};}//add the r e s t r i c t i o n to a fresh policyvar policy=ZAC.newPolicy().add(nWindowsRestriction(3));The code above shows the use of three interesting elements:a stateful restriction,a restriction factory, and the use of event.proceed().Stateful restrictions.A restriction can have any number of additional properties apart from rule and action.In the example,the nWindows property is used to keep track of the number of windows opened by the script.Therefore the restriction returned by nWindowsRestriction is called a stateful restriction.The only consequence associated to a stateful restriction is that when it is added to more than one policy,its state is shared among these policies.For this reason,a restriction like the one returned by nWindowsRestriction will allow three windows in total,summing up all the windows opened by all scripts the restriction applies to.Restriction factory.To define a restriction,creating an object with the appropriate properties suffices. However,using a restriction factory like the nWindowsRestriction function has two advantages.First,it permits to easily parameterize the restriction(the n argument in the example).And second,it permits to obtain a different instance each time the generator is invoked.This can be used to avoid the sharing issue associated to stateful restrictions.The proceed method.The proceed method can be used to execute the original behavior the event parameter represents in the script.In the example,the call to the open function.The proceed method accepts the same parameters the original event does.If specified,these parameters replace the original parameters passed to the event.If omitted,the event is executed with the original parameters.IV.A DVANCED F EATURESA.Privileged ExecutionIn some cases,a piece of code needs to perform a sensitive action on behalf of another piece of code.This could be the case of the info function presented before:it may allow any entity to display an alert dialog,regardless of its access control policy.However,the stack-based access control mechanism presented before does not permit that.For this reason,languages like Java[8]provide a way to relax this constraint by executing a privileged action:during the execution of a privileged action,the restrictions of the objects in the controlflow before the privileged action are omitted.Only the ones pertaining to objects up to the one initiating the privileged action are considered.In terms of the stack inspection mechanism, privileged execution is analogous to stop looking in the stack of execution when the frame that initiated the privileged action is reached.It is important to notice that the privileged execution mechanism does not circumvent access control:any object can start a privileged execution,but doing so,it cannot get rid of its own restrictions,because they are maintained.In other words,a very restricted object can start a privileged execution,however,during the privileged action,the restrictions of the object are present.In ZAC,a privileged action is started by a self call to doPrivileged,and the code to execute in this privileged context is specified as the body of the function passed as parameter.Therefore,the info function can be implemented this way:function info(msg){this.doPrivileged(function(){alert(msg);});}Fig.7.Stack inspection in presence of privileged execution.Figure7depicts the stack-based access control process in presence of privileged execution:when the alertfunction is about to be called,the stack is inspected up to the frame that initiated the privileged action,thus the frame corresponding to the object that has the ZAC.R ALERT restriction is not reached. doPrivileged acts just as a marker method signaling a privileged execution.Objects can use their own implementations of doPrivileged,the only requirement is to maintain the name.A default implementationof this method is to simply invoke the function argument:obj.doPrivileged=function(action){action();};The semantics of ZAC for privileged execution defines that any self call to doPrivileged starts a privilegedaction.Non self calls to doPrivileged are not considered privileged executions.In consequence,an untrustedobject cannot call doPrivileged on a trusted object to bypass access control.B.Taking Advantage of AspectScriptAs mentioned before,ZAC is implemented on top of AspectScript.AspectScript is an extension toJavaScript adding support for aspect-oriented programming[5].In aspect-oriented programming,executionof a program is represented as a series of join points(a function call,a property access,an object creation,etc.—see Figure6).A pointcut identifies a set of join points,and a piece of advice is the action to betaken at a join point matched by a pointcut.In AspectScript,an aspect is a pointcut-advice pair,whereboth pointcuts and advices are plain JavaScript functions that receive a join point as parameter. AspectScript’s aspects corresponds exactly to ZAC’s restrictions,where the rule property is the pointcut, and the action property is the piece of advice.The policy enforcement(stack-based access control and privileged actions)is implemented based on dynamic deployment of aspects and expressive scoping[14]. ZAC depends only on AspectScript to be secure:if AspectScript generates all the events associated to the execution of all untrusted objects,these objects will not be able to do anything without ZAC being aware of it.This is the reason why ZAC policies cannot be circumvented.The fact that ZAC is implemented on top of AspectScript brings many benefits,of which we highlighttwo:the ample variety pointcuts included in AspectScript,and the ability to reason about the programexecution.AspectScript includes several predefined pointcuts that can be composed to identify more intricateactions.For example,the following pointcut identifies the calls to alert that occur inside the body of anymethod of obj:var PCs=AspectScript.Pointcuts;var pc=PCs.c a l l(alert).and(PCs.within(obj));9 Pointcuts in AspectScript can also match sequences of events,optionally restricted by temporal condi-tions.This can be useful in access control to,for instance,forbid the invocations to alert that occur too frequently,say more than one per second.The ability of ZAC to reason about the execution of a program derives from the fact that AspectScript generates join points for every action in the scripts,evaluating pointcuts for each one of them.In a capability-based model,for instance,reasoning about the history of program execution is impossible.This is because the model considers accessing a reference and executing some methods as the only way to threaten a system.However,there are other interesting security properties that are related to the actual computation of programs.An example of a security property based on actual computation—which is actually checked by most browsers—is to ensure that a third-party script does not degrade the interactive experience of the user:if a script takes too long to execute,the browser suspends its execution and asks the user whether to simply abort the script.While such a restriction is beyond the realm of capabilities,it is straightforward to define with ZAC:function nInstructionsRestriction(n){return{nInstructions:0,rule:function(event){return++nInstructions>n;},action:function(event){i f(confirm(”This s c r i p t i s running for too long.Abort i t?”){throw”Cannot execute more than”+n+”i n s t r u c t i o n s”;}nInstructions=0;return event.proceed();}};}For simplicity,we use instruction count rather than actual time.The point here is just to give an idea of the wide range of policies that can be expressed using dynamic AOP as a foundation for defining restrictions.V.C ONCLUSIONThe ubiquity of the JavaScript language and the myriad of ways in which it is being used turn access control into a crucial element for a safe web experience.In this article we presented ZAC,a lightweight practical library for access control in JavaScript comprising very interesting features which permit to express security properties not enforceable with other approaches,such as per-object restrictions and bounded-time execution.ZAC’s implementation is based on aspect orientation,which,apart from constituting a solid ground currently under active development,brings many practical benefits in terms of expressiveness.Availability.ZAC is available at http://pleiad.cl/aspectscript/zac,and AspectScript at http://pleiad.cl/aspectscript.R EFERENCES[1]AdSafe..[2]Caja./p/google-caja.[3]John Clements and Matthias Felleisen.A tail-recursive machine with stack inspection.ACM Transactions on Programming Languagesand Systems(TOPLAS),26(6):1029–1052,2004.[4]John Clements,Ayswarya Sundaram,and David Herman.Implementing continuation marks in javascript.In Proceedings of theWorkshop on Scheme and Functional Programming,2008.[5]Tzilla Elrad,Robert E.Filman,and Atef Bader.Aspect-oriented munications of the ACM,44(10),October2001.[6]FBJS./index.php/FBJS.。

用户评论方面级情感分析研究

用户评论方面级情感分析研究

用户评论方面级情感分析研究陈虹,杨燕+,杜圣东西南交通大学信息科学与技术学院,成都611756+通信作者E-mail:***************.cn 摘要:方面级情感分析是自然语言处理的热门研究方向之一,相比于传统的情感分析技术,基于方面的情感分析是细粒度的,能够判断句子中多个目标的情感倾向,能更加准确地挖掘用户对目标的情感极性。

针对以往研究忽略目标单独建模的问题,提出了一种基于双向长短期记忆神经网络(BiLSTM )的交互注意力神经网络模型(Bi-IAN )。

该模型通过BiLSTM 对目标和上下文分别进行建模,获得目标和上下文的隐藏表示,提取其中的语义信息。

接下来利用交互注意模块学习上下文和目标之间的注意力,分别生成目标和上下文的表示,捕捉目标和上下文之内和之间的相关性,并重构评价对象和上下文的表示,最终通过非线性层得到分类结果。

在数据集SemEval 2014任务4和Chinese review datasets 上的实验训练显示,在正确率和F 1-score 上,比现有的基准情感分析模型有更好的效果。

关键词:方面级情感分析;深度学习;循环神经网络(RNN );注意力机制文献标志码:A中图分类号:TP391.1Research on Aspect-Level Sentiment Analysis of User ReviewsCHEN Hong,YANG Yan +,DU ShengdongSchool of Information Science and Technology,Southwest Jiaotong University,Chengdu 611756,ChinaAbstract:Aspect-based sentiment analysis has become one of the hot research directions of natural language pared with the traditional sentiment analysis technology,aspect-based sentiment analysis is aimed at specific targets in sentences,and can judge the sentiment tendency of multiple targets in a sentence,and more accurately mine the sentiment polarity of the target.It is a fine-grained sentiment analysis technology.Aiming at the fact that the previous research ignored the problem of separate modeling of targets,an interactive attention network model based on bidirectional long short-term memory (Bi-IAN)is proposed.The model uses bidirectional long short-term memory (BiLSTM)to model the targets and the context respectively,to obtain hidden representation and extract the semantic information.Next,the attention vector between the context and the targets is learnt through interactive learning,and then the representation of the target and the context are generated.The relevance within and between the target and the context is captured,the representation of the target and context is reconstructed,and finally the model gets the classification result through the non-linear layer.Experimental training on the dataset SemEval 2014task 4and Chinese review datasets shows that the model proposed has better results than the existing benchmark sentiment analysis model in terms of accuracy and F 1-score.Key words:aspect-level sentiment analysis;deep learning;recurrent neural network (RNN);attention mechanism计算机科学与探索1673-9418/2021/15(03)-0478-08doi:10.3778/j.issn.1673-9418.2007011基金项目:国家自然科学基金(61976247);国家科技支撑计划(2015BAH19F02)。

人工智能岗位招聘笔试题与参考答案(某大型集团公司)

人工智能岗位招聘笔试题与参考答案(某大型集团公司)

招聘人工智能岗位笔试题与参考答案(某大型集团公司)(答案在后面)一、单项选择题(本大题有10小题,每小题2分,共20分)1、以下哪个算法不属于监督学习算法?A、决策树B、支持向量机C、K最近邻D、朴素贝叶斯2、在深度学习中,以下哪个概念指的是通过调整网络中的权重和偏置来最小化损失函数的过程?A、过拟合B、欠拟合C、反向传播D、正则化3、以下哪个技术不属于深度学习中的卷积神经网络(CNN)组件?A. 卷积层B. 激活函数C. 池化层D. 反向传播算法4、在自然语言处理(NLP)中,以下哪种模型通常用于文本分类任务?A. 决策树B. 朴素贝叶斯C. 支持向量机D. 长短期记忆网络(LSTM)5、题干:以下哪项不属于人工智能的核心技术?A. 机器学习B. 深度学习C. 数据挖掘D. 计算机视觉6、题干:以下哪个算法在处理大规模数据集时,通常比其他算法更具有效率?A. K最近邻(K-Nearest Neighbors, KNN)B. 支持向量机(Support Vector Machines, SVM)C. 决策树(Decision Tree)D. 随机森林(Random Forest)7、以下哪个技术不属于深度学习领域?A. 卷积神经网络(CNN)B. 支持向量机(SVM)C. 递归神经网络(RNN)D. 随机梯度下降(SGD)8、以下哪个算法不是用于无监督学习的?A. K-均值聚类(K-means)B. 决策树(Decision Tree)C. 主成分分析(PCA)D. 聚类层次法(Hierarchical Clustering)9、以下哪个技术不属于深度学习中的神经网络层?A. 卷积层(Convolutional Layer)B. 循环层(Recurrent Layer)C. 线性层(Linear Layer)D. 随机梯度下降法(Stochastic Gradient Descent)二、多项选择题(本大题有10小题,每小题4分,共40分)1、以下哪些技术或方法通常用于提升机器学习模型的性能?()A、特征工程B、数据增强C、集成学习D、正则化E、迁移学习2、以下关于深度学习的描述,哪些是正确的?()A、深度学习是一种特殊的机器学习方法,它通过多层神经网络来提取特征。

人工智能基础概念复习题含参考答案

人工智能基础概念复习题含参考答案

人工智能基础概念复习题含参考答案一、单选题(共60题,每题1分,共60分)1、决策树中,同一路径上的所有属性之间是()关系A、逻辑与B、因果C、逻辑或D、相关正确答案:A2、CRISP-DM将数据挖掘的过程抽象为四个层次:阶段、一般任务、()和过程实例A、分析B、建模C、具体任务D、规划正确答案:C3、智能机器人可以根据()得到信息。

A、感知能力B、学习能力C、思维能力D、行为能力正确答案:A4、学习器的实际预测输出与样本的真实输出之间的差异称为A、精度B、误差C、查准率D、错误率正确答案:B5、()是将人类语言经过处理转化为机器所能理解语言的一门技术。

A、大数据B、自然语言处理C、语音识别D、计算机视觉正确答案:B6、大数据的最显著特征是()A、数据价值密度高B、数据处理速度快C、数据类型多样D、数据规模大正确答案:D7、假设你在卷积神经网络的第一层中有5个卷积核,每个卷积核尺寸为7×7,具有零填充且步幅为1。

该层的输入图片的维度是224×224×3。

那么该层输出的维度是多少?()A、217x217x3B、218x218x5C、220x220x7D、217x217x8正确答案:B8、图像灰度的方差表示图像的哪种属性A、图像细节B、图像饱和度C、图像整体亮度D、图像对比度正确答案:D9、专用人工智能的简称是()。

A、AIGB、AINC、ANID、AGI正确答案:C10、数据管理以()活动为基础。

A、数据预处理B、数据处理C、数据分析D、数据可视化正确答案:A11、避免由于过拟合造成貌似线性可分的结果,一个解决的办法是允许支持向量机在一些样本上出错,为此引入()的概念。

A、正则化B、软间隔C、核函数D、硬间隔正确答案:B12、有三种方法可以帮助决策者确定决策的作用:()、场景分析和What-If分析A、回归分析B、测试C、建模D、假设分析正确答案:B13、关于表述数据可视化在数据科学中重要地位说法中,下列不正确的是()。

中科大算法设计与分析分布式算法部分作业部分答案

中科大算法设计与分析分布式算法部分作业部分答案
算法设计与分析 第二次作业
1. 分析在同步和异步模型下汇集算法的复杂性。 分析在同步和异步模型下பைடு நூலகம்集算法的复杂性。
解:与广播算法分析时间复杂性的步骤一致,一两句的说明 与广播算法分析时间复杂性的步骤一致, 不是分析。 不是分析。 <1> 同步模型 引理:在汇集算法的每个容许执行里, 引理:在汇集算法的每个容许执行里,树中每个高为 t 轮里收到所有孩子的msg。 子树根结点在第 t 轮里收到所有孩子的msg。 归纳证明。。。 归纳证明。。。 定理:当生成树高为 d 时,存在一个时间复杂度为O(d)的 定理: 存在一个时间复杂度为O(d)的 同步汇集算法。 同步汇集算法。 <2> 异步模型 引理:在汇集算法的每个容许的执行里, 引理:在汇集算法的每个容许的执行里,树中每个高为 t 收到所有孩子的msg。 的子树根结点在时刻 t 收到所有孩子的msg。 归纳证明。。。 归纳证明。。。 定理: 存在一个时间复杂度为O(d)的 定理:当生成树高为 d 时,存在一个时间复杂度为O(d)的 异步汇集算法。 异步汇集算法。
6.
证明同步环上不存在匿名的、 证明同步环上不存在匿名的、一致性的 Leader选举算法 Leader选举算法。 选举算法。
解:由Lemma3.1可得。 解:由Lemma3.1可得。 假设R是大小为n>1的环(非均匀),A 假设R是大小为n>1的环(非均匀),A是其上的一 个匿名算法,它选中某处理器为leader。因为环是 个匿名算法,它选中某处理器为leader。因为环是 同步的且只有一种初始配置,故在R 同步的且只有一种初始配置,故在R上A只有唯一的 合法执行。 Lemma3.1: 在环R上算法A Lemma3.1: 在环R上算法A的容许执行里,对于每 轮k,所有处理器的状态在第k轮结束时是相同的。 ,所有处理器的状态在第k Note:每个处理器同时宣布自己是Leader! Note:每个处理器同时宣布自己是Leader!

orienternet算法原理

orienternet算法原理

orienternet算法原理
OrientedNet算法是一种用于图像分割的深度学习算法,它是基于神经网络的语义分割模型。

该算法的原理主要包括以下几个方面:
1. 网络结构,OrientedNet算法采用了一种特殊的神经网络结构,通常是基于卷积神经网络(CNN)或者全卷积神经网络(FCN)的变种。

这种网络结构通常包括编码器和解码器部分,编码器用于提取输入图像的特征,解码器用于将提取的特征映射到像素级的预测结果上。

2. 方向感知机制,OrientedNet算法在网络结构中引入了方向感知机制,这是其与传统的语义分割模型的主要区别之一。

这种机制能够帮助网络更好地理解图像中物体的方向信息,从而在分割过程中更加准确地捕捉物体的边界和轮廓。

3. 损失函数,为了训练神经网络,OrientedNet算法通常会设计特定的损失函数,以衡量模型预测结果与真实标签之间的差异。

在OrientedNet中,损失函数通常会结合方向信息,以帮助网络更好地学习和预测图像中物体的方向和形状。

4. 数据增强,为了提高模型的泛化能力,OrientedNet算法通
常会采用数据增强技术,通过对训练数据进行旋转、翻转、缩放等
操作,来生成更多多样化的训练样本,从而帮助模型更好地学习物
体的方向和形状信息。

总的来说,OrientedNet算法的原理主要包括网络结构、方向
感知机制、损失函数和数据增强等方面,它通过引入方向感知机制,能够更好地理解图像中的方向信息,从而在图像分割任务中取得更
好的效果。

希望这些信息能够帮助你更好地理解OrientedNet算法
的原理。

different levels of representation

different levels of representation

different levels of representation
在人工智能领域中,不同层次的表示方法对于构建智能系统至关重要。

这些层次包括符号表示、连接表示和深度表示。

符号表示是一种基于符号的处理方式,它将知识表示为符号,并通过逻辑推理进行知识的处理。

这种表示方法在早期的专家系统等领域得到了广泛应用。

连接表示是一种基于神经网络的表示方法,它将知识表示为神经元之间的连接权重。

这种表示方法在深度学习中得到了广泛应用,因为它能够自动地学习数据的内在特征,并能够处理大规模的数据集。

深度表示是一种基于深度学习的表示方法,它通过构建深度神经网络来学习数据的层次特征。

这种表示方法在图像识别、自然语言处理等领域得到了广泛应用,因为它能够自动地提取数据的层次特征,并能够提高模型的泛化能力。

在构建智能系统时,选择合适的表示方法需要根据具体的应用场景和数据特点来进行选择。

随着人工智能技术的不断发展,这些表示方法也将会不断地发展和完善,为智能系统的构建提供更多的选择和可能性。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

J OURNAL OF O BJECT T ECHNOLOGY Online at http://www.jot.fm. Published by ETH Zurich, Chair of Software Engineering ©JOT, 2007Vol. 6, No. 3, March - April 2007 ASPECT ORIENTED PROGRAMMING IN .NET. BASED ON ATTRIBUTES Miguel Katrib Mora and Yamil Hernández SaáComputer Science Department.University of HavanaAbstractAspect Oriented Programming proposes an approach to increase code functionality withaspects that are not part of the main code functionality. The current work shows howcan be done AOP in .NET thanks to one of the most interesting .NET innovations: itscapacity to put custom metadata inside a software component by means of .NET attributes. This paper defines different kinds of such attributes to represent aspects andshows how the functionality embedded in the attributes can be integrated with the functionality of the code decorated by them.Such aspect-attributes are inserted into an existing .NET component without forcingreprogramming the client code of the component. Then the code of the aspect functionality is woven into the code of the component.1 INTRODUCTIONThe dream of software developers is a world in which components could be easy assembled using high level languages and tools. But this would be a very simplistic point of view to assume a world in which each problem domain could be factored into discrete components only interacting by method invocation. Such a premise ignores the fact that some aspects of an application program tend to permeate all its parts.The application code tends to become contaminated with code snippets trying to deal with those "aspects" that are not the central part of the problem domain. A classical example of such aspect is security (most applications are worried about security despite security is not the central bussinees of them). These aspects usually obstruct the original code crossing the problem domain and affecting the goal to obtain reusable solutions. To provide reuse mechanisms for these problems is the focus of the so called Aspect Oriented Programming (AOP) [1].Based on the separation of concerns principle,AOP tries to provide mechanisms for factoring out the parts of an application that are not pertinent to the central problem domain. Then, the AOP approach could offer two main benefits: Application code will be Cite this column as follows: Miguel Katrib Mora and Yamil Hernández Saá: “Aspect Oriented Programming in .NET. Based on Attributes”, in Journal of Object Technology, vol. 6, no. 3, March-April 2007, pp. 53-70 http://www.jot.fm/issues/issue_2007_03/article1ASPECT ORIENTED PROGRAMMING IN .NET. BASED ON ATTRIBUTES54J OURNAL OF O BJECT T ECHNOLOGY V OL.6, NO.3V OL.6, NO.3 J OURNAL OF O BJECT T ECHNOLOGY55ASPECT ORIENTED PROGRAMMING IN .NET. BASED ON ATTRIBUTES56J OURNAL OF O BJECT T ECHNOLOGY V OL.6, NO.3The parameter, result, is used when an AfterAttribute is attached to a property or to a non void method. In such case the result parameter will receive the value returned by the method or property, so this value could be used by the Advice method.The parameter method receives the MethodBase reflection object describing the called method. Example, for the call x.F(...) the value passed to this parameter is the MethodBase object corresponding to F.The value passed to parameters, is an object[] array with the parameters used in the call to the method x.F(...).If there are parameters of value type they will be received transparently as object type (without mediation of the client code) thanks to the boxing mechanism. A null value will be passed when the target method doesn't have parameters. Aspects types according to the interwoven patternDifferent types of aspects attributes are defined. The interwoven mechanism of the Advice depends on the type of the aspect and the call to the method that has beendecorated with this aspect. As shown in Listing 2 the following aspects inherit from AspectAttributeBeforeAspect: The Advice is executed before executing the called method or property (get or set method).AfterAspect: The Advice is executed after executing the called method or property (get or set method).InsteadAspect: The Advice is executed instead of the called method or property (get or set method). Note the attribute usage of Instead has AllowMultiple = false because only one instead aspect has sense.Example of BeforeAspectLets a classclass A{...public void F1(){...}public void F2(){...}}It is possible to count the calls to the method F1 decorating the method F1 with the aspect CountingCalls (Listing 3)class A{...[CountingCalls]public void F1(){...}public void F2(){...}}To count the calls to all the methods of a type B we can decorate the class definition. [CountingCalls]class B{V OL.6, NO.3 J OURNAL OF O BJECT T ECHNOLOGY57ASPECT ORIENTED PROGRAMMING IN .NET. BASED ON ATTRIBUTES58J OURNAL OF O BJECT T ECHNOLOGY V OL.6, NO.3V OL.6, NO.3 J OURNAL OF O BJECT T ECHNOLOGY59ASPECT ORIENTED PROGRAMMING IN .NET. BASED ON ATTRIBUTES60J OURNAL OF O BJECT T ECHNOLOGY V OL.6, NO.3V OL.6, NO.3 J OURNAL OF O BJECT T ECHNOLOGY61ASPECT ORIENTED PROGRAMMING IN .NET. BASED ON ATTRIBUTES62J OURNAL OF O BJECT T ECHNOLOGY V OL.6, NO.3The second approach is to produce a target assembly with the same functionality as the original plus the aspect functionality included but without dependencies to the original. To implement the later approach it is necessary to extract code from the original assembly to replicate it in the target. But such "copy and paste" capabilities are not offered by the .NET namespace System.Reflection. To solve it we used the library Reflection.Editor [5, 6]. This library emulates the capabilities of the .NET System.Reflection but also supports IL code extraction and manipulation. The first step to generate the final assembly using Reflection.Editor is to create an "edition assembly". This edition assembly clones the original, ensuring the same functionality, but allows its modification.Assembly sourceAssembly = Assembly.LoadFrom("...originalAssembly.dll"); EditionAssembly targetAssembly = new EditionAssembly(sourceAssembly);The next step is to change the name of each method M decorated with aspects by the name Hidden_M. This is done by the following functionality of the Reflection.Editor.OriginalMethod.SetName("Hidden_" + );Then a new public method, with the same signature as the original, is generated.EditionMethod newMethod = eType.DefineMethod(, originalMethod.Attributes, originalMethod.ReturnType, paramTypes);This new method includes the code to manage the aspects and to call the renamed method (the original functionality) according to the aspect pattern (before, after, etc). The process is illustrated in Figure 1.Original Assemblyclass A{ ... [CountingCalls] public void F1(){...} public void F2(){...} }Edition Assemblyclass A{ ... [CountingCalls] public void F1(){...} [CountingCalls] private void Hidden_F1(){...} public void F2(){...} }The original method is renamed and “hidden”The code of this aspect manager method is emitted using the ILSnippet of Reflection.EditorFigure 1To produce the code of this method is used a feature of the Reflection.Editor named ILSnippet. An ILSnippet supports IL code emission and IL code "edition".VOL. 6, NO. 3JOURNAL OF OBJECT TECHNOLOGY63ASPECT ORIENTED PROGRAMMING IN .NET. BASED ON ATTRIBUTESIn short an ILSnippet is a "sequence" of IL instructions, plus local variable definitions and exception handlers. Reflection.Editor allows to extract the body of a method as an ILSnippet, Then by copying, inserting and changing this snippet it is possible to obtain the weaving of the main code with the aspect code. IL code can be emitted adding IL instructions to an ILSnippet using the ILSnippet method AppendInstruction(OpCode opCode , object operand). An IL instruction can be accessed by its index. The myILSnippet[k] returns the IL instruction at position k in the ILSnippet Resume the example of the method F1 decorated with the CountingCalls aspectclass A{ ... [CountingCalls] public void F1(){...} public void F2(){...} }The generated code for the aspect manager will look like the code excerpt of Listing 7.Listing 7private AspectAttribute[][] typeAspects; private AspectAttribute[][] Aspect_Of_Method_F1(); public class A { public A(); public void F1(){...}; private void Hidden_F1(){...}; }Here typeAspects[0] is an array of BeforeAttribute attributes and typeAspects [1] is an array of AfterAttribute attributes attached to a type definition and then applied to all methods of the type Aspect_Of_Method_F1 is an array containing three arrays as shown in Listing 8Listing 8this.Aspect_Of_Method_F1=new AspectAttribute[][3];this.Aspect_Of_Method_F1[0]=((BeforeAttribute[])MethodBase. GetCurrentMethod().GetCustomAttributes(typeof(BeforeAttribute),true)); this.Aspect_Of_Method F1[1]=((InsteadAttribute[])MethodBase. GetCurrentMethod().GetCustomAttributes(typeof(InsteadAttribute),true)); this.Aspect_Of_Method_F1[2]=((AfterAttribute[])MethodBase. GetCurrentMethod().GetCustomAttributes(typeof(AfterAttribute),true));64JOURNAL OF OBJECT TECHNOLOGYVOL. 6, NO. 3contains the BeforeAttribute that decorates method F1 this.Aspect_Of_Method_F1[1] contains the InsteadAttribute that decorates method F1 this.Aspect_Of_Method_F1[2] contains the AfterAttribute that decorates method F1 Then the method F1 will manage its aspects and will call the original F1 that was renamed to Hidden_F1. The code excerpt of Listing 9 shows the F1 emitted code to retrieve the BeforeAspect attributes.this.Aspect_Of_Method_F1[0]Listing 9... myILS.AppendInstruction(OpCodes.Ldarg_0); myILS.AppendInstruction(OpCodes.Ldfld, fbMethodAspects); myILS.AppendInstruction(OpCodes.Ldc_I4_0); myILS.AppendInstruction(OpCodes.Call, typeof(MethodBase).GetMethod("GetCurrentMethod")); myILS.AppendInstruction(OpCodes.Ldtoken, typeof(BeforeAttribute)); myILS.AppendInstruction(OpCodes.Call, typeof(Type).GetMethod("GetTypeFromHandle", new Type[] { typeof(RuntimeTypeHandle)} )); myILS.AppendInstruction(OpCodes.Ldc_I4_1); myILS.AppendInstruction(OpCodes.Callvirt, typeof(MemberInfo).GetMethod("GetCustomAttributes", new Type[] { typeof(Type), typeof(bool) })); myILS.AppendInstruction(OpCodes.Castclass, typeof(BeforeAttribute[])); //The BeforeAspects are stored in fbMethodAspects[0] myILS.AppendInstruction(OpCodes.Stelem_Ref); ...Listing 10 generates the code to invoke the Advice method of each Before aspectListing 10... myILS.AppendInstruction(OpCodes.Ldarg_0); myILS.AppendInstruction(OpCodes.Ldfld, fbMethodAspects); //Load the BeforeAspects stored in fbMethodAspects[0] myILS.AppendInstruction(OpCodes.Ldc_I4_0); myILS.AppendInstruction(OpCodes.Ldelem_Ref); //Load the BeforeAspect stored in fbMethodAspects[0][count] myILS.AppendInstruction(OpCodes.Ldloc_S, count);VOL. 6, NO. 3JOURNAL OF OBJECT TECHNOLOGY65ASPECT ORIENTED PROGRAMMING IN .NET. BASED ON ATTRIBUTESmyILS.AppendInstruction(OpCodes.Ldelem_Ref); //Load the Advice args (target,result,method,parameters) myILS.AppendInstruction(OpCodes.Ldarg_0); myILS.AppendInstruction(OpCodes.Call, typeof(MethodBase).GetMethod("GetCurrentMethod")); myILS.AppendInstruction(OpCodes.Ldloca_S, returnValue); myILS.AppendInstruction(OpCodes.Ldc_I4_S, paramTypes.Length); myILS.AppendInstruction(OpCodes.Newarr, typeof(Object)); myILS.AppendInstruction(OpCodes.Stloc_S, parameters); myILS.AppendInstruction(OpCodes.Ldloc_S, parameters); for (int i=0; i<paramTypes.Length; i++) { myILS.AppendInstruction(OpCodes.Ldc_I4_S,i); myILS.AppendInstruction(OpCodes.Ldarg_S,i+1); myILS.AppendInstruction(OpCodes.Stelem_Ref); myILS.AppendInstruction(OpCodes.Ldloc_S, parameters); } //Invoke the Advice myILS.AppendInstruction(OpCodes.Callvirt, typeof(AspectAttribute).GetMethod("Advice") ); ...If there is an methodListing 11...Insteadattribute then Listing 11 generate the code to invoke itsAdvicemyILS.AppendInstruction(OpCodes.Ldarg_0); myILS.AppendInstruction(OpCodes.Ldfld, fbMethodAspects); //Load the InsteadAspect stored in fbMethodAspects[1][0] myILS.AppendInstruction(OpCodes.Ldc_I4_1); myILS.AppendInstruction(OpCodes.Ldelem_Ref); myILS.AppendInstruction(OpCodes.Ldc_I4_0); myILS.AppendInstruction(OpCodes.Ldelem_Ref); //Load the Advice args (target,result,method,parameters) myILS.AppendInstruction(OpCodes.Ldarg_0); myILS.AppendInstruction(OpCodes.Call, typeof(MethodBase).GetMethod("GetCurrentMethod")); myILS.AppendInstruction(OpCodes.Ldloca_S, returnValue); myILS.AppendInstruction(OpCodes.Ldc_I4_S, paramTypes.Length); myILS.AppendInstruction(OpCodes.Newarr, typeof(Object)); myILS.AppendInstruction(OpCodes.Stloc_S, parameters); myILS.AppendInstruction(OpCodes.Ldloc_S, parameters); for (int i=0; i<paramTypes.Length; i++) { myILS.AppendInstruction(OpCodes.Ldc_I4_S,i);66JOURNAL OF OBJECT TECHNOLOGYVOL. 6, NO. 3myILS.AppendInstruction(OpCodes.Ldarg_S,i+1); myILS.AppendInstruction(OpCodes.Stelem_Ref); myILS.AppendInstruction(OpCodes.Ldloc_S, parameters); } //Invoke the Advice myILS.AppendInstruction(OpCodes.Callvirt, typeof(AspectAttribute).GetMethod("Advice")); ...Otherwise, Listing 12 generates the code to invoke the original method (renamed as Hidden_F1). Note method Hidden_F1 was generated using the Reflection.Editor copy, paste and rename capabilities.Listing 12... myILS.AppendInstruction(OpCodes.Ldarg_0); //Load the method args for (int i=0; i<paramTypes.Length; i++) myILS.AppendInstruction(OpCodes.Ldarg_S, i+1); // Invoke the original method renamed as "Hidden_ " + method name myILS.AppendInstruction(OpCodes.Call, hidden_mb); //Store the method return in returnValue if (hidden_mb.ReturnType != typeof(void)) { if (hidden_mb.ReturnType.IsValueType) myILS.AppendInstruction(OpCodes.Box, hidden_mb.ReturnType); myILS.AppendInstruction(OpCodes.Stloc_S, returnValue); } ...The code to invoke the Advice method of each AfterAspect is generated like those for each BeforeAspect. Presented approach, using Reflection.Editor capabilities, generates a new assembly that keeps the original functionality (without reference dependencies to the original assembly) but including also the code executing the aspects. Therefore, this new assembly can substitute the original in any project that wants to apply aspects functionality. Using Reflection.Editor library it is also possible to implement the reverse process, i.e., remove aspects evaluation from the code to obtain an assembly equivalent to the original.VOL. 6, NO. 3JOURNAL OF OBJECT TECHNOLOGY67ASPECT ORIENTED PROGRAMMING IN .NET. BASED ON ATTRIBUTES4 RELATED WORKSAn alternative to incorporate aspects in .NET is based on the use of contexts and messages exchange [7]. Nevertheless, this approach forces the client code to handle the infrastructure of messages exchanges. Another drawback of this approach is that each attribute defined for aspect purposes must repeat the same pattern in its implementation, so lacking reusability. In [8] we proposed an approach of aspects “interwoven” based on intercepting the calls to methods decorated by the aspect. This is done using the .NET context infrastructure and the concepts of real and transparent proxies. But such infrastructure overloads performance. Furthermore, this solution forces to do modifications in the client code. AOP offers an interesting alternative for specification of nonfunctional component properties (such as fault-tolerance properties or timing behavior), an aspect-specific tool that adds fault tolerance to .NET components using aspect oriented techniques is described in [9]. There are approaches based on the use of pre-processors [10], however, such approaches request the acceptation of new source languages or language modifications. Our current work has focused in the use of .NET attributes to express non-functional component properties without disturbing the existing language syntax and semantics. There are a variety of language extensions with AspectJ [11] as most prominent example. The CAMEO project [12] extends the C# compiler to add AOP extensions similar to those in AspectJ. It uses XML aspect definition files and outputs standard C# code which is compiled by the standard compiler. CAMEO is a static weaver. CLAW is a .NET dynamic weaver implemented in C++ using the Common Object Model (COM) to extend the CLR. by linking in to the profiling mechanism, the CLAW architecture is defined in [13]. With this mechanism, it is possible to add a new method and to inject IL code at runtime into an existing method body, relocate methods from one type to another, and recompile existing methods. But this is a low level and tightly coupled approach depending on the profiler feature.CONCLUSIONSTo do AOP based on modifications of existing languages, changing compilers and building a lot of acompanning tools is not a pragmatic solution. The approach proposed in the current paper tries to follow the mainstream of .NET not requesting changes in the source languages, but offering libraries, a single tool and proposing an AOP programming methodology. As was explained, this can be achieved under .NET thanks the .NET support to attributes and the enhanced reflection capabilities. The .NET reflection constrains to manipulate the IL code of assembly and to weave it with code of other assembly was overcome with the new Reflection.Editor library. A detailed68JOURNAL OF OBJECT TECHNOLOGYVOL. 6, NO. 3description of this library goes beyond the scope of this paper and could be explained in a future paper. Other patterns of aspects could be considered in further works: • • • aspects to express functionality to execute when the called method throws an exception aspects to indicate a timeout for the execution of a method (useful in remote applications) aspects to express undo-redo capability of a method executionREFERENCES[1] Gregor Kiczales and others, Aspect Oriented Programming, Springer Verlag, Proceedings of ECOOP 1997 [2] Barnaby Tom, Bock Jason, Applied .NET Attributes, APress 2003 [3] Box Don, Sells Chris Essential .NET: The Common Language Runtime, AddisonWesley 2003 [4] del Valle Mario, Katrib Miguel, El poder de la reflexión en .NET, dotNetManía No 3, Abril 2004 [5] Bacallao Erick, Katrib Miguel, Parodi Yoelvis, Reflection.Editor una biblioteca para programar la edición de ensamblados .NET DotNetmanía No 15, Mayo 2005 [6] Bacallao Erick, Katrib Miguel, Parodi Yoelvis, Entretejido de Código IL en Ensamblados .NET usando Reflection.Editor, DotNetmanía No 23, Febrero 2006 [7] Shukla Drama, Fell Simon, Sells Chriss Aspect-Oriented Programming Enables Better Code Encapsulation and Reuse¸MSDN Mag, March 2003. [8] Hernández Yamil, Katrib Miguel, Aspectos e Intercepción de Métodos en .NET, dotNetManía No 10, Diciembre 2004 [9] Schult W., Polze A., Aspect-Oriented Programming with C# and .Net. In Proc. of International Symposium on Object-oriented Real-time distributed Computing (ISORC) 2002, pp. 241-248, Crystal City, VA, USA, Mayo 2000. [10] Safonov Vladimir, : Concepts and Architecture, .NET Developer's Journal, October 2004. [11] Kiczales G, Hilsdale E, Huguin J, Kersten M, Palm J, Griswold V, An Overview of AspectJ, Springer-Verlag proceedings of the ECOOP 2001. [12] M. Devi Prasad and B.D. Chaudhary. AOP support in C# , AOSD 2003 [13] Lam J., Cross Language Aspect Weaving. Demonstration, AOSD 2002, Enschede, 2002.VOL. 6, NO. 3JOURNAL OF OBJECT TECHNOLOGY69ASPECT ORIENTED PROGRAMMING IN .NET. BASED ON ATTRIBUTESAbout the authors Miguel Katrib (mkm@matcom.uh.cu) is a PhD professor at the Computer Science Department of the University of Havana where he leads the WEBOO group dedicated to web and object oriented programming. Miguel authored several papers in programming languages and object technologies. He is an enthusiast of .NET technology working as redactor for the spanish journal dotNetManía. He is also a .NET programming advisor of the software company CARE Technologies, Denia, Spain. Yamil Hernández (yhsaa@matcom.uh.cu) is an instructor at the Computer Science Department of the University of Havana. He is developer of WEBOO group dedicated to web and object oriented programming. Yamil is an enthusiast of .NET technology. His main interested areas are Aspect and Object Oriented Programming, Reflection and Compiling Techniques.70JOURNAL OF OBJECT TECHNOLOGYVOL. 6, NO. 3。

相关文档
最新文档