A Case for Goal-oriented Programming Semantics

合集下载

【计算机专业文献翻译】面向对象编程具有多方面的吸引力

【计算机专业文献翻译】面向对象编程具有多方面的吸引力

英文文摘Why has object-oriented programming had such a sweeping impact on the software development community?Object-oriented programming appeals at multiple levels. For managers, it promises faster and cheaper development and maintenance. For analysts and designers, the modeling process becomes simpler and produces a clear, manageable design. For programmers, the elegance and clarity of the object model and the power of object-oriented tools and libraries makes programming a much more pleasant task, and programmers experience an increase in productivity. Everybody wins, it would seem.If there’s a downside, it is the expense of the learning curve. Thinking in objects is a dramatic departure from thinking procedurally, and the process of designing objects is much more challenging than procedural design, especially if you’re trying to create reusable objects.In the past, a novice practitioner of object-oriented programming was faced with a choice between two daunting tasks:1.Choose a language such as Smalltalk in which you had to learn a largelibrary before becoming productive.2.Choose C++ with virtually no libraries at all,and struggle through thedepths of the language in order to write your own libraries of objects.It is, in fact, difficult to design objects well –for that matter, it’s hard to design anything well. But the intent is that a relatively few experts design the best objects for others to consume. Successful OOP languages incorporate not just language syntax and a compiler, but an entire development environment including a significant library of well-designed, easy to use objects. Thus, the primary job of most programmers is to use existing objects to solve their application problems. The goal of this chapter is to show you whatobject-oriented programming is and how simple it can be.This chapter will introduce many of the ideas of Java and object-orientedpr ogramming on a conceptual level, but keep in mind that you’re not expected to be able to write full-fledged Java programs after reading this chapter. All the detailed descriptions and examples will follow throughout the course of this book.The progress of abstractionAll programming languages provide abstractions. It can be argued that the complexity of the problems you can solve is directly related to the kind and quality of abstraction. By “kind” I mean: what is it that you are abstracting? Assembly language is a small abstraction of the underlying machine. Manyso-called “imperative” languages that followed (such as FORTRAN, BASIC, and C) were abstractions of assembly language. These languages are big improvements over assembly language, but their primary abstraction still requires you to think in terms of the structure of the computer rather than the structure of the problem you are trying to solve. The programmer must establish the association between the machine model (in the “solution space”) and the model of the problem that is actually being solved (in the “problem space”). The effort required to perform this mapping, and the fact that it is extrinsic to the programming language, produces programs that are difficult to write and expensive to maintain, and as a side effect created the entire “programming methods” industry.The alternative to modeling the machine is to model the problem you’re trying to solve. Early languages such as LISP and APL chose particular views of the world (“all problems are ultimately lists” or “all problems are algorithmic”). PROLOG casts all problems into chains of decisions. Languages have been created for constraint-based programming and for programming exclusively by manipulating graphical symbols. (The latter proved to be too restrictive.) Each of these approaches is a good solution to the particular class of problem they’re designed to solve, but when you step outside of that domain they become awkward.The object-oriented approach takes a step farther by providing tools for the programmer to represent elements in the problem space. This representation is general enough that the programmer is not constrained to any particular type of problem. We refer to the elements in the problem space and their representations in the s olution space as “objects.” (Of course, you will also need other objects that don’t have problem-space analogs.) The idea is that the program is allowed to adapt itself to the lingo of the problem by adding new types of objects, so when you read the code d escribing the solution, you’re reading words that also express the problem. This is a more flexible and powerful language abstraction than what we’ve had before. Thus OOP allows you to describe the problem in terms of the problem, rather than in the terms of the solution. There’s still a connection back to the computer, though. Each object looks quite a bit like a little computer; it has a state, and it has operations you can ask it to perform. However, this doesn’t seem like such a bad analogy to objects in the real world; they all have characteristics and behaviors.译文为什么面向对象的编程会在软件开发领域造成如此震憾的影响?面向对象编程具有多方面的吸引力。

基于Java的飞机大战游戏的设计与实现论文

基于Java的飞机大战游戏的设计与实现论文

毕业设计(论文)任务书第1页第2页第3页基于Java的飞机大战游戏的设计与实现摘要现如今,随着智能手机的兴起与普及,加上4G(the 4th Generation mobile communication ,第四代移动通信技术)网络的深入,越来越多的IT行业开始向手机行业转移重心。

而手机行业中游戏方面的利润所占比重较大,并且手机游戏大多数则是由Java语言开发研制的。

所以我想顺应时代发展,用学到的Java知识对游戏进行一次深入的了解与创作。

Java语言在我们大学学习中占了很大的比重,其优点甚多:面向对象,可靠,安全,多平台可移植,高性能,多线程等。

面向对象是相对于c语言的面向过程来说的,在面向对象编程中,我们用Java去新建一个对象,调用其方法就能实现我们的目标,并不需要了解这个对象的方法的具体实现过程;Java的可靠安全特点体现Java不支持指针,禁止第三方访问,杜绝了外部风险。

所以使用Java开发游戏,是一个正确的选择。

大学学习即将结束,在毕业之际,我想用我4年里学习的知识为自己编写一个属于自己的游戏——飞机大战游戏,为我的大学生活画上圆满的句号。

关键词:Java游戏;面向对象;可靠安全;多线程Design And Implementation Of Airplane WargameBased On JavaAbstractNowadays, with the emergence and popularization of smart phones, plus 4 g (the 4 th Generation mobile communication, the fourth Generation mobile communication technology) the development of the Internet, more and more in the IT industry began to shift to the mobile phone industry center of gravity. Aspect of the game of the mobile phone industry profits account for a large proportion, and most mobile game is developed by Java language. So I want to keep up with the development of The Times, use Java knowledge for an in-depth understanding of the game and creation.Java language learning in our universities accounted for a large proportion of its many advantages: Object-oriented, reliable, secure, multi-platform portable, high-performance, multi-threading.Object-oriented process-oriented with respect to the terms of the c language, object-oriented programming, specifically we use Java to create a new object, call its methods will be able to achieve our goal,we do not need to know the object's method of implementation ; reliable safety features reflect Java Java does not support pointers to prohibit third-party access, to eliminate the external risk. Therefore, the use of Java development aircraft war game, is the right choice.University coming to an end, on the occasion of the graduation, I want to use my four years studying knowledge and made themselves a game of their own - Aircraft war game for my college life painting satisfactory conclusion.Keywords:Java game; object oriented; reliable and secure; multi thread目录1 引言 (1)1.1 项目背景 (1)1. 2 国内外研究现状 (3)1.3 项目主要工作 (4)1.4 本文组织结构 (6)2 开发平台与开发技术 (7)2. 1 IntelliJ IDEA简介 (7)2. 2 IntelliJ IDEA与Eclipse 、MyEclipse的比较 (8)2. 3 Java (10)3 可行性研究 (13)3. 1 技术可行性 (13)3. 2 经济可行性 (13)3. 3 操作可行性 (14)3. 4 用户使用可行性 (14)3. 5 法律可行性 (14)4 需求分析 (15)4. 1 系统需求概述 (16)4. 2 功能模块设计 (17)4.2.1 游戏状态控制功能模块 (17)4.2.2 游戏难度的调整模块 (17)4.2.3 游戏界面绘画功能模块 (17)4.2.4 玩家游戏控制功能模块 (17)4. 3 游戏难点分析 (18)4.3.1 绘图美化 (18)4.3.2 多线程技术的实现 (18)4.3.3 防碰撞问题的解决 (18)4.3.4 动画的实现 (18)5 飞机大战功能实现 (19)5.1 模型图 (19)5.2 软件功能模块 (19)5.3 游戏首页的实现 (20)5.3.1 界面实现 (20)5.3.2 流程图 (21)5.3.3 核心代码 (22)5.4 游戏开始模块的实现 (24)5.4.1 界面实现 (24)5.4.2 流程图 (25)5.4.3 核心代码 (25)5.5 发射子弹模块的实现 (27)5.5.1 界面实现 (27)5.5.2 流程图 (28)5.5.3 核心代码 (29)5.6 积分模块的实现 (33)5.6.1 界面的实现 (33)5.6.2 核心代码 (34)5.7 防碰撞逻辑 (37)5.7.1 核心代码 (37)5.8 游戏操作的实现 (39)5.8.1 核心代码 (39)5.9 特殊NPC蜜蜂 (41)6 系统测试 (42)6.1 测试的定义及其重要性 (43)6.1.1 测试的定义 (43)6.1.2 测试的重要性 (44)6.2 测试方法 (46)6.3 测试结果 (50)7 结论 (51)参考文献 (52)致谢 (54)外文文献 (55)中文翻译 (63)1 引言1.1 项目背景90后的我们,童年最开始接触电子游戏是在游戏厅,那时候的飞机大战游戏机前,往往人山人海,绚丽多彩的画面,带感操作让人沉醉不能自拔。

visual basic 2012 大学教程(第10章)

visual basic 2012 大学教程(第10章)

10. Object-Oriented Programming: Inheritance and PolymorphismSay not you know another entirely, till you have divided an inheritancewith him.—Johann Kasper LavaterThis method is to define as the number of a class the class of all classessimilar to the given class.—Bertr and RussellA philosopher of imposing stature doesn’t think in a vacuum. Even hismost abstract ideas are, to some extent, conditioned by what is or is notknown in the time when he lives.—Alfred North WhiteheadObjectivesIn this chapter you’ll learn:• What inheritance is and how it promotes software reuse.• To use keyword Inherits to create a derived class that inherits attributes andbehaviors from a base class.• To use access modifier Protected to give derived-class methods access to base-class members.• How constructors are used in inheritance hierarchies.• What polymorphism is and how it makes systems extensible and maintainable.• To distinguish between abstract and concrete classes.Outline10.1 Introduction10.2 Base Classes and Derived Classes10.3 Business Case Study: Commission Employees Class Hierarchy10.3.1 Creating Base Class CommissionEmployee10.3.2 Creating Derived Class BasePlusCommissionEmployee10.3.3 Testing Class BasePlusCommissionEmployee10.4 Constructors in Derived Classes10.5Protected Members10.6 Introduction to Polymorphism: A Polymorphic Video Game10.7 Abstract Classes and Methods10.8 Case Study: Payroll System Class Hierarchy Using Polymorphism10.8.1 Abstract Base Class Employee10.8.2 Concrete Derived Class SalariedEmployee10.8.3 Concrete Derived Class CommissionEmployee10.8.4 Indirect Concrete Derived Class BasePlusCommissionEmployee10.8.5 Demonstrating Polymorphic Processing10.9 Online Case Study: Interfaces10.10 Wrap-UpSummary | Terminology | Self-Review Exercises | Answers to Self-Review Exercises | Exercises10.1. IntroductionThis chapter continues our discussion of object-oriented programming by introducing inheritance, a form of software reuse in which a new class is created quickly and easily by absorbing an existing class’s members and customizing them with new or modified capabilities. With inheritance, you can save time during program development and build better software by reusing proven, high-quality classes. Enormous numbers of these classes are available in class libraries provided by Microsoft and independent software vendors.When creating a class, rather than declaring completely new members, you can designate that the new class inherits the members of an existing class. The existing class is called the base class, and the new class is the derived class.A derived class can add its own instance variables, Shared variables, properties and methods, and it can customize methods and properties it inherits. Therefore, a derived class is more specific than its base class and represents a more specialized group of objects.We explain and demonstrate polymorphism, which enables you to conveniently program ―in the general‖ rather than ―in the specific.‖ As we send method calls in thisgeneral way, the specific objects ―do the right thing.‖ You’ll see that polymorphism simplifies programming with classes and makes it easy to extend systems with new capabilities.10.2. Base Classes and Derived ClassesInheritance enables an is-a relationship. In an is-a relationship, an object of a derived class also can be treated as an object of its base class. For example, a car is a vehicle. Figure 10.1 lists several simple examples of base classes and derived classes—base classes tend to be more general and derived classes tend to be more specific. Base-class objects cannot be treated as objects of their derived classes—although all cars are vehicles, not all vehicles are cars (the other vehicles could be trucks, planes or bicycles, for example).Fig. 10.1. Inheritance examples.Because every derived-class object is an object of its base class, and one base class can have many derived classes, the set of objects represented by a base class is typically larger than the set of objects represented by any of its derived classes. For example, the base class Vehicle represents all vehicles, including cars, trucks, boats, bicycles and so on. By contrast, derived class Car represents a smaller, more specific subset of vehicles. CommunityMember Inheritance HierarchyFigure 10.2 shows a sample UML class diagram of an inheritance hierarchy. A college community has thousands of community members, including employees, students and alumni. Employees are either faculty members or staff members. Faculty members are either administrators (such as deans and department chairpersons) or teachers. The hierarchy could contain many other classes. For example, students can be graduate or undergraduate students. Undergraduate students can be freshmen, sophomores, juniors or seniors.Fig. 10.2. Inheritance hierarchy for university CommunityMembers.Each arrow in the inheritance hierarchy represents an is-a relationship. As we follow the arrows upward in this class hierarchy, we can state, for instance, that ―an Employee is a CommunityMember‖ and ―a Teacher is a Faculty member.‖A direct base class is the class from which a derived class explicitly inherits. An indirect base class is inherited from two or more levels up in the class hierarchy. So, class CommunityMember is the direct base class of Employee, Student and Alumnus, and is an indirect base class of all the other classes in the diagram. Starting from the bottom of the diagram, you can follow the arrows and apply the is-a relationship up to the topmost base class. For example, an Administrator is a Faculty member, is an Employee and is a CommunityMember. Shape Inheritance HierarchyNow consider the Shape hierarchy in Fig. 10.3. It begins with base class Shape, which is inherited by derived classes TwoDimensionalShape and ThreeDimensionalShape—Shape s are either TwoDimensionalShape s or ThreeDimensionalShape s. The third level of the hierarchy contains more specific types of TwoDimensionalShape s and ThreeDimensionalShape s. As in Fig. 10.2, we can follow the arrows from the derived classes at the bottom of the diagram to the topmost base class in this class hierarchy to identify several is-a relationships. For example, a Triangle is a TwoDimensionalShape and is a Shape, while a Sphere is a ThreeDimensionalShape and is a Shape. Shape is a direct base class of classes TwoDimensionalShape and ThreeDimensionalShape, and is an indirect base class of all the classes on the third level.Fig. 10.3. Inheritance hierarchy for Shapes.10.3. Business Case Study: Commission Employees Class HierarchyIn this section, we use a business-oriented inheritance hierarchy containing types of employees in a company’s payroll app to discuss the relationshi p between a base class and its derived class. All employees of the company have a lot in common, but commission employees (who will be represented as objects of a base class) are paid a percentage of their sales, while base-salaried commission employees (who will be represented as objects of a derived class) receive a percentage of their sales plus a base salary. First, we present base class CommissionEmployee. Next, we create a derived class BasePlusCommissionEmployee that inherits from class CommissionEmployee. Then we present an app that creates a BasePlusCommissionEmployee object and demonstrates that it has all the capabilities of the base class and the derived class, but calculates its earnings differently.10.3.1. Creating Base Class CommissionEmployeeConsider class CommissionEmployee (Fig. 10.4). The Public services of class CommissionEmployee include:• a constructo r (lines 11–20)• properties FirstName (line 4), LastName (line 5), SocialSecurityNumber (line 6), GrossSales (lines 23–36) and CommissionRate (lines 39–52)• methods CalculateEarnings (lines 55–57) and ToString (lines 60–66).Click here to view code image1' Fig. 10.4: CommmissionEmployee.vb2' CommissionEmployee base class.3Public Class CommissionEmployee4Public Property FirstName() As String' auto-implemented5Public Property LastName() As String' auto-implemented6Public Property SocialSecurityNumber() As String' auto-implemented7Private grossSalesValue As Decimal' gross weekly sales8Private commissionRateValue As Double' commission percentage 910' five-argument constructor11Public Sub New(first As String, last As String,12 ssn As String, sales As Decimal, rate As Double)1314' implicit call to class Object's constructor occurs here15 FirstName = first16 LastName = last17 SocialSecurityNumber = ssn18 GrossSales = sales ' validate and store gross sales19 CommissionRate = rate ' validate and store commission rate20End Sub' New2122' property GrossSales23Public Property GrossSales() As Decimal24Get25Return grossSalesValue26End Get2728Set(sales As Decimal)29If sales >= 0D Then' validate gross sales30 grossSalesValue = sales ' valid31Else32Throw New ArgumentOutOfRangeException( 33"Gross sales must be greater than or equal to 0")34End If35End Set36End Property' GrossSales3738' property CommissionRate39Public Property CommissionRate() As Double40Get41Return commissionRateValue42End Get4344Set(rate As Double)45If rate > 0.0 AndAlso rate < 1.0Then' validate rate46 commissionRateValue = rate ' valid47Else48Throw New ArgumentOutOfRangeException( 49"Interest rate must be greater than 0 and less than 1") 50End If51End Set52End Property' CommissionRate5354' calculate earnings55Public Overridable Function CalculateEarnings() As Decimal56Return Convert.ToDecimal(CommissionRate) * GrossSales57End Function' CalculateEarnings5859' return String representation of CommissionEmployee object60Public Overrides Function ToString() As String61Return"commission employee: " & FirstName & " " & LastName & 62vbCrLf & "social security number: " & SocialSecurityNumber & 63vbCrLf & "gross sales: " & String.Format("{0:C}", GrossSales) & 64vbCrLf & "commission rate: " &65 String.Format("{0:F}", CommissionRate)66End Function' ToString67End Class' CommissionEmployeeFig. 10.4. CommissionEmployee base class.The class also declares Private instance variables grossSalesValue and commissionRate-Value (lines 7–8) to represent the employe e’s gross sales and commission rate. Recall that the compiler automatically generates a Private instance variable for each auto-implemented property, so a CommissionEmployee actually has five Private instance variables.The Set accessors of properties GrossSales and CommissionRate validate their arguments before assigning the values to instance variables grossSalesValue and commissionRateValue, respectively. Properties FirstName, LastName and SocialSecurityNumber are auto-implemented in this example, becaus e we’re not providing any validation code in their Set accessors. We could validate the first and last names—perhaps by ensuring that they’re of a reasonable length. The social security number could be validated to ensure that it contains nine digits, with or without dashes (for example, 123-45-6789 or 123456789).All Classes Inherit Directly or Indirectly from Object (from Namespace System)You use inheritance to create new classes from existing ones. Every class except Object inherits from an existing class. When you do not explicitly specify the base class for a new class, the compiler implicitly assumes that the class Inherits from Object. The class hierarchy begins with class Object (in namespace System), which every class directly or indirectly extends (or ―inherits from‖). So, the beginning of class CommissionEmployee could be written asPublic Class CommissionEmployeeInherits ObjectYou typically do not include ―Inherits Object‖ in your code, since it’s implied. Class CommissionEmployee inherits the methods of class Object—class Object does not have any fields. One of the methods inherited from class Object is ToString, so every class has a ToString method that returns a String representation of the object on which it’s called. We discuss the default behavior of method ToString momentarily. CommissionEmployee ConstructorConstructors are not inherited, so class CommissionEmployee does not inherit class Object’s constructor. However, class CommissionEmployee’s constructor (lines 11–20) calls Object’s constructor implicitly. In fact, the first task of any derived-class constructor is to call its direct base class’s con structor, either explicitly or implicitly (if no constructor call is specified), to ensure that the instance variables declared in the base class are initialized properly. The syntax for calling a base-class constructor explicitly is discussed in Section 10.3.2. If the code does not include an explicit call to the base-class constructor, Visual Basic implicitly calls the base class’s default or parameterless constructor. The comment in line 14 of Fig. 10.4 indicates where the implicit call to the base class Object’s default constructor occurs (you do not need to write the code for this call). Object’s default constructor does nothing. Even if a class does not have constructors, the default constructor that the compiler implicitly creates for the class will call the base class’s default or parameterless constructor. After the implicit call to Object’s constructor occurs, lines 15–19 assign values to the class’s properties.Method CalculateEarnings and Declaring Methods OverridableMethod CalculateEarnings (lines 55–57) calculates a CommissionEmployee’s earnings. Line 56 multiplies the CommissionRate by the GrossSales and returns the result. A base-class method must be declared Overridable if a derived class should be allowed to override the method with a version more appropriate for that class. When we create class BasePlusCommissionEmployee, we’ll want to override (redefine) CommissionEmployee’s CalculateEarnings method to customize the earnings calculation for a BasePlusCommissionEmployee. For this reason, we declared CalculateEarnings as Overridable in line 55. In BasePlusCommissionEmployee, we’ll declare method CalculateEarnings with the keyword Overrides.Method ToString and Overriding Base Class MethodsMethod ToString (lines 60–66) returns a String containing information about the CommissionEmployee. The keyword Overrides (line 60) indicates that this method overrides (redefines) the version of ToString that was inherited from CommissionEmployee’s base class (that is, Object). In class Object, method ToString is declared as:Public Overridable Function ToString() As Stringso that ToString can be overridden in any derived class.If you do not override ToString in class CommissionEmployee, the default implementation inherited from class Object would return only"missionEmployee"—for this example, we named the project InheritanceTest.10.3.2. Creating Derived Class BasePlusCommissionEmployeeMost of a BasePlusCommissionEmployee’s capabilities are similar, if not identical, to the those of class CommissionEmployee (Fig. 10.4). Both classes require instance variables for the first name, last name, social security number, gross sales and commission rate, and properties and methods to manipulate that data. To create class BasePlusCommissionEmployee without using inheritance, we probably would have copied the code from class CommissionEmployee and pasted it into class BasePlusCommissionEmployee, then modified the new class to include a base salary instance variable, and the methods and properties that manipulate the base salary, including a new CalculateEarnings method. This copy-and-paste approach is often error prone and time consuming. Worse yet, it can spread many physical copies of the same code (including errors) throughout a system, creating a code-maintenance nightmare. Is there a way to ―absorb‖ the instance variables and methods of one class in a way that makes them part of another class without duplicating code? Indeed there is—using the elegant object-oriented programming technique of inheritance.Software Engineering Observation 10.1With inheritance, the common instance variables and methods of all the classesin the hierarchy are declared only in a base class. When changes are required forthese common features, you need to make the changes only in the base class—derived classes then inherit the changes. Without inheritance, the changes wouldneed to be made to all the source-code files that contain copies of the code inquestion.Declaring Class BasePlusCommissionEmployeeWe now discuss the second part of our introduction to inheritance by declaring the derived class BasePlusCommissionEmployee (Fig. 10.5), which inherits most of its capabilities from class CommissionEmployee (line 4). A BasePlusCommissionEmployee is a CommissionEmployee (because inheritance passes on the capabilities of class CommissionEmployee), but class BasePlusCommissionEmployee also has• instance variable baseSalaryValue (line 6)• property BaseSalary (lines 19–32).Also, BasePlusCommissionEmployee provides• a constructor (lines 9–16)• a customized version of method CalculateEarnings (lines 35–37)• a customized version of method ToString (lines 40–43).Click here to view code image1' Fig. 10.5: BasePlusCommissionEmployee.vb2' BasePlusCommissionEmployee inherits from class CommissionEmployee.3Public Class BasePlusCommissionEmployee4Inherits CommissionEmployee56Private baseSalaryValue As Decimal' base salary per week78' six-argument constructor9Public Sub New(first As String, last As String,10 ssn As String, sales As Decimal,11 rate As Double, salary As Decimal )1213' use MyBase reference to call CommissionEmployee constructor14MyBase.New(first, last, ssn, sales, rate)15 BaseSalary = salary ' validate and store base salary16End Sub' New1718' property BaseSalary19Public Property BaseSalary() As Decimal20Get21Return baseSalaryValue22End Get2324Set(salary As Decimal)25If salary >= 0D Then' validate base salary26 baseSalaryValue = salary ' valid27Else28Throw New ArgumentOutOfRangeException(29"Base salary must be greater than or equal to 0")30End If31End Set32End Property' BaseSalary3334' calculate earnings35Public Overrides Function CalculateEarnings() As Decimal36Return BaseSalary + MyBase.CalculateEarnings()37End Function' CalculateEarnings3839' return String representation of BasePlusCommissionEmployee object40Public Overrides Function ToString() As String41Return"base-plus-" & MyBase.ToString() & vbCrLf &42"base salary: " & String.Format("{0:C}", BaseSalary)43End Function' ToString44End Class' BasePlusCommissionEmployeeFig. 10.5. BasePlusCommissionEmployee class inherits from classCommissionEmployee.Inheriting from Class CommissionEmployeeKeyword Inherits in line 4 of the class declaration indicates that class BasePlusCommissionEmployee inherits all of the Public members (and, as we’ll soon see, Protected members if there were any) of class CommissionEmployee. We do not redeclare the base class’s Private instance variables—these are nevertheless present (but hidden) in deriv ed class objects. Even though they’re present, they’re declared Private in the base class, so as we’ll see in a moment, we’ll have to make a special provision to access this base-class information from the derived class. The CommissionEmployee constructor is not inherited. Thus, the Public services of BasePlusCommissionEmployee include its• constructor (lines 9–16)• the Public methods and properties inherited from class CommissionEmployee• property BaseSalary (lines 19–32), which cannot be auto-implemented because it performs validation in its Set accessor• method CalculateEarnings (lines 35–37)• method ToString (lines 40–43).BasePlusCommissionEmployee ConstructorEach derived-class constructor must implicitly or explicitly call its base-class constructor to ensure that the instance variables inherited from the base class are properly initialized. BasePlusCommissionEmployee’s six-argument constructor (lines 9–16) explicitly calls class CommissionEmployee’s five-argument constructor (line 14) to initialize the base class portion of a BasePlusCommissionEmployee object (that is, the five instance variables from class CommissionEmployee). Line 14 uses the base-class constructor call syntax—keyword MyBase, followed by the dot (.) separator, followed by New and a set of parentheses containing the arguments to the base-class constructor—first, last, ssn, sales and rate. Then, line 15 initializes the BasePlusCommissionEmployee’s base salary.If the BasePlusCommissionEmployee constructor did not include line 14, Visual Basic would attempt to invoke class CommissionEmployee’s parameterless or default constructor, which does not exist, so a compilation error would occur. The explicit base-class constructor call (line 14) must be the first statement in the derived-class constructor’s body.Overriding Method CalculateEarningsClass BasePlusCommissionEmployee’s CalculateEarnings method (lines 35–37) overrides class CommissionEmployee’s CalculateEarnings method (Fig. 10.4, lines 55–57) to calculate the earnings of a base-salaried commission employee. The new version obtains the portion of the employee’s earnings based on co mmission alone by calling CommissionEmployee’s CalculateEarnings method with the expressionMyBase.CalculateEarnings() (line 36). BasePlusCommissionEmployee’s CalculateEarnings method then adds the BaseSalary to this value to calculate the total earnings of the derived-class employee. Note the syntax used to invoke an overridden base-class method from a derived class—place the keyword MyBase and a dot (.) separator before the base-class method name. By having BasePlusCommissionEmployee’s CalculateEarnings method invoke CommissionEmployee’s CalculateEarnings method to calculate part of a BasePlusCommissionEmployee object’s earnings, we avoid duplicating the code and reduce code-maintenance problems.Overriding Method ToStringBasePlusCommissionEmployee’s ToString method (lines 40–43) overrides class CommissionEmployee’s ToString method (Fig. 10.4, lines 60–66) to return a String representation that’s appropriate for a BasePlusCommissionEmployee. The derived class creates part of a BasePlusCommissionEmployee object’s String representation by concatenating "base-plus-" with the String returned by calling CommissionEmployee’s ToString method via the expression MyBase.ToString() (Fig. 10.5, line 41). BasePlusCommissionEmployee’s ToString method then concatenates the remainder of a BasePlusCommissionEmployee object’s String representation (that is, the value of class BasePlusCommissionEmployee’s base salary) before returning the String.10.3.3. Testing Class BasePlusCommissionEmployeeFigure 10.6 tests class BasePlusCommissionEmployee. Lines 9–10 create a BasePlusCommissionEmployee object and pass "Bob", "Lewis", "333-33-3333", 5000, 0.04 and 300 to the constructor as the first name, last name, social security number, gross sales, commission rate and base salary, respectively. Lines 13–22 use BasePlusCommissionEmployee’s properties to output the object’s data. Notice th at we’re able to access all of the Public properties of classes CommissionEmployee and BasePlusCommissionEmployee here. Lines 25–26 calculate and display the BasePlusCommissionEmployee’s earnings by calling its CalculateEarnings method. Because this method is called on a BasePlusCommissionEmployee object, the derived-class version of the method executes. Next, lines 29–31 modify the GrossSales, CommissionRate and BaseSalary properties. Lines 34–36 output the updated data—this time by calling the BasePlusCommissionEmployee’s ToString method. Again, because this method is called on a BasePlusCommissionEmployee object, the derived classversion of the method executes. Finally, lines 39–40 calculate and display the BasePlusCommissionEmployee’s updated earnings.Click here to view code image1' Fig. 10.6: InheritanceTest.vb2' Testing derived class BasePlusCommissionEmployee.3Public Class InheritanceTest4' demonstrate class BasePlusCommissionEmployee5Private Sub InheritanceTest_Load(sender As Object,6 e As EventArgs) Handles MyBase.Load78' instantiate BasePlusCommissionEmployee object9Dim employee As New BasePlusCommissionEmployee(10"Bob", "Lewis", "333-33-3333", 5000D, 0.04, 300D)1112' get base-salaried commission employee data13 outputTextBox.AppendText(14"Employee information obtained by properties:" & vbCrLf & 15"First name is " & employee.FirstName & vbCrLf &16"Last name is " & stName & vbCrLf &17"Social Security Number is " & employee.SocialSecurityNumber & 18vbCrLf & "Gross sales is " &19 String.Format("{0:C}", employee.GrossSales) & vbCrLf &20"Commission rate is " &21 String.Format("{0:F}", missionRate) & vbCrLf &22"Base salary is " & String.Format("{0:C}", employee.BaseSalary)) 2324' display the employee's earnings25 outputTextBox.AppendText(vbCrLf & vbCrLf & "Earnings: " &26 String.Format("{0:C}", employee.CalculateEarnings()))2728' modify properties29 employee.GrossSales = 10000D' set gross sales30 missionRate = 0.05' set commission rate31 employee.BaseSalary = 1000D' set base salary3233' get new employee information34 outputTextBox.AppendText(vbCrLf & vbCrLf &35"Updated employee information returned by ToString: " &36vbCrLf & employee.ToString())3738' display the employee's earnings39 outputTextBox.AppendText(vbCrLf & vbCrLf & "Earnings: " &40 String.Format("{0:C}", employee.CalculateEarnings()))41End Sub' InheritanceTest_Load42End Class' InheritanceTestFig. 10.6. Testing derived class BasePlusCommissionEmployee.10.4. Constructors in Derived ClassesCreating a derived-class object begins a chain of constructor calls in which the derived-class constructor, before performing its own tasks, invokes its direct base class’s constructor either explicitly (via the MyBase reference) or implicitly (calling the base class’s default or parameterless constructor). Similarly, if the base class is derived from another class (as is every class except Object), the base-class constructor invokes the constructor of the next class up the hierarchy, and so on. The last constructor called in the chain is always the constructor for class Object. The original derived-class constructor’s body finishes executing last.Each base class’s construct or initializes the base-class instance variables that are part of the derived-class object. For example, When a program creates a BasePlusCommissionEmployee object (Fig. 10.6, lines 9–10), the BasePlusCommissionEmployee constructor is called. That constructor, before executing its full body code, immediately calls CommissionEmployee’s constructor (Fig. 10.5, line 14), which in turn calls Object’s constructor. Class Object’s constructor has an empty body, so it immediately returns control to the CommissionEmployee’s constructor, which then initializes the Private instance variables of CommissionEmployee (Fig. 10.4, lines 15–19) that are part of the BasePlusCommissionEmployee object. When the。

Journal of Information Systems Education Volume 11(3-4) MOO An Active-Learning Environment

Journal of Information Systems Education Volume 11(3-4) MOO An Active-Learning Environment

Journal of Information Systems Education Volume 11(3-4)MOO: An Active-Learning Environment For Teaching Object-Oriented Concepts In Business Information Systems CurriculaJohn Towellt Department of Computer Science, Carroll College Waukesha, WI 53186, U.S.AAbstractObject-oriented concepts may become increasingly necessary for understanding and using business information systems. Business students are often exposed to object- oriented concepts in non-programming courses. We have used a text-based virtual reality, called a MOO, to provide students with an opportunity to learn object-oriented concepts by actively creating and using objects -but without writing code. After one lecture and two fifty minute labs, 75% of 172 business students successfully solved a goal-oriented exercise which required the use of object-oriented concepts. The MOO environment allowed the student to experience as well as learn object-orientated concepts without the use of a rigorous programming language.Keywords: Object-oriented, business students, virtual reality, MOO, teaching, presence, constructionistINTRODUCTIONEducating business students during these times of tumultuous technological change often appears an uncertain task. There is no doubt that the complexities of business information systems will continue to increase and there are those who believe this complexity will require the use of thinking styles based on object-orientation (Fingar, 1996). Teaching fundamental object-oriented (00) concepts is often conducted in non-programming courses in the business college curriculum. Hence, in the absence of an active- learning experience, such as programming, the students' understanding remains descriptive. We were interested in the use of text-based virtual reality to create an active-Iearning 00 experience without the rigors of programming. This manuscript describes a type of text-based virtual reality called a Moo, and how it was used as a tool for teaching 00 concepts in an introductory business information systems course. The results reported here demonstrate that 00jtowell@concepts can be learned by business students after one traditional lecture and two laboratory exercises in the MOO.2. METHODSNETWORKED VIRTUAL ENVIRONMENTS -MOOThe text-based virtual reality used in the studies reported here is of the MOO (Multi-user dimension Object Oriented) type. This system, developed primarily at Xerox P ARC(Palo Alto Research Center) by Pavel Curtis (Curtis, 1992), is composed of a server and a database which are available(ftp:///pub/MOO/) at no cost. Theserver can provide simultaneous connections for hundreds of Internet users via the telnet protocol (or other more specialized clients). It acts as a parser for interpreting commands given by connected users, and it serves as a database management system. The database contains information about objects that constitute the environment inJournal ofInfonnation Systems Educatio] Volume 11(3-4)which the user operates. This information includes the structure of the environment, or topography which typically consists of rooms connected by entrances/exits that can be navigated with the use of simple commands. The topography of the environment used here, called OMIS MOO (Figure I ), was recorded on a map which could be easily seen by the user. The database also contains information about objects contained within the topography and finally, it contains information about the object to which the user is connected. This object can be thought of as an avatar or virtual representation of the user and will be referred to in this manuscript as simply the virtual student. Virtual students can easily communicate by textual exchange with any other virtual students (and the instructor) who occupy the same room. More sophisticated techniques are available for communicating with those who are in other rooms or even in other networked MOOs. The MOO environment is extensible and students need not know how to program to build and characterize their own rooms, exits/entrances and objects. We have hypothesized that this combination of "being in" an architecture of connected rooms (in a virtual sense), building and interacting with objects, and communicating with others, creates an environment which is aptly suited for active-Ieaming or constructionist experiences (Papert, 1991 ), particularly with regard to object-oriented concepts. Others have also recognized the potential of this environment for teaching (Haynes, 1998).ccO"IS "OO~~ OOMDr. B. TOWELL c OMIS Wlt-iGI. TOWELLWEST WltiG STUDEtiT OffiCESLlBRAR...ROOMFigureOMI535152Topography ofOMIS MOOSAMPLE POPULA TIONThe subjects in the current studies were composed of students in two sections of "Introduction to Business Inrormation Systems" taught in the College of Business at Northern Illinois University (NIU) spring 1999. The total number of students was 172. Marketing and management majors composed roughly half of the classes, operations management and information systems (OMIS) majors constituting approximately 25%, and the remaining 25% was composed of various majors including finance and accounting.PREPARATIONThree exercises were conducted before the students were presented with an 00 goal-oriented task. The first exercise was a traditional lecture on object-oriented concepts which included fundamentals such as objects, methods, attributes, inheritance, encapsulation and polymorphism. This was followed by a demonstration where the students observed inthe classroom the instructor logging into the text-based virtual reality, OMIS MOO, navigating the topography (Figure I ),looking at the map, communicating with another virtual student, and creating and manipulating objects. The second exercise involved the students logging into the MOO and was focused on proper use of the telnet client available in the NIU computer labs, connecting to the MOO, navigation, and practicing communication commands. Most of the 60 minute period was spent with the instructor interacting with students in the laboratory having difficulties using the telnet client and logging into the MOO. In between interactions with the students in the laboratory, the instructor gave directions to the virtual students in OMIS MOO for various communication commands and requested that the virtual students practice them. The third exercise required the students to be in the OMIS MOO Lecture Room (Figure I) and the instructor presented a series of slides which directed the following manipulations: (I) creation of an object called a note; (2) examination of the note's methods; and (3) using the appropriate method for writing on the note, i.e., setting an attribute. After this laboratory, students were able to connect to OMIS MOO at any time to practice and access the slides shown during the exercise. These slides were kept in the OMIS MOO Library (Figure I).GOAL-ORIENTED EXERCISEStudents were required to connect during class time to OMIS MOO and conduct the assignment that was posted on an object in the 'ISL LAB' (Figure 1 ). This required examining the object to understand its methods and then, apply them to gain understanding of the assignment itself. Theassignment told the students to go to a designated room in the MOO and write their names on a blackboard found there. Then they were to go to another room and drop the note object they had created during the previous assignment into a box that was there. The instructions for Section 3 were the same as Section 2 except that different locations were used for the object on which they were to write their names, and the box into which they were to deposit their objects. The blackboard on which they wrote their names time- stamped the event when the appropriate command was given. The instructor was connected during the class period but only gave two types of information. First, the students were regularly informed by announcements where the assignment was located. Second, if a student sought out the instructor, the instructor would only tell the student that to leam how an object works, you must 'examine' it. A MOO object reveals its methods when the 'examine' command is given.3. RESULTSOf the two sections of85 and 87 students, 80% and 83% logged into OMIS MOO during their allotted 60 minute time period. The first part of the assignment, that which was required for receiving attendance credit, was accomplished by 85.3% of the Section 2 people and 87.5% of the Section 3 people who logged in. This task required the student to: (I) manipulate the object on which the assignment was located;Journal of Information Systems Education Volume 11(3-4)(2) go to the appropriate room; (3) determine how to write their name on the blackboard (ascertain the object's methods); and (4) execute the appropriate method (employ method to set the object's attributes). The mean times for task accomplishment for the Section 2 group and Section 3 group were 30.7 minutes and 28.3 minutes, respectively (Figure 2).'-' -- 00 u.S O (I: LJJ s m ~ ~42 O15 20 25 30 35 40 45 MINUTESFigure 2: Number of students versus time taken to accomplish object-oriented goal.The second part of the assignment was to navigate OMIS MOO to a designated room and put a note into a box that was inside the room. The notes found in the designated boxes indicated a 75% success rate for both sections.4. DISCUSSIONAlthough it is known that people are less inhibited in computer-mediated communication (Sproull, 1991) , it was nevertheless, a great surprise to observe a generally quiescent class erupt into nearly ceaseless talking when in the MOO environment. This was true for both sections and warrants the use of a moderated room which governs the number of people who may speak concurrently (Towell, 1995). It has been shown that under conditions similar to those reported here, nearly 70% of the people in a MOO report feeling some degree of "being there" or presence (Towell, 1997). At this time it has not been demonstrated to what degree various environmental factors play towards the generation of presence in text-based virtual reality. One such factor may be the imposition of the spatial metaphor (Evard, 1993) which results from seeing the map, navigating the topography and interacting with objects in the environment, including other people. Whatever these factors may be, further studies are planned to assess relationships that may exist between virtual presence and learning efficacy.The exercises discussed here were followed by increasingly difficult assignments in the MOO throughout the semester. At the end of the course the students were asked to rate on a scale of 1-5 the degree to which they agreed with the following statement; "The OMIS MOO environment did *not* help me gain any sense of what object orientation means." Nearly 75% of the students answered with a 4 or 5 which indicated that they believed the MOO had helped them gain a sense of what object orientation meant. In a similar manner the students were asked to rate the degree with whichthey agreed with the following statement; "I would rather attend a lecture than participate in a MOO laboratory." 65% answered with a 4-5. Only 16% answered with a 1-2 (preferred lecture) while the rest answered with a 3 (19%) and hence had no preference. This indicated most students preferred the MOO to a traditional lecture.s. RECOMMENDATIONSTo help meet the challenge of contemporary technological change, we recommend: (I) that business students be taught the fundamental principles of object-oriented systems; (2) that business students learn and experience object orientation without having to learn a formal programming language; and (2) that these students should be allowed to experience object orientation by active participation in an immersive object-oriented environment.6. CONCLUSIONA text-based virtual reality of the MOO type was used to study the feasibility of teaching object-oriented principles in a non-programming manner to junior- and senior-level students in the College of Business at Northern Illinois University. The student reaction to the MOO was one of surprising exuberance. After three preparatory exercises, nearly 90% of 172 students were successful in a goal-oriented exercise that required knowledge of the following principles of object-orientation: objects, methods, attributes, inheritance and encapsulation. Studies are currently underway to further assess the feasibility of using the MOO environment as a pedagogical tool in more sophisticated object-oriented tasks such as those involving polymorphism. It is concluded that the MOO-type text-based virtual reality can be used to teach object-oriented concepts in an active-Iearning environment and that the students found the MOO experience worthwhile and preferred it to a traditional lecture mode.7. REFERENCESFingar, P., 1996, The Blueprint for Business Objects. New York, NY: SIGS Books and Multimedia.Curtis, P., 1992, "Mudding: Social phenomena in text- based virtual realities." Proceedings of the 1992 Conference on Directions and Implications of Advanced Computing, Berkeley, CA.Papert, S., 1991, "Situating Constructionism," Constructionism, eds. Idit Harel, and Seymour Papert Norwood, NJ: Ablex Publishing.Haynes, C., and Jan-Rune Holmevik, 1998, High wired: On the design, use, and theory of educational MOOs, Ann Arbor, MI ,University of Michigan Press.Sproull, L., and Sara Kiesler, 1991, Connections: New ways of working in the networked organization, Cambridge, MA, MIT Press.149Journal of Infonnation Systems Education Volume 11(3-4)Towell, J., and Elizabeth Towell, 1995 "Internet conferencing with networked virtual environments." Internet Research 5(3), pp. 15-22.Towell, J., and Elizabeth Towell, 1997 "Presence in text- based networked virtual environments or "MUDS,"" Presence, 6(5) pp. 590-595.Evard, R., 1993, "Collaborative networked communication MUDS as systems tools." Proceedings of the Seventh Systems Administration Conference (LISA VII), November, pp. 1-8, Monterey, CA. AUTHOR BIOGRAPHYDr. John Towell is an assistant professor of computerscience at Carroll College. Dr. Towell received his BA from the University of Colorado and his Ph.D. from Colorado State University. His research interests are in the effects of virtual presence on learoing, communication, and knowledge creation.150。

c语言教程英文版讲义(一)

c语言教程英文版讲义(一)

2Some Informationo Lecturingn C/C++ Language n Artificial Intelligence n Specialized Englisho Phone numbers and emailn Office: A0816n Phone: 84706003-3816n Email: eecc2012@3Textbooko 书名:C 语言教程(英文版·第4版)o 原书名:A Book on C:Programming in Co 作者:(美)Al Kelley, Ira Pohl o 出版社:China Machine Pres s4Professor of Computer and Information Scienceso Ira Pohl is a Professor of ComputerScience at the University of California, Santa Cruz.o His current research is in object-orientedprogramming(OOP) and topics in software methodology. He has written widely on programming in C, C++,C# and Java.o His research interests include artificialintelligence (AI), the C#, C, C++ and Java programming languages, practical complexity problems, heuristic search methods, etc..5Reference Readingo 书名:C 语言的科学和艺术(英文版)o 原书名:The Art andScience of C:A Library Based Introduction to Computer Science o 作者:Eric S.Robertso 出版社:China Machine Pres s6Reference Readingo 书名:C 程序设计语言(第2版·新版)o 原书名:The C ProgrammingLanguageo 作者:(美)Brian W.Kernighan,Dennis M.Ritchieo 出版社: Prentice-HallInternational , Inc.7Course administrationo Class hours :72 Credits :4n Teaching hours :48 hours (3 credits)n Practice hours :24 hours (1 credits)o Grading system :100n Final exam: 60%n Homework and Quizz: 15%n Projects: 25%Course administrationo Class is 4hours of lecture a week, Monday andWednesday at 13:30pm and 8:00amo 4 hours of practice a week ,6 weeks from 6th~11th week o 8hours a week of outside-the-class.9Why do we learn C language?o Today is the era of java and .net.oC is the fundament of OS. The kernel of Unix, Linux and Windows are written by C. Windows API is the interface of C functions. Unix/Linux applications are developed by C.oIf you want to be the superior of programmer, you must learn C language.oC# derived from C/C++What skills will you acquire?o You’re going to be able to write.o You’re going to be able to read.o Understand abilities and limits.o Understand what you can and cannot do.11How to study C programming:Some proverbso Standardization of formatn Well begun, half done.n A year ’s plan starts spring.o Have patiencen A workman must first sharpen his tools if he is to dohis work well.n Right tool for the right job.o Debug routinen Everything has a hard beginning.n Practice makes perfect.To follow, without halt, one aim:there the secret of success.12How to study C programming:o 1. Read all assigned reading in the textbook.--Not just once.--one paragraph at a time.--close the book, summarize the paragraph you just read.--If you could not summarize it quickly and accurately,read it again .o 2. Read your lecture notes in the same way.Type in all the programs you saw in class and make sure you understand them.o 3. Read the documentation of strcpy , strcat , strcmp ,malloc , calloc , strlen , printf , sprint , sscanf etc. Know how to find the documentation of any C library function and what is meant by "the documentation".o 4. Read your homework and make sure you know how itworks. The exams will definitely include several questions about the homework programs.13What I expect from you as a student:o Show up for classo Show up for class on timeo Know what the topic is for that dayo Have already read the corresponding part of the textbook (see the lecture schedule)o After the class meets, go over the material again (textbook, and notes, if any)o Do your homework (and on time!)o Do your own homework by yourself . (You can discuss it orally but you must do your own writing.)o Arrange your schedule so that you have identifiable hours each week to spend on this course.oWork at a steady pace throughout the semester instead of in frantic bursts just before the final exam.14What will we learn?o Program o Functionsn Declarationso Constant o Variablen fundamental :int, char, float, double n structured: array, struct, union n pointern Statementso assignmento control: if, for, do, while,…o compound o null150 Starting from Zero2 Lexical Element,Operators, and C System 3The Fundamental Data Types 4Flow of Control 5Functions6Arrays, Pointers and Strings7Bitwise Operators and Enumeration Types 8The preprocessor 9Structures and Unions 10Structures and List Processing11Input/Output and the Operating System13 Moving from C to C++Contents 16o Some termsn Computer language n Programn Programming n Algorithmo Program ’s Constitutionn Some representation of fundamental data n Give instructions to computer(decription of recipe)C/C++ Language17o What is the program?n data structure+algorithm=program n data structure+algorithm+structured programming method+language tool= programo Three basic structuresn Sequential n conditional n IterationC/C++LanguageNikiklaus Wirth——Computer Scientist18o 0.1 C ’s background o 0.2 C ’s Characteristic o 0.3 ANSI C Standard o 0.4 From C to C++o 0.5 From C and C++ to Java0 Starting from Zero19The basic organization of a computer system0.1 C ’s background Arithmetic sectionStorage sectionControl section Input device Output deviceresultprogramdataCPU20Machine languagesAssembly languagesHigh-level languageProcedure -oriented Object-oriented0.1 C ’s backgroundThe development of programming languages211.In the mid-1970s,UNIX spread throughout BellLabs.2.By 1980,several C compilers were put forward onthe market.3.By now,there are many versions of C languages.0.1 C ’s background The origin of C language 22True dialogueArtificial intelligence “ dialogues”Command languages(as in OS)Problem-oriented languages(Fortran, Pascal)Machine-oriented languages(BCPL,B)Assembly languagesHardware0.1 C ’s backgroundThe place of the C languageþýüþýülow-levelHigh-levelconcrete abstractdetailedgeneralpastfuture C23Algol60 (1960,an international committee)CPL (1963,Cambridge & Univ.of London)BCPL (1967, Martin Richards)B (1970, Ken Thompson)C (1972, Dennis Ritchie)0.1 C ’s background The development of the C language240.2 C ’s characteristicp C is a small language Keyword p C is the native language of Unix p C is portable Pascal p C is terse Operator p C is modularp C is the basis for C++ and Java p C is efficient on most machinesp C is not without criticism0.3 ANSI C Standard 26p C often serves as the kernel for more advanced or morespecialized languages.p C++ is an object-oriented language,it is the extension of C.0.4 From C to C++27p Java was designed for work on the Internetp It allows the programmer to write secure and portableprograms that can be downloaded from the Internet and run on your local machine.p Java borrows ideas from both C and C++ and is designed to run in a machine-and system-independent manner.0.5 From C and C++ to Java 28o Operating system o Source file o Text editor o Compiler o Object codeProgramming and preparation29We must do: 1. Edit it (*.c)2. Compile it (*.obj)3. Run it (*.exe)It depends on the system we are using.Programming and preparation 30Programming and preparation31VC++6.0Programming and preparation32“File ”→“New ”33“Files ”→“C++ Source Files ”34“File ”→“Save ”35“Build ”→“Compile test1.c ”36“Build ”→“Build test1.exe ”37“Build ”→“Execute test1.exe ”3839sea1.c#include <stdio.h>int main (){printf(“from sea to shining C\n ”);return 0;}Examplesfrom sea to shining CLibrary function 40sea2.c#include <stdio.h>void main(){printf(“from sea to ”);printf( “shining C ”);printf(“\n ”);}Examplesfrom sea to shining C41sea3.c#include <stdio.h>void main(){printf(“from sea\n ”);printf( “to shining \nC\n ”);}Examplesfrom sea to shining C42******************* from sea ** to shining C *******************43sea4.co #include <stdio.h>o void main()o {o printf("\n\n\n\n\n\n\n\n\n\n");o printf(" ******************\n");o printf(“* from sea *\n");o printf(“* to shining C *\n");o printf(" ******************\n");o printf("\n\n\n\n\n\n\n\n\n\n");o}Examples 44n miles and yards, kilometers. n Convert yards to miles, divide by 1760.0n Convert miles to kilometers, conversion factor 1.609n miles=yards/1760.0;nkilometers=1.609*miles;ExamplesIn English units, a marathon is defined to be2638542.245/* marathon .c The distance of a marathon in kilometers.*/Examples#include <stdio.h>void main(){ int miles,yards;float kilometers;miles=26;yards=385;kilometers=1.609*(miles+yards/1760.0);printf(“\nA marathon is %f kilometers.\n\n”, kilometers);}A marathon is 42.185969 kilometers.46/*The distance of a marathon in kilometers.*/Examplesp Convert the distance of a marathon in miles and yards to kilometers p int ,floatp V ariables must be declared at the beginning of the program p Identifier consists of a sequence of letters,digits,andunderscores,but may not start with a digit.p Comment p Semicolonp Assignment statement p precedence47Homeworko Write an interactive program that converts pounds andounces to kilograms and e symbolic constants that are defined at the top of the file outside of main().o 2. For a three-figure integer, get its unit's place , ten ’splace and hundred's place figure.o pute the roots of quadratic equation :ax 2+bx+c=0o 4.Input the three edges of a triangle, compute its area.o 5. Compute the BODY MASS INDEX(BMI)t= weight (kg)/height (m x m)ïïïîïïïíì³<£<£<£<II 0Obese .30 I 9Obese .9252t9Overweigh .42329Normal .225.18ht 5Underweig .18t t t t t 48Thank you!49Keywords( standard C:32)auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef unsigned union void volatile while50Keywords(C++:32)bad_cast bad_typeid bool catch classconst_cast delete dynameic_cast except explicitfinally friend inline mutable namespace new operator private protected public reinterpret-cast static_cast template this throwtrue try type-info typeid typename using virtual<51Control statements(9)if( )~else~for( )~while( )~do~while( )continue break switch goto return<52C & PascalC Pascal{ } BEGIN….END if(e) s; IF(e) THEN sint i ; VAR i:INTEGERint a[10]; VAR a:ARRAY[1..10] OF INTEGER int f(); FUNCTION f():INTEGERint *p;VAR p:-INTEGER<53Operatorsarithemetic:+ -* / % ++ --relational:< <= == > >= !=logical:!&& ||bitwise:<< >> ~ | ^ &assignment:= += -= *= /= %= &= ^= |= <<= >>=conditional:?:comma:,pointer:* &Bit count:sizeof case:(type-name)member:. ->index:[]others:( ) -<54Data TypesData typestandardstructure d pointer voidtypedefnumericchar enumintegral realfloatdoubleshort long intarraystruct union <55portableif (x>0) then BEGIN A:=1;B:= 2END;#define THEN #define BEGIN {#define := =#define END ; ;}if (x>0) {A=1;B=2;}<。

Security Mitigations for ROP Attacks

Security Mitigations for ROP Attacks

Security Mitigations for Return-Oriented Programming AttacksPiotr BaniaKryptos Logic Research2010AbstractWith the discovery of new exploit techniques,new protection mechanisms are needed as well.Mit-igations like DEP(Data Execution Prevention) or ASLR(Address Space Layout Randomization) created a significantly more difficult environment for vulnerability exploitation.Attackers,however, have recently developed new exploitation methods which are capable of bypassing the operating sys-tem’s security protection mechanisms.In this paper we present a short summary of novel and known mitigation techniques against return-oriented programming(ROP)attacks.The techniques described in this article are related mostly to x86-321processors and Microsoft Win-dows operating systems.1IntroductionIn order to increase the security level of the op-erating system,Microsoft has implemented several mitigation mechanisms,such as DEP and ASLR. Data Execution Prevention(DEP)is a security fea-ture that prohibits the application from executing code from non-executable memory area.To ex-ploit a vulnerability,an attacker mustfind a ex-ecutable memory region and be able tofill it with necessary data(e.g.,shellcode instructions).Gen-erally,achieving this goal using old exploitation techniques is made significantly more difficult with the addition of the DEP mechanism.As a result, attackers improved upon the classic“return-into-1Some of the techniques can be also applied on other ar-chitectures,albeit some of them are only available for x86-32 family(e.g.,the ones based on creating new segment descrip-tors).libc”technique and started using return-oriented programming(ROP)[3,7]to bypass Data Execu-tion Prevention.Techniques like ROP are still based on the at-tacker understanding memory layout characteris-tics,leading Microsoft to implement Address Space Layout Randomization(ASLR)as a countermea-sure.ASLR renders the layout of an application’s address space less predictable because it relocates the base addresses of executable modules and other memory mappings.In order to bypass DEP protec-tion mechanism ROP technique was introduced.In this article we present novel and known mechanisms which are created specifically to prevent attackers from exploiting vulnerabilities based on the ROP method.Presented mitigations will be divided in two general categories:•Compiler-level mitigations—mitigations thatcan be only applied by the compiler or linker.•Binary-level mitigations—mitigations thatcan be applied without knowing the sourcecode of the protected code fragment.2Return-oriented Program-mingReturn-oriented programming is a known exploita-tion technique which allows the attacker to use stack memory to indirectly execute previously picked instructions(so called gadgets).Typically each gadget ends with the x86subroutine return instruction2(RET),which further transfers the ex-ecution to the next gadget or the payload itself.2However other instructions may be used as well like jmp reg,call reg etc.1For more information regarding the return-oriented programming technique please refer to[1,3,7].3Compiler-level mitigations In this section we present ROP protection mecha-nisms which can be applied at the compiler-level. However this doesn’t mean they are not imple-mentable at the binary-level-they are simply sub-stantially easier to implement at the compiler-level. We will also try to underline advantages and dis-advantages of described mechanisms.The biggest disadvantage of compiler-level miti-gations is the fact that they require code recompi-lation in order to be effective.It is often hard to quickly implement such kind of changes in the real world.3.1Call-Ret relationsAs previously stated,most gadgets use return instructions to transfer execution control to an-other gadget or payload.In order tofind useful gadgets,attackers scan the process memory or the binary module for return instruction opcodes and, after such opcode is found,they try to perform backward disassembly in order to decide whether following gadget is useful(correct)or not.Return instruction opcodes can often be found in the middle of different instructions.Results,how-ever,show that most of the time original return instructions RET are used.Typically they also represent the highest number of return opcodes found in the entire module’s executable area (cf.Figure1).For the remainder of this article RET instructions emitted in the original program’s code will be named as“original return instruction”.3.1.1Testing for CALLsIn typical applications,every procedure(function) is executed by using call-procedure instruction.Ev-ery CALL instruction saves procedure linking infor-mation on the stack and branches to the procedure specified by the destination operand.Our ROP mitigation technique relies on a fact that each re-turn address popped from the stack by the RET in-struction is preceded by CALL instruction.WhenFigure1:RET opcode offsets in sample modules (offset equal to1indicates that this is an original RET instruction).2a ROP attack occurs the return address points to another gadget(orfinally a payload).It is unlikely that an attacker will be able to pick the return ad-dresses preceded by CALL instruction operands(see Table1for details).Testing for CALL instructions located before the return address popped from the stack should be a reliable method against ROP at-tacks.Module Name N1[#]N2[#]ntdll.dll6528138(2.11%)ieframe.dll452322109(4.66%)bib.dll5966317(5.31%)aswEngin.dll508951547(3.03%) Table1:Number of gadgets preceded by rela-tive,memory indirect,register indirect procedure-call instruction("minimal/not extended"address-ing mode assumed).Where:•N1represents total number of gadgets•N2represents number of gadgets preceded by the procedure-call instruction•gadget represents a valid single instruction or sequence of instructions without any special filtering applied regarding the gadget useful-nessHowever,the method itself has some drawbacks. CALL instructions can be encoded in various ways (relative,absolute,indirect),which can influence the scanner’s performance and also the potential reliability of this method.Secondly,only origi-nal return instructions can be protected.In other words,using different instructions(like indirect jumps or calls)for linking gadgets will be not detected.On the other hand,the CALL opcode checking method can be based on opcode-frequency statistics,which could decrease the potential per-formance slowdown.Additionally,since only spec-ified(valuable for attacker)return instructions can be protected,this should have a positive influence for the program’s performance.3.1.2Emitting magic valuesThis method was introduced by the Pax Team[5] and it relies on emitting magic bytes after everycalleeepilogue:mov register,[esp]cmp[register+1],MAGICjnz.1retn.1:jmp espcaller:call calleetest eax,MAGICListing1:Protection of the executionflow changes via the return instructions.CALL instruction and testing them at the function epilogue,as shown in Listing1.This method seems to be more reliable than the method described in Section3.1.1,although it also has some major drawbacks.First of all,the TEST instruction isn’t neutral for the application con-text’s state,since the EFLAGS register is modified by this instruction.Thisflaw3,however,can be easily fixed by simply emitting JMP OVER_MAGIC instruc-tion after each CALL.A more serious limitation of this method is the fact that every module used by the application would have to be created(compiled and linked)with the same MAGIC value.This is necessary since execution transfers may occur from one module to another4.Since this approach would be almost impossible to implement in the real world there is another so-lution which can be used here.We propose that Windows’Portable Executable loader be responsi-ble for synchronizing every MAGIC value after each system boot(and after specified module is loaded). This would of course require creating a new section (or some new,specific data directory)with all the MAGIC values offsets that should be updated by the executable loader.3.2Obfuscating instructionsThis approach addresses the problem where the RET instruction opcode is a part of different instruction (typically it is located among thefirst1-3bytes,3Whether this is aflaw or not depends mostly on the application binary interface;in most cases the caller is re-sponsible for saving theflags.4Modules that don’t perform execution transfers to other modules can be left“unsynchronized”.3not including instruction opcode).Owing to our tests and external sources[7]most of such opcodes are found in the ModR/M byte.A second large source of RET opcodes is found in immediate dis-placements.In order to prevent from effectively using such cases in the ROP attack we propose that every instruction with RET opcode inside of its body will be obfuscated in a special manner. Of course control transfer instructions or any other instructions that use immediate data offsets are an exception to this rule since the immediate displace-ments are calculated by the linker.The potential obfuscation can be done in following fashion:•If RET opcode is found in thefirst byte after the original instruction opcode,a jump land should be emitted just before this instruction.Such jump land should consist of a short un-conditional jump instruction and a land(up to16bytes)of INT3or other worthless for at-tacker single byte instructions.Such emitted instructions will never be executed by the orig-inal programflow because of the unconditional jump,which transfers the execution directly to the potentially dangerous instruction.Such action should decrease the number of effective gadgets used for creating the ROP chain.•If RET opcode is spotted in immediate constant values such instruction should be obfuscated for example by splitting ADD REG,IMM32into two ADD instructions where the IMM32operand for both of them would be free of return in-struction opcodes.Of course special care must be taken regarding the EFLAGS register state after each such transition.•If RET opcode is found in ModR/M byte, which indicates using EAX register as desti-nation operand and EBX register as source operand(e.g.,MOV EAX,EBX),such instructions can be transformed into equivalent form which doesn’t include return instruction opcodes.For example MOV EAX,EBX↔PUSH EBX;POP EAX(0x530x58).As previously mentioned,the presented solutions can only be applied to instructions that do not use immediate displacements,as those are handled by the linker.1:mov esp,eaxret2:xchg eax,espret3:add esp,<number>retListing2:Typical stack pivot sequences.4Binary-level mitigationsIn this section we present mitigations against ROP attacks that can be applied without any informa-tion of the program’s original source code.All miti-gations included in this section can be implemented at the binary-level.4.1Stack EncapsulationTo make a ROP attack work,the attacker must be able to point the stack pointer into the controlled data.In typical stack-buffer overflow vulnerabili-ties this is not needed,but in other vulnerabilities (e.g.,heap-overflow)this is often a must.In order to achieve this goal,the attackers use the so called stack pivot sequence[1].Listing2shows some com-monly used stack pivot sequences.Our mechanism tries to take advantage of this information.When a new thread is created,operating systems reserve some necessary space for its stack memory. Stack borders are described in the INITIAL_TEB structure which is passed in one of parameter of NtCreateThread function.Additionally stack bor-ders are also available in the Thread Information Block(FS:[0x04]-top stack,FS:[0x08]-current bottom stack).When the attacker uses the pivot sequence he typically exceeds the stack border lim-its set by the thread initialization procedure.The methods described in the following sections were designed to recognize this behavior.Similar sup-port must be taken when dealing withfibers,since they also use separate stacks.4.1.1New stack segment descriptor Microsoft Windows systems allow usermode appli-cations to create their own local descriptor table (LDT).Most current operating systems use theflat memory model,where there is no need to create4xor eax,eaxlea edi,[esp+VALUE]stosdstosd...Listing3:Typical program instructions. additional segments for every running application. This would be in fact a step back to the old seg-mented memory model.On Windows platforms,in usermode,all segments’base addresses are equal to zero,except the one pointed by the FS register(the GS segment register is not used5).In our mitiga-tion mechanism we have developed two approaches that protect the system against the stack pivoting technique.Our initial technique was to create a stack segment descriptor each time new a thread is created with a base address equal to the stack bottom and limit corresponding to stack size.Af-ter the new segment is created we initialize the SS segment register with a new value.This method however has a big drawback,which is explained on the listing below(Listing3).The LEA instruction is responsible for initializ-ing the EDI register with the effective address of ESP+VALUE.However,the value that will be stored in the EDI register is still relative to the stack seg-ment base address(which is not null in our case). The problems start with instructions that don’t use the SS segment register for addressing purposes. For example,the STOSD instruction uses the ES seg-ment register;its execution will end with an ac-cess violation,since the base address of the seg-ment pointed by ES segment register is different. In other words the LEA instruction does not honor the segment registers when calculating the effective address.To resolve this issue we were forced to change the base address of the newly created stack segments. To avoid unnecessary access violations,the stack segment base address was set to zero and its limit was set to the stack’s top value.This has some dis-advantages,since the attacker would need to initial-ize new stack pointer value with an address higher than the segment limit to trigger the mechanism. Most of the time,however,newly allocated buffers have higher addresses since the thread’s stack mem-5This is true for x86-32architectures onlyory allocation was done earlier(there are a few ob-vious exceptions to this rule).Each time the at-tacker tries to exceed the boundaries of the current stack segment a general protection fault occurs and, at this point,ourfiltering procedure decides if the selected process is being exploited and needs to be terminated.As a side note,there is one small problem with this method.Instructions that use the EBP regis-ter for memory addressing are also using the stack segment specified by the current segment selector. This means that if the EBP is not related to the stack memory and the destination address exceeds the stack segment boundaries a general protection fault will occur.Such cases however can be eas-ilyfiltered and the execution can be resumed after emulating the faulting instruction. Countermeasures In order to bypass the stack encapsulation protection,an attacker would need to initialize the stack pointer with a lower memory address than the stack’s top value.For example at-tacker can heap-spray the memory and then cause the application to create a new thread that will be used to trigger the vulnerability.By doing this at-tacker fake stack will be below the stack base.An-other way would be to execute a gadget that reini-tializes the stack segment with the original value (constant between Windows versions)by,for ex-ample,executing a POP SS instruction.To disable this attack we are constantly monitoring the value of the SS segment register,and we reinitialize it ev-ery time execution returns from a system call(since kernel reinitializes the segment registers values be-fore the control is returned to the usermode).4.1.2Monitoring stack pointer changes Another approach for detecting the stack pivoting technique is to monitor the stack pointer value at crucial areas.For example,instead of setting an-other segment for stack space we can hook impor-tant offensive API functions(e.g.,VirtualAlloc, VirtualProtect)and test the stack pointer value there.Obviously,there is no guarantee that the attacker wouldn’t be able to restore the original stack pointer before using such API functions.To improve the security level of this protection mech-anism we also propose that newly allocated mem-ory regions(or memory regions with changed page 5protection rights)with executable pages should be marked as non-executable6.Now the page marked as non-executable by our mechanism will work as a decoy.If the processor is trying to execute the non-executable page(page protection was previously changed by our mechanism)then wefirstly apply ourfiltering procedure which tests the stack pointer value.If everything is correct,the executable rights are re-enabled and the execution is continued—the entire mechanism works like a one-time decoy. 4.2Code EncapsulationThe ROP technique,just like any other,has some strategic points.One of those is the fact that the at-tacker must know the virtual addresses of the used gadgets.Because so,the ASLR mechanism success-fully obstructs the exploitation process.However, in some cases the attacked application is either not compatible with ASLR or just uses external mod-ules which do not support the ASLR mechanism. There are also cases where the attacker is able to leak or guess the wanted virtual address,rendering the ASLR mechanism relatively easy to bypass.In this section we present a mechanism which will take advantage of this(ROP)technique’s weak spot. As stated in Section4.1.1,Windows systems al-low usermode applications to create their own lo-cal descriptor tables.In this mechanism we pro-pose that each loaded module’s code in the appli-cation’s address space(including the main mod-ule)will have a separate segment for code sections7, as Figure2shows.Each time a execution transfer between modules or execution transfer using a full virtual address(including module imagebase value) occurs,a general protection fault will happen.At this point thefiltering procedure decides whether this execution transfer attempt is valid or an attack attempt.This method has some drawbacks:•A lot of control transfers are done through API calls and since they require a code segment switch a general protection fault is thrown ev-ery time such action occurs.Since this hasa negative impact on the application’s per-formance,entire import address table entries 6this requires having a CPU with NX bit support7this mechanism is a bit similar to PaX SEGMEXEC[6]Figure2:Not-encapsulated and encapsulated mod-ules inside of the process memory.should be redirected to specific API stubs asshown in Listing4.This solution should successfully decrease thenegative performance impact because of thedecreased number of GP faults.However,thisis only one aspect of the problem,since the re-quested API must be able to return correctlyto the specified location which is outside thecurrent code segment.There are a few waysto solve this issue.One of the potential so-lutions can be based on faking the return ad-dress in the API land stub and then recalculat-ing the correct address when RET instructionscause the GP fault.Every potential solutionhere,however,will decrease the program per-formance.Additionally,since API lands canbe only generated either before the base ad-dress of the specified module or attached tothe end of it the code segment borders needto be expanded as well(at least in cases thatdon’t overwrite module’s memory).•Special care must be taken when dealing withcase-switch offsets since they also contain vir-tual addresses that don’t apply to the newcode segment limits.This issue can be par-tially resolved with using module relocationinformation and applying some heuristic scan-ning mechanism.All case-switch offsets foundshould be recalculated again and now pointto relative addresses.However,some modulesdo not provide relocation information whichmakes dealing with such cases hard and prob-ably slow.6CALL DWORD PTR DS:[0x406010]original memory at0x406010:(ptr to user32.CreateWindowExA)00406010A9E4377Epatched memory at0x406010:00406010dd offset api_land1api_land1:jmp user32_cs:rel_offsetListing4:Example implementation of IAT redirec-tion.•Some Portable Executable modules like SHELL32.DLL are pretty large(8MB-16MB).This causes some additional problems,since ifa function callback address located in differ-ent module has a virtual address somewhere between this0-X MB range and some instruc-tion will try to execute this virtual address the mechanism will fault.This is caused be-cause the function’s callback virtual address is located within the limits of the current code segment,and therefore the GP fault does not occur.This is a major drawback since it will likely lead to an application crash.Potential workarounds for this issue would be to disallow (or reserve)the memory located at the0-X MB range.However,this would require an inter-action with the system’s Portable Executable loader.•As explained before,every time kernel returns control to the usermode code segment regis-ters are reinitialized with default values.Thus, the protection mechanism needs to re-initialize them as well each time such action happens.•Additionally the number of segment descrip-tors is limited however this is not a problem for most of the applications since the number of loaded modules is not high.•Special care must be taken when dealing with original code hooks,since such cases exists in some of the applications(for ex-ample in IEXPLORE.EXE this is done by the IEFRAME.DLL module).Countermeasures The attacker would have to restore the original CS register value by,for exam-ple,returning into a RETF instruction.To protect against such attacks,firstly the current CS segment will be monitored at the crucial program places and secondly all the newly generated code segment se-lector values will be pseudo-randomized.4.3Code DecoysThis approach requires a processor with NX bit[2] support.The method itself is rather simple and it can be described in few steps:1.Mechanism setups a page faultfilter and alsomodulefilter,which activates each time aftera new module is mapped into process memory.2.All code sections from selected module foundin the process memory are relocated to randommemory address with the preservation of thesection alignment(see Figure3).3.After the relocation is done original code sec-tions are marked as not-executable(see Fig-ure3).4.Each time a page fault occurs because of anexecution attempt of not-executable memory,thefiltering procedure decides if it should re-calculate the instruction pointer and continuethe execution or to kill the process because ofexploitation attempt.Figure3:Code decoys created from original mod-ules.A similar idea was also used by the PaX Team in RANDEXEC mechanism and also by Matt Miller in the WehnTrust project[4].7To improve the performance of this mechanism, special care must be taken when dealing with case-switch offset tables—this was already mentioned in Section4.2.Additional performance improve-ments can be achieved with import address table redirecting,not unlike the idea explained in Sec-tion4.2.It is important,however,to point out that this idea can also lower the protection level of this mechanism.Countermeasures The attacker would have to guess or leak the mirrored code address.5AcknowledgmentsAuthor would like to thank Brad Spengler,Matt Miller and the Kryptos Logic team for helping with this article.6ConclusionIn this article,a number of promising techniques which can be used against the return-oriented pro-gramming attacks were presented.Most of the implementation problems of such mitigations are directly linked to a heavy perfor-mance impact.This is also a major factor in dis-couraging incorporation of these(and other)ROP mitigations into the selected platforms.Our secu-rity mitigations do not solve the problem of using return-oriented programming attacks completely, but they can effectively trammel and limit their usage.References[1]Dino A.Dai Zovi.Practical Return-OrientedProgramming.http://trailofbits.files./2010/04/practical-rop.pdf.[2]Eric Grevstad.CPU-Based Security:The NXBit./chips/article.php/3358421.[3]Erik Buchanan,Ryan Roemer,Stefan Savage,Hovav Shacham.Return-oriented Program-ming:Exploitation without Code Injection.https:///presentations/bh-usa-08/Shacham/BH_US_08_Shacham_Return_Oriented_Programming.pdf.[4]Matt Miller.WehnTrust a Host-based IntrusionPrevention System(HIPS)for Windows2000,XP,and Server2003.http://wehntrust./.[5]PaX Team.Pax Future.http://pax./docs/pax-future.txt. [6]PaX Team.Segmexec.http://pax./docs/segmexec.txt.[7]Hovav Shacham.The geometry of innocentfleshon the bone:Return-into-libc without functioncalls(on the x86).In Sabrina De Capitani diVimercati and Paul Syverson,editors,Proceed-ings of CCS2007,pages552–61.ACM Press,October2007.8。

中国海洋大学本科计算机专业人才培养方案

专业人才培养方案学科门类 专业代码 授予学位.(从级本科生开始执行)本专业学生本专业学生主要学习计算机科学与技术方面的基本理论和基本知识,接受从事研究与应用计算机的基本训练,具备研究和开发计算机软硬件系统的基本能力。

毕业生应获得以下几方面的知识和能力:1. 掌握现代计算机科学与技术的基本理论,基本知识;2. 系统地掌握计算机软硬件的分析和设计的基本方法;3. 具有研究开发计算机软,硬件的基本能力;4. 了解计算机科学与技术的发展动态,具有学习新理论及新技术的能力;5. 掌握文献检索,资料查询的基本方法,具有获取信息的能力。

三、支撑学科计算机科学与技术,下属计算机应用技术,计算机软件与理论,计算机系统结构三个二级学科。

我校计算机科学与技术学科拥有计算机应用技术专业博士点、计算机科学与技术一级学科硕士授权点,并拥有计算机技术、软件工程和农业信息化三个工程硕士授权领域。

我校“计算机应用技术”学科是山东省“十一五”重点学科。

并有教育部海洋信息技术工程中心作为学科支撑。

四、核心课程高级程序设计语言,集合论与代数结构,图论,计算机组成原理,数据结构,操作系统,计算机网络,编译原理,微型计算机系统,数据库原理,软件工程,网络与信息安全五、特色课程本培养方案在课程内容上体现了海洋和数字家电特色。

主要有四大特色课程群,分别是:1. 以“水下网络通信”和“数字家庭”为核心的计算机网络与嵌入式系统课程群。

包括计算机网络、微型计算机系统、单片机与ARM系统设计与开发等。

2. 以“海洋虚拟现实与可视化”和“数字媒体服务”为核心的数字媒体动漫课程群。

包括计算机图形学、数字图像处理、游戏设计与开发等。

3. 以“海洋数值模式高性能计算”和“嵌入式硬件系统”为核心的计算机体系结构与算法设计课程群。

包括计算机系统结构、微型计算机系统、等。

4. 以“海洋信息集成服务平台”与“数字家庭软件技术集成”为核心的知识工程与软件工程课程群。

包括软件工程、UML面型对象分析、.NET应用与开发、J2EE应用与开发等。

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

计算机专业英语考试试题及答案一、选择题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.。

浙江省网络课程平台-跨文化交际题库(附答案)

Course11.Intercultural competence is the ability to communicate effectively and appropriately in intercultural situations based on one’s intercultural knowledge, _______ and attitudes.【skills】2.Intercultural competence is the ability to communicate effectively and appropriately in intercultural situations based on one’s intercultural knowledge, skills and__________.【attitudes】3.Intercultural competence is the ability to communicate effectively and _____in intercultural situations based on one’s int ercultural knowledge, skills and attitudes.【appropriately】4.Some scholars classify four kinds of intercultural communication. They are ______, interethnic communication, interregional communication and interracial communication.【Intelnational communication】5.Intercultural communication involves interaction between people whose cultural and _________symbol systems are distinct enough to alter the communication event.【perception】1.Taking pictures without asking is considered as violation of privacy in a certain cultural groups.【√】2.Communication barriers are caused by the same communication having different meaning in different cultures.【√】3.International communication takes place between such groups as African Americans and Latin Americans.【×】4.Different people may have different interpretations about what we say and behave because we have different values.【√】5.Intercultural communication involves interaction between people whose cultural perceptions and symbol systems are similar to alter the communication event.【×】Course21.A person’s culture is ___________.【learned】2.Which of the descriptions below is NOT an accurate representation of the relationship between communication and culture?【. Culture and communication are not really related to each other】3.People learn the lessons of culture through __________.【.proverbs myths mass medla all the above】4.According to Edward Tylor, which one of the following is not included by the complex term of culture?【institution】1.The SPEAKING model is a model to analyze spoken and written texts.【×】2.Culture is transmitted from generation to generation to ensure that its crucial messages and elements are passed on.【√】3.Communication can simply refer to the act and process of sending messages among people to connect and interact with other human beings.【×】4.Failure in interaction arose because people in different cultures may choose similar rules and genres to conduct the dialogue.【×】5.Culture is dynamic, which is ongoing and subject to change.【√】6.Feedback is essential to good communication.【√】Course31.In China, as in other Asian societies that have accepted the teaching of Confucius, people are believed to be basically good, yet the ________has a lot of impact on them.【environment】2.Periodic increases in yang are accompanied by corresponding decreases in yin─this followed by an __________ cycle in which yin increases while yang decreases.【opposite】3.People who have the Taoist world view hold that the universe is best seen as an infinite system of elements and_______ in balanced dynamic interaction. Further, two of the forces present in this universe are good and evil.【forces】4.In the Bible story of Adam and Eve, God threw them out of the Garden of Eden because they ate the fruit from ___________.【the tree of knowledge】5.The traditional Western belief about human nature is that human beings are basically ______________.【evil】6.According to Christian teaching, all humans have been born with ___________.【original sin】1.Westerners don’t think we can perfect our nature even if we keep on doing good things.【×】2.Much of Europe also have a good/evil approach to human nature. They believe that while we might be born evil, through learning and education we can become good.【√】3.The traditional Western belief about human nature is that human beings are basically evil.【√】Intercultural conflicts are often caused by differences in value orientations.【√】5.People who have the Taoist world view hold that the universe is best seen as an infinite system of elements and forces in balanced dynamic interaction.【√】6.British anthropologist, Florence Kluckhohn, identified five orientations, five categories of beliefs and behaviors that are universal.【×】7.Buddhism maintains that people are born evil.【×】8.As a result of the rise of humanism in the West, the basic belief has changed to one of seeing humans as a mixture of good and evil. Everybody has both good side and bad side.【×】9.Yang and yin are cyclic; they are regularly repeated; they go through natural periods of balanced increase and decrease.【√】1.Case analysis:Lucia, a Native American college student, when one of her uncles passed away during the first week of school, was expected to participate in family activities. She traveled out of state with her family to his home, helped cook and feed other family members and attended the wake and the funeral. Then her aunt became ill, and she had to care for her. Thus, she missed the first two weeks of school. Some of her professors were sympathetic; others were not. Questions: What was troubling Lucia? Why did she feel troubled?【Lucia feels almost constantly torn between the demands of her collectivistic family and the demands of the individualistic professors and adminstration.】Course41.Being-in-becoming orientation stresses the idea of【development and growth】2.The Arab proverb “The eye cannot rise above the eyebrow” demonstrates ______________attitude.【authoritarian orientation】From former president Lyndon Johnson’s speech“Yesterday is not ours to recover, but tomorrow is ours to win or to lose.”,we can see Americans believe that they can _____________.【control and future】4.Most Latin cultures have the view that the__________ activity is the one that matters the most.【current】5.In present-oriented societies, the past and present often exist side by side. People don’t see any contradiction in that fact. They find it easier to combine __________ and modern ideas and enjoy whatever they have.【tradition】1.In present-oriented societies, the past and present don’t often exist side by side.【错】2.Cultural orientation of controlling nature can also be seen in what is most controversial today, bioengineering and genetic programming.【对】3.The Western approach doesn’t value technology, change and science.【错】4.Many Japanese believe that humans are dominating the nature.【错】5.In Western medicine, the human body is treated as an object that can be studied and then controlled.【对】Course51.C.B. Halverson created a Cultural Context Inventory for us to understand the bigger picture of the context. There are 4 components: Association, Interaction, Temporality, and _____________.【learning】2.America is a _________ culture.【low-context】3.High context communication is communication that places values on implicit information and ___________ cues in order to understand the message. 【nonverbal】4.High context communication is communication that places values on ____________ information and nonverbal cues in order to understand the message.【implicit】5.China is a _________________ culture.【high-context】1.High context communication “Relies heavily on subtle, often non-verbal cues to convey meaning, save face, and maintain social harmony. Communic ators…discover meaning from the context in which a message is delivered.”【对】2.Networking is not important in high-context cultures.【错】3.Examples of high-context cultures include: Asian, African, Arab, Central European, and Latin American countries.【对】4.While high-context communication is a lens in which we can analyze how a message is being interpreted, we can categorize cultures according to generalizations about their communication patterns that influence their communication habits.【错】5.Intercultural communication is a type of communication that shares information across different cultures and societal groups.【对】Course61.In low-context cultures, the communication goal is the exchange of information, ideas, and opinions. When there is a disagreement, it is not _______.【personal】2.Adler & Elmhorts say low context communication “uses ______________ primarily to express thoughts, feelings, and ideas as clearly and logically as possible【language】3.The meaning of a statement in low context culture is in the __________________.【Words spoken】4.Examples of low-context cultures include: American, _______________, Scandinavian, and French.【German】5.Temporality illustrates low-context culture’s approach to time. Events and tasks are _____________and done at specific times【scheduled】6.In low-context cultures, space is compartmentalized and __________ is of the upmost importance.【privacy】7.In low-context cultures, the communication goal is the _______________ of information, ideas, and opinions. 【exchange】8.Low context communication is communicating information ____________ so the message is carried and the information is well determined.【indirectly】1.The low-context association also manifests in a task-oriented mindset where productivity relies on procedures and focusing on the end goal, as well as the identity being found in one’s self and their own accomplishments.【对】2.The meaning of a statement in low context culture is largely in the body language.【错】Course71.Most countries around the world are _______________ .【collectivistic】2.Collectivistic countries typically consist of people that can expect their relatives to look after them in exchange for _____________.【loyalty】3._______________ is the most important in a high power distance society.【respect】The fundamental issue in the Power Distance Dimension is how a society handles _____________ among people.【inequalities】5.Hofstede’s cultural dimensions represent independent preferences for one circumstance or situation over another that distinguishes _____________ from each other.【countries】1.The Power Distance Dimension expresses the degree to which the less powerful members of a society accept and expect that power to be distributed unequally.【对】2.People feel comfortable with inequality and accept the unbalanced distribution of power in a society of high distance power.【对】3.Malaysia is a low distance power culture.【错】4.In societies with lower power distance, people accept a social hierarchy in which everybody has a role to play.【错】5.The first dimension is the Power Distance Dimension.【对】Course81.In the long-term orientation versus short-term orientation dimension, the ________ the score the more emphasis the country shows for long-term orientation.【higher】2.In a masculine society, people regard ______________ as more central to one’s life.【work】3.Countries exhibiting strong Uncertainty Avoidance need ___________ rules.【formal】4.A faminine society at large is more -oriented___________.【concensus】Russia is a typical example of indulgent culture.【错】2.Many countries in Latin America are feminine societies while Spain and Portugal both are categorized as masculine societies.【错】3.Masculinity represents a preference in society for achievement, power, and possessions.【对】4.Planning everything carefully, Germans are not keen on uncertainty.【对】5.Short-term orientation does not emphasize a respect for tradition.【错】6.Indulgence stands for a society that allows relatively free gratification of basic and natural human drives related to enjoying life and having fun.【对】Course91.the four ______ of Asia(亚洲四小龙)【tigers】2.a _________ in the path/way (拦路虎)【lions】3.teach _________ to swim (班门弄斧)【fish】4.Spring up like _________(雨后春笋)【mushrooms】5.One _______ does not make a summer. (独木不成林)【seallow】6.Spend money like _________(挥金如土)【water】7.a _________ movie (黄片)【red】a _________ day (吉日)【white】9.______Fraiday(灾难的一天)【black】10.________ at one’s job (无工作经验)【red】1.Although both dove and 鸽子refer to the same bird, they connotate different meanings.【错】2.The color of red is always associated with something dangerous and threatening in the West.【对】3.猫头鹰in Chinese symbolizes wisdom.【错】4.The number of eight is taken as a lucky number in Chinese as well as English.【错】5.Verbal communication is the communication or exchange of ideas that occurs through written words.【错】6.Like Chinese people, Americans associate the moon with their home.【错】7.A word’s denotation refers to its literal or dictionary meaning.【对】8.A word’s connotation refers to its assciated meaning.【对】9.In verbal communication, we find differences at phonemic, lexical, syntactic, discourse and pragmatic levels between different cultures.【对】10.Words of the same literal meaning from different cultures always have same associated meanings.【错】Course101.The westerners tend to focus on the stages of the discourse as the most crucial __________________.【opening】2._______________ tend to look for the crucial points to occur somewhat later.【the Chinese】3.When we talk to someone who is superior to you, we tend to use______________ , because it’s more indirect and more polite.【logical pattern】4.Discourse patterns greatly depend on ___________________ .【thought pattern】5.Some factors such as ________________, social distance and weight of imposition of a request influence the choice of induction and deduction.【power distance】6.English paragraph development is characterized by _________________, directness, clarity and logic.【linearity】1.We can never take a single word as discourse.【错】2.An English paragraph typically begins with a topic statement.【对】3.Induction is a reasoning process in which particular or minor points move forwards a general or major topic.【对】4.Discourse is naturally spoken or wirtten language in context.【对】Course111.For English native speakers, an apology is necessary whenever inconvenience or offence is made with little consideration of the __________ of the people concerned.【status】2.In English the offer is mostly in the form of a/an【question】3.In Chinese, the proper use of kinship terms to address others, strangers or relatives, can show a person’s _______________, respectfulness and friendliness.【politeness】1.A Chinese name is usually arranged in the order of given name plus surname.【错】2.Some family members might call each other by their first names in English speaking countries.【对】3.The Chinese host makes the offer directly like a command or a statement.【对】1.Li Ming was a Chinese student studying in the US. He was lost on his way to the post office, so when he saw an old lady about the same age as his grandmother, he went to her for help. Li Ming: Excuse me, Granfma, could you tell me how to get to the nearest post office? The lady: Are you talking to me, young man? I’m not your grandma! Question: Was it appropriate for Li Ming to use the kinship term “grandma” as a form of addressing to the lady in this conversation?【It is not acceptable to apply a kinship term to greet a stranger in English. Li Ming made a pragmatic transfer.】Course121.Nonverbal communication is simply known as the “_________ ” language or the “hidden dimension” of communication, however you and I already know all about it!【silent】2.An American poet, Ralph Waldo Emerson, once said “What you do speaks so loudly that I cannot hear what you say”. What we “do” is our ________________.【nonverbal communication】3.Ray Birdwhistell, an American anthropologist, estimates that 65 to 70 percent of the conversation is carried by ________________ communication.【nonverbalcommunication】1.Nonverbal communication can occur without the presence of words.【对】2.Body movements can include posture, gestures, facial expressions, eye contact, and other displays.【对】1.What is kinesics?正确答案:Kinesics, or body language, refers to all nonverbal codes, which are associated with body movements. Body movements can include posture, gestures, facial expressions, eye contact, and other displays.Course131.Time perceptions include: , willingness to wait, _______________ and interactions.【punctuality】2.Hall describes proxemics as having two main types of space: territory and ______________ space.【personal】1.How you are aware of time varies by culture and normative expectations of adherence to time.【对】2.M-Time cultures are typically task-oriented.【对】3.Personal space determines how we interact in the real world. Edward Hall postulates that there are 4 zones: intimate, personal, social, and public.【对】Course151.Racism is associated with oppression and power.【√】2.Most people assume that other people perceive, evaluate, and reason about the world in the same way that they do.【√】3.It is easy to get rid of cultural biases as they are bad.【×】4.People generally perceive their own experiences, which are shaped by their own cultural forces, as natural, human, and universal.【√】5.Racism is the tendency by group in control of _____________ to use it to keep members of groups who do not have access to the same kinds of power at a disadvantage.【power】6.Stereotypes are always negative.【×】7.Ethnocentrism is “the notion that the beliefs, values, norms, and practices of one’s own culture are __________ to those of others.”【正确的,最好的,superior】8.The consequence of stereotyping is that _______________ among the members of any one group may be ignored.【differences】9.Ethnocentrism tends to ____________ cultural differences.【highlight and exaggerate】10.The disadvantage of the human information processing is that it can create some ______________ to intercultural competence.【discrimination and racism obstacles】Course161.At any given moment, one has many ‘ ________ ’ that make up your identity.【facets】2.Mr. Portokalos, the father in the movie My Big Fat Greek Wedding hangs a _______ flag to show the family’s tribute to their heritage.【Greek】3.Cultural differences and distinguishing characteristics can __________________ one culture from another.【differentiate】4.Developing one’s involves learning about __________________ and accepting the traditions, heritage, language, religion, ancestry, aesthetics, thinking patterns, and social structures of a culture.【cultural identity】5.The stage of cultural identity achievement is characterized by a dear, confident acceptance of _____________ and an internalization of one's cultural identity.【oneself】1.During the stage of unexamined cultural identity, one’s cultural characteristics are taken for granted.【√】During the stage of an examiner cultural identity, once cultural characteristics ar e taken for granted.2.When children notice that some of their playmates have different colored skin, they may fear or feel superior to them like adults.【×】even when children may notice that some of their places have different color sche me. as they are not aware of the significance associated with the color scheme, th ey do not fear or feel superior to them.3.In the second stage, for some individuals, there might be a turning point or crucial event leading to this stage.【√】In the second stage,cultural identity research involves a process of exploration and questioning about one's culture and not to learn more about it.And to understand the imp lications of membership in that culture for some individuals,there might be a turning point of crucial event leading to the stage.4.Cultural identity refers to one’s sense of belonging to a particular culture or ethnic group.【√】or i'm American by saying that you have consciously or unconsciously formed your c ultural identity and which re fers to one sense of belonging to a particular culture or et hnic group.5.Cultural identities are static, fixed, and enduring within a changing social context.【×】Cultural identities are dynamic,so your cultural identity exists within a changing soci al context.Course171.Honeymoon phase is followed by adjustment phase when the person feels confused and uncomfortable.【×】2.Culture shock is precipitated by the anxiety that results from losing all our familiar signs and symbols of social intercourse.【√】3.All through life people are confronted with new situations that require them to adjust their thinking and behavior【√】4.Adaptation is a process with ________________________ stages.【identifiable】5.When we are feeling confused, frustrated or tense because of intercultural misunderstandings, please remember that the feelings are _________________ .【only temporary】6.To adapt more successfully, we need to pay attention to differences within thenew culture: avoid making broad ________________ about everybody in the hostculture;【generalize Asians】7.To adapt more successfully, please be alert to signs of adaptation stress: health problems; loss of self-confidence; loneliness; sense of loss; severe homesickness; withdrawal from social contacts; negative feelings; behaving more_________________ than usual.【aggressively】8.The third stage of culture shock is characterized by gaining some _________________ of the new culture.【understanding】9.To adapt more successfully, please seek _____________ experiences within the new culture: if you like to watch football, watch football with people from the new culture; if you enjoy music, enjoy it with people form the new culture【positive】10.To adapt more successfully, please use your cross-cultural experience to increase your skills: Notice and ______________ the communication styles of people from the new culture【imitate】Course181.Sometimes reentry shock is even more difficult than culture shock.【√】2.When people return home to their original cultural contexts, the same processof adaptation occurs and may again involve culture shock.【√】3.Reentry shock can be depicted by the U-curve model.【×】4.The W-curve pattern suggests that when we return home, we must proceedthrough the four stages of the U-curve pattern once again.【√】5.The person who return home is the same person who left home.【×】6.There are two fundamental differences between the first and second U curves, related to issues of personal change and expectations. In the reentry phase, the sojourner has _______________ through the adaptation process.【has changed through】7.International students who return home also talk about how their friends and families expect them to be a little different (more educated) but basically the ___________________as before they went off to school.【same】8.In a new environment, one will lose all the familiar ____________ from his home culture.【similar cues from】9.Experiencing culture shock has a strong ___________________ to make people be multicultural or bicultural.【potential】10.There are two fundamental differences between the first and second U curves, related to issues of personal change and expectations. In the initial curve or phase, the sojourner is fundamentally _________________ and is experiencing new culturalcontexts.【unchanged】11.Experiencing culture shock gives the sojourners a chance to learn moreabout ___________________ and at the same time, other cultures.【themselves】12.The new environment makes demands for which one has no _________________responses.【ready-made】。

《计算机英语》课后习题答案

《计算机英语》参考答案Chapter 11.(1) 中央处理器(Central Processing Unit)(2) 随机访问内存(Random-access Memory)(3) 美国国际商用机器公司(International Business Machine)(4) 集成电路(Integrated Circuit)(5) 大规模集成电路(Large Scale Integration)(6) 超大规模集成电路(Very Large Scale Integration)(7) 个人数字助理(Personal Digital Assistant)(8) 图形用户界面(Graphical User Interface)2.(1) data(2) software(3) IC(4) ENIAC(5) supercomputer(6) superconductivity3.(1) F (ENIAC is the second digital computer after Atanasoff-Berry Computer)(2) T(3) F (Data is a unorganized)(4) T(5) T(6) T4.(1) 人工智能(2) 光计算机(3) 神经网络(4) 操作系统(5) 并行处理(6) vacuum tube(7) integrated circuit(8) electrical resistance(9) silicon chip(10) minicomputer5.数据是未经组织的内容的集合,数据可以包括字符、数字、图形和声音。

计算机管理数据,并将数据处理生成信息。

向计算机输入的数据称为输入,处理的结果称为输出。

计算机能在某一个称为存储器的地方保存数据和信息以备后用。

输入、处理、输出和存储的整个周期称为信息处理周期。

与计算机交互或使用计算机所产生信息的人称为用户。

1.(1) 发光二极管(Light-Emitting Diode)(2) 静态随机存储器(Static Random Access Memory)(3) 只读存储器(Read Only Memory)(4) 运算器(Arithmetic and Logical Unit)(5) 阴极射线管(Cathode Ray Tube)(6) 视频显示单元(Visual Display Unit)(7) 可编程只读存储器(Programmable Read Only Memory)(8) 液晶显示屏(Liquid Crystal Display)2.(1) CPU(2) peripheral(3) memory(4) modem(5) control unit(6) byte3.(1) T(2) T(3) F (RAM is volatile memory because the information within the computer chips is erased as soon as the computer is powered off whereas ROM is nonvolatile)(4) T(5) T(6) F (Microphones and digital cameras are input devices)4.(1) 寄存器组(2) 主机(3) 二进制的(4) 算法(5) 光盘(6) CD-RW(7) logic operation(8) barcode(9) peripheral device(10) volatile memory5.计算机的内存可被视为一系列的单元,可以在单元中存取数字。

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

A Case for Goal-oriented Programming SemanticsUmar Saif, Hubert Pham, Justin Mazzola Paluska, Jason Waterman, ChrisTerman, Steve Ward{umar, hubert, jmp, jwaterman, cjt, ward}@Abstract. Contemporary pervasive computing environments demand mechanism for co-herently addressing high-level user needs despite changing availability of resources. We propose the formalization of goals as the semantic basis for this mechanism, and sketch a system architecture that separates policy-rich goals-level planning code from a policy-neu-tral component assembly model.I. INTRODUCTIONPervasive computing systems immerse their users in a triad of sensors, invisible serv-ers and mobile devices that work together to satisfy user requirements according to the facilities available in her environment. Such a system must be self-managing: it must be able to continuously monitor changes in user locations and needs, respond both to compo-nent failures and newly available devices, and maintain continuity of service as the set of available resources change.As a simple example of such a pervasive computing environment, consider a user involved in a video-conference with a colleague as she wanders about a well-equipped campus. As she moves from one room to another, her video may switch from the small LCD display of her handheld to a wall-mounted plasma screen as the latter comes into view; networking technologies might shift between 802.11b and CDMA depending on resource availability, and video may degrade or disappear altogether as communication bandwidth warrants.Such adaptation in a pervasive computing environment entails more than traditional load-balancing or resource-management at a single host; it necessitates a certain degree of planning involving continuous reevaluation of available alternatives, as well as heuristic compromises to best address the user requirement using imperfect resources in the chang-ing environment of the user.Conventional techniques for constructing distributed applications, in which a top-level function is decomposed into statically-partitioned sub-functions, each affixed to a particu-lar API, makes such adaptation exceedingly difficult to program. Adaptation in a perva-sive computing environment requires planning at a macro-level, possibly involving a wholesale re-structuring of the application. If there is a change in available resources or user priorities, it is often insufficient simply to reconsider how to implement the function specified at each API: it is necessary to reconsider the reason that API was selected, and whether an alternative function and API has now become more appropriate.A more promising approach is to have the user express their requirements as an abstract high-level goal, and then let the system automatically satisfy this goal by assem-bling, on-the-fly, an implementation that utilizes the resources currently available to the user. The high degree of dynamism in the environment requires that the resolution of a goal not be a static one time process. Instead, the system must be able to continuously monitor the environment so that it may respond opportunistically to changes in connectiv-ity and available devices, assembling new implementations to sustain the high-level goal in the changing conditions.While a growing number of projects[1][2][3] discussed in section 4 show how conven-tional distributed computing paradigms may be extended to handle the heterogeneity and dynamism of a pervasive computing environment, we believe that a new set of abstrac-tions would greatly reduce the complexity of creating applications for this environment.To this end, we are building an experimental system, O2S, to explore two architectural principles:•The formalization of goals as an explicit semantic construct to express abstract high-level intentions. A goal takes the form of a generic procedure call and represents the stimulus for a planning process which can be invoked repeatedly to produce successive implementations as available resources evolve.•The stratification of application-level software into two distinct layers: a planning layer that embodies the mechanism for assembling and adapting implementations to be executed by the computation layer. The computation layer provides reasonably general mechanisms for constructing and monitoring a network of generic modules operating in parallel on different hosts. The two layers are an attempt to tease apart software for complex, adaptive systems into cognitive and reflexive components: the former focus-ing on application-specific policies, and the latter on efficient deployment and moni-toring of commodity computation.By following these two architectural principles, O2S offers a general-purpose architec-tural framework for engineering goal-oriented adaptive systems. The approach of separat-ing the adaptation mechanism from individual code modules leads to the following useful properties: 1) adaptation could be performed at a macro-level, allowing wholesale restruc-turing of the application-code in response to changes in the system, 2) policies, algorithms and mechanisms of adaptation can be engineered and evolved independently of any partic-ular application.II. GOALS AND PLANNINGIn the planning layer of O2S, goals are formalized as a language construct and used to guide the automatic construction of a component-based system. Syntactically, goals are similar to generic procedure calls: they involve a named generic service (the goal name) as well as an arbitrary number of typed parameters. Thus, TeleConference(Alice, Bob) is a high-level goal whose satisfaction requires a teleconference link between Alice and Bob, each a parameter of type Person.Unlike procedure calls, however, goals are disembodied from any block of code to be invoked during their execution. Rather, the system approaches the resolution of a goal by searching for one or more techniques, each of which constitutes a recipe for resolving a class of goals. Each technique specifies a pattern to be matched against a target goal, optional sub-goals that must be satisfied for that technique to proceed, and code to be run in order to cause the target goal to be satisfied once the specified subgoals have been achieved. Satisfaction of a top-level goal thus involves, at least conceptually, (a) the enu-meration of applicable techniques; (b) evaluation of each of the candidate techniques; (c) the heuristic selection of one technique for implementation; and (d) implementation of the chosen plan. Any of these steps may fail, possibly resulting in the system’s failure to sat-isfy the specified goal.Since techniques can require subgoals to be satisfied, step (b) in Array the above sequence may involve the recursive evaluation of anentire tree of goals and subgoals. In practice, O2S builds a goaltree (shown in figure 1) representing a (perhaps partial) universeof candidate choices, and heuristically selects a path through thistree based on an estimate of the most acceptable implementationchoice (as outlined in more detail subsequently). The resultinggoal tree, however, is saved after the implementation choices aremade; it serves as a record of the assumptions and logic leading to Figure 1: O2S Goal Treeeach decision made in the heuristic selection, allowing each deci-sion to be reconsidered should new information become available.Goal ResolutionThe planning layer of O2S is implemented as a distributed network of contexts, each of which contains a local repository of techniques, often customized to the preferences of some logical entity in the system. For instance, an individual will typically maintain a per-sonal context whose techniques reflect her preferences (e.g., a GetMyAttention goal is sat-isfied by a local technique that causes her cell phone to vibrate); however, the personal context may defer to a context maintained by her employer to specify default techniques for the satisfaction of many goals. The principal function performed by a context is the resolution of a goal instance provided as a parameter in a satisfy request. As noted above, the approach to goal resolution is expected to evolve; indeed, the O2S architecture is intended to provide a framework for that evolution. In this section, we describe the approach taken by our early prototypes.Both contexts and techniques are implemented as object instances and their externalinterfaces take the form of method-call APIs. The structure of the goal resolution take theform of a choreographed interaction between the context and a selection of the techniquesA target top-level goal (typically derived from a user command, either typed or spo-ken) is first matched against the local store of techniques. Each technique is matchedagainst the target goal; if the match succeeds, the technique is retained for evaluation. Ifno matches are found, the satisfy request reports failure (but the failure may be recover-able, as discussed below).Each matching technique returns an instance of a Planlet object used to cache the state of subsequent negotiation relating to that technique’s suitability to satisfy the specified goal. The set of planlets are collected by the context into a plan, recording the state of the search which will eventually lead to the heuristic selection of one planlet as the path of choice. The plan, and its child planlet instances, constitute one layer of the unfolding goal tree devoted to choosing an implementation strategy for the incoming goal instance.Additional layers of the goal tree are built by interrogating each planlet for subgoals, and repeating the above construction of a plan (with subordinate planlets) for each. The resulting tree is structured as alternating layers of plan and planlet nodes, which represent conceptually disjunctions and conjunctions of their inferiors. Each plan can succeed if one of its inferiors – the use of some suitable technique – leads to success; each planlet can succeed only if all of its inferiors, each corresponding to a requisite subgoal, is successful.The next step in the goal resolution process is the heuristic selection of a subtree that represents, by some criterion, the best implementation choice given currently available information. To make this determination, our current approach involves assignment of a scalar satisfaction metric to each node of the tree, and the local selection at each plan of the inferior planlet with maximal satisfaction. This primitive approach involves the encapsulation of all value judgments pertaining to a choice, including both its cost and the desirability of its outcome, onto a single dimension. Currently the metric is computed are by code within each technique, which is asked by the context to estimate the satisfaction of its outcome based on goal parameters and the results (including satisfaction) of the res-olution of each of its subgoals. Standards for such value judgments are thus embedded in techniques, and the choices made by a context in the realization of incoming goals may be heavily colored by the selection of techniques it comprises.The evaluation of a planlet is required to be idempotent, and may be done repeatedly during its lifetime. This allows flexibility in the evaluation algorithm used by a context, as well as providing the ability for the subsequent re-evaluation of any subtree should some incoming event suggest that its result might change. The plan, and the substructure that constitutes its goal tree, persists while the chosen implementation is active. Various exter-nal events, such as an error condition or change in the location of a principal, may be used to trigger re-evaluation of all or part of the tree; this may, in turn, result in a (partial) reim-plementation of the solution.It is worth mentioning that the specific heuristics of our current planning system, including the use of scalar satisfaction metric, are early steps in an ongoing research agenda. We view our architecture as defined by its network APIs rather than, say, the body of code that implements key heuristics such as goal resolution. We anticipate that alterna-tive implementations of contexts (incorporating different approaches to planning) might interoperate simultaneously within a continuously-running O2S environment, allowing incremental evolution of the planning subsystem. Among many other possibilities, we are exploring the use of current SAT-based planning techniques [4] as an alternative to the PROLOG-style planning described here.III. COMPONENT ASSEMBLYA target goal is satisfied at conclusion of the iteration of the planning process by dynamically assembling a set of generic components (called pebbles) to implement the high-level function encoded by the goal. A pebble is a lightweight, policy-neutral distrib-uted component that conforms to a standardized API. Pebbles typically implement a single function and are designed to be standalone components with well-defined, explicit ports of communication with other components. Keeping the pebbles focussed on a single opera-tion makes it easy to reuse them in many different applications. For example, typical peb-bles in our prototype system include a voice-recognition pebble, which takes an audio-stream on an input port and produces corresponding recognized text on its output port, an audio-source pebble which reads /dev/dsp and forwards that on its output port, an audio-sink pebble which accepts an audio-stream on its input port and writes to /dev/dsp of the host machine.Component (“Pebbles”) APIThe API presented by Array our component model isdesigned to hide certaincomplexities of a highlyparallel, distributed sys-tem of interconnectedcomponents under theveneer of a simple,sequential, and localizedsystem. Although ourdesign is motivated bythe implementationneeds of our goal-ori-ented planning layer, the pebbles-based computation layer is designed to be usable by (and of potential interest to) those following more conventional approaches to distributed application design.The basic API provides a mechanism for instantiating a collection of pebbles on vari-ous hosts, interconnecting them into a network, and monitoring the operation of the result-ing composite via a stream of high-level events generated by the pebbles and connections. Events are used to report component failures, user inputs, or various pebble-specific noti-fications.The health of devices hosting pebbles (and the communication paths between them) is transparently monitored by keep-alive connections; pebble state updates and debugging output are collected, filtered, and serialized for presentation to the caller; and disconnected or abandoned component processes are automatically garbage-collected. The intent is to minimize the tedium of developing and maintaining distributed applications, allowing a high-level application to focus on a simple sequential model for its “cognitive” delibera-tions, while the compute-intensive “reflexive” components are managed largely automati-cally (refer to figure 3).This approach is similar to architectural models proposed as a basis for evolvable and self-repairing software [5]. The pebbles system exports a simple architectural model in which the application is represented as a graph of connected components. This representa-tion is also adopted by a number of architecture description languages, e.g Acme [6]. By the same token as a software-architectural model provides the generic abstraction for applying analytical models to the overall architecture of a distributed application, the peb-bles’ composite serves as the generic abstraction for planning the assembly and adaptation of code modules to satisfy user goals.ConnectionsPebbles are modeled as stream-processing objects [9], and communicate using stan-dardized communication end-points. An application connects two pebbles by requesting the system to establish a communication channel that joins their appropriate service-access-points, dubbed as connectors [10]. A connector defines a unidirectional interface for message passing, analogous to a UNIX one-way socket. All connectors are derived from a common super-class and hence provide a standardized, well-known interface for sending and receiving messages. The use of a standardized, low-level communication interface avoids the interface compatibility issues associated with conventional RPC-based distributed components, making it easy to join arbitrary pebbles. Where connectors are akin to UNIX sockets as a well-known message passing interface, the communication model supported by connectors enforces a strict distinction between policy and mecha-nism: a pebble only declares a connector when defining an external service access-point, while the actual connections between pebbles are established by the planning layer to compose an application. This allows pebbles to offer a service without dictating their role in the overall distributed computation, permitting a wholesale restructing of the applica-tion by reconnecting the pebble connections.It is noteworthy that a connector declaration only defines a service access point and dictates neither the pebble to be connected to the connector nor the attributes or the proto-col to be used for the transport of messages sent via the connection. These architectural principles, often referred to as “laws of blind communication” in the software engineering literature [5], ensure that a pebble can be used to satisfy a variety of high-level goals, that a pebble is independent of the semantics of the connectors to which it is attached, and that a pebble composite can be re-wired on the fly in response to changes in user priorities or needs.IV. RELATED WORKA number of recent architectural approaches to pervasive computing share elements with our work. Several of the most relevant are discussed below.MIT’s Intentional Naming System (INS) [3] addresses these challenges at the stage of discovering and routing of network messages. Applications in INS express their intent as a set of properties required in a suitable resource and the INS overlay locates and routes intentional datagrams (network messages tagged with user intent) to the most appropriate resource in the environment of the application. This approach of pushing intent-driven adaptation down to the primitives of network communication enables conventionally-engineered applications to opportunistically access resources in a dynamically changing pervasive environment, and provides a runtime alternative to the top-level goals of O2S. Itdoes not, however, automate the internal structuring of an implementation, e.g. by the decomposition of goals into lower-level subgoals.CMU’s Aura [2] distributed computing environment defines an high-level abstraction, termed a task, layered atop individual applications. This task layer, called prism, provides a placeholder to capture user intent, and employs various resource monitoring artifacts in the Aura system to monitor and adapt underlying applications to opportunistically carry out the high-level task. Aura’s architecture is focused on adaptation and migration of con-ventionally-engineered applications rather than on automatic assembly of distributed com-ponents.The Gaia computation environment from UIUC [7] defines a programming environ-ment based on the Model-View-Controller abstraction. Using this abstraction, applications in Gaia are partitioned into four parts; a model to encode the logic of the application, a view to expose the model's state, a controller to map events in the environment of the application as input messages to the model, and a coordinator responsible for storing the bindings of different components in the application's model as well as mechanisms to access and alter these bindings. While this conceptual framework reflects a philosophy similar to that of O2S in which the application-logic is separated from individual compo-nents, the Gaia architecture defines a basis for modeling user-driven context-aware appli-cations, rather than automatic composition and runtime adaptation of distributed applications.The Ninja Paths architecture [11] from University of California Berkeley takes a simi-lar approach to O2S for automatically assembling a stream-conversion application. Given a source and a destination stream format, the NINJA Paths architecture strings together a path of stream-processing elements, dubbed as operators, which converts the stream from one format to another. Operators describe their properties, including the ingress and egress stream formats, in an XML file which is used by the NINJA Paths creator to discover the appropriate operators. Operators communicate using well-defined ports of communication which can be dynamically rewired in response to operator failures.The Pebbles’ composite API is reflective of the architecture-based software-engineer-ing models, in which the architectural model of the software is maintained at runtime and used as a basis for software evolution and verification. Oriezy et al. [5] present a data flow based approach to compose and adapt a network of distributed components, called Weaves. Much like a pebbles composite, a weave is constructed by connecting a network of tool fragments using transport services. However, the Weaves system does not provide any explicit support for representing change policies to compose and adapt a weave. Weave designers use an interactive, graphical editor to visualize and directly reconfigure a weave during runtime.Cheng et al. [6] argue for the suitability of software architectural models as a basis for analyzing and verifying self-adaptive applications in a pervasive computing environment. Much as O2S defines a layered architecture to separate the concerns of goal-resolution and planning from component assembly, Cheng et al. propose a dichotomy which sepa-rates analytical methods for evaluating the properties of the system’s architectural design from individual code modules. Though similar to Pebbles in its architectural consider-ations, Cheng. et al. propose their system as a basis for analyzing and verifying the overall structure of an distributed application against programmer-defined constraints rather than goal-driven planning and assembly of distributed components.V. CONCLUSIONWe propose goals as an explicit semantic construct for programing a pervasive com-puting environment. Goals encode high-level intentions, take the form of a generic sub-routine call and initiate a planning process which may persist during a succession of implementation choices -- each potentially involving different design approaches, recom-pilation of code, and revised user-visible performance. Each iteration of the planning pro-cess satisfies the target goal by assembling a network of pebbles (modular components) and communication channels. The pebbles component system is based on an explicit dis-tinction between mechanism and policy; individual pebbles offer a mechanism without dictating the policy specifying the role of the pebble in the overall logic of an application. Pebbles are intended for reuse in implementing a variety of applications. The API offered by the pebbles layer provides simple means by which the caller can instantiate a collection of pebbles on various hosts, interconnect them into a network and monitor the operation of the application via a stream of events generated by the pebbles and connections and adapt its structure in response to the changes in the system.VI. REFERENCES[1]Robert Grimm et al., Systems directions for pervasive computing. Proceedings of the 8th IEEEWorkshop on Hot Topics in Operating Systems (HotOS-VIII), pages 147-151, 2001.[2]David Garlan, Dan Siewiorek, Asim Smailagic, and Peter Steenkiste. Project Aura: TowardsDistraction-Free Pervasive Computing. IEEE Pervasive Computing, April-June 2002.[3]William Adjie-Winoto, Elliot Schwartz, Hari Balakrishnan, and Jeremy Lilley. The design andimplementation of an intentional naming system. Symposium on Operating Systems Principles, Kiawah Island, USA, December 1999.[4]Kautz, H., and Selman, B., BLACKBOX: A New Approach to the Application of Theorem Prov-ing to Problem Solving, In Working notes of the Workshop on Planning as Combinatorial Search, AIPS-98 Pittsburg, PA, (1998) 58--60.[5]Oriezy, P., Gorlick, M.M., Taylor, R.N., Johnson, G., Medvidovic, N., Quilici, A., Rosenblum,D., and Wolf, A. An Architecture-Based Approach to Self-Adaptive Software. IEEE IntelligentSystems 14(3):54-62, May/Jun. 1999.[6]Shang-Wen Cheng et al, Software Architecture-based Adaptation for Pervasive System. Interna-tional Conference on Architecture of Computing Systems (ARCS’02): Trends in Network and Pervasive Computing, April 8-11, 2002.[7]Manuel Roman, Christopher K. Hess, Renato Cerqueira, Anand Ranganathan, Roy H. Camp-bell, and Klara Nahrstedt. Gaia: A Middleware Infrastructure to Enable Active Spaces, In IEEE Pervasive Computing, pp. 74-83, Oct-Dec 2002.[8]Robert Grimm, et al. Programming for pervasive computing environments.Technical reportUW-CSE-01-06-01, University of Washington.[9]Peyman Oreizy and Richard N. Taylor. On the Role of Software Architectures in Runtime Sys-tem Reconfiguration, Peyman Oreizy and Richard N. Taylor. Proceedings of the International Conference on Configurable Distributed Systems (ICCDS 4). 1998.[10]Peyman Oreizy, David S. Rosenblum, Richard N. Taylor. On the Role of Connectors in Model-ing and Implementing Software Architectures. Technical Report UCI-ICS-98-04, Department of Information and Computer Science, University of California, Irvine, February 1998.[11]Steven D. Gribble et al. The Ninja Architecture for Robust Internet-Scale Systems and Services,To appear in Special Issue of Computer Networks on Pervasive Computing。

相关文档
最新文档