text
stringlengths
454
608k
url
stringlengths
17
896
dump
stringclasses
91 values
source
stringclasses
1 value
word_count
int64
101
114k
flesch_reading_ease
float64
50
104
Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video. Object-Orientation and Classes9:32 with Gabe Nadel While working in Swift, you’ve probably made frequent use of structs, protocols and composition. In this video, we’ll talk about how and why Objective-C is different as we create some simple custom classes. Updated Code Samples Teacher’s Notes - 0:00 [MUSIC] - 0:05 As the name suggests, Objective-C is made for object-orientation. - 0:08 No big shock there. - 0:10 And while you've probably been working with object-orientation for - 0:12 a while in Swift or another language, there may be some big differences. - 0:17 For example, in Objective-C, our structs just plain old C structs. - 0:21 We'll use them from time to time, but - 0:23 they aren't the powerful first-class types that we're used to in Swift. - 0:26 We're much more likely to just create custom classes if we need something more - 0:30 robust than, let's say, a mutable dictionary. - 0:33 If you'd like to learn more about C structs, I've linked a resource below. - 0:37 The objects we will subclass inherit from their superclasses and - 0:40 Objective-C classes don't support multiple inheritance. - 0:44 We do have protocols in Objective-C, and they're used frequently though not as - 0:47 frequently as in Swift, which Apple calls a protocol-oriented language. - 0:51 This difference also implies that Objective-C relies more on - 0:55 inheritance than composition. - 0:56 In a moment, we're gonna jump in and create some classes of our own. - 1:00 But if you think you might benefit first from a review of classes, instances, and - 1:04 the like, please visit the link below for a short but useful, and - 1:08 dare I say entertaining video on the basics of object-orientation. - 1:12 In our full Objective-C course, we use cars as our example for - 1:16 object-orientation. - 1:17 So here we'll switch it up just a bit to a slightly less worn analogy, animals. - 1:22 Here in this new Xcode project, let's add a class called Animal. - 1:26 We'll select Cocoa Touch Class, and - 1:29 here we can pick what we want our superclass to be. - 1:33 So Subclass of, and we're gonna leave it as an NSObject the granddaddy or - 1:36 I suppose the great-great-great-grandmommy of just about every class there is. - 1:42 And by that I mean when you go all the way up the inheritance chain for - 1:45 things like UIViews or UIDatePickers or just plain old NSStrings, - 1:49 eventually you're inheriting from NSObjects. - 1:51 If we wanted, we could also pick something less abstract from this list here. - 1:56 We'll type in the class name, Animal, and hit Next. - 2:06 Okay, first thing you'll notice is that we just got two files for - 2:10 the price of one, Animal.h and animal.m. - 2:13 In Objective-C it takes a whole village to raise a class. - 2:17 Actually it just takes these two files. - 2:18 But that's still very different than Swift where you can actually define a whole - 2:22 bunch of different classes all in one file. - 2:24 In Objective-C, the .h is the header where we define the interface, and - 2:29 the .m where we spell out the implementation. - 2:31 So let's start with Animal.h. - 2:33 Here we see that we have a class called Animal and it inherits from NSObject. - 2:38 That's what this colon right here means. - 2:41 Notice the word class isn't anywhere to be found. - 2:44 This interface declaration begins on this line here and - 2:48 ends right here with the @end keyword which Xcode provided for us. - 2:54 We'll be putting the meat of our interface in-between the two. - 2:58 Now if it isn't already clear, having an interface allows other entities, - 3:02 maybe some other class written by some other programmer on the other - 3:05 side of the world, to make use of our classes without troubling themselves - 3:10 with its inner workings. - 3:11 It exemplifies the concept of encapsulation, whereby unnecessary data in - 3:16 implementation isn't exposed, only accessed or utilized via the interface. - 3:21 Now we are by default importing the Foundation framework, - 3:25 which is important since it contains tons of really important stuff like NSString, - 3:30 NSArray, and pretty much most of what we've learned about so far. - 3:34 We don't need to import anything else here, - 3:36 but this is where you would import other frameworks like GameKit or SpriteKit. - 3:41 While we're on the topic of import, it's worth mentioning that if you want to - 3:44 import a C asset, you do that with the include keyword, not the import keyword. - 3:50 It's also worth noting that at times you may want to import one class into another - 3:55 and vice versa, which can lead to a circular reference and errors. - 3:59 If you find you need to do that, - 4:01 you'll wanna make what's called a forward declaration using the @class keyword. - 4:07 And I've linked to some further reading on that below. - 4:09 It's not complex, but it's worth looking at. - 4:12 Last point worth mentioning is that sometimes you'll see import statements - 4:16 with angle brackets like we do here, and - 4:19 other times you'll see things contained within quotes. - 4:22 The angle brackets means the searching will happen on a given path, - 4:27 whereas the quotes mean searching will occur within the entire project. - 4:31 So let's craft our Animal class. - 4:32 Why don't we start with three properties for our Animal class? - 4:36 Name, that is what the animal is called. - 4:39 Class, that is what type of animal it is, a mammal, - 4:43 bony fish, cartilage fish, reptile, bird, or amphibian. - 4:47 So yes, we just mean the vertebrate animals. - 4:50 And just for fun, let's give it a Boolean variable for whether or not it's extinct. - 4:55 Okay, to create a property, we begin with the @property keyword. - 4:59 Then we're gonna give our memory directives. - 5:03 Then we specify the type, NSString, and then we give the name. - 5:11 Now that should look familiar except for - 5:13 the stuff in the parentheses, which I promise we'll touch on in the next video. - 5:17 Next, let's add our property for what class of animal it is. - 5:21 And by the way, here when I say class, I'm talking about the biological taxonomy, - 5:26 as in fish, bird, mammal, etc. - 5:28 It has nothing to do with classes in programming. - 5:31 In fact, to avoid any confusion, - 5:34 let's use the word group even though it isn't correct biologically speaking. - 5:38 So now we want to specify a group or category of animal. - 5:42 So let's create an enum to do this. - 6:17 Now that we have our enumeration set up, let's add a property. - 6:33 You'll notice I left out the strong keyword when declaring our second - 6:37 property. - 6:39 Now, that's because enums aren't objects, so we don't specify strong or weak here. - 6:44 But again, we'll go into that in the next video. - 6:46 I also didn't need an asterisk like I did up here since this is just an enum, - 6:51 not an object. - 6:53 Lastly, let's create a BOOL for isExtinct. - 7:05 And by the way, we just declared a BOOL here. - 7:09 We use yes and no for the values here, which of course represent one and zero. - 7:14 Often you'll see a lowercase B-O-O-L for bool, but that's a bit different, - 7:19 and I've linked to some resources that go into those differences. - 7:23 Okay, now when we say interface here, we're talking abstractly - 7:28 about interfacing with the class Animal, as in how would another class engage - 7:33 with this class without needing to know its inner workings. - 7:36 Well, right here we're saying you could access and change these properties right. - 7:41 Well, this is also the place to declare user interface elements or IBOutlets you - 7:46 might want to store as properties or access from outside the class. - 7:50 We aren't creating any UI for our class, but let's say we wanted to. - 7:53 We could add it as follows. - 8:13 Okay, hm, it seems we've got an error here. - 8:16 Before clicking on it, does anyone know why? - 8:18 Well, let's see what it says. - 8:22 Unknown type name 'UIImageView'. - 8:25 Hm, looks like I spelled UIImageView correctly. - 8:28 Why isn't it showing up? - 8:30 That's right, we need to import the appropriate framework. - 8:33 So we'll head right up here. - 8:37 #import. - 8:42 UIKit/UIKit.h. - 8:48 And our error should go away. - 8:50 Great. - 8:50 We could also declare some methods for our Animal class down here, but - 8:55 we won't do that just yet. - 8:57 Before we take a break, it's worth highlighting that creating property - 9:01 like we've done here gives us our getters and setters for free. - 9:04 We can just retrieve and - 9:06 change the values from outside of the instance of the class we'll create. - 9:10 Now, that doesn't mean that we're prohibited from writing our own - 9:13 setters and getters. - 9:14 For example, you could write a custom accessor method, that's another name for - 9:17 a getter by the way, and have it closely resemble - 9:20 the computed properties you've probably crafted in Swift. - 9:24 All right, we'll pause for now, and when we come back, we'll create some instances - 9:28 of our classes and see if we can put our properties to use.
https://teamtreehouse.com/library/objectorientation-and-classes
CC-MAIN-2017-17
refinedweb
1,819
71.44
The Go to and click the Sign up Now button. Select one of the offers. I selected the Introductory Special offer because it is free and I just wanted to experiment with Windows Azure for the purposes of this blog entry. To sign up, you will need a Windows Live ID and you will need to enter a credit card number. After you finish the sign up process, you will receive an email that explains how to activate your account. Accessing the Developer Portal After you create your account and your account is activated, you can access the Windows Azure developer portal by visiting the following URL: When you first visit the developer portal, you will see the one project that you created when you set up your Windows Azure account (In a fit of creativity, I named my project StephenWalther). Creating a New Windows Azure Hosted Service Before you can host an application in the cloud, you must first add a hosted service to your project. Click your project on the summary page and click the New Service link. You are presented with the option of creating either a new Storage Account or a new Hosted Services. Because we have code that we want to run in the cloud – the WCF Service — we want to select the Hosted Services option. After you select this option, you must provide a name and description for your service. This information is used on the developer portal so you can distinguish your services. When you create a new hosted service, you must enter a unique name for your service (I selected jQueryApp) and you must select a region for this service (I selected Anywhere US). Click the Create button to create the new hosted service. Install the Windows Azure Tools for Visual Studio We’ll use Visual Studio to create our jQuery project. Before you can use Visual Studio with Windows Azure, you must first install the Windows Azure Tools for Visual Studio. Go to and click the Get Tools and SDK button. The Windows Azure Tools for Visual Studio works with both Visual Studio 2008 and Visual Studio 2010. Installation of the Windows Azure Tools for Visual Studio is painless. You just need to check some agreement checkboxes and click the Next button a few times and installation will begin: Creating a Windows Azure Application After you install the Windows Azure Tools for Visual Studio, you can choose to create a Windows Azure Cloud Service by selecting the menu option File, New Project and selecting the Windows Azure Cloud Service project template. I named my new Cloud Service with the name jQueryApp. Next, you need to select the type of Cloud Service project that you want to create from the New Cloud Service Project dialog. I selected the C# ASP.NET Web Role option. Alternatively, I could have picked the ASP.NET MVC 2 Web Role option if I wanted to use jQuery with ASP.NET MVC or even the CGI Web Role option if I wanted to use jQuery with PHP. After you complete these steps, you end up with two projects in your Visual Studio solution. The project named WebRole1 represents your ASP.NET application and we will use this project to create our jQuery application. Creating the jQuery Application in the Cloud We are now ready to create the jQuery application. We’ll create a super simple application that displays a list of records retrieved from a WCF service (hosted in the cloud). Create a new page in the WebRole1 project named Default.htm and add the following code: <"> var products = [ {name:"Milk", price:4.55}, {name:"Yogurt", price:2.99}, {name:"Steak", price:23.44} ]; $("#productTemplate").render(products).appendTo("#productContainer"); </script> </body> </html> The jQuery code in this page simply displays a list of products by using a template. I am using a jQuery template to format each product. You can learn more about using jQuery templates by reading the following blog entry by Scott Guthrie: You can test whether the Default.htm page is working correctly by running your application (hit the F5 key). The first time that you run your application, a database is set up on your local machine to simulate cloud storage. You will see the following dialog: If the Default.htm page works as expected, you should see the list of three products: Adding an Ajax-Enabled WCF Service In the previous section, we created a simple jQuery application that displays an array by using a template. The application is a little too simple because the data is static. In this section, we’ll modify the page so that the data is retrieved from a WCF service instead of an array. First, we need to add a new Ajax-enabled WCF Service to the WebRole1 project. Select the menu option Project, Add New Item and select the Ajax-enabled WCF Service project item. Name the new service ProductService.svc. Modify the service so that it returns a static collection of products. The final code for the ProductService.svc should look like this: using System.Collections.Generic; using System.ServiceModel; using System.ServiceModel.Activation; namespace WebRole1 { public class Product { public string name { get; set; } public decimal price { get; set; } } [ServiceContract(Namespace = "")] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class ProductService { [OperationContract] public IList<Product> SelectProducts() { var products = new List<Product>(); products.Add(new Product {name="Milk", price=4.55m} ); products.Add(new Product { name = "Yogurt", price = 2.99m }); products.Add(new Product { name = "Steak", price = 23.44m }); return products; } } } In real life, you would want to retrieve the list of products from storage instead of a static array. We are being lazy here. Next you need to modify the Default.htm page to use the ProductService.svc. The jQuery script in the following updated Default.htm page makes an Ajax call to the WCF service. The data retrieved from the ProductService.svc is displayed in the client template. <"> $.post("ProductService.svc/SelectProducts", function (results) { var products = results["d"]; $("#productTemplate").render(products).appendTo("#productContainer"); }); </script> </body> </html> Deploying the jQuery Application to the Cloud Now that we have created our jQuery application, we are ready to deploy our application to the cloud so that the whole world can use it. Right-click your jQueryApp project in the Solution Explorer window and select the Publish menu option. When you select publish, your application and your application configuration information is packaged up into two files named jQueryApp.cspkg and ServiceConfiguration.cscfg. Visual Studio opens the directory that contains the two files. In order to deploy these files to the Windows Azure cloud, you must upload these files yourself. Return to the Windows Azure Developers Portal at the following address: Select your project and select the jQueryApp service. You will see a mysterious cube. Click the Deploy button to upload your application. Next, you need to browse to the location on your hard drive where the jQueryApp project was published and select both the packaged application and the packaged application configuration file. Supply the deployment with a name and click the Deploy button. While your application is in the process of being deployed, you can view a progress bar. Running the jQuery Application in the Cloud Finally, you can run your jQuery application in the cloud by clicking the Run button. It might take several minutes for your application to initialize (go grab a coffee). After WebRole1 finishes initializing, you can navigate to the following URL to view your live jQuery application in the cloud: The page is hosted on the Windows Azure cloud and the WCF service executes every time that you request the page to retrieve the list of products. Summary Because we started from scratch, we needed to complete several steps to create and deploy our jQuery application to the Windows Azure cloud. We needed to create a Windows Azure account, create a hosted service, install the Windows Azure Tools for Visual Studio, create the jQuery application, and deploy it to the cloud. Now that we have finished this process once, modifying our existing cloud application or creating a new cloud application is easy. jQuery and Windows Azure work nicely together. We can take advantage of jQuery to build applications that run in the browser and we can take advantage of Windows Azure to host the backend services required by our jQuery application. The big benefit of Windows Azure is that it enables us to scale. If, all of the sudden, our jQuery application explodes in popularity, Windows Azure enables us to easily scale up to meet the demand. We can handle anything that the Internet might throw at us. Liked the app plus the “Hello world” app on default.aspx page thanks for the info,i like tour blog info because it’s meant to me about learning something new..nice job! This a good “get-go” on Windows Azure for developers, though the sample is too much simple. Now I have a little knowledge about W. Azure -thanks to this tutorial- I have tons of questions related to this topic :p One of the things I’ve really had a hard time wrapping my head around is how cloud sites interact with persistent storage (both file system and database). This article is neat in a kind of introductory way, but it doesn’t really show me a typical use case, which would be far more helpful and enticing. “In this blog entry, I make no assumptions. I assume that you have never used Windows Azure…” Er… isn’t that an assumption right there 😉 Hi Stephen, A really good article for starters and advanced people too. Thanks for sharing this awsome article. Thani
https://stephenwalther.com/archive/2010/05/10/jquery-and-windows-azure
CC-MAIN-2021-31
refinedweb
1,617
64.1
copy or transmission of this publication may be made without written permission.uk Email: rob@robmiles.All rights reserved. No reproduction.robmiles.1 Wednesday. Robert Blackburn Building The University of Hull.com Blog: and I will take a look.com If you find a mistake in the text please report the error to foundamistake@robmiles.ac. Edition 2. The author can be contacted at: The Department of Computer Science. 12 January 2011 iii . Cottingham Road HULL HU6 7RX UK Department:. . e. And you have to work hard at it. enjoy programming. The bad news about learning to program is that you get hit with a lot of ideas and concepts at around the same time when you start. and programming. And remember that in many cases there is no best solution. the fastest. If you have programmed before I'd be grateful if you'd still read the text. You can learn a lot from studying code which other folk have created. Programming is not rocket science it is. and this can be confusing. i.9. The principle reason why most folks don't make it as programmers is that they give up.ac.com C# Programming © Rob Miles 2010 5 . Persistence – writing programs is hard work.Introduction Welcome Introduction Welcome Welcome to the Wonderful World of Rob Miles™. the smallest. This is a world of bad jokes.com www. It just makes you all irritable in the morning. Reading the notes These notes are written to be read straight through. However. There are also bits written in a Posh These are really important and should be learnt by heart. The website for the book is at. Rob Miles rob@robmiles.csharpcourse. puns. Staying up all night trying to sort out a problem is not a good plan. These are based on real programming experience and are to be taken seriously. If you haven't solved a programming problem in 30 minutes you should call time out and seek help. In this book I'm going to give you a smattering of the C# programming language.hull. well.dcs. programming. Figuring out how somebody else did the job is a great starting point for your solution.robmiles.com www. Or at least walk away from the problem and come back to it. the easiest to use etc. If you have not programmed before.uk Getting a copy of the notes These notes are made freely available to Computer Science students at the University of Hull. The keys to learning programming are: Practice – do a lot of programming and force yourself to think about things from a problem solving point of view Study – look at programs written by other people. It is worth it just for the jokes and you may actually learn something. If you have any comments on how the notes can be made even better (although I of course consider this highly unlikely) then feel free to get in touch Above all. We will cover what to do when it all goes wrong later in section 5. don't get too persistent. Font. They contain a number of Programming Points. and then referred to afterwards. just ones which are better in a particular context. do not worry. Not because they are stupid. i. because it sets the context in which all the issues of programming itself are placed. Finally you will take a look at programming in general and the C# language in particular.1. 1. A better way is to describe it as: A device which processes information according to instructions it has been given. This is an important thing to do. to ensure that you achieve a ―happy ending‖ for you and your customer. However for our purposes it will do. Software uses the physical ability of the hardware. which can run programs.1 Computers Before we consider programming. we are going to consider computers. A programmer has a masochistic desire to tinker with the innards of the machine. it is hardware. Hardware is the impressive pile of lights and switches in the corner that the salesman sold you. can lead to significant amounts of confusion. This. particularly amongst those who then try to program a fridge. The box. a keen desire to process words with a computer should not result in you writing a word processor! However. C# Programming © Rob Miles 2010 6 . This general definition rules out fridges but is not exhaustive.2 Hardware and Software If you ever buy a computer you are not just getting a box which hums. Hardware is the physical side of the system. Most people do not write programs.Computers and Programs Computers 1 Computers and Programs In this chapter you are going to find out what a computer is and get an understanding of the way that a computer program tells the computer what to do. while technically correct. must also have sufficient built-in intelligence to understand simple commands to do things.1. You will discover what you should do when starting to write a program. 1. Essentially if you can kick it. At this point we must draw a distinction between the software of a computer system and the hardware. They use programs written by other people. Software is what makes the machine tick.e. The business of using a computer is often called programming. and further because there are people willing to pay you to do it. One of the golden rules is that you never write your own program if there is already one available. We must therefore make a distinction between users and programmers. to be useful. Before we can look at the fun packed business of programming though it is worth looking at some computer terminology: 1. because you will often want to do things with computers which have not been done before. and it stops working when immersed in a bucket of water. we are going to learn how to program as well as use a computer. The instructions you give to the computer are often called a program. A user has a job which he or she finds easier to do on a computer running the appropriate program.1 An Introduction to Computers Qn: Why does a bee hum? Ans: Because it doesn't know the words! One way of describing a computer is as an electric box which hums. This is not what most people do with computers. If a computer has a soul it keeps it in its software. Computers and Programs Computers to do something useful. Windows 7 is an operating system. Remember this when you get a bank statement which says that you have £8. It gives computer programs a platform on which they can execute. It also lets you run programs. The Operating System makes the machine usable. It is called software because it has no physical existence and it is comparatively easy to change.608 in your account! Data Processing Computers are data processors. Information is the interpretation of the data by people to mean something.. All computers are sold with some software. Put duff data into a computer and it will do equally useless things. Software is the voice which says "Computer Running" in a Star Trek film. Strictly speaking computers process data. it is the user who gives meaning to these patterns. An example.3 Data and Information People use the words data and information interchangeably. and something comes out of the other end: Data Computer Data This makes a computer a very good "mistake amplifier". Information is fed into them. Without it they would just be a novel and highly expensive heating system. as well as a useful thing to blame. As far as the computer is concerned data is just patterns of bits. some processing is performed. A computer program is just a sequence of instructions which tell a computer what to do with the data coming in and what form the data sent out will have. As far as the computer is concerned data is just stuff coming in which has to be manipulated in some way. A computer works on data in the same way that a sausage machine works on meat. The software which comes with a computer is often called its Operating System.1. and then generate further information. A program is unaware of the data it is processing in the same way that a sausage machine is unaware of what meat is. It looks after all the information held on the computer and provides lots of commands to allow you to manage things. You will have to learn to talk to an operating system so that you can create your C# programs and get them to go. they do something with it.. 1.. something is put in one end. ones you have written and ones from other people. humans work on information... A computer program tells the computer what to do with the information coming in. So why am I being so pedantic? Because it is vital to remember that a computer does not "know" what the data it is processing actually means. It is only us people who actually give meaning to the data (see above). Put a bicycle into a sausage machine and it will try to make sausages out of it. I regard data and information as two different things: Data is the collection of ons and offs which computers store and manipulate. C# Programming © Rob Miles 2010 7 . They seem to think that one means the other.388. As software engineers it is inevitable that a great deal of our time will be spent fitting data processing components into other devices to drive them. 2. Programming is a black art.2 Programs and Programming I tell people I am a "Software Engineer". The power and capacity of modern computers makes this less of an issue than in the past. It is into this world that we. I will mention them when appropriate. These are the traditional uses of computers. Note that this "raises the stakes" in that the consequences of software failing could be very damaging. 1. At the same time it is keeping the laser head precisely positioned and also monitoring all the buttons in case you want to select another part of the disk.) Programmer’s Point: At the bottom there is always hardware It is important that you remember your programs are actually executed by a piece of hardware which has physical limitations.. "That's interesting". CD Player: A computer is taking a signal from the disk and converting it into the sound that you want to hear. These embedded systems will make computer users of everybody.Computers and Programs Programs and Programming Note that the data processing side of computers. you will press a switch to tell a computer to make it work. as software writers are moving. A blank stare. to optimise the performance of the engine. In this case a defect in the program could result in illness or even death (note that I don't think that doctors actually do this – but you never know. processing this data and producing a display which tells you the time. setting of the accelerator etc and producing voltages out which control the setting of the carburettor. timing of the spark etc. 4. It is important to think of the business of data processing as much more than working out the company payroll. You must make sure that the code you write will actually fit in the target machine and operate at a reasonable speed. C# Programming © Rob Miles 2010 8 . Car: A micro-computer in the engine is taking information from sensors telling it the current engine speed. and ever will have. A look which indicates that you can't be a very good one as they all drive Ferraris and tap into the Bank of England at will. reading in numbers and printing out results. 3. and we will have to make sure that they are not even aware that there is a computer in there! You should also remember that seemingly innocuous programs can have life threatening possibilities. However the CD player and games console could not be made to work without built-in data processing ability. followed by a long description of the double glazing that they have just had fitted. road speed. Note that some of these data processing applications are merely applying technology to existing devices to improve the way they work. Games Console: A computer is taking instructions from the controllers and using them to manage the artificial world that it is creating for the person playing the game. For example a doctor may use a spread sheet to calculate doses of drugs for patients. It is the kind of thing that you grudgingly admit to doing at night with the blinds drawn and nobody watching. You will not press a switch to make something work. which you might think is entirely reading and writing numbers. is much more than that. Tell people that you program computers and you will get one of the following responses: 1. but you should still be aware of these aspects. examples of typical data processing applications are: Digital Watch: A micro-computer in your watch is taking pulses from a crystal and requests from buttons. oxygen content of the air. Most reasonably complex devices contain data processing components to optimise their performance and some exist only because we can build in intelligence. Asked to solve every computer problem that they have ever had. not all of them are directly related to the problem in hand.2. Programming is defined by me as deriving and expressing a solution to a given problem in a form which a computer system can understand and execute. I am going to start on the basis that you are writing your programs for a customer. tut tutting. Many software projects have failed because the problem that they solved was the wrong one. this is almost a reflex action. It is therefore very important that a programmer holds off making something until they know exactly what is required. Both you and the C# Programming © Rob Miles 2010 9 . The customers assumed that. I like to think of a programmer as a bit like a plumber! A plumber will arrive at a job with a big bag of tools and spare parts. the right thing was being built. Programming is just like this. and only at the final handover was the awful truth revealed. type of computer or anything like that. The worst thing you can say to a customer is "I can do that". The computer has to be made to understand what you are trying to tell it to do. He or she has problem and would like you to write a program to solve it. since the developers had stopped asking them questions. From Problem to Program Programming is not about mathematics. he will open his bag and produce various tools and parts. If you think that learning to program is simply a matter of learning a programming language you are very wrong. We shall assume that the customer knows even less about computers than we do! Initially we are not even going to talk about the programming language. This tells you exactly what the customer wants. Programmers pride themselves on their ability to come up with solutions. we are simply going to make sure that we know what the customer wants. fit them all together and solve your problem. In the real world such a definition is sometimes called a Functional Design Specification or FDS. which both you and the customer agree on. You are given a problem to solve. it is about organization and structure. Instead you should think "Is that what the customer wants?" This is a kind of self-discipline. You have at your disposal a big bag of tricks.Computers and Programs Programs and Programming Programming is defined by most people as earning huge sums of money doing something which nobody can understand. 1. In fact if you think that programming is simply a matter of coming up with a program which solves a problem you are equally wrong! There are many things you must consider when writing a program. What you should do is think "Do I really understand what the problem is?" Before you solve a problem you should make sure that you have a watertight definition of what the problem is. Unfortunately it is also the most difficult part of programming as well. One or two things fall out of this definition: You need to be able to solve the problem yourself before you can write a program to do it. You look at the problem for a while and work out how to solve it and then fit the bits of the language together to solve the problem you have got. The developers of the system quite simply did not find out what was required.1 What is a Programmer? And remember just how much plumbers earn…. The art of taking a problem and breaking it down into a set of instructions you can give a computer is the interesting part of programming. in this case a programming language. Having looked at it for a while. so as soon as they are given a problem they immediately start thinking of ways to solve it. The art of programming is knowing which bits you need to take out of your bag of tricks to solve each part of the problem. but instead created what they thought was required. Solving the Wrong Problem Coming up with a perfect solution to a problem the customer has not got is something which happens surprisingly often in the real world. What the system does with the information. Programmer’s Point: The specification must always be there I have written many programs for money. This is called prototyping. 1. What flows out of the system. there is no customer to satisfy. These work on the basis that it is very hard (and actually not that useful) to get a definitive specification at the start of a project.. C# Programming © Rob Miles 2010 10 . Information coming out The information that our customer wants to see is: the area of glass required for the window the length of wood required to build a frame. You as a developer don’t really know much about the customer’s business and they don’t know the limitations and possibilities of the technology. in terms of the amount of wood and glass required. This is true even (or perhaps especially) if I do a job for a friend. and involve them in the design process. It also forces you to think about what your system is not going to do and sets the expectations of the customer right at the start. "This looks like a nice little earner" you think. With this in mind it is a good idea to make a series of versions of the solution and discuss each with the customer before moving on to the next one. There are lots of ways of representing this information in the form of diagrams.. You might think that this is not necessary if you are writing a program for yourself.2. He wants to just enter the dimensions of the window and then get a print out of the cost to make the window.. Writing some form of specification forces you to think about your problem at a very detailed level. I would never write a program without getting a solid specification first. This is not true.2 A Simple Problem Consider the scenario. then you can think about ways of solving the problem. and once you have agreed to a price you start work.. Once you have got your design specification. The height of the window. Specifying the Problem When considering how to write the specification of a system there are three important things: What information flows into the system.Computers and Programs Programs and Programming customer sign it. you are sitting in your favourite chair in the pub contemplating the universe when you are interrupted in your reverie by a friend of yours who sells double glazing for a living. and the bottom line is that if you provide a system which behaves according to the design specification the customer must pay you. C# Programming © Rob Miles 2010 11 . The length of wood required for the frame.25 feet per metre. To make the frame we will need two pieces of wood the width of the window. Note that we have also added units to our description.5 metres and 2.Computers and Programs Programs and Programming You can see what we need if you take a look at the diagram below: Height of Window Width of Window The area of the glass is the width multiplied by the height. your program will regard the data as valid and act accordingly. this is very important .5 metres inclusive. we must then both sign the completed specification. Having written this all up in a form that both you and the customer can understand. In the case of our window program the metadata will tell us more about the values that are being used and produced. Remember that we are selling double glazing. and two pieces of wood the height of the window.perhaps our customer buys wood from a supplier who sells by the foot. we now have to worry about how our program will decide when the information coming in is actually valid. specifically the units in which the information is expressed and the valid range of values that the information may have. in which case our output description should read: Note that both you and the customer must understand the document! The area of glass required for the window.0 metres inclusive. Being sensible and far thinking people we do not stop here. in metres and being a value between 0. and work can commence. In the case of the above we could therefore expand the definition of data coming in as: The width of the window. For any quantity that you represent in a program that you write you must have at least this level of metadata .5 Metres and 3. This must be done in conjunction with the customer. Programmer’s Point: metadata is important Information about information is called metadata. The height of the window.. in square metres. given in feet using the conversion factor of 3. he or she must understand that if information is given which fits within the range specified. The word meta in this situation implies a "stepping back" from the problem to allow it to be considered in a broader context. so two panes will be required. in metres and being a value between 0. Ideally all this information should be put into the specification. Again. which should include layouts of the screens and details of which keys should be pressed at each stage. and emerge with another system to be approved. reminiscent of a posh tailor who produces the perfect fit after numerous alterations. including the all-important error conditions. Quite often prototypes will be used to get an idea of how the program should look and feel. They will get a bit upset when the delivery deadline goes by without a finished product appearing but they can always cheer themselves up again by suing you. In a large system the person writing the program may have to create a test harness which is fitted around the program and will allow it to be tested. suggests changes and then wait for the next version to find something wrong with.... you could for example say: “If I give the above program the inputs 2 metres high and 1 metre wide the program should tell me I need 4 square metres of glass and 19. if you are going to use prototypes it is a good thing to plan for this from the C# Programming © Rob Miles 2010 12 . or you will end up performing five times the work! If this seems that you are getting the customer to help you write the program then you are exactly right! Your customer may have expected you to take the description of the problem and go into your back room . Getting Paid Better yet. Rob's law says that 60% of the duff 40% will now be OK. In terms of code production. What will happen is that you will come up with something which is about 60% right. However.to emerge later with the perfect solution to the problem. The customer thinks that this is great.” The test procedure which is designed for a proper project should test out all possible states within the program. This is actually a good idea. muttering under your breath.. because I did mention earlier that prototyping is a good way to build a system when you are not clear on the initial specificaiton. Actually. so you accept changes for the last little bit and again retreat to your keyboard. Fact: If you expect to derive the specification as the project goes on either you will fail to do the job.Computers and Programs Programs and Programming Proving it Works In a real world you would now create a test which will allow you to prove that the program works. All the customer does is look at something. Remember this when you are working out how much work is involved in a particular job. we have come full circle here. you can expect to write as much code to test your solution as is in the solution itself. You then go back into your back room. and one we will explore later. Testing is a very important part of program development. for which they can expect to be paid. there is no ambiguity which can lead to the customer requesting changes to the work although of course this can still happen! The good news for the developer is that if changes are requested these can be viewed in the context of additional work. The customer will tell you which bits look OK and which bits need to be changed. set up a phased payment system so that you get some money as the system is developed. is something which the customer is guaranteed to have strong opinions about. There is even one development technique where you write the tests before you write the actual program that does the job. This is not going to happen. Both the customer and the supplier should agree on the number and type of the tests to be performed and then sign a document describing these. how the information is presented etc.5 feet of wood.. sometimes even down to the colour of the letters on the display! Remember that one of the most dangerous things that a programmer can think is "This is what he wants"! The precise interaction with the user .what the program does when an error is encountered. . particularly when you might have to do things like trade with the customer on features or price. Explain the benefits of "Right First Time" technology and if that doesn't work produce a revolver and force the issue! Again. It is very hard to express something in an unambiguous way using English. by using the most advanced software and hardware. When we start with our double glazing program we now know that we have to: read in the width verify the value read in the height verify the value calculate width times height times 2 and print it calculate ( width + height ) * 2 * 3.often with the help of the customer. If you do not believe me.. This is very important. One very good reason for doing this kind of thing is that it gets most of the program written for you . an art. You are wrong. Fruit Flies like a Banana! C# Programming © Rob Miles 2010 13 . 1. We cannot make very clever computers at the moment. if I could underline in red I would: All the above apply if you are writing the program for yourself. At the moment. Tape worms do not speak very good English. You do not work for your customers. English as a language is packed full of ambiguities.. why can we not use something like English?" There are two answers to this one: 1.25 and print it The programming portion of the job is now simply converting the above description into a language which can be used in a computer. all to the better. and there are limits to the size of program that we can create and the speed at which it can talk to us.3 Programming Languages Once we know what the program should do (specification).. To take the first point. you work with them. The best we can do is to get a computer to make sense of a very limited language which we use to tell it what to do. ask any lawyer! Time Flies like an Arrow. The customer may well say "But I am paying you to be the computer expert. English would make a lousy programming language. Please note that this does not imply that tape worms would make good programmers! Computers are too stupid to understand English. therefore we cannot make a computer which can understand English. Computers are made clever by putting software into them. One of the first things you must do is break down the idea of "I am writing a program for you" and replace it with "We are creating a solution to a problem". Fact: More implementations fail because of inadequate specification than for any other reason! If your insistence on a cast iron specification forces the customer to think about exactly what the system is supposed to do and how it will work. This is no excuse. I know nothing about these machines". we can make computers which are about as clever as a tape worm. Programmer’s Point: Good programmers are good communicators The art of talking to a customer and finding out what he/she wants is just that. If you want to call yourself a proper programmer you will have to learn how to do this... You might ask the question "Why do we need programming languages. 2. and how we are going to determine whether it has worked or not (test) we now need to express our program in a form that the computer can work with.. You are your own worst customer! You may think that I am labouring a point here. To take the second point. To get the maximum possible performance. having borrowed (or improved) features provided by these languages. because of all the safety stuff I might not be able to cut down certain kinds of tree. if I do something stupid C will not stop me. 1. If I was a real lumberjack I would go out and buy a professional chain saw which has no safety features whatsoever but can be used to cut down most anything.e. The managed code is fussed over by the system which runs it.4 C# There are literally hundreds of programming languages around.4. This makes the language much more flexible. 1. If I. C# bears a strong resemblance to the C++ and Java programming languages. However. As I am not an experienced chain saw user I would expect it to come with lots of built in safety features such as guards and automatic cut outs.4.1 Dangerous C I referred to C as a dangerous language. So what do I mean by that? Consider the chain saw. some political and others marketing. so I have a much greater chance of crashing the computer with a C program than I do with a safer language. something the amateur machine would not let happen. but do not think that it is the only language you will ever learn. Rob Miles. It was developed by Microsoft Corporation for a variety of reasons. These will make me much safer with the thing but will probably limit the usefulness of the tool. i. which is a highly dangerous and entertaining language which was invented in the early 1970s. In programming terms what this means is that C lacks some safety features provided by other programming languages. causing your programs to run more slowly. want to use a chain saw I will hire one from a shop. Programmer’s Point: Computers are always stupid I reckon that you should always work on the basis that any computer will tolerate no errors on your part and anything that you do which is stupid will always cause a disaster! This concentrates the mind wonderfully. you can mark your programs as unmanaged. However. Programmer’s Point: The language is not that important There are a great many programming languages around. C is famous as the language the UNIX operating system was written in. The origins of both Java and C++ can be traced back to a language called C. 1. An unmanaged program goes faster. This makes sure that it is hard (but probably not impossible) to crash your computer running managed code. A C# program can contain managed or unmanaged parts. some technical. and was specially designed for this. you will need to know at least 3! We are going to learn a language called C# (pronounced C sharp). and enable direct access to parts of the underlying computer system. If you ever make the mistake of calling the language C hash you will show your ignorance straight away! C# is a very flexible and powerful programming language with an interesting history. during your career you will have to learn more than just one. C# is a great language to start programming in. If I make a mistake with the professional tool I could quite easily lose my leg. They are simple enough to be made sense of by computer programs and they reduce ambiguity.Computers and Programs C# Programming languages get around both of these problems. but if it crashes it is capable of taking the computer C# Programming © Rob Miles 2010 14 . all this fussing comes at a price.2 Safe C# The C# language attempts to get the best of both worlds in this respect. 1. each of which is in charge of part of the overall system. and debugger. test and extend. The compiler will also flag up warnings which occur when it notices that you have done something which is not technically illegal.4. They are then located automatically when your program runs. A compiler is a very large program which knows how to decide if your program is legal. The compiler would tell you about this. How you create and run your programs is up to you. but I am not going to tell you much about it just yet. set up network connections and the like. The computer cannot understand the language directly. The use of objects is as much about design as programming. An example of a warning situation is where you create something but don't use it for anything.5 Creating C# Programs Microsoft has made a tool called Visual Studio.NET Framework. for now the thing to remember is that you need to show your wonderful C# program to the compiler before you get to actually run it. which is a great place to write programs.4. C# is a compiled programming language.3 C# and Objects The C# language is object oriented. The C# language is supplied with a whole bunch of other stuff (to use a technical term) which lets C# programs do things like read text from the keyboard. These low level instructions are in turn converted into the actual commands to drive the hardware which runs your program. Later on we will look at how you can break a program of your own down into a number of different chunks (perhaps so several different programmers can work on it).which may be part of the compiling and running system. It comprises the compiler. which can be used to compile and run C# programs. Switching to unmanaged mode is analogous to removing the guard from your new chainsaw because it gets in the way. We will look in more detail at this aspect of how C# programs work a little later. Only if no errors are found by the compiler will it produce any output. called Visual Studio Express edition. The first thing it does is check for errors in the way that you have used the language itself. It is provided in a number of versions with different feature sets. which is a great place to get started.e. Object Oriented Design makes large projects much easier to design. things that you type to the command prompt. along with an integrated editor. so a program called a compiler converts the C# text into the low level instructions which are much simpler.4 Making C# Run You actually write the program using some form of text editor . 1. Objects are an organisational mechanism which let you break your program down into sensible chunks.4. There is a free version. in case you had forgotten to add a bit of your program. Another free resource is the Microsoft .Computers and Programs C# with it. C# Programming © Rob Miles 2010 15 . This provides a bunch of command line tools. 1. and we have to know how to program before we can design larger systems. It also lets you create programs which can have a high degree of reliability and stability. i. I am very keen on object oriented programming. C# is a great language to start learning with as the managed parts will make it easier for you to understand what has happened when your programs go wrong. but may indicate that you have made a mistake somewhere. print on the screen. These extra features are available to your C# program but you must explicitly ask for them. This is not because I don't know much about it (honest) but because I believe that there are some very fundamental programming issues which need to be addressed before we make use of objects in our programs. Once you are sitting in front of the keyboard there is a great temptation to start pressing keys and typing something in which might work. The ingredients will be values (called variables) that you want your program to work with. If you had sat down with a pencil and worked out the solution first you would probably get to a working system in around half the time. instructions which manipulate the data. The program itself will be a sequence of actions (called statements) that are to be followed by the computer. types in the program and makes it work first time! 1.6 What Comprises a C# Program? If your mum wanted to tell you how to make your favourite fruitcake she’d write the recipe down on a piece of paper. It needs to know which external resources your program is going to use. I reckon that you write programs best when you are not sitting at the computer. As part of the program design process you will need to decide what items of data need to be stored. often called a source file. I am going to assume that you are using a computer which has a text editor (usually Notepad) and the . Some parts of your program will simply provide this information to tell the compiler what to do. The data has to be stored within the computer whilst the program processes it. but written for a computer to follow. i. Rather than writing the program down on a piece of paper you instead put it into a file on the computer. that is for other documents. The Human Computer Of course initially it is best if we just work through your programs on paper.e. To take these in turn: Controlling the Compiler .NET framework.NET framework installed.4.Computers and Programs C# I'm not going to go into details of how to download and install the . The recipe would be a list of ingredients followed by a sequence of actions to perform on them. Storing the Data Programs work by processing data. which you will then spend hours fiddling with to get it going. I am impressed by someone who turns up. A program can be regarded as a recipe. This is what the compiler acts on. A variable is simply a named location in which a value is held whilst the program runs. This is not good technique. All computer languages support variables of one form or another. not a cook. You must also decide on sensible names that you will use to identify these items. The C# compiler needs to know certain things about your program. A source file contains three things: instructions to the compiler information about the structures which will hold the data to be stored and manipulated. It also can be told about any options for the construction of your program which are important. Programmer’s Point: Great Programmers debug less I am not impressed by hacking programmers who spend whole days at terminals fighting with enormous programs and debugging them into shape. C# also lets you build up structures which can hold more than one item. the best approach is to write (or at least map out) your solution on paper a long way away from the machine. You will almost certainly end up with something which almost works. for example a single structure could hold all the information about a particular bank customer. C# Programming © Rob Miles 2010 16 . woodLength might be a good choice when we want to hold the length of wood required. One method may refer to others. The C# language also has a huge number of libraries available which you can use. Such a lump is called a method. for example add two numbers together and store the result. You also create identifiers when you make things to hold values. The C# language actually runs your program by looking for a method with a special name. so that your program can look at things and decide what to do. In the case of C# you can lump statements together to form a lump of program which does one particular task. The names that you invent to identify things are called identifiers. They would let you say things like "heat sugar until molten" or "mix until smooth". Main. ―Happy Christmas‖ is not part of the instructions. Objects Some of the things in the programs that we write are objects that are part of the framework we are using. which are used during the cooking process. your program ends. or very large. and do not have any special meaning. it is what needs to be written. and when Main finishes. for example ShowMenu or SaveToFile. these are things like mixing bowls and ovens. simple. It can have any name you like. A statement is an instruction to perform one particular operation. The colours just serve to make the programs easier to understand. She is using double quote characters to mark the text that is to be drawn on the cake. There are the instructions that you want the computer to perform and there are the messages that you want the program to actually display in front of the user. A method can be very small. The names of objects will be given in a different shade of blue in some of the listings in this text. In fact.Computers and Programs C# Describing the Solution The actual instructions which describe your solution to the problem must also be part of your program. It can return a value which may or may not be of interest. The words which are part of the C# language itself are called keywords. This method is called when your program starts running. and C# works in exactly the same way. They are added automatically by the editor as you write your program. These save you from "re-inventing the wheel" each time you write a program. Your mum might add the following instruction to her cake recipe: Now write the words “Happy Christmas” on top of the cake in pink icing. you'll find that programs look a lot like recipes. Identifiers and Keywords You give a name to each method that you create. Seasoned programmers break down a problem into a number of smaller ones and make a method for each. Text in a Computer Program There are two kinds of text in your program. We will look at methods in detail later in these notes. A single. and your program can contain as many methods as you see fit. The really gripping thing about programs is that some statements can change which statement is performed next. These kinds of messages are coloured red in this text. Keywords will appear blue in some of the listings in this text. and you try to make the name of the function fit what it does. To continue our cooking analogy. In a recipe a keyword would be something like "mix" or "heat" or "until". instruction to do something in a C# program is called a statement. C# Programming © Rob Miles 2010 17 . Colours and Conventions The colours that I use in this text are intended to line up with the colours you will see when you edit your programs using a professional program editor such as the one supplied as part of Visual Studio. Later on we will look at the rules and conventions which you must observe when you create identifiers. Simple Data Processing A First C# Program 2 Simple Data Processing In this chapter we are going to create a genuinely useful program (particularly if you are in the double glazing business).2 2. and you could run it.25 . Broadly speaking the stuff before these two lines is concerned with setting things up and getting the values in to be processed.2. This is the problem we set out to solve as described in section1. height = double. 2.1 A First C# Program The first program that we are going to look at will read in the width and height of a window and then print out the amount of wood and glass required to make a window that will fit in a hole of that size.Parse(heightString).WriteLine ( "The length of the wood is " + woodLength + " feet" ) . glassArea = 2 * ( width * height ) . heightString. Here it is: using System. The stuff after the two lines is concerned with displaying the answer to the user. We can now go through each line in turn and try to see how it fits into our program. } } Code Sample 1 . The actual work is done by the two lines that I have highlighted. Console. heightString = Console. widthString = Console.ReadLine(). height. woodLength. Console.WriteLine( "The area of the glass is " + glassArea + " square metres" ) .1 The Program Example Perhaps the best way to start looking at C# is to jump straight in with our first ever C# program. Then we will use additional features of the C# language to improve the quality of the solution we are producing. class GlazerCalc { static void Main() { double width. string widthString. glassArea. woodLength = 2 * ( width + height ) * 3.1. C# Programming © Rob Miles 2010 18 . If you gave it to a C# compiler it would compile. width = double. We will start by creating a very simple solution and investigating the C# statements that perform basic data processing.GlazerCalc Program This is a valid program.ReadLine().Parse(widthString). A big part of learning to program is learning how to use all the additional features of the system which support your programs. don't worry too much about classes. We have namespaces in our conversations too. We will use other namespaces later on. in that the compiler now knows that if someone tries to use the value returned by this method. The method will just do a job and then finish. we are explicitly stating that it returns nothing. C# Programming © Rob Miles 2010 19 . This is an instruction to the C# compiler to tell it that we want to use things from the System namespace. This method (and there must be one. A namespace is a place where particular names have meaning. the word static in this context means "is part of the enclosing class and is always here". When your program is loaded and run the first method given control is the one called Main. class GlazerCalc Classes are the basis of object oriented programming. In the case of our double glazing calculator the class just contains a single method which will work out our wood lengths and glass area. A class is a container which holds data and program code to do a particular job. in other words the program above should be held in a file called GlazerCalc. In programming terms the void keyword means that the method we are about to describe does not return anything of interest to us. When we get to consider objects we will find that this little keyword has all kinds of interesting ramifications. and only one such method) is where your program starts running. void A void is nothing. just make sure that you pick sensible names for the classes that you create. In the case of C# the System namespace is where lots of useful things are described. Main You choose the names of your methods to reflect what they are going to do for you. Except for Main. static This keyword makes sure that the method which follows is always present. For now. This makes our programs safer. If I want to just refer to this as Console I have to tell the compiler I'm using the System namespace. There is a convention that the name of the file which contains a particular class should match the class itself. this must be a mistake. as we shall see later. This means that if I refer to something by a particular name the compiler will look in System to see if there is anything matching that name.e. If you miss out the Main method the system quite literally does not know where to start.cs. and one other thing. In some cases we write methods which return a result (in fact we will use such a method later in the program). in order to stop someone else accidentally making use of the value returned by our Main method. I've called ours GlazerCalc since this reflects what it does. However. i. Oh.Simple Data Processing A First C# Program using System. if I am using the "Football" namespace and I say “That team is really on fire” I'm saying something good. You need to invent an identifier for every class that you create. A C# program is made up of one or more classes. One of these useful things provided with C# is the Console object which will let me write things which will appear on the screen in front of the user. But for now I'd be grateful if you'd just make sure that you put it here in order to make your programs work properly. but a class can contain much more than that if it needs to. If I am using the "Firefighter" namespace I'm saying something less. It takes the height and width values and uses them to calculate the length of wood required.25 to allow for the fact that the customer wants the length of wood in feet.e. glassArea = 2 * ( width * height ) . just like the ReadLine method. This makes the program clearer.ReadLine(). Normally C# will work out expressions in the way you would expect.Parse(heightString). The + and * characters in the expression are called operators in that they cause an operation to take place. We have seen it applied to add two integers together.25 . followed by addition and subtraction. woodLength = 2*(width + height)*3. These are what the operators work on. This is the bit that does the work. I've put one multiplication in brackets to allow me to indicate that I am working out two times the area (i. When I write programs I use brackets even when the compiler does not need them. Note that the area is given in square meters. We have seen these used in the calls of Parse and also ReadLine "The length of the wood is " This is a string literal. height = double. In the above expression I wanted to do some parts first. this time it is important that you notice the use of parenthesis to modify the order in which values are calculated in the expression. the plus here means something completely different 2. There are around 3. I put brackets around the parts to be done first. for two panes of glass). 2 Another TV show reference C# Programming © Rob Miles 2010 23 . There is no need to do this particularly. It is a string of text which is literally just in the program. but I think it makes it slightly clearer. The string of text is enclosed in double quote characters to tell the compiler that this is part of a value in the program.25 feet in a meter. This line repeats the calculation for the area of the glass. not instructions to the compiler itself. ( This is the start of the parameters for this method call. These two statements simply repeat the process of reading in the text of the height value and then converting it into a double precision value holding the height of the window. all multiplication and division will be done first. The other items in the expression are called operands. except that this one takes what it is given and then prints it out on the console.Simple Data Processing A First C# Program heightString = Console. This is the actual nub of the program itself.WriteLine This is a call of a method. i.e. Note that I use a factor of 3. Console. so I did what you would do in mathematics. The calculation is an expression much like above. + Plus is an addition operator. so no conversion is required. In this case it means "add two strings together". so I multiply the result in meters by this factor. 03 The string "2. This means that it is going to perform string concatenation rather than mathematical addition. ) The bracket marks the end of the parameter being constructed for the WriteLine method call. It is very important that you understand precisely what is going on here.0 ). The variable heightString is tagged with information that says "this is a string. woodLength This is another example of context at work. You can think of all of the variables in our program being tagged with metadata (there is that word again) which the compiler uses to decide what to do with them. When the method is called the program first assembles a completed string out of all the components. in this program the length of the wood required. use a plus with this and you concatenate". The variable woodLength is tagged with metadata which says "this is a double precision floating point value. and so the program works as you would expect.0 ). This difference in behaviour is all because of the context of the operation that is being performed.0 + 3. We have seen this with namespaces. between two double precision floating point numbers it means "do a sum". adding (or concatenating) them to produce a single result.0) and produce a double precision floating point value. + " feet" Another concatenation here.Simple Data Processing A First C# Program You will have to get used to the idea of context in your programs.0" has the text of the value 3. Whenever I print a value out I always put the units on the end.0" + 3. Here it has a string on the left hand side. It then passes the resulting string value into the method which will print it out on the console. Fortunately it can do this. giving the output: 5 But the line of code: Console. However. In the case of the previous +. C# Programming © Rob Miles 2010 24 . use a plus with this and you perform arithmetic". It would ask the value 3 to convert itself into a string (sounds strange – but this is what happens. We are adding the word feet on the end. Previously we have used woodLength as a numeric representation of a value. This result value would then be asked to provide a string version of itself to be printed. This would perform a numeric calculation (2. The C# compiler must therefore ask the woodLength data item to convert itself into a string so it can be used correctly in this position. It would then produce the output: 2. The C# system uses the context of an operation to decide what to do. Consider: Console.0 added on the end. Here it is with operators. Would regard the + as concatenating two strings.WriteLine ( "2.WriteLine ( 2. in the context it is being used at the moment (added to the end of a string) it cannot work like that.0 + 3. This makes it much easier to ensure that the value makes sense. } } .class GlazerCalc{static void Main(){double width. JustlikeIfindithardtoreadenglishwithouttheproperspacing I find it hard to read a program if it has not been laid out correctly. C# Programming © Rob Miles 2010 25 . I do it because otherwise I am just about unable to read the program and make sense of what it does.ReadLine(). For now however. woodLength. height.string widthString. A block of code starts with a { and ends with a }. And so we use the second closing brace to mark the end of the class itself. the following is just as valid: using System.Parse(widthString). I do not do this because I find such listings artistically pleasing.height = double. However. This simply indicates that the compiler is too stupid to make sense of what you have given it! You will quickly get used to hunting for and spotting compilation errors. This first close brace marks the end of the block of code which is the body of the Main method. One of the things you will find is that the compiler does not always detect the error where it takes place. including methods. A class is a container for a whole bunch of things. we only want the one method in the class. otherwise you will get what is called a compilation error. However. In C# everything exists inside a class.Console.. This is vital and must be supplied exactly as C# wants it. Items inside braces are indented so that it is very clear where they belong. } The second closing brace has an equally important job to the first.WriteLine( "The area of the glass is " + glassArea + " square metres" ) . } Now for some really important stuff. If we want to (and we will do this later) we may put a number of methods into a class. The semi-colon marks the end of this statement. We have added all the behaviours that we need. heightString.Parse(heightString). glassArea.woodLength = 2 * ( width + height ) * 3. note that just because the compiler reckons your program is OK is no guarantee of it doing what you want! Another thing to remember is that the layout of the program does not bother the compiler. consider the effect of missing out a "(" character.Console. Punctuation That marks the end of our program.ReadLine().WriteLine ( "The length of the wood is " + woodLength + " feet" ) . It marks the end of the class GlazerCalc. When the compiler sees this it says to itself "that is the end of the Main method".Simple Data Processing A First C# Program .width = double.glassArea = 2 * ( width * height ) .heightString = Console.widthString = Console. The program is essentially complete.25 . One of the things that you will have noticed is that there is an awful lot of punctuation in there. You also need to choose the type of the variable (particular size and shape of box) from the range of storage types which C# provides.you could always get the value more accurately. You chose the name to reflect what is going to be stored there (we used sensible names like woodLength in the above program). This provides us with the ability to perform the data processing part of programs. specifically designed to hold items of the given type. 2. Nasty real world type things. 2. These are real. A literal value is just a value in your program which you use for some purpose. When you are writing a specification you should worry about the precision to which values are to be held. A computer is digital.too little may result in the wrong values being used. We also need to consider the range of possible values that we need to hold so that we can choose the appropriate type to store the data. The type of the variable is part of the metadata about that variable. A programming language must give you a way of storing the data you are processing. To handle real values the computer actually stores them to a limited accuracy. Think of this as C# creating a box of a particular size. i. These are referred to as reals.1 Variables and Data In the glazing program above we decided to hold the width and the height of the windows that we are working on in variables that we described as double. The box is tagged with some metadata (there is that word again) so that the system knows what can be put into it and how that box can be used.2. A variable is a named location where you can store something. Programs also contain literal values. for example the current temperature. otherwise it is useless.2 Manipulating Data In this section we are going to take a look at how we can write programs that manipulate data. how values can be stored. teeth on a cog.2 Storing Numbers When considering numeric values there are two kinds of data: Nice chunky individual values. Even if you measure a piece of string to 100 decimal places it is still not going to give you its exact length . Programs operate on data. In the second case we can never hold what we are looking at exactly. the length of a piece of string. These are referred to as integers. it operates entirely on patterns of bits which can be regarded as numbers.2. This means that when we want to store something we have to tell the computer whether it is an integer or a real.e. they are integral. In the first case we can hold the value exactly.Simple Data Processing Manipulating Data 2. and what other types of data we can store in programs that we write. retrieved and generally fiddled with. C# Programming © Rob Miles 2010 26 . You can think of it as a box of a particular size with a name painted on the box. For each type of variable the C# language has a way in which literal values of that type are expressed. you always have an exact number of these items. apples in a basket. Because we know that it works in terms of ons and offs it has problems holding real values. What the data actually means is something that you as programmer decide (see the above digression on data). the speed of a car. The declaration also identifies the type of the thing we want to store. Before we can go much further in our programming career we need to consider just what this means. You tell C# about a variable you want to create by declaring it. Too much accuracy may slow the machine down . which we hope is adequate (and usually is). for example the number of sheep in a field. because 255 is the biggest possible value of the type can hold. In fact this may cause the value to "wrap round" to 0. depending on the range of values you would like to store: sbyte byte short ushort int uint long ulong char Note that we can go one further negative than positive. If I am using one of the "shorter" types the literal value is regarded by the compiler as being of that type: sbyte tinyVal = 127. If you want to hold even larger integers than this (although I've no idea why you'd want this) there is a long version. I could use it in my program as follows: numberOfSheep = 23 .483. An example of an integer variable would be something which kept track of the number of sheep in a field: int numberOfSheep. if I add one to the value in this variable the system may not detect this as an error. Programmer’s Point: Check your own maths Something else which you should bear in mind is that a program will not always detect when you exceed the range of a variable. not an integer. Each value will map onto a particular pattern of bits. C# Programming © Rob Miles 2010 27 . This is because the numbers are stored using "2's complement" notation. However. This means that if I do something stupid: sbyte tinyVal = 128. This creates a variable with could keep track of over two thousand million sheep! It also lets a program manipulate "negative sheep" which is probably not meaningful (unless you run a sheep bank of course and let people borrow them). In this statement the 127 is regarded as an sbyte literal. Remember that the language itself is unaware of any such considerations. The bigger the value the larger the number of bits that you need to represent it. The only issue is one of range. integer literal values An integer literal is expressed as a sequence of digits with no decimal Point: 23 This is the integer value 23.483. If you want to make sure that we never have more than 1. Which could cause my program big problems.147. as shown above.647.147.Simple Data Processing Manipulating Data Storing integer values Integers are the easiest type of value for the computer to store. in the range -2.000 sheep and the number of sheep never goes negative you must add this behaviour yourself. can hold frighteningly large numbers in C#. If I put the value 255 into a variable of type byte this is OK. When you edit your program source using Visual Studio (or another code editor that supports syntax highlighting) you will find that the names of types that are built into the C# language (such as int and float) are displayed in blue. C# provides a variety of integer types.648 to 2.. int. C# provides a type of box which can hold a real number. Finally. if you want the ultimate in precision but require a slightly smaller range you can use the decimal type. with real numbers the compiler is quite fussy about how they can and can't be combined.e.0E-324 to 1. decimal robsOverdraft. They have a decimal point and a fractional part. If you want more precision (although of course your programs will use up more computer memory and run more slowly) you can use a double box instead (double is an abbreviation for double precision). An example of a double variable could be something which held the width of the universe in inches: double univWidthInInches.5f A double literal is expressed as a real number without the f: 3.5 You can also use exponents to express double and float values: 9. A standard float value has a range of 1. A float literal can be expressed as a real number with an f after it: 2. real literal values There are two ways in which you can store floating point numbers. This is because when you move a value from a double precision variable into an ordinary floating point one some of the precision is lost. Storing real values "Real" is a generic term for numbers which are not integers. C# Programming © Rob Miles 2010 28 . When it comes to putting literal values into the program itself the compiler likes to know if you are writing a floating point value (smaller sized box) or double precision (larger sized box). This process is known as casting and we will consider it in detail a bit later. This means that you have to take special steps to make sure that you as programmer make clear that you want this to happen and that you can live with the consequences. as float or as double.Simple Data Processing Manipulating Data (the maximum value that an sbyte can hold is 127) the compiler will detect that I have made a mistake and the program will not compile. not as good as most pocket calculators). Unlike the way that integers work. hence the name float.4E48 with a precision of only 7 digits (i.7E308 and a precision of 15 digits. It is used in financial calculations where the numbers are not so large but they need to be held to very high accuracy. Depending on the value the decimal point floats around in the number. If you put an f on the end it becomes a floating point literal value. An example of a float variable could be something which held the average price of ice cream: float averageIceCreamPriceInPence.5E-45 to 3. This is takes up more computer memory but it has a range of 5.4605284E15 This is a double precision literal value which is actually the number of meters in a light year. This uses twice the storage space of a double and holds values to a precision of 28-29 digits. Character Escape Sequences This leads to the question "How do we express the ' (single quote) character". C# Programming © Rob Miles 2010 29 . Some systems will make a beep when you send the Alert character to them. The escape character is the \ (backslash) character. This may seem wasteful (it is most unlikely I'll ever need to keep track of two thousand million sheep) but it makes the programs easier to understand. at other times it will be a string. Escape in this context means "escape from the normal hum-drum conventions of just meaning what you are and let's do something special". 2. It is what your program would get if you asked it to read a character off the keyboard and the user held down shift and pressed A.Simple Data Processing Manipulating Data Programmer’s Point: Simple variables are probably best You will find that I. A character is what you get when you press a key on a keyboard or display a single character on the screen. An example of a character variable could be something which held the command key that the user has just pressed: char commandKey. and most programmers.3 Storing Text Sometimes the information we want to store is text.000 different character designs including a wide range of foreign characters. This is achieved by the use of an escape sequence. This is a sequence of characters which starts with a special escape character. char literal values You express a character by enclosing it in single quotes: 'A' This means "the character A". Some clear the screen when you send the Form feed character. tend to use just integers (int) and floating point (float) variable types. C# provides variables for looking after both of these types of information: char variables A char is a type of variable which can hold a single character. If you are editing your program using an editor that supports syntax highlighting a character literal is shown in red. You can use them as follows: char beep = '\a' . This can be in the form of a single character.2. C# uses a character set called UNICODE which can handle over 65.. An example of a string variable could be something which holds the line that the user has just typed in: string commandLine. The bad news is that you must express this value in hexadecimal which is a little bit harder to use than decimal.Simple Data Processing Manipulating Data Note that the a must be in lower case. Character code values We have already established that the computer actually manipulates numbers rather than actual letters. string literal values A string literal value is expressed enclosed in double quotes: "this is a string" The string can contain the escape sequences above: "\x0041BCDE\a" If we print this string it would print out: ABCDE . If you wish. for example "War and Peace" (that is the book not the three words). However. 41). The best news of all is that you probably don't need to do this kind of thing very often. string variables A type of box which can hold a string of text. you can express a character literal as a value from the Unicode character set. A string variable can hold a line of text. for example "Rob". or it can be very long. As an example however. In C# a string can be very short. because there are special characters which mean "take a new line" (see above) it is perfectly possible for a single string to hold a large number of lines of text. Note that I have to put leading zeroes in front of the two hex digits.and try to ring the bell. C# uses the Unicode standard to map characters onto numbers that represent them. I do this by putting an @ in front of the literal: @"\x0041BCDE\a" If I print this string I get: \x0041BCDE\a This can be useful when you are expressing things like file paths. The good news is that this gives you access to a huge range of characters (as long as you know the codes for them). The line breaks in the string are preserved when it is stored. I happen to know that the Unicode value for capital a (A) is 65. If I am just expressing text with no escape characters or anything strange I can tell the compiler that this is a verbatim string. I can therefore put this in my program as: char capitalA = '\x0041' . The verbatim character has another trick.e. if at all. C# Programming © Rob Miles 2010 30 . This is represented in hexadecimal (base 16) as four sixteens and a single one (i. which is that you can use it to get string literals to extend over several lines: @"The quick brown fox jumps over the lazy dog" This expresses a string which extends over three lines. Instead you just need to hold the states true or false. After the letter you can have either letters or numbers or the underscore "_" character. when you are given the prospect of storing floating point information. the best relationships are meaningful ones. C# has some rules about what constitutes a valid identifier: All identifiers names must start with a letter.e. 2. In the example above I've used the double type to hold the width and height of a window. For example. Also when considering how to store data it is important to remember where it comes from. It does not take into account the precision required or indeed how accurately the window can be measured. I find that with a little bit of ingenuity I can work in integers quite comfortably. They introduce a lack of precision that I am not too keen on. bool literal values These are easily expressed as either true or false: networkOK = true . According to the Mills and Boon romances that I have read. I tend to use floating point storage only as a last resort.4 Storing State using Booleans A bool (short for boolean) variable is a type of box which can hold whether or not something is true. This is really stupid. We will see other places where we create identifiers. Here are a few example declarations. float jim . you might think that being asked to work with the speed of a car you would have to store a floating point value.5 pounds (needing the use of float) I will store the price as 150 pence. However. These are the only two values which the bool type allows. C# Programming © Rob Miles 2010 31 .2. Programmer’s Point: Think about the type of your variables Choosing the right type for a variable is something of a skill. one of which are not valid (see if you can guess which one and why): int fred . Sometimes that is all you want. this makes the job much simpler. One of the golden rules of programming. along with "always use the keyboard with the keys uppermost" is: Always give your variables meaningful names. find out how it is being produced before you decide how it will be stored. Fred and fred are different identifiers. rather than store the price of an item as 1. Upper and lower case letters are different. As an example.Simple Data Processing Manipulating Data 2. I would suspect that my glazing salesman will not be able to measure to accuracy greater than 1 mm and so it would make sense to only store the data to that precision. The name of a variable is more properly called an identifier. An example of a bool variable could be one which holds the state of a network connection: bool networkOK. when you find out that the speed sensor only gives answers to an accuracy of 1 mile per hour.5 Identifiers In C# an identifier is a name that the programmer chooses for something in the program. i. char 29yesitsme . If you are storing whether or not a subscription has been paid or not there is no need to waste space by using a type which can hold a large number of possible values. This illustrates another metadata consideration.2. The equals in the middle is there mainly to confuse us. C# does this by means of an assignment statement. third . which means that: 2 = second + 1. I like to think of it as a gozzinta (see above). Programmer’s Point: Think about the names of your variables Choosing variable names is another skill you should work at. } } The first part of the program should be pretty familiar by now. But I could live with it. presumably because of the "humps" in the identifier which are caused by the capitals. They are made up of two things. it does not mean equals in the numeric sense. Expressions An expression is something which can be evaluated to produce a result. does not know or care what you are doing). This is sometimes called camel case. There are two parts to an assignment. for example consider the following: class Assignment { static void Main () { int first.. Remember that you can always do sensible things with your layout to make the program look OK: averageIceCreamPriceInPence = computedTotalPriceInPence / numberOfIceCreams. An assignment gives a value to a specified variable.6 Giving Values to Variables Once we have got ourselves a variable we now need to know how to put something into it. first = 1 . The last three statements are the ones which actually do the work. We can then use the result as we like in our program. These are assignment statements. second and third. They should be long enough to be expressive but not so long that your program lines get too complicated. second. Expressions can be as simple as a single value and as complex as a large calculation. These are each of integer type. which must be of a sensible type (note that you must be sensible about this because the compiler. Gozzintas take the result on the right hand side of the assignment and drop it into the box on the left. . first. and get the value out. C# Programming © Rob Miles 2010 32 . operators and operands. The value which is assigned is an expression. Within the Main function we have declared three variables. Perhaps the name averageIceCreamPriceInPence is a bit over the top in this respect. 2.2. second = 2 . as we already know. third = second + first .is a piece of programming naughtiness which would cause all manner of nasty errors to appear. followed by the addition and subtraction. Here are a few example expressions: 2 + 3 * 4 -1 + 3 (2 + 3) * 4 These expressions are worked out (evaluated) by C# moving from left to right. I am listing the operators with the highest priority first. one each side. Note that we use exactly the same character as for unary minus. second. If you want to force the order in which things are worked out you can put brackets around the things you want done first. Unary means applying to only one item. They are usually literal values or the identifiers of variables. A literal value has a type associated with it by the compiler. It worries about whether or not the operation I'm about C# Programming © Rob Miles 2010 33 . Being a simple soul I tend to make things very clear by putting brackets around everything. division. This can cause problems as we shall see now. subtraction. Operators Operators are the things which do the work: They specify the operation to be performed on the operands. A literal value is something which is literally there in the code. Note that this means that the first expression above will therefore return 14 and not 20. e. When C# works out an expression it looks along it for all the operators with the highest priority and does them first. In the program above first.Simple Data Processing Manipulating Data Operands Operands are things the operators work on. generally speaking things tend to be worked out how you would expect them. because of the difficulty of drawing one number above another on a screen we use this character instead Addition. but it will do for now. multiplication. It then looks for the next ones down and so on until the final result is obtained. It is also possible to use operators in a way which causes values to be moved from one type to another. third are identifiers and 2 is a literal value. Again. what they do and their precedence (priority). provided you make sure that you have as many open ones as close ones. This is not a complete list of all the operators available. C# does this by giving each operator a priority. Most operators work on two operands. as in the final example. Because these operators work on numbers they are often called the numeric operators.2. * / + unary minus.7 Changing the Type of Data Whenever I move a value from one type to another the C# compiler gets very interested in what I am doing. 2. note the use of the * rather than the more mathematically correct but confusing x. In the program above + is the only operator. just as in traditional maths all the multiplication and division is performed first in an expression. For completeness here is a list of all operators. the minus that C# finds in negative numbers. But of course you should remember that some of them (for example +) can be used between other types of data as well. -1.g. You can put brackets inside brackets if you want. It is probably not worth getting too worked up about this expression evaluation as posh people call it. just as you would yourself. Note that this applies within floating point values as well. float f = (float) d . int i = x . It gives you great flexibility. You can regard casting as the compiler's way of washing its hands of the problem. The value which gets placed in i will be invalid. and the range of floating point values is much greater than that for integers. This works fine because the floating point type can hold all the values supported by the integer type. I. You cast a value by putting the type you want to see there in brackets before it.the program will not notice but the user certainly will! C# Programming © Rob Miles 2010 34 . To understand what we mean by these terms we could consider suitcases. It considers every operation in terms of "widening and narrowing" values.5. If a program fails because data is lost it is not because the compiler did something silly. . However.5. I do not think of this as a failing in C#. If I am packing for a trip I will take a case.would cause an error as well. This is "narrowing". . It is up to you when you write your program to make sure that you never exceed the range of the data types you are using ..would cause the compiler to complain (even though at the moment the variable x only holds an integer value).999 .. i = (int) 123456781234567890. each type of variable has a particular range of possible values. float x = i. However: float x = 1. Casting We can force C# to regard a value as being of a certain type by the use of casting. If you are widening there is no problem. Widening and Narrowing The general principle which C# uses is that if you are "narrowing" a value it will always ask you to explicitly tell it that this is what you want to do. The bigger case will take everything that was in the smaller case and have room for more. As we saw above. since the compiler knows that a double is wider than a float.Simple Data Processing Manipulating Data to perform will cause data to be lost from the program. at the cost of assuming you know what you are doing. For example: double d = 1. for example: double d = 1. so I have to leave behind one of my shirts.. . as the writer of the program.the cast is doomed to fail. A cast takes the form of an additional instruction to the compiler to force it to regard a value in a particular way. if I change to a bigger case there is no problem. The compiler is concerned that you may be discarding information by such an assignment and treats it as an error. This means that if I write: int i = 1 . If I decide to switch to a smaller case I will have to take everything out of the large case and put it into the smaller one. In C# terms the "size" of a type is the range of values (the biggest and smallest) and the precision (the number of decimal places). Nothing in C# checks for mistakes like this. In the above code the message to the compiler is "I don't care that this assignment could cause the loss of information. This means that if you do things like this: int i . will take the responsibility of making sure that the program works correctly". But it might not have room. float f = d . This process discards the fractional part. Not so. The compiler thinks that the first expression. consider the following: 1/2 1/2. the more accurate answer of 0. This is because the literal value 3.4 is a double precision value when expressed as a literal. This casts the double precision literal into a floating point value. This can lead to problems. which means that the variable i will end up with the value 1 in it.25 feet in a meter). You should remember that this truncation takes place whenever you cast from a value with a fractional part (float. 2.999 (which would be compiled as a value of type double) and casts it to int. if the two operands are integer it says that the result should be integer. Essentially. This code looks perfectly legal. it is not. consider this: float x .Simple Data Processing Manipulating Data A cast can also lose information in other ways: int i . x = (float) 3. If the two are floating point it says that the result should be floating point.4 .would compile correctly.will be treated with the contempt they richly deserve. decimal) into one without.0 You might think that these would give the same result. To make life easier the creators of C# have added a different way we can express a floating point literal value in a program. . For example. even though the original number was much closer to 2.4 / "stupid" . i = (int) 1. should give an integer result. The second expression. x = 3. The code above takes 1. If I want to put a floating point literal value into a floating point variable I can use casting: float x .8 Types of Data in Expressions When C# uses an operator.4f .999 . i = 3. It therefore would calculate this to be the integer value 0 (the fractional part is always truncated). These are just values you want to use in your calculations. C# Programming © Rob Miles 2010 35 . Casting and Literal Values We have seen that you can put "literal" values into your program. which involves only integers. and this includes how it allows literal values to be used. and the variable x has been declared as a floating point. If you put an f after the value this is regarded as a floating point value. double. it makes a decision as to the type of the result that is to be produced. . in our double glazing program we had to multiply the wood length in meters by 3. so that the assignment works. However. The C# compiler knows that it is daft to divide the value 3.4 . because it involves a floating point value would however be evaluated to give a double precision floating point result. C# keeps careful track of the things that it is combining.25 to convert the length value from meters to feet (there are about 3. This is so that statements like: int i . This means that: float x . However. x = 3.5.0 by the string "stupid".2. double width = double. If you want complete control over the particular kind of operator the compiler will generate for you the program must contain explicit casts to set the correct context for the operator. The tablets are always sold in bottles of 100. so that we get 1. } } The (float) cast in the above tells the compiler to regard the values in the integer variables as floating point ones. the only hard part is figuring out how many bottles that are needed for a particular number of tablets. height = double. and the number of bottles that he needs. Later on we will see that the + operator. He enters the cost of the tablets and the number he wants. woodLength = 2 * ( width + height ) * 3. fraction = (float) i / (float) j . The interesting thing about this is that it is a pattern of behaviour which can be reused time and time again. which normally performs a numeric calculation.e. who runs a chemist shop. i. store it in an appropriate type of location and then uses the stored values to calculate the result that the user requires: string widthString = Console. string heightString = Console.Parse(heightString). One way to solve this is to add 99 to the number of tablets before you C# Programming © Rob Miles 2010 36 .ReadLine().25 .WriteLine("The area of the glass is " + glassArea + " square metres" ) . j = 2 . consider another friend of yours. Console. class CastDemo { static void Main () { int i = 3. As an example.Parse(widthString). You can very easily modify your program to do this job.2. this can make the program clearer. Console.WriteLine ( "fraction : " + fraction ) . Programmer’s Point: Casts can add clarity I tend to put the casts in even if they are not needed. using System. float fraction . glassArea = 2 * ( width * height ) .Simple Data Processing Manipulating Data The way that an operator behaves depends on the context of its use. The code that actually does the work boils down to just a few lines which read in the data. "Ro" + "b" would give the result "Rob". He wants a program that will work out the total cost of tablets that he buys.ReadLine().WriteLine ( "The length of the wood is " + woodLength + " feet" ) . Console.5 printed out rather than 1. If you just divide the number of tablets by 100 an integer division will give you the wrong answer (for any number of tablets less than 100 your program will tell you that 0 bottles are needed).9 Programs and Patterns At this point we can revisit our double glazing program and look at the way that it works. can be used between strings to concatenate them together. 2. It may not affect the result of the calculation but it will inform the reader of what I am trying to do. 3 Writing a Program The programs that we have created up until now have been very simple. we will need to create programs which do things which are more complex that this. I think that while it is not a story as such. int bottleCount = ((tabletCount + 99) / 100) . int salePrice = bottleCount * pricePerBottle . process it. All the names in the text should impart meaning and be distinct from each other.WriteLine ( "The number of bottles is " + bottleCount ) . In this section we are going to consider how we can give our programs that extra level of complexity. 2. Any time that you are asked to write a program that reads in some data. string pricePerBottleString = Console. The interesting thing here is that the program for the chemist is actually just a variation on the program for the double glazing salesman. It should look good on the page. Both conform to a pattern of behaviour (read data in.Simple Data Processing Writing a Program perform the division. do something with it and then print out the result. and look at the general business of writing programs.ReadLine(). However. It should have good punctuation and grammar. print it out) which is common to many applications. string tabletCountString = Console. Console. I'm not completely convinced that this is true.1 Software as a story Some people say that writing a program is a bit like writing a story. Console. int salePrice = bottleCount * pricePerBottle .3.Parse(tabletCountString). The various components should be organised in a clear and consistent way.WriteLine( "The total price is " + salePrice ) . I have found that some computer manuals are works of fiction. At no point should the hapless reader be forced to backtrack or brush up on knowledge that the writer assumes is there.Parse(pricePerBottleString). This makes the active part of the program as follows: int bottleCount = ((tabletCount + 99) / 100) . Part of the skill of a programmer is identifying the nature of a problem in terms of the best pattern to be used to solve it. works out some answers and then prints out the result you can make use of this pattern. 2. The different blocks should be indented and the statements spread over the page in a well formed manner. but programs are something else. They may need to repeat things until something is true. They just read data in. C# Programming © Rob Miles 2010 37 . We can then put the rest of the code around this to make a finished solution: Remember that if you divide two integers the result is always rounded down and the fractional part discarded. int pricePerBottle = int.ReadLine(). int tabletCount = int. forcing the number of bottles required to "round up" any number of tablets greater than 0. They may have to make a decision based on the data which they are given. They may need to read in a large amount of data and then process that in a number of different ways. A good program is well laid out. a good program text does have some of the characteristics of good literature: It should be easy to read. and the name of the programmer who wrote it – even if it was you. A big part of a well written program is the comments that the programmer puts there. If you write something good you should put your name on it. straight line chosen depending on a given condition repeated according to a given condition C# Programming © Rob Miles 2010 38 . and then stops. I will ignore everything following until I see a */ which closes the comment. Block Comments When the C# compiler sees the "/*" sequence which means the start of a comment it says to itself: “Aha! Here is a piece of information for greater minds than mine to ponder.2 Controlling Program Flow Our first double glazing program is very simple. It is useful for putting a quick note on the end of a statement: position = position + 1 . They help to make your program much easier to understand. This marks the start of a comment which extends to the end of that particular line of code. But don't go mad. You will be very surprised to find that you quickly forget how you got your program to work. it runs straight through from the first statement to the last. // add one to goatCount This is plain insulting to the reader I reckon. If you are using an editor that supports syntax highlighting you will find that comments are usually displayed in green. when it was last modified and why.” As an example: /* This program works out glass and wood required for a double glazing salesman. Programmer’s Point: Don't add too much detail Writing comments is a very sensible thing to do. // move on to the next customer I've annotated the statement to give the reader extra information about what it actually does. 3. but it will be very hard to tell where it is going from the inside. Often you will come across situations where your program must change what it does according to the data which is given to it. There is a chance that it might take you to the right place. and when it was last changed. 2. A program without comments is a bit like an aeroplane which has an autopilot but no windows.Simple Data Processing Writing a Program It should be clear who wrote it. Remember that the person who is reading your program can be expected to know the C# language and doesn't need things explained to them in too much detail: goatCount = goatCount + 1 . */ Be generous with your comments.3. 2. Basically there are three types of program flow: 1. If you change what you wrote you should add information about the changes that you made and why. You can also use comments to keep people informed of the particular version of the program. If you chose sensible identifiers you should find that your program will express most of what it does directly from the code itself. Line Comments Another form of comment makes use of the // sequence. 5. } if (width > MAX_WIDTH) { Console.Parse(widthString). 0. width = MAX_WIDTH .\n\n" ) .WriteLine ( "Using maximum" ) . Console. my maximum glass size becomes 4. heightString. 5. string widthString.WriteLine ( "Width is too small" ) . width = MIN_WIDTH .0 . This makes your programs much easier to read.0.e. This is both more meaningful (we are using PI not some anonymous value) and makes the program quicker to write. This is so that when you read your program you can tell which things have been defined.WriteLine ( "Width is too large. for example: const double = MAX_WIDTH 5. const const const const double double double double MAX_WIDTH = 5. These come from the metadata I was so careful to gather when I wrote the specification for the program.0 . for some reason.Parse(heightString). Anywhere you use a magic number you should use a constant of this form.75 and 3.5 . it can never be changed.0 . woodLength. There is a convention that you always give constant variables names which are expressed in CAPITAL LETTERS. if (width < MIN_WIDTH) { Console.0 . We can do this by making a variable which is constant. C# Programming © Rob Miles 2010 42 . MIN_WIDTH = 0.ReadLine().Write ( "Give the width of the window : " ). MAX_HEIGHT = 3. } Console. widthString = Console.Simple Data Processing Writing a Program values for heights and widths.141592654. width = double. const double PI=3. Console. This means that you can do things like: circ = rad * 2 * PI . and also much easier to change. height. class GlazerCalc { static void Main() { double width.ReadLine().75 . height = double. glassArea. If.5 metres I have to look all through the program and change only the appropriate values. Console. I do not like the idea of "magic numbers" in programs. heightString = Console.WriteLine ( "Using minimum" ) .Write ( "Give the height of the window : " ). We can therefore modify our double glazing program as follows: using System. Now I could just use the values 0. what I would like to do is replace each number with something a bit more meaningful. MIN_HEIGHT = 0.but these are not packed with meaning and make the program hard to change. i. C# has three ways of doing this. However often you want to repeat something while a particular condition is true. C# allows us to do this by providing looping constructions. with the height having to be entered again. woodLength = 2 * ( width + height ) * 3. Note that we get three methods not because we need three but because they make life easier when you write the program (a bit like an attachment to our chainsaw to allow it to perform a particular task more easily).Simple Data Processing Writing a Program if (height < MIN_HEIGHT) { Console.WriteLine( "The area of the glass is " + glassArea + " square metres" ) . minimum" ) . Console. glassArea = 2 * ( width * height ) .3 Loops Conditional statements allow you to do something if a given condition is true. or a given number of times.e.WriteLine ( "Using height = MIN_HEIGHT . If our salesman gives a bad height the program simply limits the value and needs to be re-run.\n\n" ) .25 . 2. In the case of our program we want to repeatedly get numbers in while we are getting duff ones. However I would still not call it perfect.WriteLine( "Height Console. do -.3. } if (height > MAX_HEIGHT) { Console. is too large. This means that if we get the number correctly first time the loop will execute just once. i. (the rest is finding out why the tool didn't do what you expected it to!).while construction which looks like this: C# Programming © Rob Miles 2010 43 . } } This program fulfils our requirements. maximum" ) . Most of the skill of programming involves picking the right tool or attachment to do the job in hand. Console.WriteLine ( "The length of the wood is " + woodLength + " feet" ) . What we would really like is a way that we can repeatedly fetch values for the width and height until we get one which fits. depending on precisely what you are trying to do. It will not use values incompatible with our specification.WriteLine( "Height Console. } is too small. ( "Using height = MAX_HEIGHT .\n\n" ) . You might think that I have pulled a fast one here.while loop In the case of our little C# program we use the do -. i. we need to ask for a value before we can decide whether or not it is valid. the answer contains elements of human psychology. raising the intriguing possibility of programs like: using System. 3. } } This is a perfectly legal C# program. Repeat. How long it will run for is an interesting question. The universe implodes. while ( true ). 3. You get bored with it.e. Note that the test is performed after the statement or block.WriteLine ( "Hello mum" ) . 4. energy futures and cosmology. class Forever { public static void Main () { do Console. (if you put the do in the compiler will take great delight in giving you an error message . even if the test is bound to fail the statement is performed once. The loop constructions we have given can be used to do this quite easily: C# Programming © Rob Miles 2010 44 . Wet Your Hair Add Shampoo and Rub vigorously.e. A condition in this context is exactly the same as the condition in an if construction. 2.but you had already guessed that of course!). Rinse with warm water. Just as it is possible with any old chainsaw to cut off your leg if you try really hard so it is possible to use any programming language to write a program which will never stop. For our program this is exactly what we want. If you think about how the loop above works the test is done after the code to be repeated has been performed once. not a powerful chainsaw situation. This is a chainsaw situation. Your electricity runs out. This allows us to repeat a chunk of code until the condition at the end becomes false. I wonder how many people are still washing their hair at the moment? while loop Sometimes you want to decide whether or not to repeat the loop before you perform it.. It reminds me of my favourite shampoo instructions: 1. i.Simple Data Processing Writing a Program do statement or block while (condition) . for loop Often you will want to repeat something a given number of times. 2. This useless program prints out hello mum 10 times. The test is a condition which must be true for the for -. i. for ( i = 1 . Eventually it will reach 11. And serve you right. C# Programming © Rob Miles 2010 45 .loop to continue. } } } The variable which controls things is often called the control variable. The precise sequence of events is as follows: 1. Test to see if we have finished the loop yet and exit to the statement after the for loop if we have. This means that you are less likely forget to do something like give the control variable an initial value. The update is the statement which is performed to update the control variable at the end of each loop. 3. i = i + 1 .WriteLine ( "Hello mum" ) . C# provides a construction to allow you to set up a loop of this form all in one: for ( setup . If you are so stupid as to mess around with the value of the control variable in the loop you can expect your program to do stupid things. finish test . It does this by using a variable to control the loop. at which point the loop terminates and our program stops. and is usually given the name i. or update it. class ForLoop { public static void Main () { int i . Perform the update.Simple Data Processing Writing a Program using System. Note that the three elements are separated by semicolons. update ) { things we want to do a given number of times } We could use this to re-write the above program as: using System. i = i + 1 ) { Console. i < 11 . while ( i < 11 ) { Console.WriteLine ( "Hello mum" ) . 4. Put the setup value into the control variable. Writing a loop in this way is quicker and simpler than using a form of while because it keeps all the elements of the loop in one place instead of leaving them spread about the program. i = 1 . The variable is given an initial value (1) and then tested each time we go around the loop. Repeat from step 2. class WhileLoopInsteadOfFor { public static void Main () { int i . The control variable is then increased for each pass through the statements. 2. 5. } } } The setup puts a value into the control variable which it will start with. if you put i back to 0 within the loop it will run forever. Perform the statements to be repeated.e. . but can still lead to problems... if (aborted) { break . they are actually used to represent states within the program as it runs. For this reason the goto is condemned as a potentially dangerous and confusing device. normally false becomes true when the loop has to be abandoned and the variable runningOK. This is a standard programming trick that you will find very useful. In this respect we advise you to exercise caution when using it.. You can break out of any of the three kinds of loop.. Note that we are using two variables as switches. This happens when you have gone as far down the statements as you need to. while (runningOK) { complex stuff . they do not hold values as such. one for every break in the loop above. There is rarely need for such convoluted code.. Your program would usually make some form of decision to quit in this way.. Going back to the top of a loop Every now and then you will want to go back to the top of a loop and do it all again.. } . for example in the following program snippet the variable aborted. bit we get to if aborted becomes true . there are a number of ways it could have got there. When you are writing programs the two things which you should be worrying about are "How do I prove this works?" and "How easy is this code to understand?" Complicated code does not help you do either of these things. The goto is a special one that lets execution jump from one part of the program to another. You can do this with the break statement.. I call these people "the stupid people". Breaking Out of Loops Sometimes you may want to escape from a loop whilst you are in the middle of it. your program may decide that there is no need or point to go on and wishes to leap out of the loop and continue the program from the statement after it. which can do things other than simple assignment. } . C# provides the continue keyword which says something along the lines of: C# Programming © Rob Miles 2010 46 ... Some programmers think they are very clever if they can do all the work "inside" the for part at the top and have an empty statement after it. In every case the program continues running at the statement after the last statement of the loop.e. This can make the code harder to understand. I find it most useful so that I can provide a "get the heck out of here" option in the middle of something. This means that if my program is at the statement immediately following the loop.. The break construction is less confusing than the goto. more complex stuff .Simple Data Processing Writing a Program Programmer’s Point: Don't be clever/stupid Some people like to show how clever they are by doing cunning things with the setup... increment and test. This is a command to leave the loop immediately. condition and update statements. i. Programmer’s Point: Be careful with your breaks The break keyword smells a little like the dread goto statement. which programmers are often scared of. The break statement lets you jump from any point in a loop to the statement just outside the loop. becomes false when it is time to finish normally. normally true.. C# Programming © Rob Miles 2010 47 .. Programmer’s Point: Get used to flipping conditions One of the things that you will have to come to terms with is the way that you often have to reverse the way you look at things.Simple Data Processing Writing a Program Please do not go any further down this time round the loop. if you get a value which is larger than the maximum or smaller than the minimum ask for another.. rather than the thing that you do.. Remember the notes about reversing conditions above when you write the code. This means that you will often be checking to find the thing that you don't want. item < Total_Items . item processing stuff . More Complicated Decisions We can now think about using a loop to test for a valid width or height. Rather than saying "Read me a valid number" you will have to say "Read numbers while they are not valid"... ... You can regard it as a move to step 2 in the list above. } The continue causes the program to re-run the loop with the next value of item if it is OK to do so.e. i.... Our loop should continue to run if: width > MAX_WIDTH or width < MIN_WIDTH To perform this test we use one of the logical operators described above to write a condition which will be true if the width is invalid: if ( width < MIN_WIDTH || width > MAX_WIDTH ) . Complete Glazing Program This is a complete solution to the problem that uses all the tricks discussed above.. Essentially we want to keep asking the user for a value until we get one which is OK. item=item+1 ) { ... To do this we have to combine two tests to see if the value is OK. additional item processing stuff . if (Done_All_We_Need_This_Time) continue .. In the following program the bool variable Done_All_We_Need_This_Time is set true when we have gone as far down the loop as we need to. do all the updating and stuff and go around if you are supposed to. for ( item = 1 . Go back to the top of the loop. heightString = Console.4 Operator Shorthand So far we have looked at operators which appear in expressions and work on two operands.0 .0 . There is a corresponding -. C# Programming © Rob Miles 2010 48 . heightString. it is a rather long winded way of expressing this. both in terms of what we have to type and what the computer will actually do when it runs the program. class GlazerCalc { static void Main() { double width.5 . } while ( width < MIN_WIDTH || width > MAX_WIDTH ) . width = double.3. because it works on just one operand.Parse(heightString).Simple Data Processing Writing a Program using System. woodLength. window_count = window_count + 1 In this case the operator is + and is operating on the variable window_count and the value 1. do { Console. Console.75 . height = double. C# allows us to be terser if we wish. It causes the value in that operand to be increased by one. const double MAX_HEIGHT = 3.operator which can be used to decrease (decrement) variables. } } 2. The ++ is called a unary operator.Parse(widthString). do { Console.25 . glassArea = 2 * ( width * height ) . We can express ourselves more succinctly and the compiler can generate more efficient code because it now knows that what we are doing is adding one to a particular variable.g.Write ( "Give the width of the window between " + MIN_WIDTH + " and " + MAX_WIDTH + " :" ). Console. const double MAX_WIDTH = 5. However. glassArea. } while ( height < MIN_HEIGHT || height > MAX_HEIGHT ).Write ( "Give the height of the window between " + MIN_HEIGHT + " and " + MAX_HEIGHT + " :" ). the line: window_count++ . widthString = Console. You can see examples of this construction in the for loop definition in the example above. string widthString.would do the same thing. e.WriteLine ( "The length of the wood is " + woodLength + " feet" ) . The purpose of the above statement is to add 1 to the variable window_count.ReadLine(). const double MIN_HEIGHT = 0. height. woodLength = 2 * ( width + height ) * 3.WriteLine( "The area of the glass is " + glassArea + " square metres" ) . const double MIN_WIDTH = 0.ReadLine()..would make j equal to 3. The fact that you can produce code like: height = width = speed = count = size = 0 . C# provides a way of getting either value. the bit on the right of the gozzinta). This is perfectly legal (and perhaps even sensible) C#. this makes the whole thing much clearer for both you and the compiler! When you consider operators like ++ there is possible ambiguity. We could put: house_cost = house_cost + window_cost. depending on which effect you want. which is OK.Simple Data Processing Writing a Program The other shorthand which we use is when we add a particular value to a variable. in that you do not know if you get the value before or after the increment. . An assignment statement always returns the value which is being assigned (i.does not mean that you should. += etc. I still don't do it. This is perfectly OK. consider the following: i = (j=0). It has the effect of setting both i and j to 0. C# has some additional operators which allow us to shorten this to: house_cost += window_cost. C# Programming © Rob Miles 2010 49 . so that the value in house_cost is increased by window_cost. j . In order to show how this is done. particularly when we get around to deciding things (see later). The other special operators. I don't think that the statement above is very easy to follow – irrespective of how so much more efficient it is. but again is rather long winded. which you can use in another statement if you like. Programmer’s Point: Always strive for simplicity Don't get carried away with this. Nowadays when I am writing a program my first consideration is whether or not the program is easy to understand. but sometimes it can be very useful. The += operator combines addition and the assignment. j = ++i . all return the value after the operator has been performed. .e. I will leave you to find them! Statements and Values One of the really funky things about C# is that all statements return a value. If you do this you are advised to put brackets around the statement which is being used as a value. Most of the time you will ignore this value. This value can then be used as a value or operand. You determine whether you want to see the value before or after the sum by the position of the ++ : i++ ++i Means “Give me the value before the increment” Means “Give me the value after the increment” As an example: int i = 2. 00}".56789 . double f = 1234. Of course if I do something mad.WriteLine ( "i: {1} f: {0}".##0. To get around this C# provides a slightly different way in which numbers can be printed.57 The 0 characters stand for one or more digits. f ). counting from 0‖. In the second write statement I have swapped the order of the numbers. f ). Integers seem to come out OK. i ) . I have used the # character to get my thousands printed out with commas: C# Programming © Rob Miles 2010 50 .3. Specifying the number of printed digits I can specify a particular number of digits by putting in a given number of zeroes: int i = 150 .56789 .WriteLine ( "i: {0} f: {1}". f ) . This provides more flexibility. i.WriteLine ( "i: {0:#.5 Neater Printing Note that the way that a number is printed does not affect how it is stored in the program. Really Fancy Formatting If you want really fancy levels of control you can use the # character.56789 The {n} part of the string says ―parameter number n. but since I've swapped the order of the parameters too the output is the same. This would print out: i: 0150 f: 01234. Note that doing this means that if the number is an integer it is printed out as 12. double f = 1234. Console. Console. A # in the format string means ―put a digit here if you have one‖: int i = 150 . the WriteLine method will fail with an error. double f = 1234. This would print out: i: 150 f: 1234. i.56789 i: 150 f: 1234. i. Using Placeholders in Print Strings A placeholder just marks the place where the value is to be printed.00}". Console. Consider: int i = 150 . Console. This would print out: i: 150 f: 1234.57 Note that if I do this I get leading zeroes printed out.00}". Console. f ) . for example {99}. i. and is also somewhat easier to use if you are printing a large number of values.Simple Data Processing Writing a Program 2.56789 .##0} f: {1:##. f. but floating point numbers seem to have a mind of their own.56789 . which is useful if you are printing things like cheques.WriteLine ( "i: {0:0} f: {1:0. When placed after a decimal point they can be used to control the number of decimal places which are used to express a value. Adjusting real number precision Placeholders can have formatting information added to them: int i = 150 .00. double f = 1234.WriteLine ( "i: {0:0000} f: {1:00000. If you have run any of the above programs you will by now have discovered that the way in which numbers are printed leaves much to be desired. it just tells the printing method how it is supposed to be printed. 57 0.00 Note that this justification would work even if you were printing a string rather than a number.15:0. double f = 1234.WriteLine ( "i: {0.56789 .00}".00}".00}".15:0.00}". C# Programming © Rob Miles 2010 51 . This is so that when I print the value 0 I actually get a value printed.-15:0.WriteLine ( "i: {0. even a piece of text. 0. Console. The value 150 does not have a thousands digit so it and the comma are left out. At the moment the output is right justified. 0 ) .00 The integer value is printed in a column 10 characters wide. You can specify the print width of any item. so if you want to print columns of words you can use this technique to do it.-10:0} f: {1. Printing in columns Finally I can add a width value to the print layout information. f ) . Console.57 f: 0. i. which makes printing in columns very easy. This would produce the output: i: 150 i: 0 f: 1234. 0 ) .10:0} f: {1. otherwise when I print zero I get nothing on the page.Simple Data Processing Writing a Program i: 150 f: 1.WriteLine ( "i: {0. Console. Console. f ) .57 Note that the formatter only uses the # characters and commas that it needs. Note also though that I have included a 0 as the smallest digit. This would produce the output: i: i: 150 f: 0 f: 1234. and the double is printed in a 15 character wide column.-10:0} f: {1.234.WriteLine ( "i: {0. i. if I want the numbers left justified I make the width negative: int i = 150 . This is very useful if you want to print material in columns: int i = 150 .56789 .-15:0.10:0} f: {1. double f = 1234. 0. Again. However. 3. it makes the program bigger and harder to write. C# lets us create other methods which are used when our program runs. This is not very efficient. Your programs will contain methods that you create to solve parts of the problem and they will also use methods that have been provided by other people.1 Methods We have already come across the methods Main. As a silly example: C# Programming © Rob Miles 2010 52 . In this section we are going to consider why methods are useful and how you can create your own. We have exactly the same piece of code to check widths and heights. WriteLine and ReadLine were provided by the creators of C# to give us a way of displaying text and reading information from the user. WriteLine and ReadLine. Essentially you take a block of code and give it a name. but they do help with the organisation of our programs. We can also use methods to break down a large task into a number of smaller ones. The method is the block of code which follows the main part in our program.1 The Need for Methods In the glazing program above we spend a lot of time checking the values of inputs and making sure that they are in certain ranges. To do this you need to define a method to do the work for you. Main is the method we write which is where our program starts. Up until now all our programs have been in a single method. as with lots of features of the C# language. we would have to copy the code a third time.Creating Programs Methods 3 Creating Programs In this chapter we will build on our programming abilities to make programs that are broken down into manageable chunks and find out how a program can store and manipulate large amounts of data using arrays. methods don't actually make things possible.1. What we would like to do is write the checking code once and then use it at each point in the program. Then you can refer to this block of code to do something for you. Methods give us two new weapons: We can use methods to let us re-use a piece of code which we have written. for example frame thickness. Method and Laziness We have already established that a good programmer is creatively lazy. 3. One of the tenets of this is that a programmer will try to do a given job once and once only. We will need both of these when we start to write larger programs. If we added a third thing to read. This is what methods are all about. WriteLine ("Hello"). You have already used this feature. However. Within the block of code which is the body of this method we can use the parameter i as an integer variable. consider the code below: using System . When the method starts the value supplied for the parameter is copied into it. } } In the main method I make two calls of doit. As an example. doit().2 Parameters At this point methods are useful because they let us use the same block of statements at many points in the program. silly ( 500 ) .3 Return values A method can also return a value to the caller. The result of running the above program would be: Hello Hello So.1. } public static void Main () { doit().WriteLine ( "i is : " + i ) .Creating Programs Methods using System . In this case it contains a single statement which prints "Hello" on the console. } } The method silly has a single integer parameter. the methods ReadLine and Parse both return results that we have used in our programs: C# Programming © Rob Miles 2010 53 . Each time I call the method the code in the block which is the body of the method is executed. class MethodDemo { static void silly ( int i) { Console. This means that when the program runs we get output like this: i is : 101 i is : 500 3. 3. they become more useful if we allow them to have parameters. A parameter is a means of passing a value into a method call. class MethodDemo { static void doit () { Console. We simply put the code inside a method body and then call it when we need it. The method is given the data to work on. we can use methods to save us from writing the same code twice. } public static void Main () { silly ( 101 ) .1. string resultString = Console.1. } while ( (result < low) || (result > high) ).ReadLine (). Console. in other words a call of sillyReturnPlus can take the place of an integer. res = sillyReturnPlus (5). C# Programming © Rob Miles 2010 54 . Console.Creating Programs Methods using System . The value that a method returns can be used anywhere in a program where a variable of that type could be used. It can then be used to read values and make sure that they are in range. double windowWidth = readValue ( "Enter width of window: ". return i. class ReturnDemo { static int sillyReturnPlus ( int i) { i = i + 1.4 A Useful Method Now we can start to write genuinely useful methods: static double readValue ( string prompt. // lowest allowed value double high // highest allowed value ) { double result = 0. do { Console. 0. double age = readValue ( "Enter your age: ". MAX_WIDTH) . // prompt for the user double low.Parse(resultString). } The readValue method is told the prompt to use and the lowest and the highest allowed values.WriteLine ( "i is : " + i ) . 70) . It is actually OK to ignore the value returned by a method. } } The method sillyReturnPlus takes the value of the parameter and returns it plus one.WriteLine ( "res is : " + res ) . We can use this method to read anything and make sure that value supplied is within a particular range. } public static void Main () { int res. The second reads an age between 0 and 70. MIN_WIDTH. result = double. but this is actually a rather pointless thing to do: sillyReturnPlus (5). return result . Console.WriteLine (prompt + " between " + low + " and " + high ).WriteLine ( "res is : " + res ) . See if you can work out what this code would display: res = sillyReturnPlus (5) + sillyReturnPlus (7) + 1. // will compile but do nothing useful 3. The first call of readValue gets the width of a window. or write one which returns an age. So I could write a method which returns the name of a person. They form an important part of the development process. prints the result out and then returns: int test = 20 . The value of test is being used in the call of addOneToParam. If you do this you should consider taking that action and moving it into a method. Console.5 Parameter Passing By Value So. The piece of C# above calls the method with the variable test as the parameter. Once you have worked out what the customer wants and gathered your metadata you can start thinking about how you are going to break the program down into methods. If a fault is found in the code you only have to fix it in one place. } The method addOneToParam adds one to the parameter. However. Console. But I can’t write a method that returns both values at the same time as a method can only return one value. Consider: static void addOneToParam ( int i) { i = i + 1. C# Programming © Rob Miles 2010 55 . Moving code around and creating methods is called refactoring. they can only return one value. only the value of a parameter is passed into a call to a method. This would print out: i is : 120 Pass by value is very safe. 3. if I want to write a method which reads in the name and the age of a person I have a problem. Method Limitations A method is very good for getting work done. unless you specify otherwise. it is a limitation when we want to create a method which returns more than one value. For example. This will be an important part of the Software Engineering we do later. This means that you can write calls like: test = 20 . Often you find that as you write the code you are repeating a particular action. addOneToParam(test + 99). changing the value of a parameter does not change the value of the thing passed in. addOneToParam(test). It then passes this value into the call. because nothing the method does can affect variables in the code which calls it. When it runs it prints out the following: i is : 21 test is : 20 It is very important that you understand what is happening here. There are two reasons why this is a good idea: 1: 2: It saves you writing the same code twice. but it can be a bit limited because of the way that it works.1. As you will find out when you try. From what we have seen of methods.WriteLine ( "test is : " + test ) .Creating Programs Methods Programmer’s Point: Design with methods Methods are a very useful part of the programmer's toolkit.WriteLine ( "i is : " + i ) . The program works out the result of the expression to be passed into the method call as a parameter. This is because. what do I mean by "passing parameters by value". when someone calls our addOneToRefParam method.6 Parameter Passing By Reference It is very important that you understand how references work. The code above makes a call to the new method. } Note that the keyword ref has been added to the information about the parameter. If you say ―Deliver the carpet to 23 High Street. Generally speaking you have to be careful with side effects. as someone reading your program has to know that your method has made changes in this way.1. Console. Console. Consider the code: static void addOneToRefParam ( ref int i) { i = i + 1. This memory location is used by the method. Effectively the thing that is passed into the method is the position or address of the variable in memory. The original value of the parameters is of no interest to the method. This is the case when we want to read in the name and age of a user. Programmer’s Point: Document your side-effects A change by a method to something around it is called a side effect of the method. rather than sending the value of a variable into a method. changes to the parameter change the variable whose reference you passed” If you find references confusing you are not alone. In this case I can replace the ref with the keyword out: C# Programming © Rob Miles 2010 56 . 3. addOneToRefParam(ref test). rather than the content of the variable. Inside the method. You have to put the word ref in the method heading and also in the call of the method.‖ you are giving the delivery man a reference. rather than passing in "20" in our above call the compiler will generate code which passes in "memory location 5023" instead (assuming that the variable test is actually stored at 5023). test = 20 . rather than using the value of the variable the reference is used to get the actual variable itself. Instead you want to just allow the method to change the variable.WriteLine ( "test is : " + test ) . Note that C# is careful about when a parameter is a reference. Sometimes you don't want this. The program will say ―Get the value from location 5023‖ rather than ―The value is 1‖. and also has the word ref in front of the parameter. In other words.1. we use them in real life all the time with no problems. Instead it just wants to deliver results to them. In other words: “If you pass by reference.Creating Programs Methods 3. If you don't understand these you can't call yourself a proper programmer! Fortunately C# provides a way that. a reference to that variable is supplied instead. In this case the output is as follows: i is : 21 test is : 21 In this case the method call has made changes to the content of the variable. instead of the value. So. Using a reference in a program is just the same. it is going to have the “side effect” of changing something outside the method itself (namely the value of the parameter passed by reference).7 Passing Parameters as "out" references When you pass a parameter as a reference you are giving the method complete control of it.WriteLine ( "i is : " + i ) . However. Note how I have rather cleverly used my readString method in my readInt one. } The readString method will read text and make sure that the user does not enter empty text. readPerson ( out name. 0. We can use the methods as follows: C# Programming © Rob Miles 2010 57 .1. } while ( ( result < low ) || ( result > high ) ).ReadLine (). Note that I must use the out keyword in the call of the method as well. result = int. do { string intString = readString (prompt) . int low. Note that it uses two more methods that I have created.Write ( prompt ) . return result .Parse(intString). The readPerson method will read the person and deliver the information into the two variables. int high ) { int result . It makes sure that a programmer can't use the value of the parameter in the method. It also allows the compiler to make sure that somewhere in the method the output parameters are assigned values. so that the user can't enter an empty string when a number is required. } The method readPerson reads the name and the age of a person. 100 ) . In the code above I have written a couple of library methods which I can use to read values of different types: static string readString ( string prompt ) { string result . age = readInt ( "Enter your age : ". return result. readString and readInt. int age .Creating Programs Methods static void readPerson ( out string name. as I am protected against forgetting to do that part of the job. This makes it harder for me to get the program wrong. out int age ) { name = readString ( "Enter your name : " ) .8 Method Libraries The first thing that a good programmer will do when they start writing code is to create a set of libraries which can be used to make their job easier. The readInt method reads a number within a particular range. 3. do { Console. out age ) . Programmer’s Point: Languages can help programmers The out keyword is a nice example of how the design of a programming language can make programs safer and easier to write. This is very useful. It means that if I mark the parameters as out I must have given them a value for the program to compile. I can call readPerson as follows: string name . } static int readInt ( string prompt. } while ( result == "" ) . result = Console. As far as the C# language is concerned you can declare a variable at any point in the block. This means that only statements in the inner block can use this variable.1 Scope and blocks We have already seen that a block is a number of statements which are enclosed in curly brackets. the variable result in the readInt method is local to the method block. 3.e. i. In other words the code: C# Programming © Rob Miles 2010 58 . If the method passes the error on to the code which called it you have to have a method by which an error condition can be delivered to the caller. When the execution of the program moves outside a block any local variables which are declared in the block are automatically discarded. int age. 100). age = readInt ( "Enter your age : ". { int j . The scope of a local variable is the block within which the variable is declared. 0. Each of these nested blocks can have its own set of local variables: { int i . This is called the scope of a variable. 3. Any block can contain any number of local variables. If the return value is non-zero this means that the method did not work and the value being returned is an error which identifies what went wrong. but you must declare it before you use it. Programmer’s Point: Always consider the failure behaviours Whenever you write a method you should give some thought to the ways that it could fail. variables which are local to that block. in that you also have to consider how the code that you write can fail.2. as well as making sure that it does the required job! We are going to discuss error management later 3. I often solve this problem by having my methods return a code value. If the method deals with the error itself this may lead to problems because the user may have no way of cancelling a command. If the method involves talking to the user it is possible that the user may wish to abandon the method. This adds another dimension to program design. If the return value is 0 this means that the method returned correctly. The C# compiler makes sure that the correctly sized chunk of memory is used to hold the value and it also makes sure that we only ever use that value correctly. The C# compiler also looks after the part of a program within which a variable has an existence.2.Creating Programs Variables and Scope string name. name = readString( "Enter your name : " ). I could add methods to read floating point values as well. } } The variable j has the scope of the inner block.2 Variables and Scope We have seen that when we want to store a quantity in our program we can create a variable to hold this information. The methods that we have created have often contained local variables. or that the user does something that may cause it to fail. 3.Creating Programs Variables and Scope { int i . In order to keep you from confusing yourself by creating two versions of a variable with the same name. for example C++.3 Data Member in classes Local variables are all very well. } } This is not a valid program because C# does not let a variable in an inner block have the same name as one in an outer block. Note that this is in contrast to the situation in other languages. It is however perfectly acceptable to reuse a variable name in successive blocks because in this situation there is no way that one variable can be confused with another. as the variable j does not exist at this point in the program. where this behaviour is allowed. } The variable i is declared and initialized at the start of the for loop and only exists for the duration of the block itself. } } The first incarnation of i has been destroyed before the second.2. This allows you to declare a control variable which exists for the duration of the loop itself: for ( int i = 0 . i = i + 1 ) { Console.WriteLine ( "Hello" ) . { int j . so this code is OK. } j = 99 . This is because inside the inner block there is the possibility that you may use the "inner" version of i when you intend to use the outer one. In order to remove this possibility the compiler refuses to allow this. We often need to have variables that exist outside the methods in a class. { int i . } { int i . i < 10 . } . C# has an additional rule about the variables in the inner blocks: { int i . Variables Local to a Method Consider the following code: C# Programming © Rob Miles 2010 59 . but they disappear when the program execution leaves the block where they are declared. { int i . { int j . For loop local variables A special kind of variable can be used when you create a for loop construction.would cause an error. Console.WriteLine ("member is : " + member). For now you just have to remember to put in the static keyword.WriteLine ("local is :" + local). } static void Main () { Console. Console.Creating Programs Variables and Scope class LocalExample { static void OtherMethod () { local = 99. The program above would print out: member is : 0 member is now : 99 This is because the call of OtherMethod would change the value of member to 99 when it runs. otherwise your program will not compile.WriteLine ("member is now : " + member). } } The variable member is now part of the class MemberExample. Variables which are Data Members of a Class If I want to allow two methods in a class to share a variable I will have to make the variable a member of the class. } } The variable local is declared and used within the Main method. This is not something to worry about just now. static void OtherMethod () { member = 99. and so the Main method and OtherMethod can both use this variable. For example. and can’t be used anywhere else. Then the methods that read the player move. Class variables are very useful if you want to have a number of methods ―sharing‖ a set of data. and calculate the computer move could all use the same board information. we will investigate the precise meaning of static later on. Static class members Note that I have made the data member of the class static. C# Programming © Rob Miles 2010 60 . if you were creating a program to play chess it would be sensible to make the variable that stores the board into a member of the class. This means declaring it outside the methods in the class: class MemberExample { // the variable member is part of the class static int member = 0 . display the board. OtherMethod(). // this will not compile } static void Main () { int local = 0. so that it is part of the class and not an instance of the class. If a statement in OtherMethod tries to use local the program will fail to compile. 1000).1000). If it helps you can think of static as something which is always with us. 0. 0. calculate results and print them. 0. Marking a variable with static means ―the variable is part of the class and is always present‖. score6. Alternatively you can think of it as stationary. You should decide which variables are only required for use in local blocks and which should be members of the class. 0. Marking a variable as const means ―the value cannot be changed‖. score2. you agree on when the software must be finished and how you are going to demonstrate it to your new customer and you write all this down and get it signed. like the background static noise on your radio when you tune it off station. ".3 Arrays We now know how to create programs that can read values in. Arrays are one way to do this. 0. With all this sorted. score11 . You decide how much money you are going to be paid. to make this the perfect project. 0. and what information it will print out. score3.1000). ". and we are going to find out about them next. : ". Only one thing is missing. 3. and therefore not going anywhere. ". C# Programming © Rob Miles 2010 61 . The next person to come and see you is the chap in charge of the local cricket team. Programmer’s Point: Plan your variable use You should plan your use of variables in your programs.1000). Bear in mind that if you make a variable a member of the class it can be used by any method in that class (which increases the chances of something bad happening to it). ". Now you can start putting the data into each variable. Finally. I am very careful to keep the number of member variables in a class to the minimum possible and use local variables if I only need to store the value for a small part of the code. ". 0. score4. What the customer wants is quite simple. : ".1000). When a game of cricket is played each member of the team will score a particular number of runs. score7 score8.Creating Programs Arrays One common programming mistake is to confuse static with const. ―This is easy‖ you think. You discuss sensible ranges (no player can score less than 0 or more than 1000 runs in a game). score5.). You draw out a rough version of what the program will accept. ". 3.1000). ". and when. It turns out that you now know about nearly all the language features that are required to implement every program that has ever been written. and that is the ability to create programs which store large amounts of data.3.1000). score9.1000).1000). all you have to do now is write the actual program itself. 0. 0. The first thing to do is define how the data is to be stored: int score1. The next thing you do is refine the specification and add some metadata. 0. score10.1 Why We Need Arrays Your fame as a programmer is now beginning to spread far and wide. 0. given a set of player scores from a game he wants a list of those scores in ascending order. Our programs can also make decisions based on the values supplied by the user and also repeat actions a given number of times. He would like to you write a program for him to help him analyse the performance of his players.1000). 1000). ―The first element has the subscript 0‖ then the best way to regard the subscript is as the distance down the array you have to travel to get to the element that you need. If you find this confusing... It then gets a piece of rope and ties the tag scores to this box. I’m sorry about this. You can think of this as a tag which can be made to refer to a given array.because boxes which can hold integers are red.. Hmmmm. It then gets some pieces of wood and makes a long thin box with 11 compartments in it. If you follow the rope from the scores tag you reach the array box. it just goes to show that not everything about programming is consistent.. There is consequently no element scores [11].is quite OK.. we know that computers are very good at sorting this kind of thing. Note that the thing which makes arrays so wonderful is the fact that you can specify an element by using a variable. C# Programming © Rob Miles 2010 62 . If you look at the part of the program which reads the values into the array you will see that we only count from 0 to 10. it probably doesn't use wood or rope. scores [i+1] . class ArrayDemo { public static void Main () { int [] scores = new int [11] . In the program you identify which element you mean by putting its number in square brackets [ ] after the array name. This part is called the subscript. Just deciding whether score1 is the largest value would take an if construction with 10 comparisons! Clearly there has to be a better way of doing this. } } } The int [] scores part tells the compiler that we want to create an array variable. (as long as you don't fall off the end of the array).3. i. 3. This is very important. We can then use things called subscripts to indicate which box in the row that we want to use. This is awful! There seems to be no way of doing it. The bit which makes the array itself is the new int [11]. Visual Basic numbers array elements starting at 1. Array Element Numbering C# numbers the boxes starting at 0. for ( int i=0.. after all. An attempt to go outside the array bounds of scores cause your program to fail as it runs.e.Creating Programs Arrays All we have to do next is sort them. This means that you specify the element at the start of the array by giving the subscript 0. C# provides us with a thing called an array.. each large enough to hold a single integer. i=i+1) { scores [i] = readInt ( "Score : ". Consider the following: using System. but you should get a picture of what is going on here. When C# sees this it says ―Aha! What we need here is an array‖. One thing adding to this confusion is the fact that this numbering scheme is not the same in other languages..2 Array Elements Each compartment in the box is called an element. When an array is created all the elements in the array are set to 0. i<11. An array allows us to declare a whole row of a particular kind of box. Actually. In fact you can use any expression which returns an integer result as a subscript. It then paints the whole box red . 0. 3. i. When Parse fails it creates an exception object that describes the bad thing that has just happened (in this case input string not in the correct format).Parse(ageString). the parse action takes place inside the try block. If a user types in an invalid string the program above will write the text in the exception. If the call of Parse throws an exception the code in the catch block runs and will display a message to the user. This is useful if the code inside the try block could throw several different kinds of exception. If your program does not contain a catch for the exception it will be caught by a catch which is part of the run time system. } The code above uses Parse to decode the age string. The Exception object also contains other properties that can be useful. try { age = int.4. Programs can have multiple levels of try – catch.4. Console.Creating Programs Exceptions and Errors int age. if the parse fails the program will not display the message "Thank you". and the program will use the catch which matches the level of the code in the try block. will look for the enclosing catch clause. Console.WriteLine("Thank you"). However.WriteLine("Invalid age value").Parse(ageString). 3. Within the catch clause the value of e is set to the exception that was thrown by Parse. An exception is a type of object that contains details of a problem that has occurred. } catch { Console. with the Exception e being a parameter to the method.3 The Exception Object When I pass a problem up to my boss I will hand over a note that describes it.4 Exception Nesting When an exception is thrown the run time system.Message). This message is obtained from the exception that was thrown. } catch (Exception e) { // Get the error message out of the exception Console. The code in this catch clause will display the exception details and then stop the program. Note that once the exception has been thrown there is no return to the code in the try block.WriteLine("Thank you"). The program above ignores the exception object and just registers to the exception event but we can improve the diagnostics of our program by catching the exception if we wish: int age. which is managing the execution of your program inside the computer. Exceptions work in the same way. } The catch now looks like a method call.WriteLine(e. The Exception type has a property called Message which contains a string describing the error. This is exactly how it works.e. try { age = int. since it means that the message reflects what has actually happened. which contains the message: Input string was not in a correct format. C# Programming © Rob Miles 2010 66 . If someone asks your Load method to fetch a file that doesn’t exist the best thing it can do is throw a “file not found” exception. not try and handle things by returning a null reference or empty item.5 Adding a Finally Clause Sometimes there are things that your program must do irrespective of whether or not an exception is thrown. releasing resources and generally tidying up. The faster you can get a fault to manifest itself the easier it is to identify the cause. 3. and the program never returns to the try part of the program. Returning a placeholder will just cause bigger problems later when something tries to use the empty item that was returned. However. In these situations any code following your try – catch construction would not get the chance to run.4. try { // Code that } catch (Exception { // Code that } finally { // Code that // is thrown } might throw an exception outer) catches the exception is obeyed whether an exception or not C# Programming © Rob Miles 2010 67 . If code in the innermost block throws an exception the run time system will find the inner catch clause. However. Programmer’s Point: Don’t Catch Everything Ben calls this Pokemon® syndrome: “Gotta catch’em all”. Don’t feel obliged to catch every exception that your code might throw. we know that when an exception is thrown the statements in the catch clause are called. The code in the catch clause could return from the method it is running within or even throw an exception itself. Statements inside the finally clause will run irrespective of whether or not the program in the try block throws an. once execution leaves that inner block the outer catch is the one which will be run in the event of an exception being thrown. Fortunately C# provides a solution to this problem by allowing you to add a finally clause to your try-catch construction. either when the statements in the try part have finished.Creating Programs The Switch Construction In the above code the statements in the finally part are guaranteed to run.7 Exception Etiquette Exceptions are best reserved for situations when your program really cannot go any further.6 Throwing an Exception Now that we know how to catch exceptions. This turns out to be very easy: throw new Exception("Boom").4. 3. You may find it rather surprising. A good example of this is the switch construction. the next thing we need to consider is how to throw them. or just before execution leaves the catch part of your program. and you should too.5 The Switch Construction We now know nearly everything you need to know about constructing a program in the C# language.5. If you are going to throw an exception this should be in a situation where your program really could not do anything else. In this case I have used the somewhat unhelpful message ―Boom‖. I reserve my exceptions for catastrophic events that my program really cannot deal with and must pass on to something else. but there is really very little left to know about programming itself. When you make a new exception you can give it a string that contains the message the exception will deliver. Each method asks the relevant questions and works out the price of that kind of item. This means that errors at this level are not worthy of exception throwing.4. The statement above makes a new exception and then throws it. You ask something like Enter the type of window: 1 = casement 2 = standard 3 = patio door Your program can then calculate the cost of the appropriate window by selecting type and giving the size. For example if a user of the double glazing program enters a window height which is too large the program can simply print the message ―Height too large‖ and ask for another value. Throwing an exception might cause your program to end if the code does not run inside a try – catch construction. Most of the rest of C# is concerned with making the business of programming simpler. 3. You can even create your own custom exception types based on the one provided by the System and use these in your error handling. 3. 3. When you come to write the program you will probably end up with something like: C# Programming © Rob Miles 2010 68 . 1. but is rather clumsy. } } } This would work OK. At the moment they just print out that they have been called. Once you have the methods in place. selection = readInt ( "Window Type : ".WriteLine("Handle patio").WriteLine("Handle Standard"). C# Programming © Rob Miles 2010 69 .WriteLine("Handle Casement").5. } static void handlePatio () { Console. Our program can use this method to get the selection value and then pick the method that needs to be used. } static void handleStandard () { Console.5.3 The switch construction Because you have to do this a lot C# contains a special construction to allow you to select one option from a number of them based on a particular value. } else { if ( selection == 2 ) { handleStandard().2 Selecting using the if construction When you come to perform the actual selection you end up with code which looks a bit like this: int selection . } else { if ( selection == 3 ) { handlePatio() . the next thing you need to do is write the code that will call the one that the user has selected. Later you will go on and fill the code in (this is actually quite a good way to construct your programs). 3 ) . if ( selection == 1 ) { handleCasement(). 3. This is called the switch construction. If you write the above using it your program would look like this. You have to write a large number of if constructions to activate each option.WriteLine ( "Invalid number" ). } These methods are the ones which will eventually deal with each type of window.Creating Programs The Switch Construction static void handleCasement () { Console. } else { Console. 3. We already have a method that we can use to get a number from the user (it is called readInt and is given a prompt string and high and low limits). break . Of course this means that the type of the cases that you use must match the switch selection value although. case 3 : handlePatio () . default : Console. case "standard" : handleStandard () . break . break . in true C# tradition. break . break . and of course if they type a character wrong the command is not recognised. default : Console. your users would not thank you for doing this.WriteLine ( "Invalid number" ) . It executes the case which matches the value of the switch variable. the compiler will give you an error if you make a mistake.Creating Programs The Switch Construction switch (selection) { case 1 : handleCasement (). The break statement after the call of the relevant method is to stop the program running on and performing the code which follows. in our case (sorry!) we put out an appropriate message. case "patio" : handlePatio () . However. Multiple cases You can use multiple case items so that your program can execute a particular switch element if the command matches one of several options: C# Programming © Rob Miles 2010 70 . } This switch uses a string to control the selection of the cases. case 2 : handleStandard () . } The switch construction takes a value which it uses to decide which option to perform.WriteLine ( "Invalid command" ) . break . break . break . since it means that they have to type in the complete name of the option. You can use the switch construction with types other than numbers if you wish: switch (command) { case "casement" : handleCasement (). Another other useful feature is the default option. In the same way as you break out of a loop. This gives the switch somewhere to go if the switch value doesn't match any of the cases available. when the break is reached the switch is finished and the program continues running at the statement after the switch. The good news is that although different operating systems use different ways to look after their files. These can be used to obtain a version of a string which is all in upper or lower case. that is how we have kept all the programs we have created so far. break . If you want to perform selection based on strings of text like this I’d advise you to take a look at the ToUpper and ToLower methods provided by the string type. break . case "patio" : case "P" : handlePatio () . so that streams can be used to read and write to files. It is also easier to add extra commands if you use a switch since it is just a matter of putting in another case.. which can make the testing of the commands much easier: switch (command. We can write a C# program which creates a file on a Windows PC and then use the same program to create a file on a UNIX system with no problems.1 Streams and Files C# makes use of a thing called a stream to allow programs to work with files. The operating system actually does the work. However. 3. 3. break . What we want to do is use C# to tell the operating system to create files and let us access them.. case "standard" : case "s" : handleStandard () . The stream is the thing that links your program with the operating system of the computer you are using. break .ToUpper()) { case "CASEMENT" : case "C" : . Data can flow up or down your stream. in files.6. I'd advise against putting large amounts of program code into a switch case. Programmer’s Point: switches are a good idea Switches make a program easier to understand as well as quicker to write.Creating Programs Using Files switch (command) { case "casement" : case "c" : handleCasement (). } The above switch will select a particular option if the user types the full part of the name or just the initial letter. Instead you should put a call to a method as I have above. Files are looked after by the operating system of the computer. We know that you can store data in this way..6 Using Files If you want your program to be properly useful you have to give it a way of storing data when it is not running.WriteLine ( "Invalid command" ) . and the C# library you are using will convert your request to use streams into instructions for the operating system you are using at the time: C# Programming © Rob Miles 2010 71 . default : Console. the way in which you manipulate files in C# is the same for any computer. A stream is a link between your program and a data resource. If this process fails for any reason. 3. is implemented as a stream. writer.txt already exists. the call of WriteLine will throw an exception. The variable writer will be made to refer to the stream that you want to write into. When the stream is created it can be passed the name of the file that is to be opened.2 Creating an Output Stream You create a stream object just like you would create any other one. If your program got stuck writing in an infinite loop it is possible that it might fill up the storage device. writer = new StreamWriter("test. file is created in place of what was there.6. The program performs operations on the file by calling methods on the stream object to tell it what to do. these are the StreamWriter and StreamReader types. The ReadLine and WriteLine methods are commands you can give any stream that will ask it to read and write data.txt"). This is potentially dangerous. Most useful programs ask the user whether or not an existing file should be overwritten. since the Console class. perhaps your operating system is not able/allowed to write to the file or the name is invalid. It means that you could use the two statements above to completely destroy the contents of an existing file. C# has a range of different stream types which you use depending on what you want to do. you will find out later how to do this. empty. If this happens. which would be bad. StreamWriter writer .WriteLine("hello world").3 Writing to a Stream Once the stream has been created it can be written to by calling the write methods it provides. This is exactly the same technique that is used to write information to the console for the user to read. When the new StreamWriter is created the program will open a file called test. and the write cannot be performed successfully. In fact you can use all the writing features including those we explored in the neater printing section to format your output.Creating Programs Using Files C# program stream File in Windows A C# program can contain an object representing a particular stream that a programmer has created and connected to a file. Each time you write a line to the file it is added onto the end of the lines that have already been written. All of the streams are used in exactly the same way. 3. C# Programming © Rob Miles 2010 72 . then the action will fail with an appropriate exception. The above statement calls the WriteLine method on the stream to make it write the text ―hello world‖ into the file test. In fact you are already familiar with how streams are used. which connects a C# program to the user.txt for output and connect the stream to it. Note however that this code does not have a problem if the file test.6.txt. We are going to consider two stream types which let programs use files. by using new. A properly written program should probably make sure that any exceptions like this (they can also be thrown when you open a file) are caught and handled correctly. All that happens is that a brand new. So. Any further attempts to write to the stream will fail with an exception. They put all the Roman artefacts in one room.6.4 Closing a Stream When your program has finished writing to a stream it is very important that the stream is explicitly closed using the Close method: writer. A namespace is. An open stream consumes a small. It will also be impossible to move or rename the file. i. a ―space where names have meaning‖. The full name of the Console class that you have been using to write text to the user is System. Whenever the compiler finds an C# Programming © Rob Miles 2010 73 . using System. If your program creates lots of streams but does not close them this might lead to problems opening other files later on. This statement tells the compiler to look in the System namespace for resources. The C# language provides the keywords and constructions that allow us to write programs. Like lots of the objects that deal with input and output. close the file or suffer the consequences. Forgetting to close a file is bad for a number of reasons: It is possible that the program may finish without the file being properly closed. this object is defined in the System. These resources are things like the Console object that lets us read and write text to the user.5 Streams and Namespaces If you rush out and try the above bits of code you will find that they don’t work.Creating Programs Using Files 3.Console. part of operating resource. each of which must be uniquely identified. and the Greek ones in another. The above uses the fully qualified name of the console resource and calls the method WriteLine provided by that resource. at the start of our C# programs.e. The using keyword allows us to tell the compiler where to look for resources. Museum curators do this all the time. 3.WriteLine("Hello World"). but on top of this there are a whole lot of extra resources supplied with a C# installation. A C# installation actually contains many thousands of resources. we’ve not had to use this form because at the start of our programs we have told the compiler to use the System namespace to find any names it hasn’t seen before. The designers of the C# language created a namespace facility where programmers can do the same kind of thing with their resources. There is something else that you need to know before you can use the StreamWriter type. once the close has been performed you can use the Notepad program to open test. In this situation some of the data that you wrote into the file will not be there. when we reflected on the need to have the statement using System.Close(). If you were in charge of cataloguing a huge number of items you would find it very helpful to lump items into groups. Namespaces are all to do with finding resources. quite literally.6. Once we have specified a namespace in a program file we no longer need to use the fully qualified name for resources from that namespace. If your program has a stream connected to a file other programs may not be able to use that file. Now we need to find out more about them. the Console class in the System namespace. However. That is. but significant.IO namespace.Console. We have touched on namespaces before. In fact it is quite OK to use this full form in your programs: System. When the Close method is called the stream will write out any text to the file that is waiting to be written and disconnect the program from the file. Sorry about that. Once a file has been closed it can then be accessed by other programs on the computer.txt and take a look at what is inside it. just because you use a namespace. We will see how you can create your own namespaces later on. C# Programming © Rob Miles 2010 74 . However.txt").txt. Namespaces are a great way to make sure that names of items that you create don’t clash with those from other programmers. Console.IO namespace. string line = reader. reads the first line from the file.6.WriteLine(line).Vases) and so the IO namespace is actually held within the System namespace. The while loop will stop the program when the end of the file is reached.ReadLine(). to use the file handing classes you will need to add the following statement at the very top of your program: using System. TextReader reader = new StreamReader("Test.Close(). Fortunately the StreamReader object provides a property called EndOfStream that a program can use to determine when the end of the file has been reached. reader = new StreamReader("Test. If the programmer miss-types the class name: Consle. } reader.WriteLine("Hello World"). 3. Console.WriteLine("Hello World"). fail to find an object called Consle and generate a compilation error. If the file can’t be found then the attempt to open it will fail and the program will throw an exception. Detecting the End of an Input File Repeated calls of ReadLine will return successive lines of a file. . displays it on the screen and then close the stream.WriteLine (line). The above program connects a stream to the file Test.EndOfStream == false) { string line = reader.Creating Programs Using Files item it hasn’t seen before it will automatically look in the namespaces it has been told to use. This is the same error that you will get if you try to use the StreamWriter class without telling the compiler to look in the System. It is possible to put one namespace inside another (just like a librarian would put a cabinet of Vases in the Roman room which he could refer to as Roman.IO. if your program reaches the end of the file the ReadLine method will return an empty string each time it is called.txt"). In other words. in that the program will create a stream to do the actual work. and so you must include the above line for file handling objects to be available.txt and display every line in the file on the console.6 Reading from a File Reading from a file is very similar to writing. reader. while (reader.the compiler will look in the System namespace. In other words. However.it knows to look in the System namespace for that object so that it can use the WriteLine method on it. . The above program will open up the file test.ReadLine(). In this case the stream that is used is a StreamReader. StreamReader reader.Close(). this does not imply that you use all the namespaces defined within it. When the property becomes true the end of the file has been reached. when the compiler sees the statement: Console. as data files are hardly ever held in the same place as programs run from) you can add path information to a filename: string path.txt". which is held in the folder data which is on drive C. These are used to organise information we store on the computer. The location of a file on a computer is often called the path to the file. One can be used for Documents.txt. This file is held in the folder November. If you have problems where your program is not finding files that you know are there. The above statements create a string variable which contains the path to a file called sales.Creating Programs Using Files 3. If you don’t give a folder location when you open a file (as we have been doing with the file Test. If you want to use a file in a different folder (which is a good idea. which is in turn held in the folder 2009.txt is in the MyProgs folder too. I’d advise you to make sure that your path separators are not getting used as control characters.exe in the folder MyProgs then the above programs will assume that the file Test. C# Programming © Rob Miles 2010 75 . Note that I have specified a string literal that doesn’t contain control characters (that is what the @ at the beginning of the literal means) as otherwise the \ characters in the string will get interpreted by C# as the start of a control sequence.6. Each file you create is placed in a particular folder.txt) then the system assumes the file that is being used is stored in the same folder as the program which is running. The backslash (\) characters in the string serve to separate the folders along the path to the file. You can create your own folders inside these (for example Documents\Stories). path = @"c:\data\2009\November\sales. the location of the folder and the name of the file itself. If you use Windows you will find that there several folders created for you automatically. another for Pictures and another one for Music. if you are running the program FileRead. The path a file can be broken into two parts.7 File Paths in C# If you have used a computer for a while you will be familiar with the idea of folders (sometimes called directories). In other words. The program we are making is for a bank. The bank manager has told us that the bank stores information about each customer. Other data items might be added later. These notes should put the feature into a useful context. the "United Friendly and Really Nice Bank of Lovely People ™". Of course if C# Programming © Rob Miles 2010 76 . We will be creating the entire bank application using C# and will be exploring the features of C# that make this easy. from video games to robots.1 Our Case Study: Friendly Bank The bulk of this section is based on a case study which will allow you to see the features of C# in a strong context. 4. otherwise known as the Friendly Bank. A lot of the things that our bank is going to do (store a large amount of information about a large number of individuals. address. At the moment we are simply concerned with managing the account information in the bank. This information includes their name. search for information for a particular person. a statement of what the system will not do. balance and overdraft value. The system must also generate warning letters and statements as required. This is equally as important. Bank Notes At the end of some sections there will be a description of how this new piece of C# will affect how we create our bank system. By setting out the scope at the beginning you can make sure that there are no unpleasant surprises later on. by implication. from a programming point of view it is an interesting problem and as we approach it we will uncover lots of techniques which will be useful in other programs that we might write.Creating Solutions Our Case Study: Friendly Bank 4 Creating Solutions 4.2 Enumerated Types These sound really posh. as a customer will not usually have clear idea of what you are doing and may well expect you to deliver things that you have no intention of providing. It is unlikely that you will get to actually implement an entire banking system during your professional career as a programmer (although it might be quite fun – and probably rather lucrative).1 Bank System Scope The scope of a system is a description of the things that the system is going to do. If anyone asks you what you learnt today you can say "I learnt how to use enumerated types" and they will be really impressed. implement transactions that change the content of one or more items in the system) are common to many other types of programs. There are many thousands of customers and the manager has also told us that there are also a number of different types of accounts (and that new types of account are invented from time to time). You are taking the role of a programmer who will be using the language to create a solution for a customer. This is also. However. Programmer’s Point: Look for Patterns The number of different programs in the world is actually quite small. account number. 4.1. For example. I could do something with numbers if I like: Empty sea = 1 Attacked = 2 Battleship = 3 Cruiser = 4 Submarine = 5 Rowing boat = 6 However. and must be managed solely in terms of these named enumerations. Sample states Enumerated types are very useful when storing state information.1 Enumeration and states Enumerated sounds posh. However.2.. C# Programming © Rob Miles 2010 77 . It can only have the given values above. 4. We know that if we want to hold an integer value we can use an int type. I have created a type called SeaState which can be used to hold the state of a particular part of the sea. in that I have decided that I need to keep track of the sea and then I have worked out exactly what I can put in it. If we want to hold something which is either true or false we can use a bool. RowingBoat } . But if you think of "enumerated" as just meaning "numbered" things get a bit easier. I am sort of assembling more metadata here. States are not quite the same as other items such as the name of a customer or the balance of their account. sometimes we want to hold a range of particular values or states. but how these are managed is not a problem for me. Of course C# itself will actually represent these states as particular numeric values. you mean you’ve numbered some states" and not be that taken with it.EmptySea. My variable openSea is only able to hold values which represent the state of the sea contents. To understand what we are doing here we need to consider the problem which these types are intended to solve. These types are called "enumerated types": enum SeaState { EmptySea. Cruiser. this would mean that I have to keep track of the values myself and remember that if we get the value 7 in a sea location this is clearly wrong. Submarine. Attacked. C# has a way in which we can create a type which has just a particular set of possible values. openSea = SeaState. Battleship. For example I must write: SeaState openSea .Creating Solutions Enumerated Types they know about programming they'll just say "Oh. class EnumDemonstration { public static void Main () { TrafficLight light . easier to understand and safer. } } Every time that you have to hold something which can take a limited number of possible values. Sold. Amber } . UnderAudit. For the bank you want to hold the state of an item as well as other information about the customer. "New". Every account will contain a variable of type AccountState which represents the state of that account. like keywords are.Creating Solutions Enumerated Types Note that types I create (like SeaState) will be highlighted by the editor in a blue colour which is not quite the same as keywords. For example. Now we have reached the point where we are actually creating our own data types which can be used to hold data values that are required by our application. RedAmber. but they are not actually part of the C# language. we could have the states "Frozen". Previously we have used types that are part of C#. for example int and double. Programmer’s Point: Use enumerated types Enumerated types are another occasion where everyone benefits if you use them. 4. We now have a variable which can hold state information about an account in our bank. If this is the case it is sensible to create an enumerated type which can hold these values and no others enum AccountState { New.2. C# Programming © Rob Miles 2010 78 . Frozen. "Closed" and "Under Audit" as states for our bank account. This shows that these items are extra types I have created which can be used to create variables. light = TrafficLight. Closed } . The program becomes simpler to write. OffTheMarket etc) then you should think in terms of using enumerated types to hold the values.Red. UnderOffer. or states (for example OnSale. Active.2 Creating an enum type The new enum type can be created outside any class and creates a new type for use in any of my programs: using System. enum TrafficLight { Red. It is important that you understand what is happening here. Green. "Active". You should therefore use them a lot. string customer address . (Remember that array subscript values start at 0).Creating Solutions Structures 4. and so on. int [] accountNos = new int [MAX_CUST] . In C# a lump of data would be called a structure and each part of it would be called a field. 4. string [] addresses = new string [MAX_CUST] . after a while you come up with the following: const int MAX_CUST = 50.2 Creating a Structure C# lets you create data structures. Establish precisely the specification.string account number . If we were talking about a database (which is actually what we are writing). This is important in many applications. and you could get a database system working with this data structure. To help us with our bank database we could create a structure which could hold all the information about a customer: C# Programming © Rob Miles 2010 79 . This is all very well.1 What is a Structure? Often when you are dealing with information you will want to hold a collection of different things about a particular item.3. 4. int [] overdraft = new int [MAX_CUST] . the lump of data for each customer would be called a record and an individual part of that lump. Negotiate an extortionate fee. A sample structure From your specification you know that the program must hold the following: customer name . The Friendly Bank has commissioned an account storage system and you can use structures to make this easier.3 Structures Structures let us organise a set of individual values into a cohesive lump which we can map onto one of the items in the problem that we are working on. 3. int [] balances = new int [MAX_CUST] . What we have is an array for each single piece of data we want to store about a particular customer. AccountState [] states = new AccountState [MAX_CUST] . 2. would be called a field. However it would be much nicer to be able to lump your record together in a more definite way. overdraft [0] holds the overdraft of the first customer.integer value The Friendly Bank have told you that they will only be putting up to 50 people into your bank storage so.integer value overdraft limit . A structure is a collection of C# variables which you want to treat as a single entity. for example the overdraft value. i.3. Consider how you will go about storing the data. Like any good programmer who has been on my course you would start by doing the following: 1.e. In our program we are working on the basis that balance[0] holds the balance of the first customer in our database. get in written form exactly what they expect your system to do.integer value account balance . string [] names = new string [MAX_CUST] . The first declaration sets up a variable called RobsAccount. just as we would any other variable type. Account [] Bank = new Account [MAX_CUST]. called Account. This would copy the information from the RobsAccount structure into the element at the start of the Bank array. // enum enum AccountState { New. public string Name .3.3 Using a Structure A program which creates and sets up a structure looks like this: using System. When the assignment is performed all the values in the source structure are copied into the destination: Bank[0] = RobsAccount. public int AccountNumber .would be the string containing the name of the customer in the element with subscript 25. public int Balance . for example: RobsAccount. which can hold the information for a single customer. the AccountNumber value in RobsAccount) You can do this with elements of an array of structures too. Active. UnderAudit. (i.Name . called Bank which can hold all the customers. The second declaration sets up an entire array of customers.e. public string Address . public int Overdraft . (full stop) separating them. Closed } . Having done this we can now define some variables: Account RobsAccount . Frozen.would refer to the integer field AccountNumber in the structured variable RobsAccount.AccountNumber . C# Programming © Rob Miles 2010 80 . This defines a structure.Creating Solutions Structures struct Account { public AccountState State. 4. which contains all the required customer information. We refer to individual members of a structure by putting their name after the struct variable we are using with a . We can assign one structure variable to another. so that: Bank [25]. } . are trying to follow a reference which does not refer to anything. You can think of them as a bit like a luggage tag. If you have the tag you can then follow the rope to the object it is tied to. class StructsAndObjectsDemo { public static void Main () { Account RobsAccount . Structures and References It then sets the name property of the variable to the string "Rob". But when we create a reference we don't actually get one of the things that it refers to. } } The account information is now being held in a class. The account class is called.Creating Solutions Objects. quite simply. If we run this program it does exactly what you would expect. The compiler knows this. this is not what it seems. what is going on? To understand what is happening you need to know what is performed by the line: Account RobsAccount. in that they can be tied to something with a piece of rope. Creating and Using an Instance of a Class We can make a tiny change to the program and convert the bank account to a class: class Account { public string Name . RobsAccount What you actually get when the program obeys that line is the creation of a reference called RobsAccount.is an attempt to find the thing that is tied to this tag and set the name property to "Rob". The compiler therefore says. Account. Since the tag is presently not tied to anything our program would fail at this point. therefore I am going to give you a 'variable undefined' error". and so it gives me an error because the line: RobsAccount. in that it prints out the name "Rob". and I could use them in just the same way. . If the structure contained other items about the bank account these would be stored in the structure as well.Name ). This looks like a declaration of a variable called RobsAccount. This is achieved by adding a line to our program: C# Programming © Rob Miles 2010 84 . We solve the problem by creating an instance of the class and then connecting our tag to it. The problem is that when we compile the program we get this: ObjectDemo.cs(12. Console.3): error CS0165: Use of unassigned local variable ' RobsAccount' So. RobsAccount. But in the case of objects.Name = "Rob". } . Such references are allowed to refer to instances of the Account. in effect.Name = "Rob". rather than a structure.WriteLine (RobsAccount. WriteLine (RobsAccount. We use it to create arrays. Structures and References class Account { public string Name . and what it can do. } } The line I have added creates a new Account object and sets the reference RobsAccount to refer to it. An object is an instance of a class. This is because the object instance does not have the identifier RobsAccount. RobsAccount = new Account(). Account RobsAccount Name: Rob We have seen this keyword new before.Creating Solutions Objects. 4. } . I'll repeat that in a posh font: “An object is an instance of a class” I have repeated this because it is very important that you understand this. This is because an array is actually implemented as an object.2 References We now have to get used to the idea that if we want to use objects. and that means that we must manage our access to a particular object by making use of references to it. Structures are kind of useful. The thing that new creates is an object.Name = "Rob". The new keyword causes C# to use the class information to actually make an instance.4. but for real object oriented satisfaction you have to have an object. it is simply the one which RobsAccount is connected to at the moment. not RobsAccount. A class provides the instructions to C# as to what is to be made. class StructsAndObjectsDemo { public static void Main () { Account RobsAccount . but you must remember that when you hold a reference you do not hold an instance. you hold a tag which is tied onto an instance… Multiple References to an Instance Perhaps another example of references would help at this point. in that you can treat a reference as if it really was the object just about all of the time. Console.Name ). Actually this is not that painful in reality. Consider the following code: C# Programming © Rob Miles 2010 85 . The two come hand in hand and are inseparable. Note that in the above diagram I have called the object an Account. we have to use references. and so we use new to create it. RobsAccount. RobsAccount. RobsAccount = new Account().Name = "Jim". Account Temp . since that is the name in the object that RobsAccount is referring to. Temp. so you need to remember that changing the object that a reference refers to may well change that instance from the point of view of other objects. The reference RobsAccount is made to refer to the new item. RobsAccount. The question is: What happens to the first instance? Again. Console. There is no limit to the number of references that can be attached to a single instance.WriteLine (RobsAccount.Name = "Jim". Console. This means that the program would print out Jim.Name ).WriteLine (RobsAccount. which has the name set to Jim. RobsAccount = new Account().Creating Solutions Objects.WriteLine (RobsAccount.Name ). Structures and References Account RobsAccount . what would the second call of WriteLine print out? If we draw a diagram the answer becomes clearer: Account RobsAccount Name: Jim Temp Both of the tags refer to the same instance of Account. Console. No References to an Instance Just to complete the confusion we need to consider what happens if an object has no references to it: Account RobsAccount . This means that any changes which are made to the object that Temp refers to will also be reflected in the one that RobsAccount refers to. this can be made clearer with a diagram: C# Programming © Rob Miles 2010 86 . The question is.Name ). This code makes an account instance. This indicates a trickiness with objects and references.Name = "Rob".Name = "Rob". sets the name property of it to Rob and then makes another account instance. RobsAccount = new Account(). RobsAccount. Temp = RobsAccount. Console.WriteLine (RobsAccount. because they are the same object.Name ). You should also remember that you can get a similar effect when a reference to an instance goes out of scope: { Account localVar . The currency in use on this island is based around 12 feet tall stones which weigh several hundred pounds each. Programmer’s Point: Try to avoid the Garbage Collector While it is sometimes reasonable to release items you have no further use for. This means that when the program execution leaves the block the local variable is discarded. called the ―Garbage Collector‖ which is given the job of finding such useless items and disposing of them.4. } The variable localVar is local to the block. C# Programming © Rob Miles 2010 87 . 4. When I work with objects I worry about how much creating and destroying I am doing.Creating Solutions Objects. Note that the compiler will not stop us from ―letting go‖ of items like this. In other words they use references to manage objects that they don’t want to have to move around. you must remember that creating and disposing of objects will take up computing power. meaning another job for the garbage collector. As far as making use of data in the instance is concerned. When you pay someone with one of these coins you don’t actually pick it up and give it to them.3 Why Bother with References? References don’t sound much fun at the moment. Consider a bank which contains many accounts. That is why we use references in our programs.. Just because the objects are disposed of automatically doesn’t mean that you should abuse the facility. localVar = new Account(). Instead you just say ―The coin in the road on top of the hill is now yours‖. If we wanted to sort them into alphabetical order of customer name we have to move them all around. it might as well not be there. with nothing referring to it. So why do we bother with them? To answer this we can consider the Pacific Island of Yap. This means that the only reference to the account is also removed. Structures and References Account RobsAccount Name: Rob Account Name: Jim The first instance is shown ―hanging‖ in space. Indeed the C# language implementation has a special process. Then C# Programming © Rob Miles 2010 88 . and also speed up searching. Without references this would be impossible. the other to a node which is ―darker‖.Creating Solutions Objects. References and Data Structures Our list of sorted references is all very good. With references we just need to keep a number of arrays of references. instead the references can be moved around. Sorting by use of a tree In the tree above each node has two references. New objects can be added without having to move any objects. but if we want to add something to our sorted list we still have to move the references around. for example they might want to order it on both customer surname and also on account number. by structuring our data into a tree form. The bank may well want to order the information in more than one way too. each of which is ordered in a particular way: Sorting by using references If we just sort the references we don’t have to move the large data items at all. We can get over this. Structures and References Sorting by moving objects around If we held the accounts as an array of structure items we would have to do a lot of work just to keep the list in order. one can refer to a node which is ―lighter‖. If I want a sorted list of the items I just have to go as far down the ―lighter‖ side as I can and I will end up at the lightest. because of the size of each account and the number of accounts being stored. don’t worry. The neat thing about this approach is also that adding new items is very easy. and if possible get someone else to do it. The thing that we are trying to do here is best expressed as: ―Put off all the hard work for as long as we can. Reference Importance The key to this way of working is that an object can contain references to other objects. and it would also be possible to have several such lists. a bit like President Kennedy did all those years ago: C# Programming © Rob Miles 2010 89 . it is a programming document. in which case the item is not in the structure.Creating Solutions Designing With Objects I go up to the one above that (which must be the next light. This all comes back to the ―creative laziness‖ that programmers are so famous for. Programmer’s Point: Data Structures are Important This is not a data structures document. Bank Notes: References and Accounts For a bank with many thousands of customers the use of references is crucial to the management of the data that they hold. This means that we can offer the manager a view of his bank sorted by customer name and another view sorted in order of balance. Just remember that references are an important mechanism for building up structures of data and leave it at that. 4. But sometime in the future you are going to have to get your head around how to build structures using these things. The references are very small "tags" which can be used to locate the actual item in memory. Sorting a list of references is very easy. I just find the place on the tree that they need to be hung on and attach the reference there. Then I go down the dark side (Luke) and repeat the process. The reason that we do this is that we would like a way of making the design of our systems as easy as possible. And if the manager comes along with a need for a new structure or view we can create that in terms of references as well. in that I can look at each node and decide which way to look next until I either find what I am looking for or I find there is no reference in the required direction. If you don’t get all the stuff about trees just yet. Searching is also very quick. This means that the only way to manipulate them is to leave them in the same place and have lists of references to them. as well as the data payload. for now we just need to remember that the reference and the object are distinct and separate. We will consider this aspect of object use later. The accounts will be held in the memory of the computer and. object based design turns this on its head.5 Designing With Objects We are now going to start thinking in terms of objects. it will not be possible to move them around memory if we want to sort them.‖ Objects let us do this. for now I’m just going to consider how I keep track of the balance of the accounts. we don’t have to worry precisely how they made it work – we just have to sit back and take the credit for a job well done.Creating Solutions Designing With Objects ―And so. C# Programming © Rob Miles 2010 90 . Instead we ask it to do these things for us. RobsAccount = new Account().1 Data in Objects So. In this section we are going to implement an object which has some of the behaviours of a proper bank account. } The Account class above holds the member that we need to store about the balance of our bank accounts. Each time I create an instance of the class I get all the members as well. This brings us back to a couple of recurring themes in this document. Members of a class which hold a value which describes some data which the class is holding are often called properties. And once we have decided on the actions that the account must perform. The account number of an account is something which is unique to that account and should never change. We have seen that each of the data items in a class is a member of it and stored as part of it.Balance = 0. RobsAccount. since this is specially designed to hold financial values. We might even identify some things as being audited. The first thing is to identify all the data items that we want to store in it. This will let me describe all the techniques that are required without getting bogged down too much. The really clever bit is that once we have decided what the bank account should do. I’ve used the decimal type for the account balance. metadata and testing. What a bank account object should be able to do is part of the metadata for this object. we then might be able to get somebody else to make it do these things. The design of our banking application can be thought of in terms of identifying the objects that we are going to use to represent the information and then specifying what things they should be able to do. we can consider our bank account in terms of what we want it to do for us. class Account { public decimal Balance. along with what should be done. 4. If our specification is correct and they implement it properly. For the sake of simplicity. That way we can easily find out if bad things are being done. We can get this behaviour by simply not providing a means by which it can be changed. Programmer’s Point: Not Everything Should Be Possible Note that there are also some things that we should not be able to do with our bank account objects. The reason that this works is that the members of the object are all public and this means that anybody has direct access to them. my fellow Americans: ask not what your country can do for you—ask what you can do for your country‖ (huge cheers) We don’t do things to the bank account. the next thing we need to do is devise a way in which each of the actions can be tested. It is important at design time that we identify what should not be possible. We have already seen that it is very easy to create an instance of a class and set the value of a member: Account RobsAccount . This means that any programmer writing the application can do things like: RobsAccount. in that an object will keep track of what has been done to it.Balance = 99.5. } The property is no longer marked as public. I want all the important data hidden inside my object so that I have complete control over what is done with it. public bool WithdrawFunds ( decimal amount ) { if ( balance < amount ) { return false .amount . You are thinking ―What is the point of making it private. 4.cs(13. Well. and stop the change from being made if I don’t like it. C# Programming © Rob Miles 2010 91 .3): error CS0122: 'PrivateMembers.Account.balance' is inaccessible due to its protection level The balance value is now held inside the object and is not visible to the outside world. but only using code actually running in the class. Ideally I want to get control when someone tries to change a value in my objects. Consider the program: class Account { private decimal balance = 0. } balance = balance . If we are going to provide a way of stopping this from happening we need to protect the data inside our objects. thanks for the vote of confidence folks. .and take away all my money.I will get an error when I try to compile the program: PrivateDemo. in our bank program we want to make sure that the balance is never changed in a manner that we can't control. The first thing we need to do is stop the outside world from playing with our balance value: class Account { private decimal balance. now you can’t change it at all‖.5. For example. This technology is the key to my defensive programming approach which is geared to making sure that. Changing private members I can tell what you are thinking at this point. If I write the code: RobsAccount. It turns out that I can change the value.2 Member Protection inside objects If objects are going to be useful we have to have a way of protecting the data within them. Instead it is now private. } } . whatever else happens. This means that the outside world no longer has direct access to it.balance = 0. The posh word for this is encapsulation. my part of the program does not go wrong.Creating Solutions Designing With Objects . return true. WithdrawFunds (5) ) { Console. They would call their balance value m_balance so that class members are easy to spot. In the code above the way that I am protecting the balance value is a reflection of how the customer wants me to make sure that this value is managed properly. This means that code running outside the class can make calls to that method.WriteLine ( "Cash Withdrawn" ) . If you don’t care about possible corruption of the member and you want your program to run as quickly as possible you can make a data member public. the rules can be broken on special occasions.).e. The method WithdrawFunds is a member of the Account class and can therefore access private members of the class. But I make the first letter of private members lower case (as in the case of the balance data member of our bank account). This has got to be the case.WriteLine ( "Insufficient Funds" ) . since the initial balance on my account is zero. task you can make it private. The convention also extends to variables which are local to a block. The most important thing in this situation is that the whole programming team adopts the same conventions on matters like these. Programmer’s Point: Metadata makes Members and Methods I haven’t mentioned metadata for at least five minutes. and expect developers to adhere to these. Some people go further and do things like put the characters m_ in front of variables which are members of a class. } else { Console. This makes it easy for someone reading my code.Creating Solutions Designing With Objects class Bank { public static void Main () { Account RobsAccount. make it private if it is a method member (i. since we want people to interact with our objects by calling methods in them. it holds data) of the class. if ( RobsAccount. So perhaps now is a good time. secret. If you want to write a method which is only used inside a class and performs some special. most development companies have documents that set out the coding conventions they use. public Methods You may have noticed that I made the WithdrawFunds method public. } } } This creates an account and then tries to draw five pounds out of it. it does something) make it public Of course. but it shows how I go about providing access to members in an account.e. but opinions differ on this one. In general the rules are: if it is a data member (i. This will of course fail. In fact. I don’t usually go that far. These (for example the ubiquitous i) always start with a lower case letter. The metadata that I gather about my bank system will drive how I provide access to the members of my classes. C# Programming © Rob Miles 2010 92 . because I reckon that the name of the member is usually enough. RobsAccount = new Account(). GetBalance() != 50 ) { Console. I have created three methods which I can use to interact with an account object. and if you don’t notice it then you might think your code is OK. The method GetBalance is called an accessor since it allows access to data in my business object. C# Programming © Rob Miles 2010 93 . return true. They then search out the programmer who caused the failure and make him or her pay for coffee for the next week. At the end of this set of statements the test account should have 50 pounds in it.Creating Solutions Designing With Objects 4.WriteLine ( "Pay In test failed" ). which is tedious. If the error count is greater than zero they print out a huge message in flashing red text to indicate that something bad has happened. } } The bank account class that I have created above is quite well behaved.3 A Complete Account Class We can now create a bank account class which controls access to the balance value: public class Account { private decimal balance = 0. My tests count the number of errors that they have found. Programmer’s Point: Make a Siren go off when your tests fail The above test is good but not great. so that it is impossible to ignore a failing test. in that it does something and then makes sure that the effect of that action is correct. Later we will consider the use of unit tests which make this much easier. You have to read that message. I can pay money in. test. } My program now tests itself. } public decimal GetBalance () { return balance. It just produces a little message if the test fails. Of course I must still read the output from all the tests.PayInFunds(50). If it does not my program is faulty. Some development teams actually connect sirens and flashing red lights to their test systems. } public void PayInFunds ( decimal amount ) { balance = balance + amount .amount . test. I could write a little bit of code to test these methods: Account test = new Account().5. public bool WithdrawFunds ( decimal amount ) { if ( balance < amount ) { return false . for example: Account test = new Account().PayInFunds(50). find out how much is there and withdraw cash. if ( test. } balance = balance . For example it should be easy to adjust how much damage a hit from an alien causes to your spacecraft. since you might be using code that you wrote some time back.e. As long as my object tests are passed. This means that whenever we create an instance of the Account class we get a balance member.6. but it does not solve all your problems. If the bugs are in an old piece of code you have to go through the effort of remembering how it works. i. Writing the tests first is actually a really good way of refining your understanding. but in the class itself. You don't do the testing at the end of the project. So. Many projects are doomed because people start programming before they have a proper understanding of the problem. When you fix bugs in your program you need to be able to convince yourself that the fixes have not broken some other part (about the most common way of introducing new faults into a program is to mend a bug). And there is a good chance that the tests that you write will be useful at some point too. the code that provides the user interface where the customer enters how much they want to withdraw will be very simple and connect directly to the methods provided by my objects. This is mainly because the quality of gameplay is not something you can design tests for. 2. and the speed of all the game objects. The other kind of program that is very hard to test in this way is any kind of game. The only solution in this situation is to set out very clearly what your tests are trying to prove (so that the human testers know what to look for) and make it very easy to change the values that will affect the gameplay. In the case of our bank account above. please develop using tests.5. However.6 Static Items At the moment all the members that we have created in our class have been part of an instance of the class. Some types of programs are really hard to test in this way. If I ever write anything new you can bet your boots that I will write it using a test driven approach. Only when someone comes back and says “The game is too hard because you can’t kill the end of level boss without dying” can you actually do something about it.Creating Solutions Static Items 4. You can write code early in the project which will probably be useful later on. We have used it lots in just about every program that we have ever written: C# Programming © Rob Miles 2010 94 . This is usually the worst time to test. Far better to test the code as you write it. Anything with a front end where users type in commands and get responses is very hard to test like this. You will thank me later. If you have a set of automatic tests that run after every bug fix you have a way of stopping this from happening. Programmer’s Point: Some things are hard to test Test development is a good way to travel.4 Test Driven Development I love test driven development. they exist outside of any particular instance. My approach in these situations is to make the user interface part a very thin layer which sits on top of requests to objects to do the work. 4. because although it is easy to send things into a program it is often much harder to see what the program does in response. This solves three problems that I can see: 1. when you have the best possible understanding of what it is supposed to do. 3.1 Static class members The static keyword lets us create members which are not held in an instance. we can also create members which are held as part of the class. I can be fairly confident that the user interface will be OK too. 4. It is very important that you learn what static means in the context of C# programs. In the program we can implement this by adding another member to the class which holds the current interest rate: public class Account { public decimal Balance . and so this method must be there already. This would be tedious. We know that this is the method which is called to run the program. (of course if I was doing this properly I'd make this stuff private and provide methods etc. for it is important: “A static member is a member of the class. RobsAccount. RobsAccount. I will write that down again in a posh font.PayInFunds (50). If the interest rate changes it must change for all accounts. in that when it starts it has not made any instances of anything. If I made fifty AccountTest instances. Static does not mean "cannot be changed". The customer has told us that one of the members of the account class will need to be the interest rate on accounts. } } The AccountTest class has a static member method called Main. but I'm keeping things simple just now). I solve the problem by making the interest rate member static: C# Programming © Rob Miles 2010 95 . not part of an instance of the class. and if I missed one account. not a member of an instance of the class” I don't have to make an instance of the AccountTest class to be able to use the Main method.Balance = 100.Creating Solutions Static Items class AccountTest { public static void Main () { Account test = new Account(). The snag is. This is how my program actually gets to work.GetBalance()). 4.2 Using a static data member of a class Perhaps an example of static data would help at this point. I've been told that the interest rate is held for all the accounts. they would all share the same Main method. Members of a class which have been made static can be used just like any other member of a class.6. In terms of C# the keyword static flags a member as being part of the class. otherwise it cannot run. public decimal InterestRateCharged . Consider the interest rates of our bank accounts.WriteLine ("Balance:" + test. } Now I can create accounts and set balances and interest rates on them. I think this is time for more posh font stuff: Static does not mean “cannot be changed”. test. It is part of the class AccountTest.InterestRateCharged = 10. possibly expensive. This means that to implement the change I'd have to go through all the accounts and update the rate. Console. Either a data member or a method can be made static. Account RobsAccount = new Account(). We have been doing this for ages with the Main method. A change to a single static value will affect your entire system. It would take in their age and income. and you don't want to have to update all the objects in your program.3 Using a static method in a class We can make methods static too. } } This checks the age and income. But of course. public static decimal InterestRateCharged . RobsAccount. not part of any instance. I can now call the method by using the class name: C# Programming © Rob Miles 2010 96 . For example. The snag is that.Balance = 100. There might be a time where the age limit changes. } } Now the method is part of the class.Creating Solutions Static Items public class Account { public decimal Balance .InterestRateCharged = 10. But you can also use them when designing your system. as Spiderman's uncle said. you must be over 17 and have at least 10000 pounds income to be allowed an account. Since it is a member of the class I now have to use the class name to get hold of it instead of the name of the instance reference. So they should always be made private and updated by means of method calls. Things like the limits of values (the largest age that you are going to permit a person to have) can be made static. int age ) { if ( ( income >= 10000 ) && ( age >= 18 ) ) { return true. Programmer’s Point: Static Data Members are Useful and Dangerous When you are collecting metadata about your project you should look for things which can be made static. at the moment. } else { return false. This means that I have to change the way that I get hold of it: Account RobsAccount = new Account(). } else { return false. not an instance of the class. } The interest rate is now part of the class. We can solve this by making the method static: public static bool AccountAllowed ( decimal income. "With great power comes great responsibility". You should be careful about how you provide access to static data items. 4. we can't call the method until we have an Account instance.6. we might have a method which decides whether or not someone is allowed to have a bank account. Account. int age ) { if ( ( income >= 10000 ) && ( age >= 18 ) ) { return true. It would then return true or false depending on whether these are acceptable or not: public bool AccountAllowed ( decimal income. minIncome' AccountManagement. } else { return false.43): error CS0120: An object reference is required for the nonstatic field.minAge' As usual. method. but of course I have fixed the age and income methods into it. int age) { if ( ( income >= minIncome) && ( age >= minAge) ) { return true.cs(19. or property 'Account. in that I now have members of the class which set out the upper limits of the age and income. using language which makes our heads spin. 21 ) ) { Console. What the compiler really means is that "a static method is using a member of the class which is not static". public static bool AccountAllowed(decimal income. since the class above will not compile: AccountManagement. } } } This is a better design. I might decide to make the method more flexible: public class Account { private decimal minIncome = 10000. a static method can run without an instance (since it is part of the class). private int minAge = 18. the compiler is telling us exactly what is wrong. method. However it is a bad program. If that doesn’t help.21): error CS0120: An object reference is required for the nonstatic field. However.WriteLine ( "Allowed Account" ). Using member data in static methods The Allowed method is OK.AccountAllowed ( 25000. how about this: The members minIncome and minAge are held within instances of the Account class. The compiler is unhappy because in this situation the method would not have any members to play with. or property 'Account. We can fix this (and get our program completely correct) by making the income and age limits static as well: C# Programming © Rob Miles 2010 97 .Creating Solutions Static Items if ( Account.cs(19. } This is nice because I have not had to make an instance of the account to find out if one is allowed. At this point we know we can’t use static because we need to hold different values for some of the instances. C# Programming © Rob Miles 2010 98 .Creating Solutions The Construction of Objects public class Account { private static decimal minIncome . Bank Notes: Static Bank Information The kind of problems that we can use static to solve in our bank are: static member variable: the manager would like us to be able to set the interest rate for all the customer accounts at once. static member method: the manager tells us that we need a method to determine whether or not a given person is allowed to have an account. Programmer’s Point: Static Method Members can be used to make Libraries Sometimes in a development you need to provide a library of methods to do stuff. The limit values should not be held as members of a class. I must make it static. this makes perfect sense. In the C# system itself there are a huge number of methods to perform maths functions. A single static member of the Account class will provide a variable which can be used inside all instances of the class. But because there is only a single copy of this value this can be changed and thereby adjust the interest rate for all the accounts. The time it becomes impossible to use static is when the manager says "Oh.7 The Construction of Objects We have seen that our objects are created when we use new to bring one into being: test = new Account(). you say. If you look closely at what is happening you might decide that what is happening looks quite a bit like a method call. Rather than shout at you for not providing a constructor method. The constructor method is a member of the class and it is there to let the programmer get control and set up the contents of the shiny new object. When an instance of a class is created the C# system makes a call to a constructor method in that class. } } } If you think about it. This is actually exactly what is happening. public static bool AccountAllowed(decimal income. 4. since we want them to be the same for all instances of the class. accounts for five year olds have a different interest rate from normal ones". being friendly here. This is because the C# compiler is. in that in this situation all we want is the method itself. therefore. when you are building your system you should think about how you are going to make such methods available for your own use. private static int minAge . making them static is what we should have done in the first place. for example sin and cos. Any value which is held once for all classes (limits on values are another example of this) is best managed as a static value. I can't make this part of any Account instance because at the time it runs an account has not been generated. } else { return false. int age) { if ( ( income >= minIncome) && ( age >= minAge) ) { return true. not an instance of a class. so that it can execute without an instance. for a change. One of the rules of the C# game is that every single class must have a constructor method to be called when a new instance is created. Again. ―We’ve been making objects for a while and I’ve never had to provide a constructor method‖. the compiler instead quietly creates a default one for you and uses that. It makes sense to make these methods static. ―But wait a minute‖. It is public so that it can be accessed from external classes who might want to make instances of the class.1 The Default Constructor A constructor method has the same name as the class. 4. in that it will result in a lot of printing out which the user of the program might not appreciate. and initial balance of an account holder when the account is created. "Hull". As an example. It turns out that I can do this very easily. Feeding the Constructor Information It is useful to be able to get control when an Account is created. the address to Hull and the initial balance to zero. but it would be even nicer to be able to feed information into the Account when I create it. 0 ).7. 4. It accepts no parameters. This means that when my program executes the line: robsAccount = new Account().. public class Account { public Account () { } } This is what the default constructor looks like. In other words I want to do: robsAccount = new Account( "Rob Miles". It is called when we perform new. we could make a constructor which just prints out that it has been called: public class Account { public Account () { Console. I might want to set the name. } } This constructor is not very constructive (ho ho) but it does let us know when it has been called. all I have to do is make the constructor method to accept these parameters and use them to set up the members of the class: C# Programming © Rob Miles 2010 99 . which we will discuss later. If you don’t supply a constructor (and we haven’t so far) the compiler creates one for us. address. but it does show how the process works.WriteLine ( "We just made an account" ).Creating Solutions The Construction of Objects You might think this is strange. . If I create my own constructor the compiler assumes that I know what I’m doing and stops providing the default one.2 Our Own Constructor For fun. This could create a new account and set the name property to Rob Miles.7.the program will print out the message: We just made an account Note that this is not very sensible. in that normally the compiler loses no time in telling you off when you don’t do something. This can cause problems. but in this case it is simply solving the problem without telling you. but it does not return anything. In the context of a C# program it means: "A method has the same name as another. I've missed off the balance value. . and nothing else. In this respect it behaves exactly as any other method call. In other words. balance = inBalance. For example. private decimal balance. string inAddress. or create a default constructor of your own for these calls to use. If your code does this the compiler simply looks for a constructor method which has two strings as parameters. but has a different set of parameters" The compiler is quite happy for you to overload methods. Something a bit like this: C# Programming © Rob Miles 2010 100 . many (but not all) of your accounts will be created with a balance value of zero.e. This can cause confusion if we have made use of the default constructor in our program and we then add one of our own. decimal inBalance) { name = inName.7. i. since I want to use the "default" one of zero.Creating Solutions The Construction of Objects class Account { // private member data private string name.e. what this means is that you can provide several different ways of constructing an instance of a class. the only way I can now make an Account object is by supplying a name. nothing in the account.cs(9. Note that adding a constructor like this has one very powerful ramification: You must use the new constructor to make an instance of a class.the compiler will stop being nice to me and produce the error: AccountTest. Just like me. address and starting balance.3 Overloading Constructors Overload is an interesting word. private string address. address = inAddress. In the context of the "Star Trek" science fiction series it is what they did to the warp engines in every other episode. // constructor public Account (string inName. If I try to do this: robsAccount = new Account(). This means that we would like to be able to write robsAccount = new Account("Rob Miles". i. In the context of the constructor of a class. the compiler only provides a default constructor if the programmer doesn't provide a constructor. } } The constructor takes the values supplied in the parameters and uses them to set up the members of the Account instance that is being created. "Hull").27): error CS1501: No overload for method 'Account' takes '0' arguments What the compiler is telling me is that there is no constructor in the class which does not have any parameters. because it can tell from the parameters given at the call of the method which one to use. In that situation you have to either find all the calls to the default one and update them. 4. The default constructor is no longer supplied by the compiler and our program now fails to compile correctly. hem hem. Of course you don't have to do this because your design of the program was so good that you never have this problem. and sets the address to "Not Supplied". even if you don't put a bug in your code. the second is not given a balance and sets the value to 0. int month. Because it is bad.would be matched up with the method which accepts three integer parameters and that code would be executed. } public Account (string inName. The scary thing is that it is quite easy to do. . If you need to change this piece of code you have to find every copy of the code and change it. you can overload any method name in your classes. balance = 0. just use the block copy command in the text editor and you can take the same piece of program and use it all over the place. int julianDate ) SetDate ( string dateInMMDDYY ) A call of: SetDate ( 23. So. string inAddress.Creating Solutions The Construction of Objects public Account (string inName. 4. } I've made three constructors for an Account instance. But you should not do this. address = "Not Supplied".4 Constructor Management If the Account class is going to have lots of constructor methods this can get very confusing for the programmer: public Account (string inName. string inAddress) { name = inName.7. address = inAddress. 2005 ). } public Account (string inName) { name = inName. int day ) SetDate ( int year. C# provides a way in which you can call one constructor from another. balance = 0. This can be useful if you have a particular action which can be driven by a number of different items of data. for example you could provide several ways of setting the date of a transaction: SetDate ( int year. Good programmers hate duplicating code. To do this I have had to duplicate code. string inAddress) { name = inName. This happens more often than you'd think. you still might find yourself having to change it because the specification changes. The third is not given the address either. It is regarded as "dangerous extra work". address = inAddress. Consider: C# Programming © Rob Miles 2010 101 . balance = inBalance. } Overloading a method name In fact. decimal inBalance) { name = inName. balance = 0. 7. address = inAddress. The first is supplied with all the information. Then you should make all the other constructor methods use this to get hold of that method. address = inAddress. "Not Supplied".7. If you try to do something stupid with a method call it should refuse to perform the action and return something which indicates that it could not do the job. The "this" constructor runs before the body of the other constructor is entered. But what is to stop the following: RobsAccount = new Account ("Rob". in the code above. 0 ) { } The keyword this means "another constructor in this class". In fact it is outside the block completely. decimal inBalance) { name = inName.Creating Solutions The Construction of Objects public Account (string inName. the body of the constructor can be empty. They simply pass the parameters which are supplied. "Hull". 1234567890). This is sensible. C# Programming © Rob Miles 2010 102 . 4. And this is a problem: Whenever we have written methods in the past we have made sure that their behaviour is error checked so that the method cannot upset the state of our object. inAddress. There will be an upper limit to the amount of cash you can pay in at once. on to the "proper" constructor to deal with. attempts to withdraw negative amounts of money from a bank account should be rejected. string inAddress ) : this (inName. The whole basis of the way that we have allowed our objects to be manipulated is to make sure that they cannot be broken by the people using them. The syntax of these calls is rather interesting. because it reflects exactly what is happening. For example. and the other constructor methods just make calls to it. You should create one "master" constructor which handles the most comprehensive method of constructing the object. 0 ) { } public Account ( string inName ) : this (inName. along with any default values that we have created. Constructors cannot fail. the highlighted bits of the code are calls to the first constructor. So we know that when we create a method which changes the data in an object we have to make sure that the change is always valid. we would not let the following call succeed: RobsAccount.PayInFunds (1234567890).5 A constructor cannot fail If you watch a James Bond movie there is usually a point at which agent 007 is told that the fate of the world is in his hands. For example. Constructors are a bit like this. so the PayInFunds method will refuse to pay the money in. in that the call to the constructor takes place before the body of the constructor method. In fact. since the call of this does all the work. string inAddress. Programmer’s Point: Object Construction Should Be Planned The way in which objects are constructed is something that you should plan carefully when you write your program. Failure is not an option. } public Account ( string inName. This means that the actual transfer of the values from the constructor into the object itself only happens in one method. balance = inBalance. As you can see in the code sample above. when the object is first created. It is a fact of programming life that you will (or at least should) spend more time worrying about how things fail than you ever do about how they work correctly. This poses a problem. } if ( SetAddress ( inAddress) == false ) { throw new Exception ( "Bad address" + inAddress) .e. and it complains about my address. } if ( SetAddress ( inAddress) == false ) { errorMessage = errorMessage + " Bad addr " + inAddress. } } If we try to create an account with a bad name it will throw an exception. i. What I want is a way in which I can get a report of all the invalid parts of the item at once. and if any of them returns with an error the constructor should throw the exception at that Point: public Account (string inName. C# Programming © Rob Miles 2010 103 . which is what we want. which is not a bad thing. It is normally when I'm filling in a form on the web. I hate it when I'm using a program and this happens. This means that the user of the constructor must make sure that they catch exceptions when creating objects. the user of the method will not know this until they have fixed the name and then called the constructor again. The only problem here is that if the address is wrong too. Programmer’s Point: Managing Failure is Hard Work This brings us on to a kind of recurring theme in our quest to become great programmers. Then I put my name right. Each new thing which is wrong is added to the message and then the whole thing is put into an exception and thrown back to the caller. I type in my name wrong and it complains about that. if ( SetName ( inName ) == false ) { errorMessage = errorMessage + "Bad name " + inName. at the expense of a little bit of complication: public Account (string inName.Creating Solutions The Construction of Objects Like James Bond. Whatever happens during the constructor call. It looks as if we can veto stupid values at every point except the one which is most important. Writing code to do a job is usually very easy. constructors are not allowed to fail. string inAddress) { string errorMessage = "". it will complete and a new instance will be created. This can be done. } } This version of the constructor assembles an error message which describes everything which is wrong with the account. } if ( errorMessage != "" ) { throw new Exception ( "Bad account" + errorMessage) . The really clever way to do this is to make the constructor call the set methods for each of the properties that it has been given. string inAddress) { if ( SetName ( inName ) == false ) { throw new Exception ( "Bad name " + inName) . Constructors and Exceptions The only way round this at the moment is to have the constructor throw an exception if it is unhappy. Writing code which will handle all the possible failure conditions in a useful way is much trickier. For example. This is a good thing. This is good. In this section you will find out the difference between an object and a component. Software components are exactly the same. Later we will come back and revisit the problem in a greater level of detail. which signals are outputs and so on. You should be familiar with the way that. some parts are not "hard wired" to the system. because it means that I can buy a new graphics adapter at any time and fit it into the machine to improve the performance. For this to work properly the people who make main boards and the people who make graphics adapters have had to agree on an interface between two devices. 4.Creating Solutions From Object to Component Programmer’s Point: Consider the International Issues The code above assembles a text message and sends it to the user when something bad happens. in a typical home computer. we just say "We need an account here" and then move on to other things. and from the point of view of what the Account class needs to do. for example which signals are inputs. This is the progress that we have made so far: representing values by named locations (variables) creating actions which work on the variables (statements and blocks) putting behaviours into lumps of code which we can give names to. the graphics adapter is usually a separate device which is plugged into the main board.. and how to design systems using them. Posh people call this "abstraction". During the specification process you need to establish if the code is ever going to be created in multiple language versions. Any main board which contains a socket built to the standard can accept a graphics card. If it is you will need to manage the storage and selection of appropriate messages.8. However.8 From Object to Component I take the view that as you develop as a software writer you go through a process of "stepping back" from problems and thinking at higher and higher levels. The next thing to do is consider how we take a further step back and consider expressing a solution using components and interfaces. enters their name and address and this is used to create the new account" this gives you a good idea of what parameters should be supplied to the constructor. from the point of view of hardware. So. if the manager says something like "The customer fills in a form. This takes the form of a large document which describes exactly how the two components interact. C# Programming © Rob Miles 2010 104 . and not what the system itself actually does. 4. That said. Fortunately there are some C# libraries which are designed to make this easier.1 Components and Hardware Before we start on things from a software point of view it is probably worth considering things from a hardware point of view. since they really relate to how the specification is implemented. components are possible because we have created standard interfaces which describe exactly how they fit together. Bank Notes: Constructing an Account The issues revolving around the constructor of a class are not directly relevant to the bank account specification as such. if you write the program as above this might cause a problem when you install the code in a French branch of the bank. And quite right too.8.e. 4. It sets out a number of methods which relate to a particular task or role. we can use anything which behaves like an Account in this position. By describing objects in terms of their interfaces however. we might be asked to create a "BabyAccount" class which only lets the account holder draw out up to ten pounds each time. decimal GetBalance (). Please don’t be tempted to answer an exam question about the C# interface mechanism with a long description of how windows and buttons work. and then we create those parts. In C# we express this information in a thing called an interface. in this case what a class must do to be considered a bank account. This might happen even after we have installed the system and it is being used. } This says that the IAccount interface is comprised of three methods. it is unfortunately the case that with our bank system we may have a need to create different forms of bank account class. If you don’t do this your programs will compile fine. Interfaces and Design So. Well. and compiled in the same way. since the compiler has no opinions on variable names. It is not obvious at this stage why components are required. i. Programmer’s Point: Interface names start with I We have seen that there are things called coding conventions. which set down standards for naming variables. a system designed without components is exactly like a computer with a graphics adapter which part of the main board. An interface is simply a set of method definitions which are lumped together. bool WithdrawFunds ( decimal amount ). one to pay money in. For example. Another convention is that the name of an interface should start with the letter I. If everything has been hard wired into place this will be impossible. These are usually either text based (the user types in commands and gets responses) or graphical (the user clicks on ―buttons‖ on a screen using the mouse). An interface is placed in a source file just like a class. From the balance management point of view this is all we need.2 Components and Interfaces One point I should make here is that we are not talking about the user interface to our program. but you may have trouble sleeping at night. another to withdraw it and a third which returns the balance on the account. When we are creating a system we work out what each of the parts of it need to do. The user interface is the way a person using our program would make it work for them. Our first pass at a bank account interface could be as follows: public interface IAccount { void PayInFunds ( decimal amount ). C# Programming © Rob Miles 2010 105 . Note that at the interface level I am not saying how it should be done. It is not possible for me to improve the graphics adapter because it is "hard wired" into the system. However.Creating Solutions From Object to Component Why we Need Software Components? At the moment you might not see a need for software components. what it is they have to do. instead of starting off by designing classes we should instead be thinking about describing their interfaces. This will earn you zero marks. An interface on the other hand just specifies how a software component could be used by another software component. I am instead just saying what should be done. return true. it has a corresponding implementation. here are two: C# Programming © Rob Miles 2010 106 .3 Implementing an Interface in C# Interfaces become interesting when we make a class implement them.CustomerAccount' does not implement interface member 'AccountManagement. } public void PayInFunds ( decimal amount ) { balance = balance + amount ..IAccount. irrespective of what it really is: public class CustomerAccount : IAccount { private decimal balance = 0. The only difference is the top line: public class CustomerAccount : IAccount { . I am going to create a class which implements the interface. You can think of me in a whole variety of ways. If a class implements an interface it is saying that for every method described in the interface. If the class does not contain a method that the interface needs you will get a compilation error: error CS0535: 'AccountManagement.Creating Solutions From Object to Component 4. In the case of the bank account.4 References to Interfaces Once we have made the CustomerAccount class compile.. } balance = balance .8. } public decimal GetBalance () { return balance.PayInFunds(decimal)' In this case I missed out the PayInFunds method and the compiler complained accordingly.amount . Implementing an interface is a bit like a setting up a contract between the supplier of resources and the consumer. } } The code above does not look that different from the previous account class.. The highlighted part of the line above is where the programmer tells the compiler that this class implements the IAccount interface. 4. so that it can be thought of as an account component. public bool WithdrawFunds ( decimal amount ) { if ( balance < amount ) { return false . } } C# Programming © Rob Miles 2010 107 . This implements all the required methods. It is simply a way that we can refer to something which has that ability (i. 4.e. rather than the particular type that they are. In C# terms this means that we need to be able to create reference variables which refer to objects in terms of interfaces they implement. There is no such physical thing as a "lecturer". I can create a BabyAccount class which implements the IAccount interface. } balance = balance . From the point of view of the university. person who implements that interface). } public decimal GetBalance () { return balance. And you can use the same methods with any other lecturer (i. The compiler will check to make sure that CustomerAccount does this. this means that we want to deal with objects in terms of IAccount. So.amount . rather than Rob Miles the individual. account.5 Using interfaces Now that we have our system designed with interfaces it is much easier to extend it. it is much more useful for it to think of me as a lecturer. It turns out that this is quite easy: IAccount account = new CustomerAccount(). but they behave slightly differently because we want all withdrawals of over ten pounds to fail: public class BabyAccount : IAccount { private decimal balance = 0. which has to manage a large number of interchangeable lecturers. This is the same in real life.PayInFunds(50). merely a large number of people who can be referred to as having that particular ability or role. In the case of our bank. and if it does. public bool WithdrawFunds ( decimal amount ) { if (amount > 10) { return false . } public void PayInFunds ( decimal amount ) { balance = balance + amount . return true. The account variable is allowed to refer to objects which implement the IAccount interface.Creating Solutions From Object to Component Rob Miles the individual (because that is who I am) A university lecturer (because that is what I can do) If you think of me as a lecturer you would be using the interface that contains methods like GiveLecture. with interfaces we are moving away from considering classes in terms of what they are.e.(the set of account abilities) rather than CustomerAccount (a particular account class). } if (balance < amount) { return false .8. Note that there will never be an instance of IAccount interface. the compilation is successful. contains the required methods). and starting to think about them in terms of what they can do.. ISpecialOffer for example). Each interface is a new way in which it can be referred to and accessed. For example.Creating Solutions From Object to Component The nice thing about this is that as it is a component we don’t have to change all the classes which use it. what I really want is a way that I can regard an object in terms of its ability to print. A class can implement as many interfaces as it needs. before you write any code at all.8.. I create the interface: public interface IPrintToPaper { void DoPrint (). The rest of the system can then pick up this object and use it without caring exactly what it is. IPrintToPaper { . 4.8. public class BabyAccount : IAccount. There are also graphical tools that you can use to draw formal diagrams to represent this information. This would be reasonable if all I ever wanted to print was bank accounts. The IAccount interface lets me regard a component purely in terms of its ability to behave as a bank account. The field of Software Engineering is entirely based on this process. However. You should also have spotted that interfaces are good things to hang tests on. 4. but using the new kind of account in our existing system is very easy. what is important to the customer. If you have a set of fundamental behaviours that all bank accounts must have (for example C# Programming © Rob Miles 2010 108 . the bank will want the account to be able to print itself out on paper. for example warning letters. I don't want to have to provide a print method in each of these.6 Implementing Multiple Interfaces A component can implement as many interfaces as are required. However. Each of these items will be implemented in terms of a component which provides a particular interface (IWarning. I may want to regard a component in a variety of ways.7 Designing with Interfaces If you apply the "abstraction" technique properly you should end up with a system creation process which goes along the lines of: gather as much metadata as you can about the problem. You might think that all I have to do is add a print method to the IAccount interface. there will be lots of things which need to be printed. We will of course have to create some tests especially for it. special offers and the like.. } Now anything which implements the IPrintToPaper interface will contain the DoPrint method and can be thought of in terms of its ability to print. When we create the account objects we just have ask if a standard account or a baby account is required. so that we can make sure that withdrawals of more than ten pounds do fail. This means that a BabyAccount instance behaves like an account and it also contains a DoPrint method which can be used to make it print out. This is actually very easy. the manager has told us that each bank account must have an account number. interface IAccount { int GetAccountNumber (). We could use these in our Account constructor to create a GUID which allows each account to have a unique number.). and more a promise. The interface mechanism gives us a great deal of flexibility when making our components and fitting them together. I have to add comments to give more detail about what the method does. We don't care what the method GetAccountNumber actually does. Inheritance lets a class pick up behaviours from the class which is its parent. This is the real detail in the specification. So this requirement ends up being expressed in the interface that is implemented by the account class. For example. as long as it always returns the value for a particular account. This is a very important value. In fact. } This method returns the integer which is the account number for this instance. It is a way that we can pick up behaviours from classes and just modify the bits we need to make new ones. The need for things like account numbers. In this respect you can regard it as a mechanism for what is called code reuse.Creating Solutions Inheritance paying in money must always make the account balance go up) then you can write tests that bind to the IAccount interface and can be used to test any of the bank components that are created. They state that we have a need for behaviours. The design of the interfaces in a system is just this.9 Inheritance Inheritance is another way we can implement creative laziness. Each GUID is unique in the world. Just because a class has a method called PayInFunds does not mean that it will pay money into the account. it just means that a method with that name exists within the class. in that it will be fixed for the life of the account and can never be changed. but we have not actually described how this should be done. we sometimes use this to good effect when building a program. Programmer’s Point: Interfaces are just promises An interface is less of a binding contract. not precisely how it does it. If a class is descended from a particular parent class this C# Programming © Rob Miles 2010 109 . By placing it in the interface we can say that the account must deliver this value. These are data items which are created based on the date. You can regard an interface as a statement by a class that it has a set of behaviours because it implements a given interface. that is down to how much you trust the programmer that made the class that you are using. but they do not necessarily state how they are made to work. has resulted in the creation of a set of methods in the C# libraries to create things called Globally Unique Identifiers or GUIDs. No two accounts should ever have the same number. It means that once we have found out what our bank account class needs to hold for us we can then go on to consider what we are going to ask the accounts to do. Once we have set out an interface for a component we can then just think in terms of what the component must do. and how good your tests are. It can also be used at the design stage of a program if you have a set of related objects that you wish to create. which really need to be unique in the world. time and certain information about the host computer. in that we can create "dummy" components which implement the interface but don't have the behaviour as such. 4. although BabyAccount does not have a PayInFunds method.e. the BabyAccount class has no behaviours of its own. We need to create a BabyAccount class which contains a lot of code which is duplicated in the CustomerAccount class. It turns out that we can do this in C# using inheritance. b. I have put the name of the class that BabyAccount is extending. In fact. C# Programming © Rob Miles 2010 110 . This works because. and only once.1 Extending a parent class We can see an example of a use for inheritance in our bank account project. And a lot of the mistakes that I make are caused by improper use of block copy. But: Programmer’s Point: Block Copy is Evil I still make mistakes when I write programs. When I create the BabyAccount class I can tell the compiler that it is based on the CustomerAccount one: public class BabyAccount : CustomerAccount. Try not to do this. But this does make things a bit tiresome when we write the program. These can be introduced and work alongside the others because they behave correctly (i. We can even create brand new accounts at any time after the system has been deployed. If you need to use it in more than one place. Wrong. Baby accounts are only allowed to draw up to 10 pounds out at a time. I can now write code like: BabyAccount b = new BabyAccount(). This means that the PayInFunds method from the CustomerAccount class is used at this point. they implement the interface). We have solved this problem from a design point of view by using interfaces. instances of the BabyAccount class have abilities which they pick up from their parent class. I write some code and find that I need something similar. Then I change most. This means that everything that CustomerAccount can do. at the moment. but not all. "This is not a problem" you probably think "I can use the editor block copy to move the program text across". of the new code and find that my program doesn't work properly. We have already noted that a BabyAccount must behave just like a CustomerAccount except in respect of the cash withdrawal method. You might think that after such a huge number of years in the job I get everything right every time. but not exactly the same. in another part of the program. What we really want to do is pick up all the behaviours in the CustomerAccount and then just change the one method that needs to behave differently. In short: Interface: "I can do these things because I have told you I can" Inheritance: "I can do these things because my parent can" 4.9. Customer accounts can draw out as much as they want.PayInFunds(50). A great programmer writes every piece of code once. By separating the thing that does the job from the description of the job (which is what an interface lets you do) we can get the whole banking system thinking in terms of IAccount and then plug in accounts with different behaviours as required. So I use block copy. BabyAccount can do.IAccount { } The key thing here is the highlighted part after the class name. So. the parent class does. make it a method. it gets everything from its parent.Creating Solutions Inheritance means that it has a set of behaviours because it has inherited them from its parent. amount . This is because it must call an overridden method in a slightly different way from a "normal" one.WithdrawFunds(5). but if you don’t have the word present. In the BabyAccount class I can do it like this: public class BabyAccount : CustomerAccount. there is one other thing that we need to do in order for the overriding to work. The C# compiler needs to know if a method is going to be overridden. the above code won't compile properly because the compiler has not been told that WithDrawFunds might be overridden in classes which are children of the parent class. public virtual bool WithdrawFunds ( decimal amount ) { if ( balance < amount ) { return false . In other words. return true.2 Overriding methods We now know that we can make a new class based on an existing one.IAccount { public override bool WithdrawFunds (decimal amount) { if (amount > 10) { return false . } } The keyword virtual means ―I might want to make another version of this method in a child class‖. We want to replace the WithdrawFunds method with a new one. b.PayInFunds(50). Virtual Methods Actually. You don’t have to override the method.Creating Solutions Inheritance 4. This means that code like: BabyAccount b = new BabyAccount(). } balance = balance . } if (balance < amount) { return false . return true. C# Programming © Rob Miles 2010 111 . The call of PayInFunds will use the method in the parent (since that has not been overridden) but the call of WithdrawFunds will use the method in BabyAccount.9. The next thing we need to be able to do is change the behaviour of the one method that we are interested in. To make the overriding work correctly I have to change my declaration of the method in the CustomerAccount class.amount . b. public class CustomerAccount : IAccount { private decimal balance = 0. This is called overriding a method. you definitely can’t. } balance = balance . } } The keyword override means "use this version of the method in preference to the one in the parent". This is because the balance value in the CustomerAccount class is private. I can use this to make the WithDrawFunds method in my BabyAccount much simpler: C# Programming © Rob Miles 2010 112 . We carefully made it private so that methods in other classes can’t get hold of the value and change it directly. We have already noted that we don’t like this much. Every class has a parent and can do all the things that the parent can do. in that it means that the balance value has to be made more exposed than we might like.3 Using the base method Remember that programmers are essentially lazy people who try to write code only once for a given problem. And we would have written this down in the specification.. the balance is very important to me and I’d rather that nobody outside the CustomerAccount class could see it. public class CustomerAccount : IAccount { protected decimal balance = 0. } I’m not terribly happy about doing this.Creating Solutions Inheritance This makes override and virtual a kind of matched pair. However. it looks as if we are breaking our own rules here. To get around this problem C# provides a slightly less restrictive access level called protected. this protection is too strict. The word base in this context means ―a reference to the thing which has been overridden‖. Bank Notes: Overriding for Fun and Profit The ability to override a method is very powerful. Of course this should be planned and managed at the design stage.9. methods in the BabyAccount class can see and use a protected member because they are in the same class hierarchy as the class containing the member. Well. It also has access to all the protected members of the classes above it. You use virtual to mark a method as able to be overridden and override to actually provide a replacement for the method. . Protection of data in class hierarchies It turns out that the code above still won’t work. for now making this change will make the program work. in that it stops the BabyAccount class from being able to change the value. Fortunately the designers of C# have thought of this and have provided a way that you can call the base method from one which overrides it.. It means that we can make more general classes (for example the CustomerAccount) and customise it to make them more specific (for example the BabyAccount). A class hierarchy is a bit like a family tree. This calls for more metadata to be gathered from the customer and used to decide which parts of the behaviour need to be changed during the lift of the project. Later we will see better ways to manage this situation. in that the WithDrawFunds method in the BabyAccount class contains all the code of the method in the parent class. This makes the member visible to classes which extend the parent.. However. 4. In other words. We would have made the WithDrawFunds method virtual because the manager would have said ―We like to be able to customise the way that some accounts withdraw funds‖.. Note that there are other useful spin-offs here. and then it is fixed for all the classes which call back to it. } } The problem with this way of working is that you are unable to use base. This is because in this situation there is no overriding.e. IAccount { public override bool WithdrawFunds (decimal amount) { if (amount > 10) { return false . } balance = balance . Because the method call returns a bool result I can just send whatever it delivers. return true. the one that the method overrides.Creating Solutions Inheritance public class BabyAccount : CustomerAccount. The use of the word base to call the overridden method solves both of these problems rather beautifully. } } The very last line of the WithDrawFunds method makes a call to the original WithDrawFunds method in the parent class. you have just supplied a new version of the method (in fact the C# compiler will give you a warning which indicates that you should provide the keyword new to indicate this): public class BabyAccount : CustomerAccount. in the top level class. This makes it more difficult to pick up behaviours from parent classes. } if (balance < amount) { return false .9. and why I’m doing it: I don’t want to have to write the same code twice I don’t want to make the balance value visible outside the CustomerAccount class. i. 4. By making this change I can put the balance back to private in the CustomerAccount because it is not changed outside it. but don’t worry too much since it actually does make sense when you think about it. If I leave it out (and leave out the override too) the program seems to work fine.IAccount { public new bool WithdrawFunds (decimal amount) { if (amount > 10) { return false . If you play around with C# you will find out that you don’t actually seem to need the virtual keyword to override a method. } return base. It is important that you understand what I’m doing here.4 Making a Replacement Method This bit is rather painful. C# Programming © Rob Miles 2010 113 .WithdrawFunds(amount).amount . If I need to fix a bug in the behaviour of the WithDrawFunds method I just fix it once. 9.. Bank Notes: Protect Your Code As far as the bank application is concerned.. i. 4. If you want to have a policy of allowing programmers to make custom versions of classes in this way it is much more sensible to make use of overriding since this allows a well-managed way of using the method that you over-rid. And yet a naughty programmer could write their own and override or replace the one in the parent: public new decimal GetBalance () { return 1000000. is that you can mark a class as sealed. The rules are that you can only seal an overriding method (which means that we can’t seal the GetBalance virtual method in the CustomerAccount class) and you can still replace a sealed method. In fact. One of the unfortunate things about this business is that you will have to allow for the fact that people who use your components might not all be nice and trustworthy.Creating Solutions Inheritance Programmer’s Point: Don’t Replace Methods I am very against replacing methods rather than overriding them. Unfortunately this is rather hard to use. which has a bit more potential. just remember that when you create a program this is another risk that you will have to consider. it always returns a balance value of a million pounds! A naughty programmer could insert this into a class and give himself a nice spending spree. However. it cannot be used as the basis for another class.. public sealed class BabyAccount : CustomerAccount. } This is the banking equivalent of the bottle of beer that is never empty. C# Programming © Rob Miles 2010 114 .. and if it didn’t all make sense there is no particular need to worry. What this means is that we need a way to mark some methods as not being able to be overridden.e. But they will want to have confidence in the code that you make.5 Stopping Overriding Overriding is very powerful. the customer will not have particularly strong opinions on how you use things like sealed in your programs. } The compiler will now stop the BabyAccount from being used as the basis of another account. C# does this by giving us a sealed keyword which means ―You can’t override this method any more‖. For a programming course at this level it is probably a bit heavy handed of me to labour this point just right now. No matter how much cash is drawn out. overriding/replacing is not always desirable. I’m wondering why I mentioned this at all. Consider the GetBalance method. This goes well with a design process which means that as you move down the ―family tree‖ of classes you get more and more specific. This means that the class cannot be extended. This is never going to need a replacement. It means that a programmer can just change one tiny part of a class and make a new one with all the behaviours of the parent.. This means that you should take steps when you design the program to decide whether or not methods should be flagged as virtual and also make sure that you seal things when you can do so.IAccount { . Another use for sealed. The code above will only work if the CustomerAccount class has a constructor which accepts two strings. However.9. balance = inBalance. They must make sure that at each level in the creation process a constructor is called to set up the class at that level. If there are some things that an account must do then we can make these abstract and then get the child classes to actually provide the implementation. Programmer’s Point: Design your class construction process The means by which your class instances are created is something you should design into the system that you build. And the account is the class which will have a constructor which sets the name and the initial balance. } But this class is an extension of the Account class. You might think that I could solve this by writing a constructor a bit like this: public CustomerAccount (string inName. 4. inBalance) { } The base keyword is used in the same way as this is used to call another constructor in the same class. the proper version of the customer account constructor is as follows: public CustomerAccount (string inName. For example. I can use it to force a set of behaviours on items in a class hierarchy.7 Abstract methods and classes At the moment we are using overriding to modify the behaviour of an existing parent method. The keyword base is used to make a call to the parent constructor. The constructor above assumes that the Account class which CustomerAccount is a child of has a constructor which accepts two parameters. It is part of the overall architecture of the system that you are building. This C# Programming © Rob Miles 2010 115 . Constructor Chaining When considering constructors and class hierarchies you must therefore remember that to create an instance of a child class an instance of the parent must first be created. to create a CustomerAccount you must first create an Account. In other words. The result of this is that programmers must take care of the issue of constructor chaining. decimal inBalance) : base ( inName. I think of these things as a bit like the girders that you erect to hold the floors and roof of a large building. It is used by a programmer to allow initial values to be set into an object: robsAccount = new CustomerAccount("Rob Miles". it is also possible to use overriding in a slightly different context. In other words. to make a CustomerAccount I have to make an Account.9. They tell programmers who are going to build the components which are going to implement the solution how to create those components. the name and the address of the new customer. in the context of the bank application we might want to provide a method which creates a warning letter to the customer that their account is overdrawn. It is of course very important that you have these designs written down and readily available to the development team.6 Constructors and Hierarchies A constructor is a method which gets control during the process of object creation. In other words.Creating Solutions Inheritance 4. decimal inBalance) { name = inName. In this situation the constructor in the child class will have to call a particular constructor in the parent to set that up before it is created. This means that a constructor in the parent must run before the constructor in the child. the first a string and the second a decimal value. "Hull"). This means that at the time we create the bank account system we know that we need this method. If you want to make an instance of a class based on an abstract parent you must provide implementations of all the abstract methods given in the parent. An instance of Account would not know what to do it the RudeLetterString method was ever called. If you think about it this is sensible. This can be useful because it means you don’t have to repeatedly implement the same methods in each of the components that implement a particular interface. However is true. This leads us to a class design a bit like this: C# Programming © Rob Miles 2010 116 . Perhaps at this point a more fully worked example might help. If you want to implement interfaces as well. but we don’t know precisely what it does in every situation. The methods in the second category must be made abstract. } The fact that my new Account class contains an abstract method means that the class itself is abstract (and must be marked as such). We could just provide a ―standard‖ method in the CustomerAccount class and then rely on the programmers overriding this with a more specific message but we then have no way of making sure that they really do provide the method. C# provides a way of flagging a method as abstract. It is not possible to make an instance of an abstract class. you may have to repeat methods as well. so you can only pick up the behaviours of one class. in that an interface also provides a ―shopping list‖ of methods which must be provided by a class. Abstract classes and interfaces You might decide that an abstract class looks a lot like an interface. abstract classes are different in that they can contain fully implemented methods alongside the abstract ones.. This means that the method body is not provided in this class. An abstract class can be thought of as a kind of template. The problem is that you can only inherit from one parent. } public virtual decimal GetBalance () { return balance. } } public class BabyAccount : Account { public override bool WithdrawFunds ( decimal amount ) { if (amount > 10) { return false . } public override string RudeLetterString() { return "Tell daddy you are overdrawn". } return base. } } C# Programming © Rob Miles 2010 117 . bool WithdrawFunds ( decimal amount ). } balance = balance . } public abstract class Account : IAccount { private decimal balance = 0.WithdrawFunds(amount). public abstract string RudeLetterString(). decimal GetBalance ().Creating Solutions Inheritance public interface IAccount { void PayInFunds ( decimal amount ). public virtual bool WithdrawFunds ( decimal amount ) { if ( balance < amount ) { return false . } public void PayInFunds ( decimal amount ) { balance = balance + amount .amount . string RudeLetterString(). } } public class CustomerAccount : Account { public override string RudeLetterString() { return "You are overdrawn" . return true. That is because.e. as we can consider something as an ―account‖ rather than a BabyAccount. even though I now have this abstract structure I still want to think of the account objects in terms of their ―accountness‖ rather than any particular specific type. Broadly: Interface: lets you identify a set of behaviours (i. I can now use their accounts. Note how I have moved all the things that all accounts must do into the parent Account class. If you have an understanding of what an interface and abstract classes are intended to achieve this will stand you in very good stead for your programming career. get their account objects (whatever they are called) to implement the interface and.9. If you want to create a related set of items. In other words the other bank must create the methods in the IAccount interface.. Any component which implements the interface can be thought of in terms of a reference of that interface type. This might seem useful. References to abstract classes References to abstract classes work just like references to interfaces. However. Objects can implement more than one interface. hey presto. including credit card. Interfaces let me describe a set of behaviours which a component can implement. If their accounts are software components too (and they should be) then all we have to do is implement the required interfaces at each end and then our systems understand each other. current account etc. I much prefer it if you manage references to abstract things (like accounts) in terms of their interface instead. 4. Once a component can implement an interface it can be regarded purely in terms of a component with this ability. then the best way to do this is to set up a parent class which contains abstract and non-abstract methods. Note also though that I have left the interface in place. Use Interface References One important consideration is that even if you make use of an abstract parent class I reckon that you should still make use of interfaces to reference the data objects themselves. methods) which a component can be made to implement. A reference to an Account class can refer to any class which extends from that parent. allowing them to present different faces to the systems that use them. Bank Notes: Making good use of interface and abstract If our bank takes over another bank and wants to share account information we might need a way to use their accounts. Then I have added customised methods into the child classes where appropriate. for example all the different kinds of bank account you might need to deal with. Abstract: lets you create a parent class which holds template information for all the classes which extend it. deposit account. C# Programming © Rob Miles 2010 118 . This gives you a degree of flexibility that you can use to good effect.8 Designing with Objects and Components For the purpose of this part of the text you now have broad knowledge of all the tools that can be used to design large software systems. The child classes can make use of the methods from the parent and override the ones that need to be provided differently for that particular class. A concrete example of this would be something like IPrintHardCopy.Creating Solutions Inheritance This code repays careful study. Then our printer can just regard each of the instances that implement this interface purely in this way. WriteLine(i).10. C# Programming © Rob Miles 2010 119 .9. Console. We have also seen that you can extend a parent object to create a child which has all the abilities of the parent.10 Object Etiquette We have considered objects "in the large". don’t worry. if I write: public class Account { . Interfaces let me describe what each component can do. These features of C# are tied up with the process of software design which is a very complex business. It is in fact a child of the object class. If you don’t get it now. Class hierarchies let me re-use code inside those components. The Object class When you create a new class this is not actually created from nowhere. Now it is time to find out how this is achieved. The important point to bear in mind is that the features are all provided so that you can solve one problem: Create software which is packaged in secure. and everything is a child of the object class. In other words. A reference to an object type can refer to any class. This has a couple of important ramifications: Every object can do what an object can do.9 Don’t Panic This is all deep stuff. but very important.1 Objects and ToString We have taken it as read that objects have a magical ability to print themselves out. This will print out: 99 The integer somehow seems to know how to print itself out.this is equivalent to writing: public class Account : object { The object class is a part of C#. And that is it. If I write the code: int i = 99. What we need to do now is take a look at some smaller. It turns out that this is all provided by the "objectness" of things in C#.Creating Solutions Object Etiquette 4. 4. interchangeable components. and also how we can give our own objects the same magical ability. (in fact we have seen that the whole basis of building programs is to decide what the objects should do and then make them do these things). plus the new ones that we add. Now we are going to see how these abilities of objects are used in making parts of the C# implementation itself work. in that we know how they can be used to design and implement large software systems. issues that relate to how we use objects in our programs. We know that an object can contain information and do things for us. 4. In other words: object o = new object(). Console. } public Account (string inName. . and so if it ever needs the string version of an object it will call this method on the object to get the text. public override string ToString() { return "Name: " + name + " balance: " + balance. } } In the tiny Account class above I've overridden the ToString method so that it prints out the name and balance value. balance = inBalance. decimal inBalance) { name = inName. This is sometimes useful if you add some data to a child class and want to print out the content of the parent first: public override string ToString() { return base.would print out: Name: Rob balance: 25 So.ToString() + " Parent : " + parentName. . the object. This means that the code: Account a = new Account("Rob". 25). you can use the base mechanism to do this.ToString()).and the results would be exactly the same. The nice thing about ToString is that it has been declared virtual. The object implementation of ToString returns a string description of the type of that object. If you look inside the actual code that makes an object work you will find a method called ToString.WriteLine(a). This means that we can override it to make it behave how we would like: class Account { private string name. the first point is the one which has the most importance here. private decimal balance. from the point of view of good etiquette. Console. Getting the string description of a parent object If you want to get hold of a string description of the parent object.WriteLine(o).would print out: System.WriteLine(o. . The ToString method The system knows that ToString exists for every object.Object You can call the method explicitly if you like: Console. It means that all classes that are made have a number of behaviours that they inherit from their ultimate parent.Creating Solutions Object Etiquette For the purpose of this part of the notes. } C# Programming © Rob Miles 2010 120 . whenever you design a class you should provide a ToString method which provides a text version of the content of that class. Point missilePosition = new Point().2 Objects and testing for equals We have seen that when object references are compared a test for equals does not mean the same as it does for values. The problem is that the above program code does not work. if ( spaceshipPosition == missilePosition ) { Console. To do this we must override the standard Equals behaviour and add one of our own: C# Programming © Rob Miles 2010 121 . but I do want my program to run quickly. since it will just make use of the upgraded method. Even though I have put the spaceship and the missile at the same place on the screen the word Bang is not printed. Adding your own Equals method The way that you solve this problem is to provide a method which can be used to compare the two points and see if they refer to the same place.y = 2. } Note that I've made the x and y members of the Point class public. missilePosition. In the game the various objects in it will be located at a particular place on the screen.WriteLine("Bang"). missilePosition. We then might want to test to see if two items have collided. This class extends the CustomerAccont and holds the name of the child's parent.Creating Solutions Object Etiquette The method above is from a ChildAccount class. When we perform an equals test the system simply checks to see if both references refer to the same location. We can express this position as a coordinate or point. To see how this might cause us problems we need to consider how we would implement a graphical computer game (makes a change from the bank for a while). I can now create instances of Point and use them to manage my game objects: Point spaceshipPosition = new Point().10. Some of the nastiest bugs that I've had to fix have revolved around programmers who have forgotten which test to use. } This is my point class. take a look at the test that is being performed. i. public int y. We know that objects are managed by named tags which refer to unnamed items held in memory somewhere. new members are added or the format of the string changes. class Point { public int x. the ChildAccount class does not have to change. they are not located at the same address in memory.y = 2. This is because I'm not that concerned about protecting them. spaceshipPosition.x = 1. with an x value and a y value.e. spaceshipPosition. Programmer’s Point: Make sure you use the right equals As a programmer I must remember that when I'm comparing objects to see if they contain the same data I need to use the Equals method rather than the == operator. The code above uses the ToString method in the parent object and then tacks the name of the parent on the end before returning it. If you find that things that contain the same data are not being compared correctly. The nice thing about this is that if the behaviour of the parent class changes. 4.x = 1. This is because although the two Point objects hold the same data. which means that the equals test will fail. Programmer’s Point: Equals behaviours are important for testing The customer for our bank account management program is very keen that every single bank account that is created is unique.. there is a very good reason why you might find an equals behaviour very useful. Bank Notes: Good Manners are a Good Idea It is considered good manners to provide the Equals and ToString methods in the classes that you create. The first thing we need to do is create a reference to a Point. because the Equals method actually compares the content of the two points rather than just their references. If the bank ever contains two identical accounts this would cause serious problems. However. If they are both the same the method returns true to the caller. and so I reckon you should always provide one. It is also very useful to make appropriate use of this when writing methods in classes.y == y ) ) { return true. The object is cast into a Point and then the x and y values are compared.Equals(spaceshipPosition) ) { Console.WriteLine("Bang"). We need to do this because we want to get hold of the x and y values from a Point (we can't get them from an object). if ( ( p. When you start to create your bank account management system you should arrange a meeting of all the programmers involved and make them aware that you will be insisting on good mannered development like this. These will allow your classes to fit in with others in the C# system. the Equals method is sometimes used by C# library methods to see if two objects contain the same data and so overriding Equals makes my class behave correctly as far as they are concerned. why should I waste time writing code to compare them in this way?” However. Note that this reference is supplied as a reference to an object.x == x ) && ( p. I could have written one called TheSame which did the job. } else { return false. The fact that everything in the system is required to be unique might lead you to think that there is no need to provide a way to compare two Account instances for equality. In fact. Note that I didn't actually need to override the Equals method. for a professional approach you should set out standards which establish which of these methods you are going to provide. You will expect all programmers to write to these standards if they take part in the project. In this situation an equals behaviour is important. } This test will work. This means that I can write code like: if ( missilePosition. } } The Equals method is given a reference to the thing to be compared.Creating Solutions Object Etiquette public override bool Equals(object obj) { Point p = (Point) obj. C# Programming © Rob Miles 2010 122 . in front of each use of a member of the class.10. A new bank account could store itself in a bank by passing a reference to itself to a method that will store it: bank.Data). I want to use the word this to mean this. Perhaps the best way to get around the problem is to remember that when I use the word this I mean "a reference to the currently executing instance of a class". The data is a counter. Confusion with this I reckon that using this is a good idea. However it might take a bit of getting used to. if we like to make it explicit that we are using a member of a class rather than a local variable.3 Objects and this By now you should be used to the idea that we can use a reference to an object to get hold of the members of that object. Console. Of course.WriteLine("Count : " + c. It means that people reading my code can tell instantly whether I am using a local variable or a member of the class. then don't worry about it for now.Data + 1. If I have a member of my class which contains methods. If this hurts your head. and I want to use one of those methods. This calls the method and then prints out the data. this as a reference to the current instance I hate explaining this. When a method in a class accesses a member variable the compiler automatically puts a this. } } The class above has a single data member and a single method member. the "proper" version of the Counter class is as follows: public class Counter { public int Data=0. public void Count () { Data = Data + 1. I end up writing code like this: C# Programming © Rob Miles 2010 123 . The Store method accepts this and then stores this somehow.Creating Solutions Object Etiquette 4. but this also has a special meaning within your C# programs. When the Store method is called it is given a reference to the currently executing account instance. c. } } We can add a this. Consider: public class Counter { public int Data=0. I can use the class as follows: Counter c = new Counter(). (dot) means "follow the reference to the object and then use this member of the class". Each time the Count method is called the counter is made one larger.Count(). public void Count () { this. We know that in this context the . in this situation we are not passing an account into the bank. instead we are passing a reference to the account. Passing a reference to yourself to other classes Another use for this is when an instance class needs to provide a reference to itself to another class that wants to use it.Store(this).Data = this. In other words. 4.Creating Solutions The power of strings and chars this. transformed in the way that you ask.11. To find out more about this. take a look at section 4. s2 = "different". because C# regards an instance of a string type in a special way. A string can be regarded as either an object (referred to by means of a reference) or a value (referred to as a value). Consider the situation where you are storing a large document in the memory of the computer. The methods will return a new string. This does not happen though. after the assignment s1 and s2 no longer refer to the same object. It is very important that you understand what happens when you transform a string. 4. when the system sees the line: s2 = "different". This hybrid behaviour is provided because it makes things easier for us programmers. . You might ask the question: "Why go to all the trouble?" It might seem all this hassle could be saved by just making strings into value types. Well. The thing that s1 is referring to is unchanged. In other words.SetName("Rob"). The second statement made the reference s2 refer to the same object as s1. It calls it immutable.11. If you think you know about objects and references. This behaviour. you should be expecting s1 to change when s2 is changed. no. string s2=s1. I regard them as a bit like bats. Console. This is because it gives you a lot of nice extra features which will save you a lot of work. You can sort out the case of the text. C# Programming © Rob Miles 2010 124 . because they seem to break some of the rules that we have learnt. 4.1 String Manipulation Strings are rather special.2 Immutable strings The idea is that if you try to change a string.account.1. 4. This saves memory and it also makes searching for words much faster.WriteLine(s1 + " " + s2). All the occurrences in the text can just refer to that one instance. This is because programmers want strings to behave a bit like values in this respect. This means "I have a member variable in this class called account.it makes a new string which contains the text "different" and makes s2 refer to that. Call the SetName method on that member to set the name to 'Rob'".11 The power of strings and chars It is probably worth spending a few moments considering the string type in a bit more detail. so changing s2 should change the object that s1 refers to as well. the C# system instead creates a new string and makes the reference you are "changing" refer to the changed one. However it does mean that we have to regard strings as a bit special when you are learning to program. So. never allowing a thing to be changed by making a new one each time it is required. is how the system implements immutable. These are exposed as methods which you can call on a string reference. they don't actually behave like objects all the time. A bat can be regarded as either an animal or a bird in many respects. string s1="Rob". This is because. By using references we only actually need one string instance with the word ―the‖ in it. trim spaces off the start and end and extract sub-strings using these methods. although strings are objects. Substring(1. It is also possible to use the same methods on them to find out how long they are: Console. s1=s1.WriteLine("The same"). modified.11. This would set the character variable firstCh to the first character in the string. You can leave out the second parameter if you like. versions of themselves in slightly different forms.Equals(s2) ) { Console.would cause a compilation error because strings are immutable.Substring(2). You can pull a sequence of characters out of a string using the SubString method: string s1="Rob". C# Programming © Rob Miles 2010 125 . The first parameter is the starting position and the second is the number of characters to be copied. This would leave the string "ob" in s1. 4.3 String Comparison The special nature of strings also means that you can compare strings using equals and get the behaviour you want: if ( s1 == s2 ) { Console. You can use an equals method if you prefer: if ( s1.2). 4. .5 String Length All of the above operations will fail if you try to do something which takes you beyond the length of the string.Length). But in C# the comparison works if they contain the same text.(remember that strings are indexed starting at location 0). In this respect strings are just like arrays.ToUpper().would leave "les" in s1. s1=s1. However. } If s1 and s2 were proper reference types this comparison would only work if they referred to the same object.11. } 4. .Creating Solutions The power of strings and chars 4.11.WriteLine ( "Length: " + s1.WriteLine("Still the same"). The Length property gives the number of characters in the string.4 String Editing You can read individual characters from a string by indexing them as you would an array: char firstCh = name[0]. you can't change the characters: name[0] = 'R'. You do this by calling methods on the reference to get the result that you want: s1=s1.11.6 Character case Objects of type string can be asked to create new. in which case all the characters up to the end of the string are copied: string s1="Miles". No other characters in the string are changed. 4.11.9 String Twiddling with StringBuilder If you really want to twiddle with the contents of your strings you will find the fact that you can't assign to individual characters in the string a real pain.11.IsLower(ch) char. If you trim a string which contains only spaces you will end up with a string which contains no characters (i. There is a corresponding ToLower method as well.IsPunctuation(ch) char. 4. but C# provides them because they make programs slightly easier to write and simpler to read. s1=s1.e. This is useful if your users might have typed " Rob " rather than "Rob". but you can assign to characters and even replace one string with another.12 Properties Properties are useful. tab or newline You can use these when you are looking through a string for a particular character. its length is zero).7 Trimming and empty strings Another useful method is Trim. It works a lot like a string.Text namespace. It is found in the System. The reason you are suffering is that strings are really designed to hold strings.IsUpper(ch) char.IsLetter(ch) char. You should look this up if you have a need to do some proper editing. which lets us select things easily. If you don't trim the text you will find equals tests for the name will fail. 4.IsDigit(ch) char. It is also very easy to convert between StringBuilder instances and strings. This removes any leading or trailing spaces from the string. 4. There are TrimStart and TrimEnd methods to just take off leading or trailing spaces if that is what you want.Trim().8 Character Commands The char class also exposes some very useful methods which can be used to check the values of individual characters. not provide a way that they can be edited. For proper string editing C# provides a class called StringBuilder.Creating Solutions Properties The ToUpper method returns a version of the string with all the letters converted to UPPER CASE.11. These are static methods which are called on the character class and can be used to test characters in a variety of ways: char. They are a bit like the switch keyword.IsLetterOrDigit(ch) char. C# Programming © Rob Miles 2010 126 . We don't need properties. s. We have seen that we can use a member variable to do this kind of thing.Age = -100210232. This is very naughty. but we have had to write lots of extra code. 4. For example. but we need to make the member value public. I can get hold of this member in the usual way: StaffMember s = new StaffMember(). the bank may ask us to keep track of staff members. s.Age = 21.3 Using Properties Properties are a way of making the management of data like this slightly easier. An age property for the StaffMember class would be created as follows: C# Programming © Rob Miles 2010 127 .2 Creating Get and Set methods To get control and do useful things we can create get and set methods which are public.12. These provide access to the member in a managed way.WriteLine ( "Age is : " + s.GetAge() ). There is nothing to stop things like: s. One of the items that they may want to hold is the age of a member of staff.12. public int GetAge() { return this. The problem is that we have already decided that this is a bad way to manage our objects.SetAge(21). Programmer’s who want to work with the age value now have to call methods: StaffMember s = new StaffMember().age. We then make the Age member private and nobody can tamper with it: public class StaffMember { private int age. } The class contains a public member.1 Properties as class members A property is a member of a class that holds a value. I can access a public member of a class directly.age = inAge. I can do it like this: public class StaffMember { public int Age. just by giving the name of the member. Console. } public void SetAge( int inAge ) { if ( (inAge > 0) && (inAge < 120) ) { this. } } } We now have complete control over our property. but because the Age member is public we cannot stop it.Creating Solutions Properties 4.12. 4. It is also possible to add properties to interfaces. } } get { return this. s. The keyword value means ―the thing that is being assigned‖. } } C# Programming © Rob Miles 2010 128 . set.4 Properties and interfaces Interfaces are a way that you can bring together a set of behaviours. based on the same source value as was used by the other property. You do this by leaving out the statements which are the body of the get and set behaviours: interface IStaff { int Age { get. They are packaged as a list of methods which a class must contain if it implements the interfaces. When the Age property is given a value the set code is run. } } This is a new property. it returns the age in months. called AgeInMonths.12. but they are much easier to use and create.ageValue = value. Write only properties are also possible if you leave out the get. 4. It can only be read. However. } } } The age value has now been created as a property. since it does not provide a set behaviour.ageValue*12. When the Age property is being read the get code is run.Age ). The really nice thing about properties is that they are used just as the class member was: StaffMember s = new StaffMember(). public int Age { set { if ( (value > 0) && (value < 120) ) { this. This means that you can provide several different ways of recovering the same value. Note how there are get and set parts to the property. Console. I can do other clever things too: public int AgeInMonths { get { return this.WriteLine ( "Age is : " + s.Creating Solutions Properties public class StaffMember { private int ageValue. This gives us all the advantages of the methods.ageValue. These equate directly to the bodies of the get and set methods that I wrote earlier.Age = 21. You can also provide read-only properties by leaving out the set behaviour. This looks very innocent. } A programmer setting the age value can now find out if the set worked or failed. the person performing the assignment would not be aware of this.NET libraries. but it has no way of telling the user of the property that this has happened.Age = 99. With our Age property above the code: s.Creating Solutions Building a Bank This is an interface that specifies that classes which implement it must contain an Age property with both get and set behaviours.Age = 121. but I reckon that would be madness. If there is a situation where a property assignment can fail I never expose that as a property. This is OK. } C# Programming © Rob Miles 2010 129 .5 Property problems Properties are really neat.13 Building a Bank We are now in a situation where we can create working bank accounts. We can express the behaviour that we need from our bank in terms of an interface: interface IBank { IAccount FindAccount (string name).would fail. However. What we now need is a way of storing a large number of accounts. return true.12. Properties Run Code When you assign a value to a property you are actually calling a method. . It is possible to use this to advantage. The only way that a property set method could do this would be to throw an exception. I suppose that it would be possible to combine a set method and a get property. bool StoreAccount (IAccount account). 4. since there is no way that the property can return a value which indicates success or failure. We can use interfaces to define the behaviour of a bank account component. and they are used throughout the classes in the .age = inAge. A SetAge method on the other hand could return a value which indicates whether or not it worked: public bool SetAge( int inAge ) { if ( (inAge > 0) && (inAge < 120) ) { this. Unfortunately there is no way you can tell that from the code which does the assignment: s. but could result in a thousand lines of code running inside the set property. 4. This gives us a way of creating new types of account as the bank business develops. in that an object can react to and track property changes. This container class will provide methods which allow us to find a particular account based on the name of the holder. But it can also be made very confusing. which is not a good way to go on. } return false. But there are a few things that you need to be aware of when deciding whether or not to use them: Property Assignment Failure We have seen that the set behaviour can reject values if it thinks they are out of range. StoreAccount(account)) { Console. I can put an account into it and then get it back again: IBank friendlyBank = new ArrayBank (50). IAccount account = new CustomerAccount("Rob". } Note that it is very important that you understand what has happened here. if (friendlyBank. We have not created any accounts at all. The constructor creates an array of the appropriate size when it is called: private IAccount [] accounts .Creating Solutions Building a Bank A class which implements these methods can be used for the storage of accounts. What we have created is an array of references. The light coloured elements are set to null. Each reference in the array can refer to an object which implements the IAccount interface. In the code above we are creating a bank with enough room for references to 50 accounts. The method to add an account to our bank has to find the first empty location in the array and set this to refer to the account that has been added: C# Programming © Rob Miles 2010 130 . When you create an instance of an ArrayBank you tell it how many accounts you want to store by means of the constructor. accounts Name : "Rob" Balance : 0 The diagram shows the state of the accounts array after we have stored our first account.WriteLine ( "Account stored OK" ). public ArrayBank( int bankSize ) { accounts = new IAccount[bankSize]. We never place an account "in" the array.1 Storing Accounts in an array The class ArrayBank is a bank account storage system which works using arrays. 4. But at the moment none of the references refer anywhere.13. } The code above creates a bank and then puts an account into it. The element at the start of the array contains a reference to the account instance. they are all set to null. instead we put a reference to that account in the array. When we add an account to the bank we simply make one of the references refer to that account instance. printing out a message if the storage worked. 0). If it reaches the end of the array without finding a match it returns null. The bank interface provides a method called FindAccount which will find the account which matches a particular customer name: IAccount fetchedAccount = arrayBank. return true. If it finds an element which contains a null reference it skips past that onto the next one. it becomes very slow as the size of the bank increases. position<accounts.Length. If it does not find a null element before it reaches the end of the array it returns false to indicate that the store has failed. position<accounts. This is much faster than a sequential search.13. When we want to work on an account we must first find it. On a bank with only fifty accounts this is not a problem. 4. } } return false. otherwise it returns a reference to the account that it found. since it uses a technique which will take us straight to the required item. or null if the account cannot be found. If it finds one it sets this to refer to the account it has been asked to store and then returns true. C# Programming © Rob Miles 2010 131 .3 Storing Accounts using a Hash Table Fortunately for us we can use a device called a "hash table" which allows us to easily find items based on a key.Creating Solutions Building a Bank public bool StoreAccount (IAccount account) { int position = 0.2 Searching and Performance The solution above will work fine. Each time we add a new account the searching gets slower as the FindAccount method must look through more and more items to find that one. } if ( accounts[position].FindAccount("Rob"). position++) { if (accounts[position] == null) { accounts[position] = account. 4.Length . This will either return the account with the required name.13. } } return null. } This code works its way through the accounts array looking for an entry with a name which matches the one being looked for. } This method works through the array looking for an element containing null. In the array based implementation of the bank this is achieved by means of a simple search: public IAccount FindAccount ( string name ) { int position=0 . However. position++) { if ( accounts[position] == null ) { continue. but if there are thousands of accounts this simple search will be much to slow. for (position=0 .GetName() == name ) { return accounts[position]. and could be used as the basis of a bank. for (position = 0. look up the ASCII code for each letter and then add these values up. We want to return a reference to an instance which implements the IAccount interface.Creating Solutions Building a Bank The idea is that we do something mathematical (called "hashing) to the information in the search property to generate a number which can then be used to identify the location where the data is stored. The name "Rob" could be converted to 82+111+98 = 291. In short.e. } } The Hashtable class can be found in the System. the as operator will generate a null reference. Of course this hash code is not foolproof. This is poetically referred to as a "hash clash".Collections namespace. the hash function gives us a starting point for our search. For example. } public bool StoreAccount(IAccount account) { bankHashtable. public IAccount FindAccount(string name) { return bankHashtable[name] as IAccount. The as operator has the advantage that if bankHashtable[name] does not return an account. It turns out to be very easy to create a bank storage mechanism based on this: class HashBank : IBank { Hashtable bankHashtable = new Hashtable(). Since this is just what the caller of our FindAccount method is expecting this can be returned back directly. This will store items for us based on a particular object which is called the key. 4. rather than always looking from the beginning of the array in our simple array based code above. or returns something of the wrong type. This greatly speeds up access to the data.Add(account. return true. It also allows you to use a reference to the key (in this case the name) to locate an item: return bankHashtable[name] as IAccount. It provides a method called Add which is given the value of the key and a reference to the item to be stored on that hash code. If we find the location we would like to use is not null we simply work our way down looking for the first free location on from that point.4 Using the C# Hashtable collection Fortunately for us the designers of the C# have created a hash table class for us to use. If a cast fails (i. Clashes can be resolved by adding a test when we are storing an account. but we can't completely avoid clashes.13.GetName(). We could look in location 291 for our account. When we want to find a given item we use the hash to take us to the starting position for the search and then look for the one with the matching name. C# Programming © Rob Miles 2010 132 . we could take all the letters in the account name string. The as operator is a form of casting (where we force the compiler to regard an item as being of a particular type). account). at run time the bank hash table returns the wrong thing) our program will fail with an exception. It is used in preference to the code: return (IAccount) bankHashtable[name]. the name "Rpa" would give the same total (82+112+97) and refer to the same location. We can do clever things with the way we combine the values to reduce the chances of this happening. We have to use the "as" part of this code as the collection will return a reference to an object. which is the name of the account holder. and there may well be more than one.. C# Programming © Rob Miles 2010 133 . When gathering metadata about a system you will often need to consider which of the properties of an item will be key fields. The cash machine uses information on the card as a key to find your account record so that it can check your balance value and then update it when the money has been withdrawn. In a real bank the key will be more complex. we can very easily change the way that the account storage part of the program works without changing anything else. In our simple bank we only have a single key.Creating Solutions Building a Bank It is interesting to note that because we have implemented our bank behaviour using an interface. This statement probably doesn't tell you much about them or what they do. In this respect the word Add can be a bit misleading. But I digress. Creating an ArrayList It is very easy to create an ArrayList: ArrayList store = new ArrayList().Add(robsAccount). But we know that when an array is created the programmer must specify exactly how many elements it contains. It lets us create something very useful. Perhaps the best way to talk about generics is to see how they can help us solve a problem for the bank. Adding Items to an ArrayList Adding items to an ArrayList is also very easy.Collections namespace. and some very clever code in the library makes sure that this works. They sound a bit scary. This leads to a "straw that breaks the camel's back" problem. because the array size was set at 10. We can always add new elements to the ArrayList. an array that can grow in size. in that what it actually does is add a reference.Advanced Programming Generics and Collections 5 Advanced Programming 5. C# Programming © Rob Miles 2010 134 . One way to solve this problem is to use a really big array. but it can hold more or less as required. store. but we aren't that keen on that because it means that for smaller banks the program might be wasting a lot of memory. where adding the 10. telling people you learned about "generics" probably conjures up images of people with white coats and test tubes. We are not putting an Account into the arraylist. starting with the simple ArrayList.001st customer to the bank is not actually a cause for celebration.1 Generics and Collections Generics are very useful.1. If it doesn't. I think the root of Generics is probably "general". Fortunately the C# libraries provide a number of solutions. in that the idea of them is that you specify a general purpose operation and then apply it in different contexts in a way appropriate to each of them. The ArrayList called storeFifty is initially able to store 50 references. If this sounds a bit like abstraction and inheritance you are sort of on the right track. It is important to remember what is going on here.000 and our program crashes.1 The ArrayList class The ArrayList is a cousin of the HashTable we have just seen. The class provides an Add method: Account robsAccount = new Account (). in that it lives in the same Systems. although there are overloaded constructors that let you give this information and help the library code along a bit: ArrayList storeFifty = new ArrayList(50). not the thing itself. but it does indicate that they are very useful. We have just seen that we can store Account references in an Array. 5. then it might be worth re-reading those bits of the book until they make sense. we are instead making one element of the arraylist refer to that account. at least amongst those who can't spell very well. Note that you don't have to set the size of the ArrayList. Account a = store[0]. This removes the first occurrence of the reference robsAccount from the store arraylist. You will no doubt remember from the discussion of object hierarchies that an object reference can refer to an instance of any class (since they are all derived from object) and so that is the only kind of reference that the arraylist works with. because a program can use a cast to change the type of the item the arraylist returns: Account a = (Account) store[0]. but with a tricky twist. an item "in" an arraylist is never actually in it. This means that I can't be sure that an arraylist you give me has nothing other than accounts in it: KitchenSink k = new KitchenSink(). A slightly larger problem is that an arraylist is not typesafe. along with a list of "special" customers and perhaps another list of those who owe it the most money. This puts a reference to a KitchenSink instance into our bank storage. Note that if the reference given is not actually in the arraylist (i. it is not necessarily destroyed. The designers of the ArrayList class had no idea precisely what type of object a programmer will want to use it with and so they had to use the object reference.WriteLine("The bank is empty").PayInFunds(50).Count == 0) { Console. When an item is removed from an arraylist.Add(k).PayInFunds(50). The reason for this is that an arraylist holds a list of object references.Remove(robsAccount). a. cast it into an Account class and then pay fifty pounds into it. a. it is just no longer on that list. This will cause problems (and an exception) if we ever try to use it as an Account. this is the only thing that it could hold. if I ran the code above when store did not contain robsAccount) this does not cause an error. To get a properly typesafe Account storage we have to take a look at generics in detail a bit later. but the arraylist class provides a really useful Remove behaviour. It would be very nice if we could just get hold of the account from the arraylist and use it. This is given a reference to the thing to be removed: store. Accessing Items in an ArrayList Items in arraylists can be accessed in just the same way as array elements. } C# Programming © Rob Miles 2010 135 . just like your name can appear on multiple lists in the real world. This is not actually a huge problem.Advanced Programming Generics and Collections Remember that it would be perfectly possible to have robsAccount in multiple arraylists.e. If the store contained more than one reference to robsAccount then each of them could be removed individually. This would get the element at the start of the arraylist. Unfortunately this won't work. store. So. Finding the size of an ArrayList You can use the property Count to find out how many items there are in the list: if (store. If you remove an item the size of the arraylist is decreased. It will have a list of all the customers. If you think about it. Removing Items from an ArrayList It is not really possible to remove things from an array. If you write this code you will get a compilation error. It might be that the bank has many lists of customers. the list actually contains a reference to that item. we can sort that out when we actually want to work with something. However. It does this by using references to objects. but this can lead to programs which are dangerous. string. not any particular class. Instead they introduced a new language feature. the fundamental behaviours of arrays are always the same. there is just no way that you can take an Account reference and place it in an array of integers. It could contain a whole bunch of KitchenSink references for all I know. And I only really find out when I start trying to process elements as Accounts and my program starts to go wrong. However. it has to use a compromise to allow it to hold references to any kind of item in a program. but having it built into the class makes it much easier. You could of course write this behaviour yourself.1. with the advantage that it is also typesafe. However. float or Account array the job that it does is exactly the same. If you give me an array of Accounts I can be absolutely sure that everything in the array is an account. this can be fixed when you move over to the List class.WriteLine("Rob is in the bank"). C# can make sure that an array always holds the appropriate type of values. generics. and because it is not quite as much a part of the language as an array is.Contains(robsAccount)) { Console. This is simply a quick way of finding out whether or not an arraylist contains a particular reference. The way that the system works. so that it becomes as much a part of C# as the array is. Generics let me write code that deal with objects as "things of a particular type". This is all to the good. and provides you with some means to work with them. To understand how it works you have to understand a bit of generics. It doesn't matter what the thing I'm dealing with is. They both let you store a large number of items and you can use subscripts (the values in square brackets) to get hold of elements from either. Whether you have an int. if you give me an ArrayList there is no way I can be sure that accounts are all it contains. that is not what the designers of C# did. ArrayLists and Arrays Arraylists and arrays look a lot the same. It holds a bunch of things in one place. Generics and Behaviours If you think about it. The ArrayList was added afterwards. being based on the generic features provided by a more recent version of the C# language. in that there is nothing to stop references of any type being added to an arraylist. If you wish you can use arraylists in place of arrays and have the benefits of storage that will grow and shrink as you need it. They also throw exceptions if you try to access elements that are not in the array. } The Contains method is given a reference to an object and returns true if the arraylist contains that reference. but the ArrayList breaks things a bit. if (a. The abilities an array gives you with an array of integers are exactly the same as those you have with an array of Accounts.Advanced Programming Generics and Collections Checking to see if an ArrayList contains an item The final trick I'm going to mention (but there are lots more things an arraylist can do for you) is the Contains method. 5. C# Programming © Rob Miles 2010 136 . the only problem that you have is that an arraylist will always hold references to objects. It is newer than the ArrayList class. One way to solve this problem would have been to find a way of making the ArrayList strongly typed. And because each array is declared as holding values of a particular type.2 The List class The List class gives you everything that an arraylist gives you. In other words. You now have a system that lets you share marbles. we might want to use the name of an account holder as a way of locating a particular account. Something like: "Divide the number of marbles by the number of friends and then distribute the remainder randomly". What the list stores is not important when making the list. What the system works on is not particularly important.Add("Rob". In this respect. which makes them the perfect way to store a large number of items of a particular type. Remove) that you can with an ArrayList. We could create a List that can hold integers in a similar way: List<int> scores = new List<int>().Account> accountDictionary = new Dictionary<string. you could also use it to share out sweets.3 The Dictionary class Just as ArrayList has a more powerful. The C# features that provide generics add a few new notations to allow you to express this.PayInFunds(50). cousin called List. For example. 5. You can do everything with a List (Add. the behaviour you want is that of a list. The List class lives in the System. However. There is no need to cast the item in the list as the type has already been established. this means that you can write code like this: accountList[0]. We can create a dictionary to hold these key/value pairs as follows: Dictionary<string.Account>(). just as long as you have a way of telling it what to store.Advanced Programming Generics and Collections This sounds a bit confusing. generics can be regarded as another form of abstraction.Generic namespace and works like this: List<Account> accountList = new List<Account>().Collections. to be made typesafe. generically enhanced.1. If you wanted to share out marbles amongst you and your friends you could come up with way of doing that. it can be a general sharing behaviour that is then applied to the things we want to share. cakes or even cars. Count. You could take your universal sharing algorithm and use it to share most anything. This looks just like the way the HashTable was used (and it is). we have a string as the key and an Account reference as the value. Since the compiler knows that AccountList holds Account references. The type between the < and > characters is how we tell the list the kind of things it can store. so the HashTable has a more powerful cousin called Dictionary. This allows the key to your hashtable. In other words statements like this would be rejected.Add(k). and will not accept the kitchen sink. C# Programming © Rob Miles 2010 137 . using a Dictionary has the advantage that we can only add Account values which are located by means of a string. and the items it stores. We can now add items into our dictionary: accountDictionary. Because we have told the compiler the type of things the list can hold it can perform type validation and make sure that nothing bad happens when the list is used: KitchenSink k = new KitchenSink(). The sharing algorithm could have been invented without worrying about the type of the thing being shared. Generics and the List In the case of generics. accountList. The above statement creates a list called acountList which can hold references to Accounts. However. since the acountList variable is declared as holding a list of Account references. robsAccount). The above statements would cause a compilation error. how about an example. use a Dictionary. You can get around this by asking the dictionary if it contains a particular key: if (d.PayInFunds(50). bool WithdrawFunds ( decimal amount ). decimal GetBalance (). How these features are used to create generic classes is a bit beyond the scope of this text. This means that our data storage requirements are that we should load all the accounts into memory when the program starts. Don't have any concerns about performance. Then we can move on to consider the code which will save a large number of them.Add("Glug". } The Dictionary class is simply wonderful for storing keys and values in a typesafe manner. k).1. Every time you need to hold a bunch of things. It also has a constructor which allows the initial name and balance values to be set when the account is created. C# Programming © Rob Miles 2010 138 .2 Storing Business Objects For our bank to really work we have to have a way of storing the bank accounts and bringing them back again. We can express the required account behaviour in terms of the following interface: public interface IAccount { void PayInFunds ( decimal amount ). The only problem with this use of a dictionary is that if there is no element with the key "Rob" the attempt to find one will result in a KeyNotFoundException being thrown. particularly library routines. The programmers who wrote these things are very clever folks . 5. 5. string GetName(). The account that we are going to work with only has two members but the ideas we are exploring can be extended to handle classes containing much larger amounts of data. If you want to be able to find things on the basis of a key. but you are strongly advised to find out more about generics as it can make writing code.ContainsKey("Rob")) { Console. and I recommend it strongly to you. } All the accounts in the bank are going to be managed in terms of objects which implement this interface to manage the balance and read the name of the account owner.WriteLine("Rob is in the bank"). If we want to our program to be able to process a large number of accounts we know that we have to create an array to manage this. and then save them when the program completes. This would find the element with the hash key "Rob" and then pay fifty pounds into it. Programmer’s Point: Use Dictionary and List You don't really have to know a lot about generics to be able to spot just how useful these two things are. We can create a class called CustomerAccount which implements the interface and contains the required methods. we'll consider how we save one account. make a List. accountDictionary. a lot easier. To start with.Advanced Programming Storing Business Objects KitchenSink k = new KitchenSink().4 Writing Generic Code The List and Dictionary classes were of course written in C# and make use of the generic features of the language. A further advantage is that we do not need to cast the results: d["Rob"]. if you think about it. } balance = balance . return true. this is the only way that we can save an account. In fact. private string name.2. since any save mechanism would need to save data in the account which is private and therefore only visible to methods inside the class. We can add a Save method to our CustomerAccount class: C# Programming © Rob Miles 2010 139 . } private decimal balance = 0. } public string GetName() { return name. } public decimal GetBalance () { return balance. 5. public virtual bool WithdrawFunds ( decimal amount ) { if ( balance < amount ) { return false. } public void PayInFunds ( decimal amount ) { balance = balance + amount . decimal initialBalance) { name = newName. but it is just here to illustrate how the data in the class can be saved and restored.Advanced Programming Storing Business Objects public class CustomerAccount : IAccount { public CustomerAccount( string newName. so it is not what I would call "production" code. } } Note that this version of the class does not perform any error checking of the input values.1 Saving an Account The best way to achieve the saving behaviour is to make an account responsible for saving itself.amount . balance = initialBalance. IO.txt". try { textIn = new System. So I could do things like: if (Rob.ReadLine(). It writes out the name of the customer and the balance of the account. string balanceText = textIn.IO. } finally { if (textIn != null) textIn.2 Loading an Account Loading is slightly trickier than saving. textOut.Save ("outputFile. The Load method above takes great pains to ensure that if anything bad happens it does a number of things: It does not throw any exceptions which the caller must catch.TextReader textIn = null. to indicate that the save was not successful.txt")) { Console.Close(). fetches the balance value and then creates a new CustomerAccount with the balance value and name. 5. } return true.Parse(balanceText). System. Note that I have written the code so that if the file output fails the method will return false. C# Programming © Rob Miles 2010 140 . textOut.Advanced Programming Storing Business Objects public bool Save ( string filename ) { try { System. } return result. When we load there will not be an account instance to load from. } catch { return false.ReadLine().StreamWriter(filename). } This would ask the account referred to by Rob to save itself in a file called "outputFile.Close() . } This method is given the name of the file that the account is to be stored in.StreamReader(filename). decimal balance = decimal. result = new CustomerAccount(nameText. } catch { return null.2. When we save an account we have an account which we want to save. A way to get around this is to write a static method which will create an account given a filename: public static CustomerAccount Load(string filename) { CustomerAccount result = null. } This method opens a file.TextWriter textOut = new System.WriteLine ("Saved OK").IO.WriteLine(name).WriteLine(balance). textOut. string nameText = textIn.IO.balance). in that it creates an instance of a class for us. } This save method can be called from our original file save method: C# Programming © Rob Miles 2010 141 . We can use this as follows: test = CustomerAccount. whatever happens. as I grow older I become more inclined to make my programs throw exceptions in situations like this. 5.txt" ). And they will probably try and blame me for the problem (which would be very unfair). but this would be confusing and inefficient. You can also get code analysis tools which are bit like "compilers with attitude" (a good one is called FxCop). you just have to make sure that. and is something you should aim for when writing code you are going to sell. However.StreamWriter( "Test.Load( "test. If the factory fails (because the file cannot be found or does not contain valid content) it will return a null result. It makes sure that the file it opens is always closed.3 Multiple Accounts The above code lets us store and load single accounts. with large numbers of file open and close actions being required (bear in mind that our bank may contain thousands of accounts). This means that their program will fail in this situation. your part doesn’t break.IO. The reference textOut refers to a stream which is connected to the file Test. at the moment we can only store one account in a file.TextWriter textOut) { textOut. However. textOut.2. These scan programs for situations where the results of methods are ignored and flag these up as potential errors. which we can test for: if (test == null) { Console.IO.IO. rather than a filename. the best place to do it is at the pub. you can argue this either way.txt" ). We could create a new file for each account.Advanced Programming Storing Business Objects It returns null to indicate that the load failed if anything bad happens. Actually. } Programmer’s Point: There is only so much you can do Note that if an incompetent programmer used my Load method above they could forget to test the result that it returns and then their program would follow a null reference if the customer is not found. At the end of the day though there is not a great deal you can do if idiots use your software. This kind of method is sometimes called a ―factory‖ method.WriteLine( "Load failed" ). since that makes sure that a failure is brought to the attention of the system much earlier. We can create a save method which accepts the stream reference as a parameter instead of a filename: public void Save(System.TextWriter textOut = new System. A stream is the thing that the C# library creates when we open a connection to a file: System. The way around this is to make sure that you document the null return behaviour in big letters so that users are very aware of how the method behaves.WriteLine(name).WriteLine(balance). This is what I would call a "professional" level of quality.txt. Using streams A better solution is to give the file save method a stream to save itself. This will open a stream and save all the accounts to it: C# Programming © Rob Miles 2010 142 .IO. Note that this is an example of overloading in that we have two methods which share the same name. The C# input/output system lets us connect streams to all manner of things. Saving and loading bank accounts Now that we have a way of saving multiple accounts to a single stream we can write a save method for the bank. Programmer’s Point: Streams are wonderful Using streams is a very good idea. not just files on a disk.IO. It reads the name and the balance from this stream and creates a new CustomerAccount based on this data.StreamWriter(filename). result = new CustomerAccount(name.Close().TextReader textIn) { CustomerAccount result = null. For example. } } return true.ReadLine(). try { string name = textIn. string balanceText = textIn. you can create a stream which is connected to a network port. decimal balance = decimal.ReadLine(). balance). } This method creates a stream and then passes it to the save method to save the item. The load method for our bank account can be replaced by one which works in a similar way. Save(textOut). try { textOut = new System.IO. } return result.TextWriter textOut = null. } This method is supplied with a text stream.Parse(balanceText). } finally { if (textOut != null) { textOut. This means that if you make your business objects save and load themselves using streams they can then be sent over network connections with no extra work from you. public static CustomerAccount Load( System. } catch { return null. } catch { return false.Advanced Programming Storing Business Objects public bool Save ( string filename ) { System. GetName().Parse(countString). We do this so that when the bank is read back in the load method knows how many accounts are required. but this would not allow us to detect if the file had been shortened. This material is provided to give you an idea of C# Programming © Rob Miles 2010 143 . account). } This reads the size of the bank and then reads each of the accounts in turn and adds it to the hash table. string countString = textIn.2. This can be obtained via the Count property of the Hashtable.IO. We have also been very careful to make sure that whenever we save and load data we manage the way that this process can fail. Note that we are using a new C# loop construction here. Health Warning This is complicated stuff. result.Count).WriteLine(bankHashtable.4 Handling different kinds of accounts The code above will work correctly if all we want to save and load are accounts of a particular type. in that everything is written in terms of the CustomerAccount class.Add(account. This is very useful when dealing with collections of data. for (int i = 0. we have seen that our customer needs the program to be able to handle many different kinds of account. and supplies each item in turn. We have done this without sacrificing any cohesion. The reason that it is here is for completeness. i++) { CustomerAccount account = CustomerAccount. Bank Notes: Large Scale Data Storage What we have done is created a way that we can store a large number of bank account values in a single file. 5. We could just write out the data and then let the load method stop when it reaches the end of the file. I don't expect you to understand this at first reading. Note that before it writes anything it writes out the number of customers in the bank. foreach (CustomerAccount account in bankHashtable. Note that this load method does not handle errors. The Load method for the entire bank is as follows: public static HashBank Load(System. foreach. in this case the Values property of the bankHashtable. } return result.Advanced Programming Storing Business Objects public void Save(System.IO.ReadLine().Values) { account.TextReader textIn) { HashBank result = new HashBank(). i < count. However. A production version of the program would check that each account was loaded correctly before adding it to the hash table.. in that only the CustomerAccount class is responsible for the content.Save(textOut). } } This is the Save method which would be added to our Hashtable based bank.Load(textIn).TextWriter textOut) { textOut. int count = int. It gets each account out of the hash table and saves it in the given stream.bankHashtable. It works its way through a collection. a special account for young people which limits the amount that can be withdrawn to no more than 10 pounds. . initialBalance) { parentName = inParentName. The customer has also asked that the BabyAccount class contains the name of the "parent" account holder. "John"). This turns out to be very easy.WithdrawFunds(amount). but it assumes a very good understanding of class hierarchies. and overrides the WithdrawFunds method to provide the new behaviour. } public BabyAccount( string newName. Banks and Flexibility We know that when our system is actually used in a bank there will be a range of different kinds of account class. Saving a child class When we want to save a BabyAccount we also need to save the information from the parent class. } } This is a complete BabyAccount implementation. parentName. } return base. the starting balance and the name of the parent. method overriding/overloading and constructor chaining. decimal initialBalance. } public override bool WithdrawFunds(decimal amount) { if (amount > 10) { return false. we have previously discussed the BabyAccount. and then sets the parent name. Note that I have created a constructor which is supplied with the name of the account holder.Advanced Programming Storing Business Objects how you really could make a working bank. This would create a new BabyAccount instance and set the reference babyJane to refer to it. It contains an additional property. The good news is that when you do understand this stuff you really can call yourself a fully-fledged C# programmer. 20. This makes use of the constructor in the parent to set the balance and name. some of which will be based on others. public string GetParentName() { return parentName. I can create a BabyAccount as follows: BabyAccount babyJane = new BabyAccount ("Jane". As an example. string inParentName) : base(newName. ReadLine(). This method breaks one of the rules of good design.IO..Parse(balanceText). in a similar way to the way the save method uses the base keyword to save the parent object. } catch { return null. Then it performs the save behaviour required by the BabyAccount class. string balanceText = textIn. } However. What we do is create constructors for the CustomerAccount and BabyAccount classes which read their information from a stream that is supplied to them: public CustomerAccount(System.TextReader textIn) { BabyAccount result = null. string balanceText = textIn. textOut.ReadLine(). decimal balance = decimal.. balance. balance = decimal. string parent = textIn. try { string name = textIn. The way to do this is to go back to the construction process.Save(textOut). What we really want to do is make the CustomerAccount responsible for loading its data and the BabyAccount just look after its content. it first calls the overridden method in the parent to save the CustomerAccount data.WriteLine(parentName). We know that a constructor is a method which gets control when an instance of a class is being created. but when it runs it will not work correctly.TextReader textIn) { name = textIn.Parse(balanceText). } This method overrides the Save method in the parent CustomerAccount. I can therefore write code like this: C# Programming © Rob Miles 2010 145 . result = new BabyAccount (name. If I forget to do this the program will compile. as it means that if the data content and save behaviour of the parent class changes we don't need to change the behaviour of the child. } This constructor sets up the new CustomerAccount instance by reading the values from the stream that it is supplied with.ReadLine(). parent).IO. and it can be passed information to allow it to do this. However. I'm not particularly keen on this approach.Advanced Programming Storing Business Objects public override void Save(System.IO. This is very good design.TextWriter textOut) { base. A constructor can be used to set up the data in the instance. } return result.ReadLine().ReadLine(). However. } This removes the dependency relationship completely. bool Save(string filename).TextReader textIn = new System. void Save(System. this is reasonable behaviour. there is a problem here. string GetName(). in that when we are loading the accounts we don't actually have an instance to call any methods on. At the start this did not include the save behaviours. but it could be updated to include them: public interface IAccount { void PayInFunds ( decimal amount ).TextWriter textOut) { textOut. bearing mind we are reading from a stream of data. Also. Interfaces and the save operation When we started this account development we set out an interface which describes all the things which an instance of an account should be able to do. } } C# Programming © Rob Miles 2010 146 . textIn. If the behaviour of the CustomerAccount constructor changes we do not have to change the BabyAccount at all. account. we don't actually know what kind of item we are loading. so that we can ask instances of a particular kind of account to load themselves. This is a good idea. bool WithdrawFunds ( decimal amount ). decimal GetBalance ().IO.ReadLine().Save(textOut).IO.WriteLine(bankHashtable. since the account container will not have to behave differently depending on what kind of account it is saving.IO.Name). You might think it would be sensible to add load methods to the IAccount interface.TextReader textIn) : base (textIn) { parentName = textIn. things get a little trickier.IO. they just throw exceptions if something goes wrong.GetType().Advanced Programming Storing Business Objects System. it just has to call the save method for the particular instance. This is very useful when we store our collection of accounts.Count). result = new CustomerAccount(textIn).Close(). The save method for our bank could look like this: public void Save(System. Bearing in mind that the only way that a constructor can fail is to throw an exception anyway. The solution to this problem is to identify the type of each instance in the steam when we save the classes. This creates a new CustomerAccount from the stream. Now I can create a constructor for the BabyAccount which uses the constructor of the parent class: public BabyAccount(System.StreamReader(filename). Loading and factories When it comes to loading our classes back. Note that these constructors do not do any error checking. } We can now ask any item which implements the IAccount interface to save itself to either a file or a stream.Values) { textOut.WriteLine(account. foreach (CustomerAccount account in bankHashtable.TextWriter textOut).IO. } Again. } } } This class only contains a single method. string countString = textIn.Add(account.ReadLine().TextReader textIn) { switch (name) { case "CustomerAccount": return new CustomerAccount(textIn). This means that when the stream is read back in this information can be used to cause the correct type of class to be created. except that it has an additional line. this looks very like our original load method.bankHashtable. The method is given two parameters.MakeAccount(className. The neatest way to do this is to create a factory which will produce instances of the required class: class AccountFactory { public static IAccount MakeAccount( string name. int count = int. case "BabyAccount": return new BabyAccount(textIn). } return result. It involves writing code which will search for C# classes which implement particular interfaces and creating them automatically. It makes use of the method GetType(). i++) { string className = textIn. which can be called on an instance of a class to get the type of that class.ReadLine(). Factory Dependencies Note that we now have a genuine dependency between our system and the factory class.TextReader textIn) { HashBank result = new HashBank(). creates one. which is static. In other words. which has been highlighted.Parse(countString). textIn). account). result. However this kind of stuff is beyond the scope of this text. There is in fact a way of removing the need to do this. If we ever add a new type of account we need to update the behaviour of the factory so that it contains a case to deal with the new account type. If the name is not recognized it returns null.IO.IO. IAccount account = AccountFactory. if the account is of type CustomerAccount the program will output: CustomerAccount Rob 100 The output now contains the name of the type of each class that has been written. C# Programming © Rob Miles 2010 147 . default: return null. for (int i = 0.Advanced Programming Storing Business Objects This looks very like our original method. System. i < count. It uses the name to decide which item to make. except that it uses the factory to make account instances once it has read the name of the class from the stream. The bank load method can use this factory to create instances of accounts as they are loaded: public static HashBank Load(System. This writes out the name of the class. and then returns that to the caller. Having got the type we can then get the Name property of this type and print that.GetName(). the name of the class to be created and a stream to read from. If it is going to reject names it would be very useful to the user if they could be told why a given name was not valid. The way that we manage the saving of items (by using a method in the class) and loading (by using a constructor) is not symmetrical. but I reckon this is worth doing since it is important you start to understand that what you are writing now. The job of the business object is to make sure that the data that it holds is always correct. there is no dishonour in this way of working. there is more to it than just changing one string for another. It is important that this is always stored safely but people may want to change their name from time to time. 5.Advanced Programming Business Objects and Editing Bank Notes: Messy Code You might think that the solutions above are rather messy. It is not their job to talk to users. Programmer’s Point: Production Code From now on all the code examples are going to be given in the context of production code. This is because classes like CustomerAccount are what is called business objects. When you want to move from objects to storage and back you will find that you hit these issues and this solution is as good as any I've found. so the validation process should provide feedback as to why it did not work. 5. The new name must be a valid one. This means that the business object must provide a way that the name can be changed.3. are just those that "real" programmers are up against. However. However. A good software engineer would provide something like this: C# Programming © Rob Miles 2010 148 . consider the name of the bank account holder.1 The role of the Business Object We have taken a very strict line in our banking system to stop any of the bank account components from actually talking to the user. they are strictly concerned with keeping track of the information in the bank account of the customer. We now also know how to save the information in a class instance.3 Business Objects and Editing We have seen how to design a class which can be used to hold information about the customers in our bank.. This means that the account must be able to reject names it doesn't like. Now we need to consider how we can make our account management system genuinely useful. and also perform this for a large number of items of a range of different types. Managing a bank account name As an example. This is code which I would be happy to have supplied in a product. and the problems you are grappling with. This might make the examples a bit more complex than you might like. The validate method will reject a name string which is empty. the natural thing to do is create tests for them: C# Programming © Rob Miles 2010 149 . } string trimmedName = name. since I also use the method myself when I validate the name. } public static string ValidateName ( string name ) { if ( name == null ) { return "Name parameter null".Length > 0 ) { return false. } The name is stored as a private member of the account class. The validate method is called by the set method so that my business object makes sure that an account never has an invalid name. or just contains spaces. Testing Name Handling Of course. reply = ValidateName(inName). } return "".name. if ( reply. if ( trimmedName. There is a method to get the name. public string GetName() { return this. The validate method returns a string which gives an error message if the string is rejected. at the moment I've just given two. another to set it and another to validate it. The reasons why a name is invalid are of course part of the metadata for the project. If it is. the string is rejected. The programmer has provided three methods which let the users of my Account class deal with names.Length == 0 ) { return "No text in the name". I provide the validate method so that users of my class can check their names to make sure that they are valid.name = inName.Trim(). There may be several reasons why a name is not valid. It trims off all the spaces before and after the name text and then checks to see if the length of the resulting string is empty. } this.Trim(). I’ve also made this method static so that names can be validated without needing to have an actual instance of the account. This does not involve me in much extra work. once we have these methods.Advanced Programming Business Objects and Editing private string name. return true. } public bool SetName ( string inName ) { string reply . WriteLine("Empty name test failed"). } if (!a. 50). errorCount++. if (!a. } reply = CustomerAccount.SetName(" Pete ")) { Console.WriteLine("Pete GetName failed"). And that is the matter of error handling. } reply = CustomerAccount. errorCount++. errorCount++. if (reply != "No text in the name") { Console. At the moment the errors supplied by my validation methods are strings. Then I make sure that I can set the name on an account. In a genuine production environment the errors would be numeric values.ValidateName(null). } These are all the tests I could think of. This is because they are much easier to compare in tests and it also means that my program could be made to work in a foreign language very easily. All I would need is a lookup table to convert the message number to an appropriate string in the currently active language.Advanced Programming Business Objects and Editing int errorCount=0. errorCount++. } CustomerAccount a = new CustomerAccount("Rob".GetName() != "Pete" ) { Console.WriteLine("Null name test failed"). errorCount++.ValidateName(" "). } if (errorCount > 0 ) { SoundSiren().WriteLine("Jim SetName failed").WriteLine("Pete trim SetName failed"). } if ( a. if (reply != "No text in the name") { Console.WriteLine("Jim GetName failed"). Editing the Name We now have a business object that provides methods which let us edit the name value.ValidateName(""). errorCount++.WriteLine("Blank string name test failed"). if (reply != "Name parameter null") { Console. errorCount++. I can now write code to edit this property: C# Programming © Rob Miles 2010 150 . First I test ValidateName to make sure that it rejects both kinds of empty string. Programmer’s Point: Use Numbers Not Messages There is one issue which I have not addressed in my sample programs which stops them from being completely perfect. Finally I check that the space trimming for the names works correctly. string reply. } if ( a. You should consider issues like this as part of the metadata in your project. The fact that the system must work in France and Germany is something you need to be aware of right at the start.GetName() != "Jim" ) { Console. reply = CustomerAccount.SetName("Jim")) { Console. reply = account. string reply.ReadLine().account. string reply. This is not the most elegant solution. } this. in that if the account class changes the editor may need to be updated.Length == 0 ) { break. while (true) { Console. } Console.WriteLine( "Invalid name : " + reply ).ValidateName(newName). This code will perform the name editing for an account instance referred to by account. There will be a dependency between the editor class and the account class. If the name is not valid the message is printed and the loop repeats. } public void EditName () { string newName.Write ( "Enter new name : " ) .Length == 0 ) { break.Write ( "Enter new name : " ) . } Console. If the name is valid the loop is broken and the name is set. if ( reply. newName = Console.ValidateName(newName). Console.SetName(newName). Creating an Editor class The best way to do this is to create a class which has the job of doing the editing.Advanced Programming Business Objects and Editing while (true) { Console. reply = this.WriteLine( "Name Edit" ).account = inAccount. but this is something we will just have to live with. but it does keep the user informed of what it is doing and it does work.SetName(newName). It will read a new name in. newName = Console. This class will work on a particular account that needs to be edited. } } C# Programming © Rob Miles 2010 151 . public AccountEditTextUI(Account inAccount) { this. When I want to edit an account I create an editor instance and pass it a reference to the account instance: public class AccountEditTextUI { private IAccount account.WriteLine( "Invalid name : " + reply ). if ( reply. } account.account. Now that we have our edit code we need to put it somewhere.ReadLine(). GetName() ). I would use the name editor as follows: CustomerAccount a = new CustomerAccount("Rob". I've extended the account class to manage the account balance and added edit methods which pay in funds and withdraw them. The class keeps track of the account it is editing.ToLower().WriteLine ( " Enter name to edit name" ). My edit class contains a method which does this: This is my edit method which repeatedly reads commands and dispatches them to the appropriate method. I pass it a reference to this account when I construct it. Console. Console. This code creates an instance of a customer account.WriteLine ( " Enter draw to draw out funds" ). It then passes that reference to the service methods which will do the actual work. command = Console. Console. 50). This means that anything which behaves like an account can be edited using this class. The edit method is passed a reference to the account which is being edited. AccountEditTextUI edit = new AccountEditTextUI(a). command = command. do { Console. If I want to "give" a class something to work on I will do this by calling a method in that class and passing the reference as a parameter to this method.2 A Text Based Edit System We now have a single method in our editor class which can be used to edit the name of a bank account. Programmer’s Point: Get used to passing references around It is important that you get used to the idea of passing references between methods.Write ("Enter command : ").ReadLine(). Note that I trim the command string and convert it to lower case before using it to drive the switch construction which selects the command.EditName(). Console.Advanced Programming Business Objects and Editing This is my account editor class. You will use this technique when you create different editing forms 5.WriteLine ( "Editing account for {0}". Note also that the editor remembers the account class that is being edited so that when I call EditName it can work on that reference. It then creates an editor object and asks it to edit the name of that account. exit to exit program" ). edit.3. Console.Trim(). account. command = command. Note that the editor class is passed a reference to the IAccount interface. switch ( command ) { C# Programming © Rob Miles 2010 152 . public void DoEdit (CustomerAccount account) { string command. not a reference to the account class.WriteLine ( " Enter pay to pay in funds" ). At the moment it can only edit the name. but I will add other edit methods later. The user interface must always work on the basis that it will use the business object to perform this kind of validation. Bank Notes: More Than One User Interface The bank may have a whole range of requirements for editing account details.4.4 A Graphical User Interface It should come as no surprise that a graphical user interface on the screen is represented by objects. break. The only exception to this is the situation where the customer has assured you that the program will only ever be written for use in a particular language.1 Creating a Form If I want a form on the screen for the user to interact with. I hope that you can see that the only way we can manage all these different ways of interacting with the bank account is to separate the business object (the account itself) from the input/output behaviour. This class can be found in the System. The menu for my bank account edit method sample code prints out text which is hard wired to English. 5. When we are dealing with windows on the screen our program is actually calling methods in the objects to make them do things like change size and colour.Windows. In a properly written program this would be managed in terms of message numbers to make it easier to change the text which is output. } } while ( command != "exit" ). break. Everything should be managed in terms of message numbers. The C# libraries contain a set of resources which help you manage the internationalization of your programs. These will range from an operator in a call centre. } Programmer’s Point: Every Message Counts You should remember that every time your program sends text to the user you may have a problem with language. case "draw" : WithDrawFunds(account). I need to create an instance of an object to do this for me. As a general rule in a production system you should never write out straight text to your user (this includes the names of commands that the user might type in). The object that I create is a Form.Advanced Programming A Graphical User Interface case "name" : EditName(account). case "pay" : PayInFunds(account). Note that we never do things like allow the user interface code to decide what constitutes a valid name. 5. an operator on a dial up terminal. The only thing that can decide on the validity of a name is the account object itself. This question is not the responsibility of the front end. a customer on a mobile phone and a customer at a cash machine. break.Forms namespace. I can create an instance of this class and ask it to do things for me: C# Programming © Rob Miles 2010 153 . it disappears and the program ends.ShowDialog().Windows. For example. It can 'contain' a number of graphical components which are used to build the user interface. } } This creates a label. } } The Form class provides a method called ShowDialog. We must create the components and add them to the form to make our user interface. class FormsDemo { public static void Main () { Form f = new Form().Forms. The result of this code is a form which looks like this: I can fiddle with the properties of a component to move it around on the screen and do lots of interesting things: C# Programming © Rob Miles 2010 154 . f. f.Add(title).ShowDialog(). title. to add a label to the form we can do the following: using System. f. This asks the form to show itself and pause the program until the form is closed. Adding Components to a Form A form is a container.Text="Hello". sets the text property of the label to ―Hello‖ and then adds it to the controls which are contained by the frame.Controls. Label title = new Label ().Advanced Programming A Graphical User Interface using System.Windows. If I run the program above the following appears on the screen: When the window is closed with the red button.Forms. class FormsDemo { public static void Main () { Form f = new Form(). The TextBox gives me a great deal of functionality for very little effort on my part. The Color class is found in the System.Forms. f. The origin (i.Top=50.Text="Hello". green and blue components. f.Yellow. It lets the user cut and paste text in and out of the box using the Windows clipboard. class FormsDemo { public static void Main () { Form f = new Form().Left=50. It provides a whole set of static colour values and also lets you create your own colours by setting the intensity of the red.ShowDialog(). it behaves like every text field you've ever used on a windows screen. but it provides text edit behaviour. The Windows Forms library provides a TextBox component which is used for this. but what I want to do is provide a way that the name text can be edited.Drawing.Advanced Programming A Graphical User Interface using System.0) is in the top left hand corner of the screen.Controls. title. In short. The user can then enter text into the textbox and modify it. Label title = new Label (). This is a component just like a label.Add(title). title. } } The position on the screen is given in pixels (a pixel being an individual dot on the screen). It lets the user type in huge amounts of text and scrolls the text around to make it fit in the box.Windows. I can create and use a TextBox in my program as follows: C# Programming © Rob Miles 2010 155 . The program above would display a form as below: By adding a number of labels on the form and positioning them appropriately we can start to build up a user interface.e. Editing Text with a TextBox Component Displaying labels is all very well.ForeColor = Color.Drawing namespace. title. title. the pixel at 0.BackColor = Color. I can then read the text property back when I want the updated value.Red. using System. This is because it is actually the same thing as every text field you've ever used. title. I can set the text property of the TextBox to the text I want to have edited. Controls.Controls.Text = "Rob". It also lets you change the text in the name for whatever you want. But at the moment we have no way of signalling when the edit has been finished. I've also set the name text we are editing to be Rob.Add(nameTextBox). Label nameLabel = new Label(). using System. nameLabel.Left=100. Now we are going to find out how to make one work. You have pressed buttons like these thousands of times when you have used programs. I can place it on the form and manage its position just like any other: C# Programming © Rob Miles 2010 156 .Windows. nameLabel. nameTextBox. } } I've fiddled slightly with the position of the label and given it a more sensible name.Top=50. nameTextBox.Add(nameLabel). but it is not bad for 25 or so lines of code. For that we need a button which we can press to cause an event.ShowDialog(). f. f. class FormsDemo { public static void Main() { Form f = new Form(). nameLabel.Left=0. just to show how the components work. This will trigger my program to store the updated name and close the form down. f.Text="Name". The Button Component What we want is a button that the user can press when they have finished editing the name.Drawing.Forms. nameTextBox. A Button is just like any other component. If you run this program you get a form as follows: This is not particularly flashy.Top=50. TextBox nameTextBox = new TextBox().Advanced Programming A Graphical User Interface using System. ShowDialog(). Up until now our programs have run from beginning to end.Left=0.Add(finishButton). duh).Windows.Left=100. nameTextBox. C# Programming © Rob Miles 2010 157 . nameTextBox. nameLabel.Top=50. nameLabel. f. The windows forms system uses delegates to manage this. finishButton. f. In the early days of computers this is how they were all used. finishButton.Forms.Text="Finished".Add(nameLabel). (well.Text="Name".2 Events and Delegates Events are things that happen. f. When the program wants something from the user it waits patiently until that information is supplied (usually by means of a call of the ReadLine method).Top=80. } } This gives me a button on the form which I can press: However at the moment nothing happens when the button goes down.Drawing.Controls. Rather than waiting for the user to do something our programs must respond when an event is generated. finishButton. Button finishButton = new Button(). class FormsDemo { public static void Main() { Form f = new Form().Top=50. f. 5. TextBox nameTextBox = new TextBox(). The upshot of this is that the programming language must provide some means by which events can be managed.Advanced Programming A Graphical User Interface using System.Add(nameTextBox). To get this to work we have to bind a method in our program to the event which is generated when the button is pressed. Nowadays program use is quite different. nameLabel. using System. Label nameLabel = new Label(). This means that the way our programs work has to change.4. Users expect to interact with items on a screen by pressing "buttons" and triggering different actions inside the program.Controls.Left=100. nameTextBox.Text = "Rob". At any given instant the program was either running through code or waiting for input.Controls. store it if it was OK and then close down the edit form. Label nameLabel = new Label(). f.Left=0.Windows.Controls. The form decides which of the components on the form should be given the event and calls a method in that component to tell it "you've been pressed". A delegate is an object which can be used to represent a particular method in an instance of a class. nameTextBox. The actual code to create a delegate and assign it to a method is as follows: using System. finishButton. to button press.Text="Name". Then it looks for people to tell about the event. So. the delegate is going to represent the method that we want to have called when the button is pressed. when the user clicks on the button on our form this is registered by the Windows operating system and then passed into the form as an event. Button Events To get back to the problem we are solving.Left=100.Add(nameLabel).Top=50. The list is actually a list of delegates.Add(finishButton). We pass the button a reference to this delegate and it can then call the method it represents when the button is pressed.Left=100. nameTextBox. finishButton. f. In the case of our button. nameLabel.Text = "Rob". The good news is that creating a delegate instance for a windows component is such a common task that the forms library has provided a delegate class which does this for us. finishButton. using System. finishButton.Advanced Programming A Graphical User Interface Events and method calls In C# an event is delivered to an object by means of a call to a method in that object. using System. from mouse movement.Drawing.ShowDialog().Add(nameTextBox). The button keeps a list of people to tell about events. From the point of view of our name editing form we would like to have a particular method called when the "Finished" button is pressed by the user. so we can use this class every time we need to create a delegate. Button finishButton = new Button().Text="Finished". In this respect you can regard an event and a message as the same thing.Top=80. class FormsDemo { public static void Main() { Form f = new Form(). The signature of the method that is called when the event occurs is the same for every kind of event.Click += new EventHandler(finishButton_Click). The button then does its animation so that it moves in and out.Forms. We just need to create an instance of this class to get a delegate to give to the button. nameLabel. nameLabel. C# Programming © Rob Miles 2010 158 . to window closing. TextBox nameTextBox = new TextBox(). This method would validate the new name. f.Controls.Controls. nameTextBox. to get a button to run a method of ours we need to create a delegate object and then pass that to the button so that it knows to use it when the event occurs.Top=50. f. The EventHandler delegate class is in the System namespace and can refer to methods which are void and accept two parameters. In the completed editor this method will finish the edit off for us. often our methods will ignore the values supplied. C# Programming © Rob Miles 2010 159 . However. we might want to use them to provide information such as the mouse coordinates.4.Advanced Programming A Graphical User Interface } private static void finishButton_Click( object sender. Our form can then be regarded as a customised version of an empty form.WriteLine ("Finish Pressed"). 5. } } The highlighted code is the bit that ties a delegate to the click event. In the code above I have an event handler method called finishButton_Click which accepts these parameters (but doesn't do anything with them). EventArgs e) { Console. This is because I have made everything by hand and there is no edit object as such. Instead it prints out a message each time the button is pressed. If you compile the above program and run it you will find that each time you press the Finish button the program prints out a message. but it is not production code. We passed it a reference to our account and it managed the edit process. This will be used in almost exactly the same way as the text editor. And the way that you create customised versions of classes is to extend them. Note that we don’t actually have to use the parameters. This is a standard technique for using windows components. for example when we are capturing mouse movement events. Extending the Windows Form class It turns out that the best way to create a class to do this job is to extend the Form class to make a new form of our own. a reference to the object which caused the event and a reference to an EventArgs instance which contains details about the event which occurred. If you remember our text editing code you will recall that we had an object which did the editing for us.3 An Account Edit Form My example code above is OK for showing how the forms work and components are added to them. sometimes. The idea is that when the form is created the constructor in the form makes all the components and adds them to the form in the appropriate places. returning when the edit was complete. To make a proper account editor we need to create a class which will do this job for us. finishButton.Top=80. private Button finishButton.Left=100.nameTextBox).account. } private void finishButton_Click(object sender.Text). IAccount account.finishButton.finishButton.nameLabel.Dispose().MessageBox.Length > 0 ) { System. if ( reply.Add(this. this.Form { private Label nameLabel. this. return. this. this.Text = this.finishButton. All the form components are created in the constructor for the form.nameLabel. this.Text="Finished". this.account = inAccount. This code is the windows equivalent of the AccountEditTextUI method that we created previously. this.GetName(). } } The form will be passed a reference to the account instance which is being edited.ValidateName(nameTextBox.Windows.Controls.Controls. this.Left=100.Advanced Programming A Graphical User Interface using System.Add(this. } this. this.nameTextBox.Controls. this.SetName( nameTextBox.Forms. The finishButton_Click method gets the name out of the text box and validates it.EventArgs e) { string reply = account. this. private TextBox nameTextBox. this.Show(reply) .nameTextBox.finishButton).Click += new System.EventHandler(finishButton_Click).nameLabel.Windows.nameLabel).Windows.Text="Name".Left=0. If the name is invalid it uses a static method in the windows forms system to pop up a message box and report an error: C# Programming © Rob Miles 2010 160 . public AccountEditForm (IAccount inAccount) { this.account.nameTextBox = new TextBox(). this.Top=50. When the user presses the finish button the form must make sure that the name is valid.Forms.Text) .nameTextBox.Forms. public class AccountEditForm : System.finishButton = new Button(). this. It then gets the properties out of the form and displays them for editing. If it is the name of the account class should be set and the form must then dispose of itself.Add(this. System.Top=50. using System.nameLabel = new Label(). this. this. this. ever assume you know that the user interface should work in a particular way.Advanced Programming A Graphical User Interface This is how we tell the user that the name is not correct. Console. This means that while the form is on the screen the rest of the system is paused. However.ShowDialog(). Modal Editing The call of ShowDialog in the edit form is modal. Once we have disposed of a form we can never use it again. The Dispose method is important because we must explicitly say when we have finished with the instance. it is important to remember that although it automates a lot of the actions that I have performed by hand above. a. The design of this should start at the very beginning of the product and be refined as it goes.WriteLine ( "Name value : " + a. It then creates an edit form and uses that to edit the name value in the account. AccountEditForm edit = new AccountEditForm (a). We then pass a reference to the account into the constructor of an AccountEditForm. C# Programming © Rob Miles 2010 161 . We will need to create a new form instead. I have had to spend more time re-working user interface code than just about any other part of the system. edit. All the components on the form are destroyed and the form is removed from the screen. If we just removed a reference to the form object it will still remain in memory until the garbage collector gets around to noticing it. Using the Edit form To use the edit form we must first construct an account instance. Visual Studio and Form Editing The Visual Studio application can take care of all the hard work of creating forms and adding components to them. Disposing of forms The Dispose method is used when we have finished with this form and we want to get rid of it. The good news is that with something like Visual Studio it is very easy to produce quite realistic looking prototypes of the front end of a system. In the code above the WriteLine is not performed until after the edit form has been closed.GetName()). Programmer’s Point: Customers really care about the user interface If there is one part of the system which the customer is guaranteed to have strong opinions about it is the user interface. There are a number of different forms of this Show method which you can use to get different forms of message box and even add extra buttons to it. Never. It will also look after the creation of delegates for button actions. the fundamental principles that drive the forms it produces are exactly the same. Account a = new Account(). These can then be shown to the customer (get them signed off even) to establish that you are doing the right thing.SetName("Rob"). This piece of test code creates an account and sets the name of the account holder to Rob. clocks going tick and messages arriving via the network. I call a delegate ―A way of telling a piece of program what to do when something happens‖. These techniques are very useful. An example of a method we might want to use with this delegate you could consider is this one: C# Programming © Rob Miles 2010 162 . The way that C# does this is by allowing us to create instances of delegate classes which we give the event generators. for example we provided a custom WithdrawFunds for the BabyAccount class which only lets us draw out a limited amount of cash. Delegates are useful because they let us manipulate references to methods.5 Using Delegates Events and delegates are a very important part of C#. This means I can use it as a kind of method selector. A delegate is a "stand in" for a method.Advanced Programming Using Delegates 5. If you call the delegate it calls the method it presently refers to. They include stuff like people pressing buttons in our user interface. In each case we need to tell the system what to do when the event occurs. A delegate type is created like this: public delegate decimal CalculateFee (decimal balance). Therefore you should read this text carefully and make sure you understand what is going on. The bank will have a number of different methods which do this. the delegate for that method will have exactly the same appearance and cannot be used in any other way. Note that I've not created any delegates yet. This word is used to distinguish a delegate from things like pointers which are used in more primitive languages like C.1 Type safe delegates The phrase type safe in this context means that if the method accepts two integer parameters and returns a string. Once I've compiled the class the methods in it cannot change. This delegate can stand in for a method which accepts a single decimal parameter (the balance on the account) and returns a decimal value (the amount we are going to charge the customer). Don’t worry about this too much. In C you can create pointers to methods. Using a Delegate As an example. depending on the type of customer and the status of that customer. Just remember that delegates are safe to use. This means that you can call them in the wrong way and cause your program to explode. When the event occurs (this is sometimes called the event "firing") the method referred to by the event is called to deliver the message.5. Delegates are an important part of how events are managed in a C# program. but the C environment does not know (or even care) what the methods really look like. It might want to have a way in which a program can choose which fee calculation method to use as it runs. A posh description would have the form: A delegate is a type safe reference to a method in a class. I've just told the compiler what the delegate type CalculateFee looks like. We have seen that things like overriding let us create methods which are specific to a particular type of object. consider the calculation of fees in our bank. We can manage which particular method is going to be called in a given situation in terms of a lump of data which we can move around. 5. but they are hard wired into the code that I write. Events are things that happen which our program may need to respond to. I can change that by making another delegate: calc = new CalculateFee (FriendlyFee). If I want to use this in my program I can make an instance of CalculateFee which refers to it: CalculateFee calc = new CalculateFee (RipoffFee). but they can also be the source of really nasty bugs. In the future. 5. The calc delegate presently refers to a delegate instance which will use the RipoffFee method. they are the way that we will be able to keep on improving the performance of our computer systems. } } This is a rather evil fee calculator. They can make programs much easier to create. If you are overdrawn the fee is 100 pounds. The track is the statements that the thread is executing. Delegates are used a lot in event handlers and also to manage threads (as you will see below). 5. rather than as a good way to write programs.Advanced Programming Threads and Threading public decimal RipoffFee (decimal balance) { if ( balance < 0 ) { return 100. This gives us another layer of abstraction and means that we can now design programs which can have behaviours which change as the program runs. You can regard a list of delegates as a list of methods that I can call. it is best just to consider them in terms of how we use delegates to manage the response of a program to events. I don’t use them much beyond this in programs that I write. where the speed of computer processors is going to be limited by irritating things like the speed of light and the size of atoms. Programmer’s Point: Use Delegates Sensibly Allowing programs to change what they do as they run is a rather strange thing to want to do. You can visualise a thread as a train running along a track.6 Threads and Threading If you want to call yourself a proper programmer you need to know something about threads. This of course only works if FriendlyFee is a method which returns a value of type decimal and accepts a single decimal value as a parameter. In the same way that you can put more than one train on a C# Programming © Rob Miles 2010 163 . If you are in credit the fee is 1 pound. } else { return 1.6. This means that it can be managed in terms of references. An instance of a delegate is an object like any other. The thread usually starts in the Main method and finishes when the end of this method is reached. For now however. Now when I "call" calc it will run the FriendlyFee method.1 What is a thread? At the moment our programs are only using a single thread when they run. I’m presenting this as an example of how delegates let a program manipulate method references as objects. Now I can "call" the delegate and it will actually run the ripoff calculator method: fees = calc(100). so I can build structures which contain delegates and I can also pass delegates in and out of methods. programs that use threads can also fail in spectacular and confusing ways. in that if we wish to do more than one thing at the same time it is very useful just to send a thread off to perform the task. As far as the thread is concerned it is running continuously. for (count = 0.2 Why do we have threads? Threads make it possible for your computer to do something useful while one program is held up. count < 1000000000000L.3 Threads and Processors Consider the following method: static private void busyLoop() { long count. Bugs caused by threading are amongst the hardest ones to track down and fix because you have to make the problem happen before you can fix it. a computer can run more than one thread in a single block of program code. 5. The Windows system actually creates a new thread of execution which runs the event handler code. and I suggest that you follow these carefully. waiting for its turn to run. These could be performed ―in the background‖ while the user continues to work on the document.6. 5. giving each thread the chance to run for a limited time before moving on to run another. Threads are also how Windows forms respond to events. When a thread is not running it is held in a ―frozen‖ state. If we wrote a word processor we might find it useful to create threads to perform time consuming tasks like printing or spell checking. It is possible for systems to fail only when a certain sequence of events causes two previously well behaved threads to “fight” over a shared item of data. The first is by rapidly switching between active threads.Advanced Programming Threads and Threading single track. count = count+1) { } } C# Programming © Rob Miles 2010 164 . rather than try interleaving the second task with the first. You have not been aware of this because the operating system (usually Windows) does a very good job of sharing out the processing power. The programs that you have been writing and running have all executed as threads in your computer. but in reality a thread may only be active for a small fraction of a second every now and then. A modern computer can perform many millions of instructions per second. Your system can play music and download files while your program waits for you to press the next key. Programmer’s Point: Threads can be dangerous In the same way that letting two trains share the same railway track can sometimes lead to problems. A computer can support multiple threads in two ways. Newer machines now have ―dual core‖ or even ―quad core‖ processors which can actually run multiple threads simultaneously. it makes sense to share this ability amongst several tasks. Threads provide another level of ―abstraction‖. I’m going to give some tips on how to make sure that your programs don’t fall foul of threading related bugs.6. and the circumstances that cause the fault may only occur every now and then. You have seen that a ―click‖ event from a Button component can be made to run an event handler method. The second way to support multiple threads is to actually have more than one processor. This is how your program can be active at the same time as other programs you may wish to use alongside it. The first computers had only one processor and so were forced to use ―time slicing‖ to support multiple threads. The method above can only ever use a maximum of 25% of my system.Threading. The easiest way to make sure that we can use all the threading resources is to add a using directive at the start of our program: using System. We have used namespaces to locate resources before when we used files. which means that it can run four threads at a time. since it only runs on one of the four available processors. From the look of the above graph. If I stop my program running I get a display like the one below. the leftmost processor and the rightmost processor are quite busy but the middle two processors are not doing anything. Now all the processors are just ticking over. If I start up Windows Task Manager I see the picture below: My laptop has four processor cores. You can see little graphs under the CPU (Central Processor Unit) Usage History part of the display showing how busy each processor is. If I run a program that calls this method the first thing that happens is that the program seems to stop. One job of the operating system is to manage threads on your computer and decide C# Programming © Rob Miles 2010 165 . as my programs run on multiple processors. The Thread class provides a link between your program and the operating system. When we start using more than one thread we should see more of the graphs climbing up. Programmer’s Point: Multiple Threads Can Improve Performance If you can work out how to spread your program over several threads this can make a big difference to the speed it runs at.6. This class lives in the System namespace. 5.Advanced Programming Threads and Threading This method does nothing. Then the fan in my laptop comes on as the processor starts to heat up as it is now working hard. but it does do it many millions of times.4 Running a Thread An individual thread is managed by your program as an instance of the Thread class. class ThreadDemo { static private void busyLoop() { long count. } } The above code creates a thread called t1 and starts it running the busyLoop method. Selecting where a Thread starts running When you create a thread you need to tell the thread where to start running.Start(). Creating a Thread Once you have your start point defined you can now create a Thread value: Thread t1 = new Thread(busyLoopMethod). for (count = 0. This delegate type can refer to a method that does not return a value or accept any parameters. This is the point at which the thread begins to run. t1.Advanced Programming Threads and Threading exactly when each should get to run. A delegate is a way of referring to a method in a class. The delegate type used by threads is the ThreadStart type. This changes the Task Manager display: C# Programming © Rob Miles 2010 166 . count < 1000000000000L. When we start running t1 it will follow the delegate busyLoopMethod and make a call to the busyloop method. This is like telling your younger brother where on the track you’d like him to place your train. It also calls busyLoop directly from the Main method. You do this by using delegates.Start(). busyLoop(). Starting a Thread The Thread class provides a number of methods that your program can use to control what it does. it is waiting to be started. The variable t1 now refers to a thread instance. By calling methods provided by the Thread class you can start and stop them. count = count+1) { } } static void Main() { ThreadStart busyLoopMethod = new ThreadStart(busyLoop). To start the thread running you can use the Start method: t1. Note that at the moment the thread is not running. You can create a ThreadStart delegate to refer to this method as follows: ThreadStart busyLoopMethod = new ThreadStart(busyLoop). If you take a look at the busyLoop method above you will find that this method fits the bill perfectly. Thread t1 = new Thread(busyLoopMethod). This means that there are two processes active. i = i + 1) { Thread t1 = new Thread(busyLoopMethod). we can create many more threads than this: for (int i = 0.Start(). } This loop will create 100 threads. If you run too many threads at once you will slow everything down. If you run this code you might actually find that the machine becomes slightly less responsive. In fact. t1. Now our computer is really busy: All the processors are now maxed out. i < 100. This is actually the basis of a type of attack on your computer. and that all the cooling fans come on full blast. This makes your computer unusable by starting a huge number of threads which tie up the processor. all running the busyLoop method. Fortunately Windows boosts the priority of threads that deal with user input so you can usually get control and stop such wayward behaviour. This is potentially dangerous.Advanced Programming Threads and Threading Now more of the usage graphs are showing activity and the CPU usage is up from 25% to 50% as our program is now using more processors. and the CPU usage is up to 100%. called a Denial of Service attack. Making lots of Threads From the displays above you can see that if we create an additional thread we can use more of the power the computer gives us. Programmer’s Point: Two Many Threads Will Slow Everything Down Note that nothing has stopped your program from starting a large number of threads running. C# Programming © Rob Miles 2010 167 . 4. count = count+1) { } } The count variable is declared within the body of the method. 3. static object sync = new object(). You can do this by using a feature called mutual exclusion or mutex. count < 1000000000000L. but now every thread running busyLoop is sharing the same count variable. Consider the following sequence of actions: 1. 2. Before the addition can be performed. Thread 1 is stopped and Thread 20 is allowed to run. static private void busyLoop() { for (count = 0. The single track problem was solved by using a single brass token which was held by the engine driver. for (count = 0. What we need is a way of stopping the threads from interrupting each other. As the threads run they are all loading. This is because the variable is local to the busyLoop method: static private void busyLoop() { long count.Advanced Programming Threads and Threading 5. Both are dangerous. When the train left the single track section the driver handed the token back. When they entered the single track they were given the token.5 Threads and Synchronisation You might be wondering why all the threads don’t fight over the value of count that is being used as the loop counter. This means that each method has its own copy of this local variable. It is now very hard to predict how long this multi-threaded program will take to finish. Anyone wanting to enter the track had to wait for their turn with the token. it is as if the data for each thread is held in trucks that are pulled along behind the train. Thread 20 fetches the value of count. C# Programming © Rob Miles 2010 168 .6. it has overwritten the changes that Thread 20 made. Sometime later Thread 1 gets control again. count < 1000000000000L. We could make a tiny change to this code and make the count variable a member of the class: static long count. Mutual exclusion works in just the same way by using an instance of an object to play the role of the token. We can return to our train analogy here. Because of the way that Thread 1 was interrupted during its calculation. count = count + 1) { } } The method looks very similar. Using Mutual Exclusion to Manage Data Sharing Allowing two threads to share the same variable is a bit like allowing two trains to share the same piece of track. must be allowed to complete without being interrupted. adds one to it and stores it back in memory. The statement count = count + 1. If you are still thinking about threads as trains. incrementing and storing the value of count and overwriting changes that they have made. This is potentially disastrous. adds 1 to the value it fetched before it was stopped and stores the result back in memory. Thread 1 fetches the value of the count variable so that it can add 1 to it. each thread will end when the call of busyloop finishes. t1. Monitor. This queue is held in order. This would cause the executing thread to wait until the thread t1 finishes.Exit(sync). with the other threads lining up for their turn. A thread instance provides a Join method that can be called to wait for another thread to complete operation. there is no chance of Windows interrupting the increment statement and switching to another process.Exit calls can only be performed by one thread at a time. The Monitor class looks after all this for us. Programmer’s Point: Threads can Totally Break your Program If a thread grabs hold of a synchronisation object and doesn’t let go of it. see if a thread is still active and suspend and remove threads. and thread b has got object y and is waiting for object x. Once execution leaves the statements between the Monitor calls the thread can be suspended as usual. this will stop other threads from running if they need that object. I’m going to wait for him to call me”. This will certainly pause your program. called the “Deadly Embrace” is where thread a has got object x and is waiting for object y. This asks the operating system to destroy that thread and remove it from memory.6.Advanced Programming Threads and Threading This object doesn’t actually hold any data. C# Programming © Rob Miles 2010 169 . Joining Threads You might want to make one thread wait for another to finish working. This method is given the number of milliseconds (thousandth’s of a second) that the execution is to pause. Monitor. In our examples above. we don’t need to know how it works.Abort().Sleep(500). perhaps to allow the user to read the output or to wait a little while for something to happen you should use the Sleep method which is provided by the Thread class: Thread.Enter(sync). but at the expense of any other threads that want to run. Threads that aren’t able to run are ―parked‖ in a queue of waiting threads.Join(). These let you pause threads. The above call would pause a program for half a second. so the first thread to get to the entry point will be the first to get the token. wait for a thread to finish. You can abort a thread by calling its Abort method: t1. This is the computer version of “I’m not calling him to apologise. This is a really good way to make your programs fail.Enter and Monitor. 5. All the increment operations will complete in their entirety. If you just want your program to pause. In other words. count = count + 1. Another one. Thread Control The Thread class provides a set of methods that you can use to control the execution of a thread. A thread finishes when it exits the method that was called when it started. The code between the Monitor. It is just used as the token which is held by the active process. Pausing Threads As you can see above. one way to ―pause‖ a thread is to create a loop with an enormous limit value.6 Thread Control There are a number of additional features available for thread management. If variables sometimes get ―out of step‖ then this is a sure sign that you have several threads fighting over data items.999% of the time may fail spectacularly.Running ThreadState.7 Staying Sane with Threads Threads are very useful. You should protect any variables shared between threads by using the Monitor class as described above. Often the only way to investigate the problem is to add lots of write statements so that the program makes a log that you can examine after it has failed. You should try to avoid any ―Deadly Embrace‖ situations by making your threads either producers or consumers of data. t1. When we get a problem we look at what has happened and then work out what the fault is. if you are very lucky. time spent writing the log output affects the timing of events in the program and can often cause a fault to move or. is to create a multi-threaded application which starts up a thread to deal with each incoming request. Synchronisation problems like the ―Deadly Embrace‖ described above may only appear when two users both request a particular feature at exactly the same time.Resume(). This is an enumerated value which has a number of possible values. We know that our programs sometimes produce errors when they run. They let your program deal with tasks by firing off threads of execution. at which point we can begin to fix it. This is mostly because we have done something wrong. Up until now our programs have been single threaded and we have been able to put in the data which causes the problem.Running ) { Console. when a specific set of timing related events occur. If consumers are always waiting for producers C# Programming © Rob Miles 2010 170 . This will cause the program to fail. threads can also be a great source of frustration. A program which works fine for 99.Suspend(). The best way to create a system that must support many users. to display a message if thread t1 is running: if ( t1. Finding the state of a thread You can find out the state of a thread by using its ThreadState property. but simply make it pause for a while. This will stop inadvertent data corruption. waiting to join with another thread or waiting for a Monitor As an example.Stopped ThreadState. However.WriteLine("Thread Running"). you can call the Suspend method on the thread: t1. } 5.6. or just lock up completely. This makes the code easier to manage and also means that your program can make the best use of the processing power available.WaitSleepJoin the thread is running the thread has finished executing the thread method the thread has been suspended the thread is executing a Sleep. The thread is put to sleep until you call the Resume method on that thread.Suspend ThreadState. The most useful are: ThreadState. Of course. for example a web server.ThreadState == ThreadState. Unfortunately when you add multi-threading to a solution this is no longer true. When you have problems with a multi-threaded system the biggest difficultly is always making the fault occur so you can fix it.Advanced Programming Threads and Threading If you don’t want to destroy a thread. vanish completely. Now we are going to take a closer look at exceptions and see about creating our own exception types.exe"). 5.Diagnostics namespace. In a C# program you can create a process and start it in a similar way to starting a thread. so you can add a Using statement to make it easier to get hold of the class: using System.8 Threads and Processes You can regard different threads as all living in the computer together in the same way that a number of trains can share a particular railway.Start("Notepad. You can also create Process instances that you can control from within your program in a similar manner to threads. and not tacked on afterwards.Advanced Programming Structured Error Handling (and producers never wait for consumers) then you can be sure that you never get the situation where one thread waits for a thread that is waiting for it. The above line of C# would start the Notepad program. When you are using a word processor and a web browser at the same time on your computer each of them is running on your computer as a different process. This is actually a very important part of the design process. You can also use the Process class to start programs for you. We have been on the receiving end of exceptions already. Your word processor may fire off several threads that run within it (perhaps one to perform spell checking). We have seen that if something bad happens whilst a file is being read. but nothing in the word processor program can ever directly access the variables in the browser. In programming terms this is a move from threads to processes. Programmer’s Point: Put Threads into your Design I think what I am really saying here is that any thread use should be designed into your program. Processes are different from threads. the system will throw an exception to indicate that it is unhappy.7 Structured Error Handling By now I hope that you are starting to think very hard about how programs fail.Diagnostics.. or a Parse method is given an invalid string. The Start method is supplied with the name of the program that you want to start. To start a program on your system you can use the Start method on the Process class: Process. The next step up is to have more than one railway.6. If you want to use threads the way that they are managed and how they communicate should be decided right at the start of your design and your whole system should be constructed with them in mind. When something bad happens the program must deal with this in a managed way. This means that potentially badly behaved code like this has to be enclosed in a try – catch construction so that our program can respond sensibly. 5. The key to achieving this is to think about making your own custom exceptions for your system. You should also be thinking that when you build a system you should consider how you are going to manage the way that it will fail. C# Programming © Rob Miles 2010 171 . This class is held in the System. in that each process has its own memory space which is isolated from other processes. To create a standard exception with a message I pass the constructor a string. along with everything else in your system. You can generate System.Exception class has a default constructor which takes no parameters. can just use this to make an Exception instance. 5.Exception when something goes wrong. I can do this with the code: if ( inName. If I want to use this with my bank exception I have to sort out the constructor chaining for my exception class and write code as follows: public class BankException : System.7.7. but they are all based on the parent Exception class. there is a version of the Exception constructor which lets us add a message to the exception. This can be picked up and used to discover what has gone wrong.Length == 0 ) { throw new BankException( "Invalid Name" ). you will need to design how your program will handle and generate errors.Exception class.Exception { public BankException (string message) : base (message) { } } This makes use of the base keyword to call the constructor of the parent class and pass it the string message.2 Creating your own exception type Creating your exception type is very easy. I can catch the exception myself as follows: C# Programming © Rob Miles 2010 172 . but this means that exceptions produced by your code will get mixed up with those produced by other parts of the system. This means that.Exception class: public class BankException : System. or it might be one supplied by the system.7. This all (of course) leads back to the metadata which you have gathered. In the code above I make a new instance of the bank exception and then throw that.Exception { } This works because the System. The default constructor in BankException (which is added automatically by the compiler).Advanced Programming Structured Error Handling 5. At this point the execution would transfer to the ―nearest‖ catch construction. However.3 Throwing an Exception The throw keyword throws an exception at that point in the code. If you want your code to be able to explicitly handle your errors the best way forward is to create one or more of your own exceptions. If the exception is caught by the system it means that my program will be terminated. This might be a catch of mine. It can be done by simply extending the System. For example.1 The Exception class The C# System namespace holds a large number of different exceptions. } The throw keyword is followed by a reference to the exception to be thrown. If you want to throw your own exceptions you are strongly advised to create your own exception type which extends the system one. I might want to throw an exception if the name of my account holder is an empty string. 5. However. The thing that is thrown must be based on the System. in that the specification will give you information about how things can fail and the way that the errors are produced. e. The reference exception is set to refer to the exception which has been thrown. This helps a great deal in working with different languages. If doing this causes an exception to be thrown. The Message member of an exception is the text which was given. you need to design in your handling of errors. It can contain a text message which you can display to explain the problem to the user. We can have many catch constructions if we like. } The code tries to create a new account. and the message printed. } catch (BankException exception) { Console. depending on how the code fails: C# Programming © Rob Miles 2010 173 . as with just about everything else. Note that. 5. you should seriously consider extending the exception class to make error exceptions of your own which are even more informative. i. the catch invoked.4 Multiple Exception Types It is worth spending time thinking about how the exceptions and errors in your system are to be managed. Errors should be numbered. the code in the exception handler is obeyed.WriteLine( "Error : " + exception. newAddress).Exception { public BankExceptionBadName (string message) : base (message) { } } public class BankExceptionBadAddress : System. However.Message). This means that if I try to create an account with an empty name the exception will be thrown.7. your exceptions should be tagged with an error number.Exception { public BankExceptionBadAddress (string message) : base (message) { } } Now I can use different catches.Advanced Programming Structured Error Handling Account a. try { a = new Account(newName. and the catch will be matched up to the type of exception that was thrown: public class BankExceptionBadName : System. If the customer can say “Error number 25” when they are reporting a problem it makes it much easier for the support person to respond sensibly. Programmer’s Point: Design your error exceptions yourself An exception is an object which describes how things have gone wrong. To do this we have to solve two problems: how we physically spread the code that we write around a number of files how we logically identify the items in our program.WriteLine("Invalid address : " + addrException. error handlers are rather hard to test.WriteLine("Invalid name : " + nameException. 5. This will be called if the exception is not a name or an address one.8. In this section we are going to see how a large program can be broken down into a number of different chunks. since the code doesn’t get exercised as much as the rest of the system.Exception exception ) { Console. it is worth the effort! Error handling should be something you design in. As a professional programmer you must make sure that your error handling code is tested at least as hard as the rest of the system.8 Program Organisation At the moment we have put the entire program source that we have created into a single file. When you create the system you decide how many and what kind of errors you are going to have to manage. 5. and most of the time you will be using test data which assumes everything is OK.Message). At the very end of the list of handlers I have one which catches the system exception. This means that errors are more likely to get left in the error handlers themselves. This might mean that you have to create special test versions of the system to force errors into the code. Believe me. C# Programming © Rob Miles 2010 174 . } Each of the catches matches a different type of exception.1 Using Separate Source Files In a large system a programmer will want to spread the program over several different source files. The two problems are distinct and separate and C# provides mechanisms for both. When you design your solution to a problem you need to decide where all the files live. They only get run when something bad happens. } catch (System. } catch (BankExceptionBadAddress addrException) { Console. } catch (BankExceptionBadName nameException) { Console. in that the error handler is supposed to put things right and if it fails it will usually make a bad situation much worse. Of course this is a recipe for really big disasters.WriteLine("System exception : " + exception. try { a = new Account("Rob".Advanced Programming Program Organisation Account a. but now we are starting to write much larger programs and we need a better way to organise things. This is fine for teeny tiny projects. ""). Programmer’s Point: Programs often fail in the error handlers If you think about it.Message). This is especially important when you consider that a given project may have many people working on it.Message). which we compile and run. Our bank account class does not have a main method because the program will never start by actually running an account.exe' does not have an entrypoint defined The compiler is expecting to produce an executable program. Note that I have made the Account class public. Consider a really simple Account class: public class Account { private decimal balance = 0. We could put it into a file called "Account. Instead other programs will run and create accounts when they need them. The compiler can tell that it is being given an option because options always start with a slash character: csc /target:library AccountManagement. we might want to create lots of other classes which will deal with bank accounts. So.As I add more account management The problem is that the compiler now gets upset when I try to compile the file: error CS5001: AccountManagement. } public bool WithDrawFunds ( decimal amount ) { if ( amount < 0 ) { return false . because it has been told to produce a library rather than a program. since it does not know where the program should start. If I look at what has been created I find that the compiler has not made me an executable. I use the target option to the compile command.Advanced Programming Program Organisation In our bank management program we have identified a need for a class to keep track of a particular account. However. Options are a way of modifying what a command does. return true. The class will be called Account. } if ( balance >= amount ) { balance = balance . } else { return false .amount . public void PayInFunds ( decimal amount ) { balance = balance + amount. instead it has made me a library file: C# Programming © Rob Miles 2010 175 .cs" if we wanted to. the compiler cannot make an executable file.cs The compiler will not now look for a Main method. These have an entry point in the form of the Main method. } } } This is a fairly well behaved class in that it won't let us withdraw more money than we have in the account. So instead I have decided to put the class into a file called "AccountManagement. You can apply the protection levels to classes in the same way that you can protect class members. Generally speaking your classes will be public if you want them to be used in libraries. Creating a Library I solve this problem by asking the compiler to produce a library instead. This is so that classes in other files can make use of it.cs". } public decimal GetBalance () { return balance. This means that the content of this file will be loaded dynamically as the program runs.exe the library containing the Account class code the executable program that creates an Account instance Both these files need to be present for the program to work correctly.cs(7. } } This makes a new account. The compiler now knows where to find all the parts of the application. puts 50 pounds in it and then prints out the balance. test. Using a Library Now I have a library I next have to work out how to use it.3): error CS0246: The type or namespace name 'Account' could not be found (are you missing a using directive or an assembly reference?) AccountTest.cs.Advanced Programming Program Organisation AccountManagement. which is the library that contains the required class. which causes further errors. and so it can build the executable program. If I try to compile it I get a whole bunch of errors: AccountTest. Firstly I'm going to create another source file called AccountTest.WriteLine ("Balance:" + test. This is because of the "dynamic" in dynamic link library.cs(6. It means that library is only loaded when the program runs. To solve the problem I need to tell the compiler to refer to AccountManagement to find the Account class: csc /reference:AccountManagement.cs(5.dll AccountTest. class AccountTest { public static void Main () { Account test = new Account().dll The language extension dll stands for dynamic link library. Console.GetBalance()). Deleting System Components This means that if I do something horrid like delete the Acccountmanagement. not when it is built. In this case there is just the one file to look at. Library References at Runtime We have now made two files which contain program code: AccountManagement.dll file and then run the program this causes all kinds of nasty things to happen: C# Programming © Rob Miles 2010 176 .dll AccountTest. This means that it fails to create test.37): error CS0246: The type or namespace name 'test' could not be found (are you missing a using directive or an assembly reference?) The problem is that the compiler does not know to go and look in the file AccountManagement.cs to find the Account class.3): error CS0246: The type or namespace name 'test' could not be found (are you missing a using directive or an assembly reference?) AccountTest. This contains a Main method which will use the Account class: using System.cs The reference option is followed by a list of library files which are to be used.PayInFunds (50). the new version is picked up by AccountTest automatically. When you think about selling your application for money you must make sure that you have a managed approach to how you are going to send out upgrades and fixes. Which would be bad.FileNotFoundException: File or assembly name AccountManagement. rubber stamps. reserved for what happens. Windows itself works in this way. little pens on chains (pre-supplied with no ink in of course) and the like from suppliers. If I modify the AccountManagement class and re-compile it. Programmer’s Point: Use Version Control and Change Management So many things end up being rooted in a need for good planning and management. The good news is that I can fix the broken parts of the program without sending out an entire new version. and mean that at design time we have to make sure that we name all our classes in a way which will always be unique.8. The good news is that there are ways of making sure that certain versions of your program only work with particular program files. If the two systems ever meet up we can expect a digital fight to the death about what "Account" really means. was not found. and then make sure you use it. Of course this only works as long as I don't change the appearance of the classes or methods which AccountTest uses.IO. We don't just want to break things into physical chunks. This makes management of the solution slightly easier. File name: "AccountManagement" at AccountTest. Perhaps the programmers might decide that a sensible name for such a thing would be Account. We also want to use logical ones as well. or one of its dependencies. and the number of times that I've installed a new program (or worse yet an upgrade of an existing one) which has broken another program on the computer is too numerous to happily remember. We have decided that Account is a sensible name for the class which holds all the details of a customer account. There is a special phrase. Updating System Components Creating a system out of a number of executable components has the advantage that we can update part of it without affecting everything else. but if you don't do this you will either go mad or bankrupt. Unless the fixed code is exactly right there is a good chance that it might break some other part of the program. We can also have an C# Programming © Rob Miles 2010 177 . But we also have another problem. consider the situation in our bank.Main() … lots of other stuff This means that we need to be careful when we send out a program and make sure that all the components files are present when the program runs. If you are not sure what I mean by this. 5. And here we are again. The bank will buy things like paper clips. The bad news is that you have to plan how to use this technology. A far better way would be to say that we have a CustomerBanking namespace in which the word Account has a particular meaning.2 Namespaces We can use library files to break up our solution into a number of files. It may well wish to keep track of these accounts using a computer system. You could say that the bank has an account with such a supplier. But if you consider the whole of the bank operations you find that the word "account" crops up all over the place.Advanced Programming Program Organisation Unhandled Exception: System. "dll hell". If this sounds boring and pedantic then I'm very sorry. Arrgh! We are now heading for real problems. But this would be messy. The bad news is that this hardly ever works. We could solve the problem by renaming our account class CustomerBankAccount. Or both. in this case CustomerBanking. This creates a variable which can refer to instances of the Account class. } } } } I have used the namespace keyword to identify the namespace. If we want to create an instance of the class we use the fully qualified name again: test = new CustomerBanking. } if ( balance >= amount ) { balance = balance . with the namespace in front. } public decimal GetBalance () { return balance. However. C# Programming © Rob Miles 2010 178 . in that they are not defined in the same namespace. public void PayInFunds ( decimal amount ) { balance = balance + amount. The Account class we use is the one in the CustomerBanking namespace. one created outside any namespace) can just be referred to by its name. they are very easy to set up: namespace CustomerBanking { public class Account { private decimal balance = 0. return true.Advanced Programming Program Organisation EquipmentSupplier namespace as well. is known as a fully qualified name. This is followed by a block of classes. Every class declared in this block is regarded as part of the given namespace. } else { return false . Using a Class from a Namespace A Global class (i. If I want to use the Account class from the CustomerBanking namespace I have to modify my test class accordingly. If you want to use a class from a namespace you have to give the namespace as well.e. This is because we have not explicitly set up a namespace in our source files. A name like this. A given source file can contain as many namespace definitions and each can contain as many classes as you like. } public bool WithDrawFunds ( decimal amount ) { if ( amount < 0 ) { return false . Putting a Class in a Namespace Up until now every name we have used has been created in what is called the global namespace.amount .Account(). CustomerBanking. This prevents the two names from clashing.Account test. WriteLine ( "Hello World" ).at the very top. Of course the namespaces that you use should always be carefully designed. Nesting Namespaces You can put one namespace inside another. C# Programming © Rob Miles 2010 179 . If it finds one. This allows you to break things down into smaller chunks. However.RudeLetters . This means that the programmer can just write: Console. It is perfectly OK to spread the classes around a number of different source files. The System namespace is where a lot of the library components are located.WriteLine ( "Hello World" ). you'd probably figured that one out already.8. In terms of declaring the namespace you do it like this: namespace CustomerBanking { namespace Accounts { // account classes go here } namespace Statements { // statement classes go here } namespace RudeLetters { // rude letter classes go here } } Now I can use the classes as required: using CustomerBanking.it automatically looks in the CustomerBanking namespace to see if there is a class called Account. But then again.IO namespace with an appropriate include: using System. 5. The System namespace is like this. there is a namespace which is part of the System namespace which is specifically concerned with Input/Output. it is common for most programs to have the line: using System.IO . If there is it uses that. and this means of course more planning and organising.3 Namespaces in Separate Files There is no rule that says you have to put all the classes from a particular namespace in a particular file. Console then all is well and it uses that. We do this with the using keyword: using CustomerBanking . We can use these by means of fully qualified names: System. I'll go and have a look for a thing called Console in all the namespaces that I've been told to use".Console. You have to make sure that the files you want to use contain all the bits that are needed.Advanced Programming Program Organisation Using a namespace If you are using a lot of things from a particular namespace C# provides a way in which you can tell the compiler to look in that namespace whenever it has to resolve the name of a particular item. The compiler goes "ah. We have already used this technique a lot. When the compiler sees a line like: Account RobsAccount. . If it finds two Console items (if I was an idiot I could put a Console class in my CustomerBanking namespace I suppose) it will complain that it doesn't know which to use. You get to use the items in the System. . and only one. if you formalize (or perhaps even automate) the fault reporting process you can ensure that you get the maximum possible information about the problem. It is important to stress to users that any fault report will only be taken seriously if it is well documented. those which always happen and those which sometimes happen. the reason why problems with programs are called bugs is that the original one was caused by an actual insect which got stuck in some contacts in the computer. Programmer’s Point: Design Your Fault Reporting Process Like just about everything else I've ever mentioned.9. you can perform the sequence which always causes the bug to manifest itself and then use suitable techniques to nail it (see later). you will simply be told "There's a bug in the print routine". 5. if a user reports a fault the evidence may well be anecdotal. but there will still be some things that need to be fixed.1 Fault Reporting We have already seen that a fault is something which the user sees as a result of an error in your program. The two types of Fault Faults split into two kinds. The sad thing is that most of the bugs in programs have been put there by programmers. 5. However. I've been programming for many years and only seen this in a handful of occasions. some will always be better than others. Faults which always happen are easy.OverdraftWarning) or you can get hold of items in a namespace with using. Also. debugging is working very hard to find out how stupid you were in the first place. the steps taken to manifest it will be well recorded. and the time taken to deal with them. There is a strong argument for ignoring a fault report if you have not been given a sequence of steps to follow to make it happen.Advanced Programming Debugging Programmer’s Point: Fully Qualified Names are Good There are two ways you can get hold of something. However. Not everyone is good at debugging. This is not however how must bugs are caused. but it means that when I'm reading the code I can see exactly where a given resource has come from. and we are going to explore some of these here. Having said that there are techniques which you can use to ease the process. assigned to programmers and tracked very carefully. In a large scale development fault reports are managed. you should set up a process to deal with faults that are reported. In other words. causing it to fail. is valuable information about the quality of the thing that you are making. If a program fails as part of a test.9 Debugging Some people are born to debug. this approach will not make you popular with users.e. Faults are uncovered by the testing process or by users. It is very rarely that you will see your program fail because the hardware is faulty. The good news is that if you use a test driven approach to your development the number of faults that are found by the users should be as small as possible. Incidentally. Of the two I much prefer the fully qualified name. you will not be supplied with a sequence of steps which cause the fault to appear. If I just see the name OverdraftWarning in the code I have no idea where that came from and so I have to search through all the namespaces that I'm using to find it. The number of faults that are reported. C# Programming © Rob Miles 2010 180 . You can spell out the complete location by using a Fully Qualified Name (CustomerBanking. i. the way in which you manage your fault reports should be considered at the start of the project. I know that this makes the programs slightly harder to write. In other words.RudeLetters. stops completely) or when it does the wrong thing. incorrect comparison operators. for example a program may fail when an item is removed from a database. This does not mean that there is no sequence (unless you are suffering from a hardware induced transient of some kind – which is rather rare) but that you have not found the sequence yet. some folks are just plain good at finding bugs. Rather than make assumptions. this can be harder to find.9. or the loading department turn on the big hoist and inject loads of noise into the mains. 5. What this means is that you do not have a definite sequence of events which causes the system to fail. C# Programming © Rob Miles 2010 181 . Look for: use of un-initialised members of classes typographical errors (look for incorrectly spelt variable names. It is best if the person you are talking to is highly sceptical of your statements.Advanced Programming Debugging Faults which sometimes happen are a pain. find out if another department uses the machine to do a payroll run at that time and fills up all the scratch space. where the program crashes (i. do – while constructions which never fail. This can lead to the most annoying kind of fault. or in code which overwrote the memory where the database lives. or the size of the document which is being edited when the print is requested. If the bug appears on Friday afternoons on your UNIX system. The manifestation of a fault may be after the error itself has actually occurred.2 Bugswatting You can split faults into other categories. A fault may change or disappear when the program itself is changed. You might track this down to the number of pages printed. errors which overwrite memory will corrupt different parts of the program if the layout of the code changes.even if it is just the cat! The act of explaining the problem can often lead you to deduce the answer. where you put in extra print statements to find out more about the problem. If you assume that "the only way it could get here is through this sequence" or "there is no way that this piece of code could be obeyed" you will often be wrong. methods that call themselves by mistake and recurse their way into stack overflow an exception that is not caught properly If your program does the wrong thing. If the fault changes in nature this indicates problems with program or data being corrupted. but the error may be in the routine which stored the item. for loops which contain code which changes the control variable. Here are some tips: Don't make any assumptions. add extra code to prove that what you think is happening is really happening.e. Surprisingly. crashes are often easier to fix. wrongly constructed logical conditions) As I said above. invalid loop termination's. This is particularly important if the bug is intermittent. and the problem promptly disappears! If you suspect such an error. An example would be a print function which sometimes crashes and works at other times. Explain the problem to someone else . They usually point to: a state which is not catered for (make sure that all selection statements have a default handler which does something sensible and that you use defensive programming techniques when values are passed between modules) programs that get stuck into loops. or the amount of text on the page. improperly terminated comments) logical errors (look for faults in the sequence of instructions. your first test is to change the code and data layout in some way and then re-run the program. Look at all possible (if seemingly unrelated) factors in the manifestation of the bug. Alternatively you may find the answer as soon as you come back to the problem. just maybe this might be the best way forward.Advanced Programming Debugging Leave the problem alone for a while. You also need to be aware of the C# Programming © Rob Miles 2010 182 . Programmer’s Point: Bug Fixes Cause Bugs The primary cause of bugs is probably the bug fixing process. This does not mean that every program that I write is useless. and whether or not a fault in the code is a "stopper" or not. Go off and do something different and you may find that the answer will just appear. heaven forbid.3 Making Perfect Software There is no such thing as perfect software. Alternatively. and then look at the changes made since? If the system is failing as a result of a change or. I have been nearly moved to tears by the sight of people putting in another loop or changing the way their conditions operate to "see if this will make the program work". explained the code to a friend and checked all your assumptions then maybe. I start introducing bugs. Rip it up and start again In some projects it is possible that the effort involved in starting again is less than trying to find out what is wrong with a broken solution that you have created. But if it does something like always output the first page twice if you do a print using the Chinese font and a certain kind of laser printer this might be regarded as a problem most users could live with. This is because when people change the program to make one bit of it work the change that they make often breaks other features of the system. 5. with inputs. look carefully at how the introduction of the feature affects other modules in the system. prioritise them and manage how they are dealt with. Part of the job of a project manager in a development is deciding when a product is good enough to sell. or sometimes destroys the filestore of the host computer. A good Source Code Control System is very valuable here. The only way round this is to make sure that your test process (which you created as a series of lots of unit tests) can be run automatically after you've applied the fix. This at least makes sure that the fix has not broken anything important. When considering faults you must also consider their impact. If the program crashes every third time you run it. in that it can tell you exactly what changes have been made from one version to the next. As soon as I create a useful program. such programs will be very small and therefore not be good for much. this is probably the behaviour of a stopper bug. A stopper is a fault which makes the program un-saleable. This means that you need to evaluate the impact of the faults that get reported to you. In other words you must know how the program is supposed to work before you try and fix problems with what it actually does. This means that either the impossible is happening. just like throwing a bunch of electrical components at the wall and expecting a DVD player to land on the floor is also not going to work. However. or one of your assumptions that it is impossible is wrong! Can you get back to a state where the bug was not present. Remember that although the bug is of course impossible. One thing that I should make clear at this point is that the process of debugging is that of fixing faults in a solution which should work. I have found statistics which indicate that "two for one" is frequently to be expected. If you have taken some time off from debugging. Such efforts are always doomed. a bug fix. In other words I can write programs that I can guarantee will contain no bugs. One of the rules by which I work is that "any useful program will have bugs in it". try to move back to a point where the bug is not there. in that every bug fix will introduce two brand new bugs. just that it will not be perfect.9. it is happening. and then introduce the changes until the bug appears. outputs and some behaviours. a fault in a video game is much less of a problem than one in an air traffic control system. If you are serious about this business you should be reading at least one book about the subject at any one time. but there are quite a few things missing from this text. that you know how to solve it before you start writing code and that you manage your code production process carefully.2 Further Reading Code Complete Second Edition: Steve McConnell Published by Microsoft: ISBN 0-7356-1967-0 Not actually a book about C#. For example. You should take a look at the following things if you want to become a great C# programmer: serialisation attributes reflection networking 5. If you have any serious intention to be a proper programmer you should/must read/own this book. 5.Advanced Programming The End? context of the development. More a book about everything else. 5. How to be a programmer This web site is also worth a read.edu/howto/HowToBeAProgrammer.html C# Programming © Rob Miles 2010 183 . It covers a range of software engineering and programming techniques from the perspective of "software construction".1 Continuous Development A good programmer has a deliberate policy of constantly reviewing their expertise and looking at new things. as it covers the behaviours of a programmer very well indeed:. And I've never stopped programming. reading books about programming and looking at other people's code. because we don't have time to teach them all. It is not even all you need to know to be a C# programmer.10. I have been programming for as long as I can remember but I have never stopped learning about the subject. However.10. it is quite a good start.10 The End? This is not all you need to know to be a programmer. Read some of the recommended texts at the end of this document for more on this aspect of programming. The key to making software that is as perfect as possible is to make sure that you have a good understanding of the problem that you are solving.mines. It can be used to represent a real world item in your program (for example bank account). When writing programs we use the word to mean "an idealised description of something". but you can use it as the basis of. An accessor is implemented as a public method which will return a value to the caller. Call When you want to use a method. Base base is a C# keyword which has different meanings depending on the context in which it is given. abstract one. it can be treated as a Receipt) but it works in its own way. Accessor An accessor is a method which provides access to the value managed within a class. is reached the sequence of execution returns to the statement immediately following the method call. Note that if the thing being given access to is managed by reference the programmer must make sure that it is OK for a reference to the object is passed out. Effectively the access is read only. cheque receipt. Each "real" receipt class is created by extending the parent. Class A class is a collection of behaviours (methods) and data (properties).Glossary of Terms The End? 6 Glossary of Terms Abstract Something which is abstract does not have a "proper" existence as such. but we do know those behaviours which it must have to make it into a receipt. For example. In C# terms a class is abstract if it is marked as such. We can therefore create an abstract Receipt class which serves as the basis of all the concrete ones. wholesaler receipt etc. This means that it is a member of the receipt family (i. You can't make an instance of an abstract class. we may decide that we need many different kinds of receipt in our transaction processing system: cash receipt. We don't know how each particular receipt will work inside. you call it. in that the data is held securely in the class but code in other classes may need to have access to the value itself. a concrete one. or the return statement. starting at the first statement in its body. but it does not say how they are to be realised. C# Programming © Rob Miles 2010 184 . or if it contains one or more method which is marked as abstract. If the object is not to be changed it may be necessary to make a copy of the object to return to the caller. It is used in a constructor of a child class to call the constructor in the parent. or template for. When the end of the method. It is also used in overriding methods to call the method which they have overridden. When a method is called the sequence of execution switches to that method. In the case of component design an abstract class contains descriptions of things which need to be present.e. Whenever you need to collect a number of things into a single unit you should think in terms of creating a class. The compiler will produce an executable file which is run. Writing compilers is a specialised business. identifiers and symbols producing a stream of program source which is fed to the "parser" which ensures that the source adheres to the grammar of the programming language in use. the pre-processor. for example all the players in a football team or all the customers in a bank. The first phase. C# Programming © Rob Miles 2010 185 . which produces the executable file which is later run by the host. Otherwise the compiler will refuse to compile your program. Programmers use constructors to get control when an instance is created and set up the values inside the class. A collection class will support enumeration which means that it can be asked to provide successive values to the C# foreach construction. and the parent class has a constructor. If a class is a member of a hierarchy. The use of class hierarchies is also a way of reusing code. Component A component is a class which exposes its behaviour in the form of an interface. Constructor A constructor is a method in a class which is called as a new instance of that class is created.Collections namespace. it is important when making the child that you ensure the parent constructor is called correctly. The final phase is the code generator. One form of a collection is an array. When creating a system you should focus on the components and how they interact. they used to be written in assembly language but are now constructed in high level languages (like C#!). The collection classes can be found in the System. A compiler is a large program which is specially written for a particular computer and programming language. Another is the hashtable. You only need to override the methods that you want to update. Whenever you want to store a number of things together you should consider using a collection class to do this for you. takes the source which the user has written and then finds all the individual keywords. This means that rather than being thought of in terms of what it is (for example a BabyCustomerAccount) it is thought of in terms of what it can do (implement the IAccount interface to pay in and withdraw money).Glossary of Terms The End? Code Reuse A developer should take steps to make sure that a given piece of program is only written once. Compiler A compiler takes a source file and makes sense of it. rather than repeating the same statements at different parts of a program. Most compilers work in several phases. Cohesion A class has high cohesion if it is not dependent on/coupled to other classes. Their interactions are expressed in the interfaces between them. which allows you to easily find a particular item based on a key value in that item. This is usually achieved by putting code into methods and then calling them. Collection The C# library has the idea of a collection as being a bunch of things that you want to store together. For example a user interface class may be dependent on a business object class (if you add new properties to the business object you will need to update the user interface). However. Delegates are used to inform event generators (things like buttons. is right before you do anything is another way of saving on work. Exception An exception is an object that describes something bad that has just happened. A delegate is created for a particular method signature (for example this method accepts two integers and returns a float). a reference to the instance/class which contains the method and a reference to the method itself. The fact that a delegate is an object means that it can be passed around like any other.Glossary of Terms The End? Coupling If a class is dependent on another the two classes are said to be coupled. When the event occurs the method is called to deliver notification. Creative Laziness It seems to me that some aspects of laziness work well when applied to programming. It usually means that you have not properly allocated responsibility between the objects in your system and that two objects are looking after the same data. When a running C# Programming © Rob Miles 2010 186 . Windows components make use of delegates (a delegate is a type safe reference to a method) to allow event generators to be informed of the method to be called when the event takes place. timers and the like) of the method which is to be called when the event they generate takes place. in that you should aim for high cohesion and low coupling. where you try and pick up existing code. Dependency is often directional. too much dependency in your designs is a bad thing. since it makes it harder to update the system. Delegate A delegate is a type safe reference to a method. timers going tick etc. Making sure the spec. Event An event is some external occurrence which your program may need to respond to. A dependency relationship exists between two classes when a change in code in one class means that you might have to change the other as well. It can then be directed at a method in a class which matches that signature. Exceptions are part of the way that a C# program can deal with errors. buttons being pressed. Code reuse. As an example see the discussion of the CustomerAccount and ChildAccount Load method on page 145. structuring the design so that you can get someone else to do a lot of the work is probably the best example of creative laziness in action. Events include things like mouse movement. Many modern programs work on the basis of events which are connected to methods. windows being resized. is a good example of this. Dependency In general. Generally speaking a programmer should strive to have as little coupling in their designs as possible. it is unlikely that changes to the way that the user interface works will mean that the business object needs to be altered. However. Coupling is often discussed alongside cohesion. Note that the delegate instance holds two items. keys being hit. GUIDs are used for things like account references and tags which must be unique. It gives an identifier by which something can be referred to. Globally Unique Identifier (GUID) This is something which is created with the intention of it being unique in the world. amongst other things. and is often called the Functional Design Specification. In the above example the message would be set to ―Oh Dear‖. Most operating systems and programmer libraries provide methods which will create GUIDs. Functional Design Specification Large software developments follow a particular path. which contains code that is executed whether or not the exception is thrown. all developments must start with a description of what the system is to do. The precise path followed depends on the nature of the job and the techniques in use at the developer. This is the most crucial item in the whole project. Hierarchy A hierarchy is created when a parent class is extended by a child to produce a new class with all the abilities of the parent plus new and modified behaviours specific to the requirements of the child. The Exception object contains a Message property that is a string which can be used to describe what has gone wrong. from the initial meeting right up to when the product is handed over. Extending the child produces a further level of hierarchy.Glossary of Terms The End? program gets to a position where it just can’t continue (perhaps a file cannot be opened or an input value makes no sense) it can give up and ―throw‖ an exception: throw new Exception("Oh Dear"). You can make a program respond to exceptions by enclosing code that might throw an exception in a try – catch construction. If the exception is not ―caught‖ the program will end at that point. whether the exception // was thrown or not } A try – catch construction can also contain a finally clause. If an attempt is made to change the content of an immutable object a new object is created with the changed content and the "old" one C# Programming © Rob Miles 2010 187 . GUID creation involves the use of random values and the date and time. The classes at the top of the hierarchy should be more general and possibly abstract (for example BankAccount) and the classes at the lower levels will be more specific (for example ChildBankAccount). Immutable An immutable object cannot be changed. or FDS. however.. Interfaces make it possible to create components. It may also accept a parameter to work on. We don't care precisely what the component is. For more detail see the description of hierarchy. A message is delivered to an object by means of a call of a method inside that object. The string class is immutable. A public method is how an object exposes its behaviours. A class which implements an interface can be referenced purely in terms of that interface. Each particular range of computer processors has its own specific machine code. Member A member of a class is declared within that class. Methods are used to break a large program up into a number of smaller units.dll (dynamic link library) and will not contain a main method. It contains a number of very simple operations. for example move an item from the processor into memory. Metadata must be gathered by the programmer in consultation with the customer when creating a system. A class which implements an interface must contain code for each of the methods. or add one to an item in the processor. If a method is public it can be called by code other classes. The fact that the age value is held as an integer is metadata. Methods are sometimes called behaviours.Glossary of Terms The End? remains in memory. Inheritance Inheritance is the way in which a class extends a parent to allow it to make use of all the behaviours and properties the parent but add/customise these for a slightly different requirement. Machine code Machine Code is the language which the processor of the computer actually understands. Method A method is a block of code preceded by a method signature. Interface An interface defines a set of actions. Library A library is a set of classes which are used by other programs. Data members are sometimes called properties. The fact that it cannot be negative is more metadata. as long as it implements the interface it can be thought of purely in terms of that ability. They are also used to allow the same piece of program to be used in lots of places in a large development. which makes them easier to use in programs. The actions are defined in terms of a number of method definitions. The method has a particular name and may return a value. Metadata Metadata is data about data. It can either do something (a method) or hold some data (variable). each of which performs one part of the task. This gives strings a behaviour similar to value types. C# Programming © Rob Miles 2010 188 . The difference between a library and a program is that the library file will have the extension . which means that machine code written for one kind of machine cannot be easily used on another. It operates at all kinds of levels. Three different. A programmer creating a namespace can use any name in that namespace. methods could be provided to set the date. Private A private member of a class is only visible to code in methods inside that class. A namespace can contain another namespace. the new method is called. Namespaces let you reuse names. machine code is much harder to transfer. Overload A method is overloaded when one with the same name but a different set of parameters is declared in the same class. year information or by a text string or by a single integer which is the number of days since 1st Jan. The change will hopefully be managed. Override Sometimes you may want to make a more specialized version of an existing class. in that invalid values will be rejected in some way. not the overridden one in the parent. A portable application is one which can be transferred to a new processor or operating system with relative ease. Namespace A namespace is an area within which a particular name has a particular meaning. allowing hierarchies to be set up. it just gives the names by which they are known. You do this by creating a child class which extends the parent and then overriding the methods which need to be changed. Note that a namespace is purely logical in that it does not reflect where in the system the items are physically located. The programmer can then provide methods or C# properties to manage the values which may be assigned to the private members. In that case the SetDate method could be said to have been overloaded. High Level languages tend to be portable. C# provides the using keyword to allow namespaces to be "imported" into a program. This may entail providing updated versions of methods in the class. overloaded. the more portable something is the easier it is to move it onto a different type of computer. Methods are overloaded when there is more than one way of providing information for a particular action. A fully qualified name of a resource is prefixed by the namespace in which the name exists. for example a date can be set by providing day. each with the same name. Portable When applied to computer software. C# Programming © Rob Miles 2010 189 . Computers contain different kinds of processors and operating systems which can only run programs specifically written for them. It is conventional to make data members of a class private so that they cannot be changed by code outside the class. month. The only reason for not making a data member private is to remove the performance hit of using a method to access the data. You can use the base keyword to get access to the overridden method if you need to.Glossary of Terms The End? Mutator A mutator is a method which is called to change the value of a member inside an object. When the method is called on instances of the child class. This is implemented in the form of a public method which is supplied with a new value and may return an error code. Public A public member of a class is visible to methods outside the class. 2) . int b) – has the signature of the name Silly and an float parameter followed by an integer parameter. 2) . Note that the type of the method has no effect on the signature.would call the second. whereas: Silly(1.0f. An example of a property of a BankAccount class would be the balance of the account. . The C# language has a special construction to make the management of properties easy for programmers. If you do this the result is that there are now two tags which refer to a single object in memory. It is kind of a half way house between private (no access to methods outside this class) and public (everyone has access). It lets you designate members in parent classes as being visible in the child classes. The reference has a particular name. It is conventional to make the method members of a class public so that they can be used by code in other class. This means that you don’t need to create an C# Programming © Rob Miles 2010 190 . It is text which you want to pass through a compiler to produce a program file for execution. This means that the code: Silly(1. Reference A reference is a bit like a tag which can be attached to an instance of a class. Static In the context of C# the keyword static makes a member of a class part of a class rather than part of an instance of the class. Protected A protected member of a class is visible to methods in the class and to methods in classes which extend this class.Glossary of Terms The End? Property A property is an item of data which is held in an object.would call the first method. int b) – has the signature of the name Silly and two int parameters. A public method is how a class provides services to other classes. The signature is the name of the method and the type and order of the parameters to that method: void Silly(int a. Source file You prepare a source file with a text editor of some kind. One reference can be assigned to another. Another would be the name of the account holder. Signature A given C# method has a particular signature which allows it to be uniquely identified in a program. void Silly(float a. . C# uses a reference to find its way to the instance of the class and use its methods and data. This means that if you create a four element array you get hold of elements in the array by subscript values of 0. but they are more efficient to use in that accessing structure items does not require a reference to be followed in the same way as for an object. Stream A stream is an object which represents a connection to something which is going to move data for us. Structures are useful for holding chunks of related data in single units. Subscript This is a value which is used to identify the element in an array. Static members are useful for creating class members which are to be shared with all the instances.1. It is also used as a reference to the current instance. The best way to regard a subscript is the distance down the array you are going to move to get the element that you want. for use in non-static methods running inside that instance. This means that the first element in the array must have a subscript value of 0. to a network port or even to the system console. The movement might be to a disk file.Glossary of Terms The End? instance of a class to make use of a static member. for example interest rates for all the accounts in your bank. and there is nothing in the actual C# source file that determines the colour of the text. It is used in a constructor of a class to call another constructor. Streams remove the need to modify a program depending on where the output is to be sent or input received from. C# Programming © Rob Miles 2010 191 . It must be an integer value. the first element of the array) and extend up to the size of the array minus 1. This this is a C# keyword which has different meanings depending on the context in which it is given. It also means that static members are accessed by means of the name of their class rather than a reference to an instance. and structures are copied on assignment. Subscripts in C# always start at 0 (this locates. Structures are also passed by value into methods. Syntax Highlighting Some program editors (for example Visual Studio) display different program elements in different colours. Keywords are displayed in blue. confusingly. You put your program into a test harness and then the program thinks it is in the completed system. Note that the colours are added by the editor.2 or 3. to make it easier for the programmer to understand the code. It is not managed by reference. A test harness is very useful when debugging as it removes the need for the complete system (for example a trawler!) when testing. strings in red and comments in green. They are not as flexible as objects managed by reference. Test harness The test harness will contain simulations of those portions of the input and output which the system being tested will use. Structure A structure is a collection of data items. e. x = y causes the value in y to be copied into x.Glossary of Terms The End? Typesafe We have seen that C# is quite fussy about combining things that should not be combined. For this to take place the method in the parent class must have been marked as virtual. Virtual Method A method is a member of a class. not afterwards when it has crashed. Unit tests should be written alongside the development process so that they can be applied to code just after (or in test drive development just before) the code is written. Value types are passed as values into method calls and their values are copied upon assignment. Making a method virtual slightly slows down access to it. and work on the basis that the programmer knows best. This kind of fussiness is called type safety and C# is very big on it. Try to put a float value into an int variable and the compiler will get cross at this point. C# Programming © Rob Miles 2010 192 . One of these mistakes is the use of values or items in contexts where it is either not meaningful to do this (put a string into a bool) or could result in loss of data or accuracy (put a double into a byte). Changes to the value in x will not affect the value of y. Of course. Note that this is in contrast to reference types where the result of the assignment would make x and y refer to the same instance. that thing must be the right thing. The reason for this is that the designers of the language have noticed a few common programming mistakes and have designed it so that these mistakes are detected before the program runs. I can call the method to do a job. This is why not all methods are made virtual initially. Sometimes I may want to extend a class to produce a child class which is a more specialized version of that class. Some other languages are much more relaxed when it comes to combining things. if you really want to impose your will on the compiler and force it to compile your code in spite of any type safety issues you can do this by using casting. Value type A value type holds a simple value. i. I think it is important that developers get all the help they can to stop them doing stupid things. C# is very keen on this (as am I). In that case I may want to replace (override) the method in the parent with a new one in the child class. They assume that just because code has been written to do something. and a language that stops you from combining things in a way that might not be sensible is a good thing in my book. Only virtual methods can be overridden. Unit test A unit test is a small test which exercises a component and ensures that it performs a particular function correctly. in that the program must look for any overrides of the method before calling it..Glossary of Terms Index ( () 20. 21 { { 20 + + 23 A abstract classes and interfaces 116 methods 115 references to abstract classes 118 accessor 93. 124 case 125 Glossary of Terms 193 .. 177 global 178 nesting 179 separate files 179 using 179 namespaces 73 narrowing 34 nested blocks 58 nesting namespaces 179 new 85. 89. 136 global namespace 178 gozzinta 21 graphical user interface 153 GUID 109 N namespace 19. 31 if 39 immutable 124 information 7 inheritance 109 integers 27 interface abstraction 104 design 108 implementing 106 implementing multiple 108 reference 106 O object class 119 object oriented 15 objects 83. 159 Dispose 161 modal 161 fridge 6 fully qualified name 73 G Generics 134. 53 parenthesis 23 Parse 22 pause 169 plumber 9 pointers 162 print formatting 50 Glossary of Terms 194 . 52 base method 112 Main 17 overriding 111 replace 113 sealed 114 stopping overriding 114 virtual 111 mutator 91. 127 F files streams 141 foreach 143 Form 153.Glossary of Terms operands 33 operators 33 M member protection 91 MessageBox 161 metadata 11 methods 17. 35 loops 43 break 46 continue 46 do . 98 H hash table 131 Hashtable 132 I identifier 17.while 43 for 44 while 44 P parameters 22.. Glossary of Terms print placeholders 50 priority 33 private 91. 182 programming languages 13 properties 90. 67. 69 case 70 System namespace 19 Glossary of Terms 195 .. 103 Data Structures are Important 89 Delegates are strong magic 164.. 180. 85. 87 parameters 56 to abstract class 118 replacing methods 113 return 53 S scope 76. 124 comparison 125 editing 125 immutable 124 Length 125 literal 23 StringBuilder 126 structures 79 accessing 80 defining 79 subscripts 62 switch 68. 126 in interfaces 128 public 92 punctuation 25 R ReadLine 21 recipie 16 reference 84. 94 data 95 methods 96 story telling 37 stream 71 streams 141 StreamWriter 72 string 29. 87 sealed 114 searching 131 semicolon 21 source files 174 Star Trek 7 statement 17 returning values 49 static 19. 93. 78 Every Message Counts 153 Flipping Conditions 47 Fully Qualified Names are Good 180 Give Your Variables Sensible Names 32 Good Communicators 13 Great Programmers 16 Importance of Hardware 8 Importance of Specification 10 Interfaces are just promises 109 Internationalise your code 104. 92 program Main 19 program flow 38 programmer 6 Programmers Point Always provide an equals behaviour 122 Avoid Many Dimensions 65. .
https://www.scribd.com/doc/47587209/Rob-Miles-CSharp-Yellow-Book-2010
CC-MAIN-2017-34
refinedweb
80,109
75.1
bean BeanBean Bean is a small, fast, cross-platform, framework-agnostic event manager designed for desktop, mobile, and touch-based browsers. In its simplest form - it works like this: bean; Bean is included in Ender's starter pack, "The Jeesh". More details on the Ender interface below. APIAPI Bean has five main methods, each packing quite a punch. on(element, eventType[, selector], handler[, args ])on(element, eventType[, selector], handler[, args ]) bean.on() lets you attach event listeners to both elements and objects. Arguments - element / object (DOM Element or Object) - an HTML DOM element or any JavaScript Object - event type(s) (String) - an event (or multiple events, space separated) to listen to - selector (optional String) - a CSS DOM Element selector string to bind the listener to child elements matching the selector - handler (Function) - the callback function - args (optional) - additional arguments to pas to the callback function when triggered Optionally, event types and handlers can be passed in an object of the form { 'eventType': handler } as the second argument. Examples // simplebean;// optional arguments passed to handlerbean;// multiple eventsbean;// multiple handlersbean;bean;// Alternatively, you can pass an array of elements.// This cuts down on selector engine work, and is a more performant means of// delegation if you know your DOM won't be changing:bean;bean;; // 1bean; // 2bean; // 3// later:bean; // trigger 2bean; // trigger 1bean; // remove 1, 2 & 3// fire() & off() match multiple namespaces with AND, not OR:bean; // trigger 1bean; // remove nothing Notes - Prior to v1, Bean matched multiple namespaces in fire()and remove()calls using OR rather than AND. one(element, eventType[, selector], handler[, args ])one(element, eventType[, selector], handler[, args ]) bean.one() is an alias for bean.on() except that the handler will only be executed once and then removed for the event type(s). Notes - Prior to v1, one()used the same argument ordering as add()(see note above), it now uses the new on()ordering. off(element[, eventType[, handler ]])off(element[, eventType[, handler ]]) bean.off() is how you get rid of handlers once you no longer want them active. It's also a good idea to call off on elements before you remove them from your DOM; this gives Bean a chance to clean up some things and prevents memory leaks. Arguments - element / object (DOM Element or Object) - an HTML DOM element or any JavaScript Object - event type(s) (optional String) - an event (or multiple events, space separated) to remove - handler (optional Function) - the specific callback function to remove Optionally, event types and handlers can be passed in an object of the form { 'eventType': handler } as the second argument, just like on(). Examples // remove a single event handlersbean;// remove all click handlersbean;// remove handler for all eventsbean;// remove multiple eventsbean;// remove all eventsbean;// remove handlers for events using object literalbean Notes - Prior to Bean v1, remove()was the primary removal interface. This is retained as an alias for backward compatibility but may eventually be removed. clone(destElement, srcElement[, eventType ])clone(destElement, srcElement[, eventType ]) bean.clone() is a method for cloning events from one DOM element or object to another. Examples // clone all events at once by doing this:bean;// clone events of a specific typebean; fire(element, eventType[, args ])fire(element, eventType[, args ]) bean.fire() gives you the ability to trigger events. Examples // fire a single event on an elementbean;// fire multiple typesbean; Notes - An optional args array may be passed to fire()which will in turn be passed to the event handlers. Handlers will be triggered manually, outside of the DOM, even if you're trying to fire standard DOM events. setSelectorEngine(selectorEngine)setSelectorEngine(selectorEngine); Notes querySelectorAll()is used as the default selector engine, this is available on most modern platforms such as mobile WebKit. To support event delegation on older browsers you will need to install a selector engine. The Event object Bean implements a variant of the standard DOM Event object, supplied as the argument to your DOM event handler functions. Bean wraps and fixes the native Event object where required, providing a consistent interface across browsers. // prevent default behavior and propagation (even works on old IE)bean;// a simple shortcut version of the above codebean;// prevent all subsequent handlers from being triggered for this particular eventbean; Notes - Your mileage with the Eventmethods ( preventDefaultetc.) may vary with delegated events as the events are not intercepted at the element in question. Custom eventsCustom events;bean; mouseenter, mouseleavemouseenter, mouseleave Bean provides you with two custom DOM events, 'mouseenter' and 'mouseleave'. They are essentially just helpers for making your mouseover / mouseout lives a bit easier. Examples bean;bean; Object supportObject support Everything you can do in Bean with an element, you can also do with an object. This is particularly useful for working with classes or plugins. var inst = ;bean;//later on...bean; Ender Integration APIEnder Integration API If you use Bean with Ender its API is greatly extended through its bridge file. This extension aims to give Bean the look and feel of jQuery. Add events - on - $(element).on('click', fn); - addListener - $(element).addListener('click', fn); - bind - $(element).bind('click', fn); - listen - $(element).listen('click', fn); Remove events - off - $(element).off('click'); - unbind - $(element).unbind('click'); - unlisten - $(element).unlisten('click'); - removeListener - $(element).removeListener('click'); Delegate events - on - $(element).on('click', '.foo', fn); - delegate - $(element).delegate('.foo', 'click', fn); - undelegate - $(element).undelegate('.foo', 'click'); Clone events - cloneEvents - $(element).cloneEvents('.foo', fn); Custom events - fire / emit / trigger - $(element).trigger('click') Special events - hover - $(element).hover(enterfn, leavefn); - blur - $(element).blur(fn); - change - $(element).change(fn); - click - $(element).click(fn); - dblclick - $(element).dblclick(fn); - focusin - $(element).focusin(fn); - focusout - $(element).focusout(fn); - keydown - $(element).keydown(fn); - keypress - $(element).keypress(fn); - keyup - $(element).keyup(fn); - mousedown - $(element).mousedown(fn); - mouseenter - $(element).mouseenter(fn); - mouseleave - $(element).mouseleave(fn); - mouseout - $(element).mouseout(fn); - mouseover - $(element).mouseover(fn); - mouseup - $(element).mouseup(fn); - mousemove - $(element).mousemove(fn); - resize - $(element).resize(fn); - scroll - $(element).scroll(fn); $(element).select(fn); - submit - $(element).submit(fn); - unload - $(element).unload(fn); Browser supportBrowser support Bean passes our tests in all the following browsers. If you've found bugs in these browsers or others please let us know by submitting an issue on GitHub! - IE6+ - Chrome 1+ - Safari 4+ - Firefox 3.5+ - Opera 10+ ContributingContributing! ContributorsContributors - Jacob Thornton (GitHub - Twitter) - Rod Vagg (GitHub - Twitter) - Dustin Diaz (GitHub - Twitter) Special thanks to: Licence & copyrightLicence & copyright Bean is copyright © 2011-2012 Jacob Thornton and licenced under the MIT licence. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE file for more details.
https://www.npmjs.com/package/bean
CC-MAIN-2018-43
refinedweb
1,085
50.63
Specifying default values to function parameters in C++ By: Abinaya Emailed: 1671 times Printed: 2148 times For every parameter you declare in a function prototype and definition, the calling function must pass in a value. The value passed in must be of the declared type. Thus, if you have a function declared as long myFunction(int); the function must in fact take an integer variable. If the function definition differs, or if you fail to pass in an integer, you will get a compiler error. The one exception to this rule is if the function prototype declares a default value for the parameter. A default value is a value to use if none is supplied. The preceding declaration could be rewritten as long myFunction (int x = 50); This prototype says, "myFunction() returns a long and takes an integer parameter. If an argument is not supplied, use the default value of 50." Because parameter names are not required in function prototypes, this declaration could have been written as long myFunction (int = 50); The function definition is not changed by declaring a default parameter. The function definition header for this function would be long myFunction (int x) If the calling function did not include a parameter, the compiler would fill x with the default value of 50. The name of the default parameter in the prototype need not be the same as the name in the function header; the default value is assigned by position, not name. Any or all of the function's parameters can be assigned default values. The one restriction is this: If any of the parameters does not have a default value, no previous parameter may have a default value. If the function prototype looks like long myFunction (int Param1, int Param2, int Param3); you can assign a default value to Param2 only if you have assigned a default value to Param3. You can assign a default value to Param1 only if you've assigned default values to both Param2 and Param3. Program below demonstrates the use of default values. A demonstration of default parameter values. 1: // Demonstrates use 2: // of default parameter values 3: 4: #include <iostream.h> 5: 6: int AreaCube(int length, int width = 25, int height = 1); 7: 8: int main() 9: { 10: int length = 100; 11: int width = 50; 12: int height = 2; 13: int area; 14: 15: area = AreaCube(length, width, height); 16: cout << "First area equals: " << area << "\n"; 17: 18: area = AreaCube(length, width); 19: cout << "Second time area equals: " << area << "\n"; 20: 21: area = AreaCube(length); 22: cout << "Third time area equals: " << area << "\n"; 23: return 0; 24: } 25: 26: AreaCube(int length, int width, int height) 27: { 28: 29: return (length * width * height); 30: } Output: First area equals: 10000 Second time area equals: 5000 Third time area equals: 2500 Analysis: On line 6, the AreaCube() prototype specifies that the AreaCube() function takes three integer parameters. The last two have default values. This function computes the area of the cube whose dimensions are passed in. If no width is passed in, a width of 25 is used and a height of 1 is used. If the width but not the height is passed in, a height of 1 is used. It is not possible to pass in the height without passing in a width. On lines 10-12, the dimensions length, height, and width are initialized, and they are passed to the AreaCube() function on line 15. The values are computed, and the result is printed on line 16. Execution returns to line 18, where AreaCube() is called again, but with no value for height. The default value is used, and again the dimensions are computed and printed. Execution returns to line 21, and this time neither the width nor the height is passed in. Execution branches for a third time to line 27. The default values are used. The area is computed and then printed. DO remember that function parameters act as local variables within the function. DON'T try to create a default value for a first parameter if there is no default value for the second. DON'T forget that arguments passed by value can not affect the variables in the calling function. DON'T forget that changes to a global variable in one function change that variable for all functions. Be the first one to add a comment
http://www.java-samples.com/showtutorial.php?tutorialid=256
CC-MAIN-2017-17
refinedweb
732
68.7
How will this scheduled event actually process? In the backtest log, I get the following result: 2017-02-21 09:31:00 :BTS 2017-02-21 09:31:00 :2017-02-21 09:00:00 ... self.Schedule.On(self.DateRules.EveryDay(), self.TimeRules.At(9, 0), Action(self.BeforeTradingStart)) def BeforeTradingStart(self): # This is where we will run daily code checks to ensure lists are synced with positions. # additionally, will determine how many days a position has been held in Portfolio self.Log("BTS") now = self.Time self.Log(str(now)) So, whether backtesting, papertrading, or live trading, when is the function BeforeTradingStart actually executing? at 9:00 am, or 9:31 am?
https://www.quantconnect.com/forum/discussion/2344/scheduling-a-function-event-before-market-open/*
CC-MAIN-2018-51
refinedweb
113
52.56
DISKTAB(5) BSD Reference Manual DISKTAB(5) disktab - disk description file #include <disktab.h> disktab is a simple database which describes disk geometries and disk partition characteristics. It is used to initialize the disk label on the disk. The format is patterned after the termcap(5) terminal database. En- tries in disktab consist of a number of colon (':') separated fields. The first entry for each disk gives the names which are known for the disk, separated by "|" characters. The last name given should be a long name fully identifying the disk. The following list indicates the normal values stored for each disk en- try: Name Type Description ty str Type of disk (e.g., removable, winchester). dt str Type of controller (e.g., SMD, ESDI, floppy). ns num Number of sectors per track. nt num Number of tracks per cylinder. nc num Total number of cylinders on the disk. sc num Number of sectors per cylinder (default: ns*nt). su num Number of sectors per unit (default: sc*nc). se num Sector size in bytes (default: DEV_BSIZE). sf bool Controller supports bad144-style bad sector forwarding. rm num Rotation speed in RPM (default: 3600). sk num Sector skew per track (default: 0). cs num Sector skew per cylinder (default: 0). hs num Headswitch time in usec (default: 0). ts num One-cylinder seek time in usec (default: 0). il num Sector interleave (n:1) (default: 1). d[0-4] num Drive-type-dependent parameters. b0 str Pathname to primary bootstrap. b1 str Pathname to secondary bootstrap. bs num Boot block size (default: BBSIZE). sb num Superblock size (default: SBSIZE). ba num Block size for partition "a" (bytes). bd num Block size for partition "d" (bytes). be num Block size for partition "e" (bytes). bf num Block size for partition "f" (bytes). bg num Block size for partition "g" (bytes). bh num Block size for partition "h" (bytes). fa num Fragment size for partition "a" (bytes). fd num Fragment size for partition "d" (bytes). fe num Fragment size for partition "e" (bytes). ff num Fragment size for partition "f" (bytes). fg num Fragment size for partition "g" (bytes). fh num Fragment size for partition "h" (bytes). oa num Offset of partition "a" (sectors). ob num Offset of partition "b" (sectors). oc num Offset of partition "c" (sectors). od num Offset of partition "d" (sectors). oe num Offset of partition "e" (sectors). of num Offset of partition "f" (sectors). og num Offset of partition "g" (sectors). oh num Offset of partition "h" (sectors). pa num Size of partition "a" (sectors). pb num Size of partition "b" (sectors). pc num Size of partition "c" (sectors). pd num Size of partition "d" (sectors). pe num Size of partition "e" (sectors). pf num Size of partition "f" (sectors). pg num Size of partition "g" (sectors). ph num Size of partition "h" (sectors). ta str Type of partition "a" (4.2BSD, swap, etc.). tb str Type of partition "b". tc str Type of partition "c". td str Type of partition "d". te str Type of partition "e". tf str Type of partition "f". tg str Type of partition "g". th str Type of partition "h". /etc/disktab getdiskbyname(3), disklabel(5), disklabel(8), newfs(8) The disktab description file appeared in 4.2BSD..
http://www.mirbsd.org/htman/i386/man5/disktab.htm
CC-MAIN-2017-17
refinedweb
547
71.82
Simulating Railroad Crossing Lights Everyone has seen a railway crossing before, and if you're a railfan you've probably spent more than a few hours stuck behind them waiting for their infernal blink-blink-blink to stop so you can continue chasing your train! How do you make your model crossing blink like that though? The simple answer would be a 555 timer in astable mode with some set and reset triggers. But that would be easy, and when you're an software engineer everything looks like a software problem. So instead, we attack the problem with a sledgehammer and use an Arduino. Kidding aside, there are very valid reasons why you might want to use an Arduino for such a simple problem. Suppose you're using the excellent Arduino CMRI library to connect your layout to JMRI, and you have some infra red train detectors (coming soon from the Utrainia Electrik Company) wired up. It would then be very easy to get JMRI to set an output bit whenever a train is detected near the crossing; then in your Arduino you can flash the lights as appropriate. So to turn this into a practical example, I decided to write a small library to achieve just this. Enter: CrossingFlasher! This small Arduino library exposes just three small methods to let you start, stop, and update your crossing lights. It handles all the timing for you, and flashes them at the correct 3Hz flashing rate that we use here in NZ. And how would one use this on in Arduino C/MRI? #include <CMRI.h> #include <CrossingFlasher.h> CMRI cmri; CrossingFlasher bucks(2, 3); // crossbucks on pins 2 and 3 void setup() { Serial.begin(9600); } void loop() { // 1: process incoming CMRI data cmri.process(); // 2: update output. Reads bit 0 of T packet and sets the LED to this if (cmri.get_bit(0) == true) bucks.on(); else bucks.off(); // 3: update cross bucks bucks.update(); } Pretty simple huh? We've just wired up a set of crossbucks to pins 2 and 3 on our Arduino, and told them to flash whenever we set output bit 0 in JMRI (System Name: ML1). Using some Logix rules in JMRI it would be easy to trigger this from a block occupancy detector, a push button, or a broken-beam type detector. Piece of cake. A bit more work and you could even play the crossing sounds through JMRI. If you need to run more than one pair of crossbucks, just connect multiple LEDs to each Arduino output pin.
http://www.utrainia.com/46-simulating-railroad-crossing-lights
CC-MAIN-2019-51
refinedweb
425
72.56
access - check user's permissions for a file #include <unistd.h> int access(const char *pathname, int mode)); access checks whether the process would be allowed to read, write or test for existence of the file (or other file sys- tem object) whose name is pathname. If pathname is a sym- bolic link permissions of the file referred to by this sym- bolic link are tested. mode is a mask consisting of one or more of R_OK, W_OK, X_OK and. Simi- larly, a DOS file may be found to be "executable," but the execve(2) call will still fail. direc- tories sym- bolic link. ENOTDIR A component used as a directory in pathname is not, in fact, a directory. ENOMEM Insufficient kernel memory was available. ELOOP Too many symbolic links were encountered in resolv- ing pathname. EIO An I/O error occurred. access returns an error if any of the access types in the requested call fails, even if other types might be success- ful. secu- rity hole, because the user might exploit the short time interval between checking and opening the file to manipulate it. SVID, AT&T, POSIX, X/OPEN, BSD 4.3 stat(2), open(2), chmod(2), setuid(2), setgid(2).
http://www.linuxsavvy.com/resources/linux/man/man2/access.2.html
CC-MAIN-2018-05
refinedweb
205
74.49
You’ve probably been told before not to re-invent the wheel, but when it comes to my own code I couldn’t disagree more. I love re-inventing the wheel because it helps you understand why things are designed the way they are, and occasionally allows you to make something better. I’m currently “thinking out loud” about a whole new approach to the way I implement state machines that can provide functionality I had been wanting but not thought was possible – until now. The Problem You can see State Machine’s used in a lot of my code. In particular I make use of them in the Tactics RPG and Tic Tac Toe projects. The StateMachine and the State scripts are all MonoBehaviour subclasses which allows me to use things like GetComponent and AddComponent to make getting and changing state nice and easy. In addition, I could use MonoBehaviour abilities like Coroutines, or the ability to grab other components attached to the same GameObject. I felt like I had a whole host of beneficial and powerful features with my original architecture. Still, I always felt like something was missing, or just not right. Perhaps it just wasn’t as good as it could be. My primary complaint was that the whole architecture was based on “has a” rather than “is a”, and what I mean by this is that my object, say a “Game Controller”, has a “State Machine”, and it has several “State” components. So for example, when it comes time to perform “setup” on the “Game Controller” then I could create a special state for this task. However, the “Setup State” is its own object instantiated from its own class. It needs to know about its owner, but can only see what the owner exposes in the interface. In order to expose something to the state, it would also become exposed to everything else. Wouldn’t it be nice if the setup state could somehow have special privileges or permissions to see private fields or access private methods on the owner which other classes could not see? Even when a state only needs access to things which are already public, I still have to refer to them in the sense of the owner. For example, if a state refers to the Game Controller’s hero, it might need to use something like “owner.hero” instead of just “hero”. This would either end up making all of the code a little longer, or would require patterns such as convience wrappers. I often used the later approach and would make a common base class that my other states would inherit from. This class would automatically cache the owner, and use properties to wrap the owner’s fields and properties as if it were its own. Both of my primary complaints would be solved if I could think of the state as an “is a” instead of a “has a”. This would mean that the “state” ought to be able to act as if it was actually the “owner”. This would give me direct access to all fields, properties, and methods, etc, regardless of if they were public or private. This was a big challenge though because I had to keep several things in mind: - I still want to keep the “state as an object” pattern, so I can determine when state changes and act on it. If the owner is the state, there is no object change when a state changes. - There are no C++ style “friends” in C#. The only way to access something private is to be the class itself or to be defined inside the class, such as an embedded class. This option wouldn’t be compatible with a Monobehaviour. - I still need a common interface so that the state machine can act at a lower abstract level. I just want “Enter” and “Exit” methods. - I can use extensions on a class, but can only use methods, and can’t add new fields which might be needed to properly maintain the state. I also can’t keep re-defining the same method names needed by the state machine interface for multiple different states. The Solution I decided that I could “inject” the functionality I wanted. By making a state a simple container for “action” methods, I could still have separate objects for each state. I could maintain a common abstract enterface with “Enter” and “Exit” calls. I could even, in a way, allow a state to act as the owner itself and have full access to everything, even all private details (really it is the delegate that had access). I took it a step further, and made the owner a partial class, with separate definitions for each state in its own file. Because of this, I can also maintain clean and simple code where all of the logic unique to a state was organized nicely on its own. Want to see what this looks all like with actual code? Glad you asked! State using UnityEngine; using System; using System.Collections; public class State { #region Fields public Action Enter; public Action Exit; #endregion #region Factory Methods public static State Empty () { return new State(DoNothing, DoNothing); } public static State EnterOnly (Action enter) { return new State(enter, DoNothing); } public static State ExitOnly (Action exit) { return new State(DoNothing, exit); } #endregion #region Constructor public State (Action enter, Action exit) { Enter = enter; Exit = exit; } #endregion #region Private static void DoNothing () { } #endregion } Here’s the State class. See how it isn’t an abstract base class? With this new architecture, I don’t expect to actually create subclasses of State, but will probably always use them as simple “dumb” containers. The only expected purpose of the object is to hold the references to the two “Action” delegates, “Enter” and “Exit”. I created a few convenience Factory Methods just in case you wanted a state that didn’t implement one or both of the actions. The constructor expects both actions – neither action should ever be “null”. I also created a static method called DoNothing, that (surprise) doesn’t do anything. This will be the default method for any state that doesn’t need to be fully implemented. State Machine using UnityEngine; using System; using System.Collections; using System.Collections.Generic; [Serializable] public class StateMachine { string current = string.Empty; Dictionary<string, State> states = new Dictionary<string, State>(); public State CurrentState { get { return states.ContainsKey(current) ? states[current] : null; } } public void Register (string key, State state) { if (!string.IsNullOrEmpty(key) && state != null) states[key] = state; } public void Unregister (string key) { if (string.Equals(key, current)) ChangeState(string.Empty); if (states.ContainsKey(key)) states.Remove(key); } public void Clear () { ChangeState(string.Empty); states.Clear(); } public void ChangeState (string key) { if (string.Equals(key, current) || key == null) return; if (states.ContainsKey(current)) states[current].Exit(); current = key; if (states.ContainsKey(current)) states[current].Enter(); } } I also decided not to make the state machine a subclass of MonoBehaviour. I don’t actually “need” to, because functionality you would need can be injected directly into the state. Note that I also tagged this class as Serializable even though I have no serialized or public fields. If you look at the upper right corner of the Inspector pane, just to the right of the lock icon, is a hamburger looking menu button. You can use this to switch between “Normal” and “Debug” modes, but while in Debug, you will actually be able to see the private fields of your objects. Any Monobehaviour which has a state machine (even a private one) would then appear in the inspector, and you would be able to read the name of the current state field as well. Since I am not using MonoBehaviour based states, I need something to be able to maintain all of the state references so I can easily switch back and forth between them. I decided to use a Dictionary for this which maps from a string “key” to an instance of a State “value”. The dictionary is also private so you will be required to use the “Register” and “Unregister” methods which provides me a chance for a little error handling. If you need to clean up, you can use a simple “Clear” method to remove all states from the machine. Note that when I unregister or clear, it will first “Exit” the current state if applicable. The ChangeState method will be used the most. It expects a “key” to know which state to transition to. This also means you must have already registered the state by that key. The method checks to make sure that you aren’t attempting to change to the current state, and will exit early in that condition. It also checks to make sure you don’t pass a “null” value for the key, becuase that isn’t compatible with the dictionary. When transitioning from one state to another, I always give the original state the opportunity to “Exit” before allowing the new state the opportunity to “Enter”. Demo Consumer using UnityEngine; using System.Collections; using System.Collections.Generic; public partial class BattleController : MonoBehaviour { #region Fields StateMachine _stateMachine = new StateMachine(); int _aNumber; bool _aBool; #endregion #region MonoBehaviour void Awake () { RegisterStates(); _stateMachine.ChangeState(ActiveState); } void OnDestroy () { _stateMachine.Clear(); } #endregion #region Private void RegisterStates () { _stateMachine.Register(ActiveState, new State(ActiveStateEnter, ActiveStateExit)); _stateMachine.Register(PassiveState, new State(PassiveStateEnter, PassiveStateExit)); } #endregion } Here is the first part of a class which consumes our State Machine code. It is a MonoBehaviour but is defined as a partial class – this still works, you just have to make sure that when you connect a script to an object that the name of the file matches the name of the class. This demo doesn’t actually do anything, it simply demonstrates how to create a few states which can see and directly act on the members of the owner. All of the fields are left implicitly private to help re-iterate the flexibility of this approach. In the “Awake” method, I register all of the potential states that my implementation could need, and then change state to one of them. In the “Destroy” method, I clear all the states, which isn’t strictly necessary, but I like to clean up after myself. The RegisterStates method references strings and methods which aren’t defined anywhere you can see yet. Don’t forget that the class is defined as “partial” – you will see them in another file. using UnityEngine; using System.Collections; public partial class BattleController : MonoBehaviour { public const string ActiveState = "Active"; void ActiveStateEnter () { _aNumber++; _stateMachine.ChangeState(PassiveState); } void ActiveStateExit () { if (_aNumber >= 10) _aNumber = 0; } } This code exists in another file named “BattleControllerActive.cs” even though the name of the class is still “BattleController”. Don’t forget that you must include the “partial” keyword in the definition of this class or the compiler will complain at you. Note that you can’t add this file to GameObjects in the Unity Editor, but any fields you define here can still be visible in the inspector as part of the BattleController component. Within the same class (even a partial class) I can’t redefine a method with a same name as another method. This means I can’t have two “Enter” methods, but I can use a sort of naming convention like I did here. I am treating this partial class as if it were a state called “ActiveState” so I use that as a prefix on the “Enter” and “Exit” methods I actually wanted. Inside of these methods I “work” with the private properties defined in the original partial class file, even though I am not really doing anything useful. It is just placeholder code to show that I can do stuff. Cool huh? using UnityEngine; using System.Collections; public partial class BattleController : MonoBehaviour { public const string PassiveState = "Passive"; void PassiveStateEnter () { _aBool = true; } void PassiveStateExit () { _aBool = false; } } Like before, this code exists in yet another file named “BattleControllerPassive.cs” even though the name of the class is still “BattleController”. I use the same sort of naming convention as I did in the “ActiveState” version, and I modify one of the other private fields just for fun. Summary In this lesson I “thought out loud” about some new architecture I intend to add to my future projects as a replacement for my old State Machine code. With the new architecture, states no longer need a reference to their owner, because they act using code injected from the owner itself. This allows direct access to anything and everything, without needing to also expose access to any other classes. Note that I haven’t battle tested my ideas yet, so I don’t actually know how much I do or don’t like it. At the moment I feel like I will love it, but until I try working with it in a “real” project (or three) it can be hard to tell the full scope of the pros and cons of the new approach. As always, I’d love to hear your thoughts, so drop a comment below! 14 thoughts on “Partial Class State Machine” Interesting read! Are you planning on trying this out in the card game tutorial you have been thinking about? Yep, I would use it in every project from here on out – unless I get a bunch of negative feedback on it for some reason 🙂 I was finally able to find some time to go and rip out the old state system and put in the new one in the game I am making- it took all of 30 minutes, if that. Now to make a brand new state. So far I am liking it. 🙂 Awesome! How does State work? Doesn’t DoNothing need to be an Action object? A state is an object with references to methods as its data. You can pass a reference to any method in its constructor – this could be anything including an instance method on a different object which could even be private, or it could be a static method on a class. I provided convenience factory methods that create states and auto pass a reference to a static method of its own called “DoNothing” for use in the event that you don’t care what happens at a particular moment of a state transition. For example, maybe you need something to happen on entering a state, but don’t need to revert anything when exiting the same state. You can see the “Do Nothing” method inside of the State class – it has an empty body so it literally doesn’t do anything. It is also a static method, which means no instances of an object need to exist in order to reference it. I was just confused about passing the DoNothing method as an Action in the constructors but I looked up the documentation for Action on msdn and it makes sense now. Very cool, I would have used delegates but this cleans things up much better. Hm, I don’t quite get how this creates actual statefulness. The Enter and Exit define stuff that happens when you enter and exit the state, but what about in between? How do we enable or constrain what you can do WHILE a state is active? For instance, if I want to enable the player to control some actor in one state, and deactivate controls altogether in another, how would you do that? You mention that you cannot have methods with the same names in the partial classes, so how do you create different functionality for Update() (where the controls are usually handled) in different states? Sorry if I’m misunderstanding altogether, I still only barely understand state machines as a concept. Also, as far as I can tell, this approach seems to require some additional boilerplate code to be written, compared to the one used in Tactics RPG: You need to register all possible states manually, rather than having them simply ‘exist’. All states need a string name, but isn’t actually required by contract or such in any interface. Not the end of the world or anything, but string matching, even when they’re consts, does pet peeve me out. On the other hand, you do get rid of the need to have both a superstate and a controller, so that’s one less class. Great questions, here goes… In my own personal experience, when using state machines with Unity I primarily only use “enter” and “exit” methods (“update” can be used directly from any MonoBehaviour or coroutine as needed), and I use those as opportunities to modify traits of other entities and not the state itself. For example, I might have a state for a boss that determines what moves it will use, or a state for a menu that determines what buttons to display. When those states have their “enter” method invoked, then they will update the target entity accordingly. If you need the state itself to store information you can still do this by creating a subclass of “State” and add whatever fields you wish. But here again, I almost always would have only added fields to store the values I would want to apply on something else anyway. By injecting the enter method, all of the fields to change can be the fields on the entity itself – no need to duplicate them in a separate state object. Whatever values you assign in the implemented method are “captured” without even needing extra fields. Imagine you have a Game controller, which holds a state machine for Play, Pause, etc. When I change states to the play state, I might use the “enter” method to find a “player input” component and enable it. Likewise, when we “exit” the state we might disable the “player input” component so that it wont function in any other game state such as pause or game-over, etc. The player input component would have handled its own update loop while the component was enabled, so there was no need for the state machine to manage it. Regarding the additional code – yes, you do need to register the states, but this allows the states not to need to be a monobehaviour subclass. This feature by itself is appealing for a variety of reasons, like less overhead, portability, the ability to share and reuse states, etc. Regarding the string for each state, you can think of this as a unique id. It is required, because the string is the key which you pass to the state machine to change states. It allows you to provide your own identifiers for any state, which could allow you to have multiple states in a state machine that share the same class. Also keep in mind that we are not “matching” strings in the sense of slow string comparison checks. The dictionary creates a hash of the string and looks up values using that value. This is significantly more performant than GetComponent as well. Furthermore, if you do create const values for your keys then you also have compile time checking, code completion hints, etc – all the features you would hope for. If I missed anything or you need additional clarification, just ask. Ah, thanks, that clarifies a lot. I might have picked a bad example though, being quite simple & binary. Turning the component off/on works in that example, but I wonder about a more complex case. Namely, I’m trying to imagine the example in the game programming patterns book with the partial class state machine: His implementation of the state machine seems to basically be the same as the one you use Tactics RPG (I guess it’s the standard way?): State as seperate classes with a superclass and an owner. Here, controls are different in complex ways for each state, which is handled inside the state themselves. In Unity, one would have this code in a seperate Update() for each state. Is this still possible to do with the partial class state machine? Or would you say that it’s just as practical to do this by modifying fields and the like during “enter”? Yep, both the state machine in that article and the one used in my Tactics RPG are a pretty standard implementation of a State Machine. However, those patterns were designed for C++ and now we have some nice new features with C# so I re-imagined the approach using modern techniques. It is definitely possible to do separate updates per state using this pattern. It might look something like the following: 1. Add an additional “Action” field to the “State” class called “Update”. 2. Optionally add additional convenience factory methods which allow you to pass an update method 3. Add an “Update” method to the “StateMachine” class. This method should then call “Update” on its current state (assuming it has one, and assuming the state has an update method) 4. Whatever it is that requires the StateMachine with an Update method, needs to invoke it. For example, if you have an Enemy script which is a MonoBehavior, then you can use the Update method from there to call StateMachine.Update() Now you can implement it – suppose you had a JumpState, then you might add a JumpStateUpdate method which you pass to the constructor. Cool, thanks, that makes sense. And I would figure you could use the same procedure for any other in-built Unity function (though I suppose the cases where you’d need to do something for instance in Awake() that you could not do in Enter() or the “base” class Awake() are few and far between). I honestly still have thoughts, quibbles and questions but as this point, I really just need to try it out for myself and experiment with it. Thanks for the answers and thanks for a great blog! It’s benefiting not just my Unity programming, but my skills and mindset as a programmer in general. Keep it up! I was directed here by a previous coworker of yours. I fail to grasp all the benefits of this system, still it has been a huge help to me, thank you for sharing your work! Welcome. May I ask who the the coworker is? I’m glad the code has helped you. I’m not sure how many different implementations of state machines you have worked with, but I tend to recreate them a lot and see pros and cons in every approach. My favorite features of this variation is that the state IS the instance of whatever it is supposed to be a state OF. What this means is that I can allow a state to have access to all of the internal private code of the target object without needing to expose anything in a way that could be abused by other objects – its sort of like a C++ Friend.
http://theliquidfire.com/2016/05/12/partial-class-state-machine/
CC-MAIN-2020-16
refinedweb
3,818
69.01
XML tree wrapper API. Contains a DOM tree or an elementtree (depending on used XML parser) Definition at line 152 of file xmlifApi.py. Constructor of wrapper class XmlTreeWrapper. Input parameter: 'xmlIf': used XML interface class 'tree': DOM tree or elementtree which is wrapped by this object 'useCaching': 1 if caching shall be used inside genxmlif, otherwise 0 Definition at line 158 of file xmlifApi.py. Return the string representation of the contained XML tree. Definition at line 253 of file xmlifApi.py. Creates a copy of a whole XML DOM tree. Definition at line 186 of file xmlifApi.py. Create an ElementWrapper object. Input parameter: tupleOrLocalName: tag name of element node to be created (tuple of namespace and localName or only localName if no namespace is used) attributeDict: attributes for this elements curNs: namespaces for scope of this element Returns an ElementWrapper object containing the created element node. Definition at line 171 of file xmlifApi.py. Retrieve the wrapper object of the root element of the contained XML tree. Returns the ElementWrapper object of the root element. Definition at line 197 of file xmlifApi.py. Retrieve the contained XML tree. Returns the contained XML tree object (internal DOM tree wrapper or elementtree). Definition at line 205 of file xmlifApi.py. Return the string representation of the contained XML tree. Input parameter: 'prettyPrint': aligns the columns of the attributes of childNodes 'printElementValue': controls if the lement values are printed or not. Returns a string with the string representation of the whole XML tree. Definition at line 213 of file xmlifApi.py. Set external cache usage for the whole tree unlink commands are ignored if used by an external cache Input parameter: used: 0 or 1 (used by external cache) Definition at line 235 of file xmlifApi.py. Break circular references of the complete XML tree. To be called if the XML tree is not longer used => garbage collection! Definition at line 245 of file xmlifApi.py. Return 1 if caching should be used for the contained XML tree. Definition at line 230 of file xmlifApi.py.
https://docs.ros.org/en/jade/api/mavlink/html/classpymavlink_1_1generator_1_1lib_1_1genxmlif_1_1xmlifApi_1_1XmlTreeWrapper.html
CC-MAIN-2022-27
refinedweb
346
58.89
This is the mail archive of the gcc-patches@gcc.gnu.org mailing list for the GCC project. "Zack Weinberg" <zack@codesourcery.com> writes: | Gabriel Dos Reis <gdr@integrable-solutions.net> writes: | | > | While this diagnostic is technically more accurate, I think it's both | > | more confusing and poorer English. How's this? | > | | > | error: '<::' cannot begin a template-argument list | > | > The confusing thing about this suggestion is that the beginning of the | > template-argument list is not '<::'. | | But it is '<::', in the most important place: in the source file. Yes, but it is not the beginning of the template-argument list! The beginning is the single character '<'. | The programmer wrote | | T<::whatever> | | and that is what s/he will see in a text editor, so the error message | is most helpful by using that sequence of symbols. Sure. And previous suggestions have been also been talking about that sequence in various ways. What is wrong about it is saying that "'<::' cannot begin a template-argument list", because, when the programmer writes T<::whatever> he/she intends to have '::' part of 'whatever' -- and in essence, that is what it is supposed to mean: '::' qualifies 'whatever'. So the formulation we're looking for should not associate '<::' with the beinning of a template-argument list. | It is vanishingly | unlikely that the programmer actually wrote T <: : whatever; cpplib | does give the ability to test for this, via the PREV_WHITE flag on the | : token, but I doubt it is worthwhile. And I doubt that is even useful. | > It is like writing | > | > +++i | > | > which gets lexed as ++ + i and not + ++ i. How would you phrase the | > diagnostic for that? | | "+++i" is a valid C99 unary-expression. It is semantically invalid, | because "+i" is not a modifiable lvalue, but it parses. So I would | say something like | | error: invalid lvalue in increment | note: "+++" is parsed as "++ +" not "+ ++" | | assuming that it is possible to detect this case at the point where | the invalid lvalue diagnostic issues. | | > Yes, that is one of the items on the C++ Evolution Working Group wishlist | > we would like to address as cleanly as possible. | | May I suggest that a plausible (and generally helpful, not just with | templates) first step would be | | #pragma STDCXX (DIGRAPHS|TRIGRAPHS) (ON|OFF) | | ? This would be trivial to implement under the #pragma GCC namespace | as a demonstration. I'm afraid anything that starts with pragma is not a first step. This kind of thing can be handled without pragma/dogma intervening. I've already seen a patch for the ">>" thingy. The one proposed by Giovanni can be handled without pragma -- in fact, instead of issueing a diagnostic we could just accept the code (assuming the token was not spelt '['). | > Also, see suggestion ES018 at | > | > | > | > for things like | > | > vector<list<int>> vl; | | What is GJ? I don't understand what you mean by "GJ". -- Gaby
https://gcc.gnu.org/ml/gcc-patches/2004-01/msg02820.html
CC-MAIN-2019-22
refinedweb
474
64.41
We value your feedback. Take our survey and automatically be enter to win anyone of the following: Yeti Cooler, Amazon eGift Card, and Movie eGift Card! package test; import java.io.*; import javax.swing.*; import static javax.swing.JOptionPane.*; public class Main { public static void main(String[] arg) throws IOException { PrintWriter outputStream = new PrintWriter (new BufferedWriter (new FileWriter("customers.txt", true))); while(true) { String name = JOptionPane.showInputDialog ("The Customers name: "); if (name == null) break; String category = JOptionPane.showInputDialog ("Customer Category (Business or Private): "); String discount = JOptionPane.showInputDialog ("Discount: "); outputStream.println(name); outputStream.println(category); outputStream.println(discount); showMessageDialog(null, "The result: " + name + " " + category + " " + discount); } outputStream.close(); } } Open in new window what is the difference with your code? DOnt' know but your code did not compile for me - this one I tried - it works Open in new window We value your feedback. Take our survey and automatically be enter to win anyone of the following: Yeti Cooler, Amazon eGift Card, and Movie eGift Card! JDialog - that's why it didn't compile originally - there was no JOptionPane befor showMeassageDialog Anyway I also moved your code out of main method - it is not a good practice Open in new window Open in new window I have some questions and I hope you can help me with them. Why is the main method in the buttom? and why is the code this? "public class Main extends Frame { public Main() " Open in new window with JOptionPane you don't need it. It does not matter where the methods are placed in a class - it will always start with method main() You name the calss Main - even thow Java is case sensitive and upper case letter allows to distingusih it from method main - it is a bad practice to do so - better name calsses with what they are doing - say MyWriter The first line public class Main ... is a class declaration and opening line the next line piblic Main() - is the openeing of specuial method - constructor of the class which always shoul be named as the class but has parenthezes as oposed to class openeing line Thanks a lot for your help!
https://www.experts-exchange.com/questions/26834798/Java-BufferedWriter-Printwriter-help.html
CC-MAIN-2017-51
refinedweb
357
62.07
My professor gave me the java.util.Arrays.sort static method and it shows an error that the import cannot be resolved. This does not happen to any of my other methods. Is this written right? import java.util.Arrays.sort; import java.util.Arrays; Importing in Java involves either importing a member class of a package, in this case (java.util is the package, Arrays is the class) import java.util.Arrays; or importing the entire package, which would be import java.util.*; There is no concept of importing an individual class method, which is what import java.util.Arrays.sort; was attempting to do , because sort is just one method of the java.util.Arrays class (there are many other methods of that class). So if you attempt to do that, you will get the error message you did.
https://codedump.io/share/ebsGENgTNLDW/1/the-import-javautilarrayssort-cannot-be-resolved
CC-MAIN-2017-09
refinedweb
141
69.48
docopt 0.6.0 Pythonic argument parser, that will make you smile docopt creates beautiful command-line interfaces Video introduction to docopt: PyCon UK 2012: Create *beautiful* command-line interfaces with Python. Installation pip install docopt==0.6.0 Alternatively, you can just drop docopt.py file into your project–it is self-contained. docopt is tested with Python 2.5, 2.6, 2.7, 3.2, 3.3 and PyPy. API from docopt import docopt docopt(doc, argv=None, help=True, version=None, options_first=False) docopt takes 1 required and 4 optional arguments: - doc could be a module docstring (__doc__) or some other string that contains a help message that will be parsed to create the option parser. The simple rules of how to write such a help message are given in next sections. Here is a quick example of such a string: "" format: - <arguments>, ARGUMENTS. Arguments are specified as either upper-case words, e.g. my_program.py CONTENT-PATH or words surrounded by angular brackets: my_program.py <content-path>. - –options. Options are words started with dash (-), e.g. --output, -o. You can “stack” several of one-letter options, e.g. -oiv which will be the same as -o -i -v. The options can have arguments, e.g. --input=FILE or -i FILE or even -iFILE. However it is important that you specify option descriptions if you want for option to have an argument, a default value, or specify synonymous short/long versions of option (see next section on option descriptions). - commands are words that do not follow the described above conventions of --options) mutualy you usage patterns. - “[-]”. Single dash “-” is used by convention to signify that stdin is used instead of a file. To support this add “[-]” to you usage patterns. “-” act as a normal command. Data validation. Development We would love to hear what you think about docopt on our issues page Make pull requrests, report bugs, suggest ideas and discuss docopt. You can also drop a line directly to <vladimir@keleshev.com>. Porting docopt to other languages. Changelog docopt follows semantic versioning. The first release with stable API will be 1.0.0 (soon). Until then, you are encouraged to specify explicitly the version in your dependency tools, e.g.: pip install docopt==0.6.0 - 0.6.0 options_first parameter. Breaking changes: Corrected [options] meaning. argv defaults returns dictionary. - 0.2.0 Usage pattern matching. Positional arguments parsing based on usage patterns. Breaking changes: docopt returns namespace (for arguments), not list. Usage pattern is formalized. - 0.1.0 Initial release. Options-parsing only (based on options description). - Downloads (All Versions): - 16019 downloads in the last day - 97575 downloads in the last week - 438157 downloads in the last month - Author: Vladimir Keleshev - Keywords: option arguments parsing optparse argparse getopt - License: MIT - Categories - Package Index Owner: vladimir - DOAP record: docopt-0.6.0.xml
https://pypi.python.org/pypi/docopt/0.6.0
CC-MAIN-2015-32
refinedweb
477
51.65
Data Science with Python Certification Course - 103k Enrolled Learners - Weekend/Weekday - Live Class Optical Character Recognition is vital and a key aspect and python programming language. The application of such concepts in real-world scenarios is numerous. In this article, we will discuss how to implement Optical Character Recognition in Python Ticket counters use this extensively for scanning and detecting of key information on the ticket to track routes and commuters details. Conversion of paper text into digital formats where cameras capture high-resolution photographs and then OCR is used to bring them into a word or a PDF format. The introduction of OCR with python is credited to the addition of versatile libraries like “Tesseract” and “Orcad”. These libraries have helped many coders and developers to simplify their code design and allow them to spend more time on other aspects of their projects. Since the benefits are enormous, let us peek into what it is and how it is done. We first need to make a class using “pytesseract”. This class will enable us to import images and scan them. In the process it will output files with the extension “ocr.py”. Let us see the below code. The function block “process_image” is used to sharpen the text we get. The following route handler and view function are added to the application (app.py). Router Handler Code //ROUTE HANDLER '}"} ) OCR Engine Code // OCR ENGINE)) // Please ensure to update the imports and add API version number. import os import logging from logging import Formatter, FileHandler from flask import Flask, request, jsonify from ocr import process_image _VERSION = 1 # API version We are adding in the JSON response of the OCR Engine’s function that is “process_image()”. JSON is used for gathering information going into and out of the API. We pass the response in an object file using “Image” library from PIL to install it. Please note that this code only performs best with .jpg images only. If we use complex libraries that can feature multiple image formats then all images can be processed effectively. Also note, in case you are interested in trying out this code by yourself, then please install PIL which is procured out of “Pillow” library first • Start out by running the app, which is “app.py”: // $ cd ../home/flask_server/ $ python app.py // • Then, in another terminal run: //$ curl -X POST -d '{"image_url": "some_url"}' -H "Content-Type: application/json" For Example: // $ curl -X POST -d '{" C:UsersakashDownloadsPic1 ": " -H "Content-Type: application/json" { "output": "ABCDEnFGH I JnKLMNOnPQRST" } // Out of the many applications of using OCR in python, the popular one is handwriting recognition. People apply this is to recreate written text which can then be populated into numerous copies rather than just photocopying the original script. This is to bring about uniformity and legibility. OCR is also useful in converting PDF’s to texts and store them as variables. This can later be then subjected to any amount of pre-processing for additional tasks. Although the concept of OCR seems to be a beneficial topic in the world of Python, it sure does share its part of disadvantages. The OCR cannot always guarantee 100% accuracy. A lot of hours of training need to be applied with the help of Artificial Intelligence concepts which can enable the OCR engine to learn and recognize poor images. Handwriting images can be recognized but they depend on several factors like the style of the writing, the color of the page, the contrast of the image and the resolution of the image. With this, we come to an end of this Optical Character Recognition in Python article. I hope you go an understanding of how exactly OCR works. To get in-depth knowledge on Python along with its various applications, you can enroll now for the best Python course training with 24/7 support and lifetime access. Got a question for us? Mention them in the comments section of “Optical Character Recognition in Python” and we will get back to you. edureka.co
https://www.edureka.co/blog/optical-character-recognition-in-python/
CC-MAIN-2022-21
refinedweb
670
61.56
CSS Selectors are the same as node selectors , You can also nest calls . That is, through CSS After the selector selects some nodes , You can continue to use... Based on these nodes CSS Selectors , Of course , You can also use the node selector 、 Method selector and CSS Selectors are mixed together . The following example will CSS Selectors are mixed with method selectors to select specific nodes . from bs4 import BeautifulSoup html = ''' <div> <ul> <li class="item1" value1="1234" value2 = "hello world"> <a href=" geekori.com</a> </li> <li class="item"> <a href=" Jingdong Mall </a> <a href=" Google </a> </li> </ul> <ul> <li class="item
https://pythonmana.com/2021/11/20211125101745042b.html
CC-MAIN-2022-21
refinedweb
105
63.19
This video demonstrates how the SlideShow extender from the ASP.NET. Joe also comments on the benefits of storing images in the file system rather than the database. Presented by Joe Stagner Duration: 19 minutes, 27 seconds Date: 16 July 2007 Watch Video | Download Video | VB Code C# Code Video downloads: WMV | Zune | iPod | PSP | MPEG-4 | 3GP Audio downloads: AAC | WMA | MPEG-4 | MPEG-3 | MPEG-2 This is a good sample. I have used it in my webbapplication.. Thanks It would be greate if the pictures should be displayed in thumbnails... and if I want a specifik image to be displayed, I click on it. Hi Joe This video is good. But I would like to display the pictures in thumbnails and when I click on a picture the picture should be displayed The control doesn't do that but as mentioned in response to one of your other comments, since the control is open source you can modify the control to do whatever you need. the C# code doesnt seem to contain the SlidesService.cs file? Thanks for all the great video's! Joe I have been following all your videos .I wanna know if it is possible to show some data along with photos as slide show ? I think the C# version of the .zip file doesnt contain the web service. Also, if you have the following error message when viewing the page on the browser "unknown web method getslides...", then you have to remove the static keyword from the GetSlides() function. After this change, it worked OK for me! In any case, check the vb.net version that works fine When I download and run the VB code example, it get Microsoft JScript runtime error: Sys.InvalidOperationException: Can't add a handler for the error event using this method. Please set the window.onerror property instead. This also happens when I try to run this example on my Godaddy.com site. Any ideas? Thanks! Anyone ever successfully used this control on a secure/Windows Auth site, or in SharePoint using Windows Auth? I can't figure out a way to pass the default credentials of the currently authenticated user via the control. I get everything to work right up to the web service call. I can verify that the web service works fine, it's an authentication issue. I've looked at the javascript created by the call and I don't see anything in there or in the properties of the control to set credentials. Is this only to be used for anonymous and public facing websites? The full details of my scenario are here: forums.asp.net/.../1265300.aspx Any ideas? I'm not having any luck figuring this out anywhere on the interweb. Thanks! Hello everyone. Joe sorry this question is aimed at you. I have recently downloaded the 2008 visual web developer edition and tried running the example you recorded on it but it keeps bringing up errors especially when i begin to type AjaxControlToolkit.Slides. Do you know why and how to fix this? The script errors happen becuase you are trying to use the 1.0 version of the toolkit with the 3.5 version of the framework. Replace the Toolkit assembly in the Bin directory with the correct version and the code should run fine. HTH ! Is it possible to change the SlideShow so that the image and/or the text are Links? Hey Joe, This one works great using the script C# as you have it set in solution instead of a web service. I then went to try to do it using the web service like you built in the video and could not bring up the photos. I'm setting the SlideShowServicePath="SlidesService.asmx" and the project builds clean, but still no luck. Any Ideas?? same here, not working with web services in c# but works fine in vb.net. Joe, please show us the code for SlidesService.cs hi, i figured it out, we should include [System.Web.Script.Services.ScriptService], remove the static and everything remain the same. This will take care of the error "unknown web method GetSlides..." here is a sample for SlidesService.cs: using System; using System.Web; using System.Collections; using System.Web.Services; using System.Web.Script.Services; using System.Web.Services.Protocols; using System.Configuration; using System.Web.UI.WebControls; using System.Web.UI; /// <summary> /// Summary description for SlidesService /// </summary> [WebService(Namespace = "")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.Web.Script.Services.ScriptService] public class SlidesService : System.Web.Services.WebService { public SlidesService () { //Uncomment the following line if using designed components //InitializeComponent(); } [System.Web.Services.WebMethod] public AjaxControlToolkit.Slide[] GetSlides() { System.Web.UI.WebControls.SqlDataSource ds = new SqlDataSource(); ds.ConnectionString = ConfigurationManager.ConnectionStrings["pictureConnectionSt ring"].ConnectionString; string testConn = ConfigurationManager.ConnectionStrings["pictureConnectionSt ring"].ConnectionString; string mySelect; int count = 0; mySelect = "SELECT TOP 20 * FROM [pictureName] ORDER BY NEWID()"; ds.SelectCommand = mySelect; System.Data.DataView dv = (System.Data.DataView)ds.Select(new DataSourceSelectArguments()); count = dv.Table.Rows.Count; AjaxControlToolkit.Slide[] slides = new AjaxControlToolkit.Slide[count]; try { for (int i = 0; i < count; i++) { slides[i] = new AjaxControlToolkit.Slide("images/" + dv.Table.Rows[i]["path"].ToString(), dv.Table.Rows[i]["name"].ToString(), dv.Table.Rows[i]["description"].ToString()); } } catch { } //slides[0] = new AjaxControlToolkit.Slide("images/Blue hills.jpg", "Blue Hills", "Go Blue"); //slides[1] = new AjaxControlToolkit.Slide("images/Sunset.jpg", "Sunset", "Setting sun"); //slides[2] = new AjaxControlToolkit.Slide("images/Winter.jpg", "Winter", "Wintery..."); //slides[3] = new AjaxControlToolkit.Slide("images/Water lilies.jpg", "Water lillies", "Lillies in the water"); //slides[4] = new AjaxControlToolkit.Slide("images/VerticalPicture.jpg", "Sedona", "Portrait style picture"); return (slides); } I hope you still monitor this. First of all a great video. I remember programming using ASP, then ASP.NET 1.0. Then I stopped development for some time. Coming back to the web development now, the progress has been revolutionary. These things were almost unthinkable back then. I would like to know whether there is any possibility to display pictures and also play videos based on the contents of a particular directory. I think this is not possible with this control but is there any other alternative. Thanks a lot and keep up the great work. Regards, Nabil Joe; I've watched you video and downloaded the codes, but when I try to type the code, the application complains about "<ajaxToolKit:ToolKitScriptManager" tag to be invalid. I am trying to incorporate this new technique into my existing asp.net website. Am I missing something? Thanks Ramin Joe, Could you please tell how I can get the slideshow working under VS 2008. I downloaded C# code and it does work under VS 2005. Under VS 2008 the image is not displayed and the buttons don't work. Thanks, Hiren I have this working nicely on a development server, but it doesn't show the images on the live server. I get the image paths from a database table, and load into an array as per the example. Is the pathname in the New Slide constructor a relative URL or an absolute path? (There is no intellisense help) MySlides(0) = New AjaxControlToolkit.Slide("images/Blue hills.jpg", "Blue Hills", "Go Blue") My folder setup is exactly like the above, but on the live server no images appear. Any ideas? I have made a C# ASP.NET site in VS 2008 and it works with no problem. I am using nested masterpages to and it works. Remember that the path to images has to be exactly "images/xxx.jpeg". I used "~/images/xxx.jpg" and then I could not get it to work...small tip! By the way...Has anyone a clue how to display a thumbnail of the next and previus photo? I want to display 3 photos in the aspx page tumbnail prev and Main photo and the next photo. When I click next everything steps like a frame displaying 3 photos from the array. Joe, Nice work because I am new to Ajax... Nice tutorial..thanks May i know izzit possible to pass-in parameter into the function GetSlides()? Something like GetSlides(byVal value as String)? I've tried but unfortunately it can't proceed Why does stuff always work in the video and not in real life. When mine ran it didn't work at all. By the way, I am new to web services. I typed in everything he did. Did you see the squiggly blue line under the word after "Return". The video flicked and all of a sudden it's gone, He said "There we go" w/o explaining what he did to get rid of it. My squiggly line is still there and I can't seem to get rid of it. hi Joe i need present slide show in asp.net with animation, is it possible ? links can be added ? Bueno ya quedó, hice un truco que se me ocurrió. usé la propiedad "ImageDescriptionLabelID" 1.-Agregar un tag(...) en "description". código de ejemplo : _ Public Function GetImagenes() As AjaxControlToolkit.Slide() Dim MySlides(5) As AjaxControlToolkit.Slide MySlides(0) = New AjaxControlToolkit.Slide("Imgs/betabel.jpg", "Betabel", "key1") MySlides(1) = New AjaxControlToolkit.Slide("Imgs/Ensalada.jpg", "Ensalada", " key2") MySlides(2) = New AjaxControlToolkit.Slide("Imgs/Filete.jpg", "Filete", "key3") MySlides(3) = New AjaxControlToolkit.Slide("Imgs/t-Bone.jpg", "T Bone", "key4") MySlides(4) = New AjaxControlToolkit.Slide("Imgs/zanahorias.jpg", "Zanahorias", "key5") MySlides(5) = New AjaxControlToolkit.Slide("Imgs/alambres.jpg", "Alabres", "key6") Return MySlides End Function 2.-Agregar la funcion javascript que saca el valor del tag oculto. Función de Ejemplo: function ir() { location.href="Pagina.aspx?key="+document.getElementById('d ato').innerHTML } </script> Could any one please help me with this control? How can I add images dynamically?? In this example it hard coded the image names. I have like 100 images that I want to display one after the other dynamically. If you can get all of your images into the dataset, then you can use the same thing like bryiantan mentioned. I have done the same way and mine is working. Only problem with me is, it seems the page is trying to refresh everytime. I have add comment box in the same page. But when the slide show is playing, the comment box's visibility set false. But when slide show is not playing, user can leave comments. But not, user can't type there, because it seems the page is trying to refresh every time and when trying to write something there, use can't type. Any one has same behaviors like mine??? Hi, Any C# video for this? Sorry for less knowledge.. hi good evening, just give the steps ,hw to work with ajax. Ok. Thanks for the video and other tutorials on the AjaxControlToolKit. They have really helped me implement several pieces into my site already (tabs, accordion). I took the c# example of the slideshow and pasted it right into my .aspx test page and it worked (I changed the image information of course). Then I began to manipulate the way it looked and it still worked great. Exactly, like I wanted. So I decided to move the code in to a control so I could modularize it and add the control to any page and any place I want it. As soon as I did that when I ran in debug it says that it can not find the webserviceFunction:getSlides. I really am kind of a newb to the AjaxControlToolKit and I can not get this to work. I have tried changing just about every parameter and moving the code to the codebehind of the control I have tried alot of things...i just can not get it to work inside the control. I move the code back to the .aspx page instead of the ascx page poof works like a charm. Help. Could someone tell me how to make this work on the 2008 version or make a slide with the 2008 version thanks and would really appreciate it. Sorry pretty new with this. Any chance this could work on pages rather than images. I have several pages I wanted to display because they retrieve data directly from the database to render chart images. We'd like to have our company bulletin show these pages (as the charts are being updated) like a slideshow. Any insight is greatly appreciated. Can this control be used to play specific slides( from 5 to 10) Did someone manage to load images from "c:\username\images\" (abolute paths) ? A note: To use a page method in a code-behind instead of a web service, the method must be static. In your ASPX markup, use the attributes just as you would the web service: SlideShowServicePath="SlideShowExtender.aspx" SlideShowServiceMethod="GetSlides" In your code-behind file, make a public, static method decorated with the same WebMethod and ScriptMethod attributes: [System.Web.Services.WebMethod] [System.Web.Script.Services.ScriptMethod] public static AjaxControlToolkit.Slide[] GetSlides() For everyone(paulconsi, Juwar) that did not catch it, the hickup is that Joeadds () to the end of the line. I did this one in 05 and it was easy to copy the code and put it in and have it work but when I tried it again after installing 08 i missed it while trying to type it in as I was watching the video. it should read: Public Function GetSlides() As AjaxControlToolkit.Slide() but even then it is still kicking out errors for me. Hi Joe, or any one that can answer this question. There was a post see below Juwar : On September 02, 2008 12:07 AM said: Has any got the answer for this as I am having the same problem I have tried every thing. Again I saw Joe move the mouse to the right press some keys and the blue line went WHAT DID JOE DO ???? Please help Chris Hello JoeStagner... Exelent Example...I like it a lot...But I would like to know how will be if I used a BaseData SQl Server and get the picture... Thanks you very much.... hi brayine i make this code in VB.net i want to return the images dynamiclly from database this is the method Function loadslides() As AjaxControlToolkit.Slide() Dim con As New Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("con1").ConnectionString) Dim col As Collection = loadid() Dim obj As New MicroBankDA.Photogallery Dim filename As String = String.Empty Dim filelink As String = String.Empty Dim size As Integer = col.Count Dim counter As Integer = 1 Dim slides(size) As AjaxControlToolkit.Slide While counter <= col.Count obj = New MicroBankDA.Photogallery obj.id = col(counter).id obj.filename = col(counter).filename obj.filelink = col(counter).filelink slides(counter) = New AjaxControlToolkit.Slide(Server.MapPath("Slideimage") & "\" & obj.filename, obj.filename, " ") counter += 1 End While con.Open() Return slides End Function //////// and this function load id from the database Function loadid() As Collection Dim com As New Data.SqlClient.SqlCommand("select id,name,link from slides", con) Dim col As New Collection Dim dr As Data.SqlClient.SqlDataReader dr = com.ExecuteReader While dr.Read obj.id = dr.Item("id") obj.filelink = dr.Item("link") obj.filename = dr.Item("name") col.Add(obj) dr.Close() con.Close() Return col now when i load the page a massage box display error in head tags i dont konw what to do !!!!!!!!!!!!!!!!!!!! Hi Joe, Good example. Do you know how I can capture event on every changed slide? can we optimizing this control ajax to get a gallery image slide hey joe, Instead of using asp:buttons as my buttons im using Images Buttons. How would i be able to switch out the play and stop button with the images i created? Posted at 02:34 in the video Can someone please kindly tell me why either the C# or the VB code doesn't work on Netscape? You must be logged in to leave a comment. Advertise | Ads by BanManPro | Running IIS7 Trademarks | Privacy Statement © 2009 Microsoft Corporation.
http://www.asp.net/learn/videos/video-163.aspx
crawl-002
refinedweb
2,663
68.36
comparing and cross product 2 views (last 30 days) Show older comments Answered: Walter Roberson on 8 Jun 2020 hi guys, why c in below return with one coulmn, it supposed to return (x,y,z,) vector? regards c=zeros[]; for i=1:length(p) if (L1(i,3)==p(i,3)) c=[c,cross(L1(i,:),p(i,:))]; end end 2 Comments Accepted Answer Walter Roberson on 8 Jun 2020 Your first column of L1 is derived from something minus itself, so the first column is going to be all 0. Your second column of L1 is derived from something minus itself, so the second column is going to be all 0. Your third-column is generally non-zero. Cross-product of [0; 0; something] and [0; 0; something_else] is always going to be 0 >> syms x1 x2 y1 y2 >> cross([x1;y1;z1],[x2;y2;z2]) ans = y1*z2 - y2*z1 x2*z1 - x1*z2 x1*y2 - x2*y1 but your x1 and x2 and y1 and y2 are all 0, and every term involves one of those variables, so every term is going to come out 0. Therefore your cross-product will come out 0 . More Answers (0) See Also Categories Community Treasure Hunt Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!
https://au.mathworks.com/matlabcentral/answers/544754-comparing-and-cross-product?s_tid=prof_contriblnk
CC-MAIN-2022-21
refinedweb
223
60.99
In this lab you analyze a large (137 million rows) natality dataset using Google BigQuery and AI Platform Notebooks. This lab is part of a series of labs on processing scientific data. To complete this lab, you need: In this lab, you: This lab illustrates how you can carry out data exploration of large datasets, but continue to use familiar tools like Pandas and Jupyter Notebooks. The "trick" is to do the first part of your aggregation in BigQuery, get back a Pandas dataset and then work with the smaller Pandas dataset locally. Google Cloud provides a managed Jupyter experience, so that you don't need to run notebook servers yourself. To launch a notebook instance on GCP: Click the Navigation menu and scroll to AI Platform, then select Notebooks. Click New Instance and select TensorFlow 2.x > Without GPUs Once the instance has fully started, click Open JupyterLab to get a new notebook environment. You will now use BigQuery, a serverless data warehouse, to explore the natality dataset so that we can choose the features for our machine learning model. To invoke a BigQuery query: In the GCP console, selecting BigQuery from the top-left-corner Navigation Menu icon. In the Query editor textbox, enter the following query: SELECT plurality, COUNT(1) AS num_babies, AVG(weight_pounds) AS avg_wt FROM publicdata.samples.natality WHERE year > 2000 AND year < 2005 GROUP BY plurality How many triplets were born in the US between 2000 and 2005? ___________ Switch back to the JupyterLab window. In JupyterLab, start a new notebook by clicking on the Python 3 icon under the Notebook header. In a cell in the notebook, type the following, then click the Run button (which looks like a play button) and wait until you see a table of data. query=""" SELECT weight_pounds, is_male, mother_age, plurality, gestation_weeks FROM publicdata.samples.natality WHERE year > 2000 """ from google.cloud import bigquery df = bigquery.Client().query(query + " LIMIT 100").to_dataframe() df.head() Note that we have gotten the results from BigQuery as a Pandas dataframe. In the next cell in the notebook, type the following, then click Run. def get_distinct_values(column_name): sql = """ SELECT {0}, COUNT(1) AS num_babies, AVG(weight_pounds) AS avg_wt FROM publicdata.samples.natality WHERE year > 2000 GROUP BY {0} """.format(column_name) return bigquery.Client().query(sql).to_dataframe() df = get_distinct_values('is_male') df.plot(x='is_male', y='avg_wt', kind='bar'); Are male babies heavier or lighter than female babies? Did you know this? _______ Is the sex of the baby a good feature to use in our machine learning model? _____ In the next cell in the notebook, type the following, then click Run. df = get_distinct_values('gestation_weeks') df = df.sort_values('gestation_weeks') df.plot(x='gestation_weeks', y='avg_wt', kind='bar'); This graph shows the average weight of babies born in the each week of pregancy. The way you'd read the graph is to look at the y-value for x=35 to find out the average weight of a baby born in the 35th week of pregnancy. Is gestation_weeks a good feature to use in our machine learning model? _____ Is gestation_weeks always available? __________ Compare the variability of birth weight due to sex of baby and due to gestation weeks. Which factor do you think is more important for accurate weight prediction? __________________________________ Step 1 In the AI Platform Notebooks page on the GCP console, select the notebook instance and click DELETE. In this lab, you learned how to carry out data exploration of large datasets using BigQuery, Pandas, and Juypter. The "trick" is to do the first part of your aggregation in BigQuery, get back a Pandas dataset and then work with the smaller Pandas dataset locally. AI Platform Notebooks provides a managed Jupyter notebooks experience, so that you don't need to run notebook servers yourself. ©Google, Inc. or its affiliates. All rights reserved. Do not distribute.
https://codelabs.developers.google.com/codelabs/scd-babyweight1/index.html?index=..%2F..codemotion-2016
CC-MAIN-2020-10
refinedweb
645
65.73
Global datastore and namespace index cause problems when migrating workspaces ----------------------------------------------------------------------------- Key: JCR-1517 URL: Project: Jackrabbit Issue Type: Bug Components: jackrabbit-core Affects Versions: 1.4 Reporter: Tobias Bocanegra Assignee: Tobias Bocanegra Issue JCR-669 introduced a global namespace index. this is used by some persistence managers in order to keep the serialization of names small (fewer bytes). unfortunately this forms a problem when a workspace needs to be migrated to another repository with other namespace indexes. so an easy migration is not possible unless you export/import the entire workspace using system view (which is almost impossible for huge workspaces). another potential problem is cause by the global data store, since all workspaces share the same. so when migrating a workspace, you would need to transfer all respective records in the datastore to the target repository. where the datastore problem can be solved by copying the respective items, the namespace indexes are a bigger problem, since the serialized items need to be adjusted. suggest to alter the bundle pm to use the 'name index' for the namespaces as well. -- This message is automatically generated by JIRA. - You can reply to this email to add a comment to the issue online.
http://mail-archives.apache.org/mod_mbox/jackrabbit-dev/200804.mbox/%3C254118579.1207178905695.JavaMail.jira@brutus%3E
CC-MAIN-2016-22
refinedweb
201
53.41
Text events are generated by text components when their contents change, either programmatically or by a user typing. public class java.awt.event.TextEvent extends java.awt.AWTEvent { // Constants public final static int TEXT_FIRST; public final static int TEXT_LAST; public final static int TEXT_VALUE_CHANGED; // Constructors public TextEvent (Object source, int id); // Instance Methods public String paramString(); } Specifies the beginning range of text event ID values. Specifies the ending range of text event ID values. The only text event type; it indicates that the contents of something have changed. The object that generated the event. The type ID of the event. Constructs a TextEvent with the given characteristics. String with current settings of the TextEvent. AWTEvent.paramString() Helper method for toString() to generate string of current settings. AWTEvent, TextListener
https://docstore.mik.ua/orelly/java/awt/ch21_26.htm
CC-MAIN-2019-18
refinedweb
128
60.21
Learn about the basic Kubernetes concepts while deploying a sample application on a real cluster. Learn about the basic Kubernetes concepts while deploying a sample application on a real cluster.Pre: 1.13.5-do.1version. If you feel like testing other versions, feel free to go ahead. Just let us know how it went. *Select a Kubernetes version*: The instructions on this article were tested with the1.13.5-do.1 version.0/Month per node option,).0/Month per node0/Month per nodeoption, and that you have at least three nodes.: --kubeconfigflag in your kubectlcommands, but this is too cumbersome. KUBECONFIGenvironment variable to avoid having to type --kubeconfigall the time. <a href="" target="_blank">auth0blog/kubernetes-tutorial</a>: replicas: 2).with. ConclusionConclusion below. Everything I learned about the Kubernetes Networking Everything I learned about the Kubernetes NetworkingAn illustrated guide to Kubernetes Networking [Part 1] You’ve been running a bunch of services on a Kubernetes cluster and reaping the benefits. Or at least, you’re planning to. Even though there are a bunch of tools available to setup and manage a cluster, you’ve still wondered how it all works under the hood. And where do you look if it breaks? I know I did. Sure Kubernetes is simple enough to start using it. But let’s face it — it’s a complex beast under the hood. There are a lot of moving parts, and knowing how they all fit in and work together is a must, if you want to be ready for failures. One of the most complex, and probably the most critical parts is the Networking. So I set out to understand exactly how the Networking in Kubernetes works. I read the docs, watched some talks, even browsed the codebase. And here is what I found out. At it’s core, Kubernetes Networking has one important fundamental design philosophy: Every Pod has a unique IP. This Pod IP is shared by all the containers in this Pod, and it’s routable from all the other Pods. Ever notice some “pause” containers running on your Kubernetes nodes? They are called “sandbox containers”, whose only job is to reserve and hold a network namespace (netns) which is shared by all the containers in a pod. This way, a pod IP doesn’t change even if a container dies and a new one in created in it’s place. A huge benefit of this IP-per-pod model is there are no IP or port collisions with the underlying host. And we don’t have to worry about what port the applications use. With this in place, the only requirement Kubernetes has is that these Pod IPs are routable/accessible from all the other pods, regardless of what node they’re on. The first step is to make sure pods on the same node are able to talk to each other. The idea is then extended to communication across nodes, to the internet and so on. On every Kubernetes node, which is a linux machine in this case, there’s a root network namespace (root as in base, not the superuser) — root netns. The main network interface eth0is in this root netns. Similarly, each pod has its own netns, with a virtual ethernet pair connecting it to the root netns. This is basically a pipe-pair with one end in root netns, and other in the pod netns. We name the pod-end eth0, so the pod doesn’t know about the underlying host and thinks that it has its own root network setup. The other end is named something like vethxxx. You may list all these interfaces on your node using ifconfig or ip a commands. This is done for all the pods on the node. For these pods to talk to each other, a linux ethernet bridge cbr0 is used. Docker uses a similar bridge named docker0. You may list the bridges using brctl show command. Assume a packet is going from pod1 to pod2. 1. It leaves pod1’s netns at eth0 and enters the root netns at vethxxx. 2. It’s passed on to cbr0, which discovers the destination using an ARP request, saying “who has this IP?” 3. vethyyy says it has that IP, so the bridge knows where to forward the packet. 4. The packet reaches vethyyy, crosses the pipe-pair and reaches pod2’s netns. This is how containers on a node talk to each other. Obviously there are other ways, but this is probably the easiest, and what docker uses as well. As I mentioned earlier, pods need to be reachable across nodes as well. Kubernetes doesn’t care how it’s done. We can use L2 (ARP across nodes), L3 (IP routing across nodes — like the cloud provider route tables), overlay networks, or even carrier pigeons. It doesn’t matter as long as the traffic can reach the desired pod on another node. Every node is assigned a unique CIDR block (a range of IP addresses) for pod IPs, so each pod has a unique IP that doesn’t conflict with pods on another node. In most of the cases, especially in cloud environments, the cloud provider route tables make sure the packets reach the correct destination. The same thing could be accomplished by setting up correct routes on every node. There are a bunch of other network plugins that do their own thing. Here we have two nodes, similar to what we saw earlier. Each node has various network namespaces, network interfaces and a bridge. Assume a packet is going from pod1 to pod4 (on a different node). pod1’s netns at eth0and enters the root netns at vethxxx. cbr0, which makes the ARP request to find the destination. cbr0to the main network interface eth0since nobody on this node has the IP address for pod4. node1onto the wire with src=pod1and dst=pod4. pod4IP. node2at the main network interface eth0. pod4isn’t the IP of eth0, the packet is still forwarded to cbr0since the nodes are configured with IP forwarding enabled. pod4IP. It finds cbr0as the destination for this node’s CIDR block. route -ncommand, which will show a route for cbr0like this: The bridge takes the packet, makes an ARP request and finds out that the IP belongs to vethyyy. The packet crosses the pipe-pair and reaches pod4 🏠 We’ll expand on these ideas and see how the overlay networks work. We will also understand how the ever-changing pods are abstracted away from apps running in Kubernetes and handled behind the scenes. Overlay networks are not required by default, however, they help in specific situations. Like when we don’t have enough IP space, or network can’t handle the extra routes. Or maybe when we want some extra management features the overlays provide. One commonly seen case is when there’s a limit of how many routes the cloud provider route tables can handle. For example, AWS route tables support up to 50 routes without impacting network performance. So if we have more than 50 Kubernetes nodes, AWS route table won’t be enough. In such cases, using an overlay network helps. It is essentially encapsulating a packet-in-packet which traverses the native network across nodes. You may not want to use an overlay network since it may cause some latency and complexity overhead due to encapsulation-decapsulation of all the packets. It’s often not needed, so we should use it only when we know why we need it. To understand how traffic flows in an overlay network, let’s consider an example of flannel, which is an open-source project by CoreOS. Here we see that it’s the same setup as before, but with a new virtual ethernet device called flannel0 added to root netns. It’s an implementation of Virtual Extensible LAN (VXLAN), but to linux, its just another network interface. The flow for a packet going from pod1 to pod4 (on a different node) is something like this: The packet leaves pod1’s netns at eth0 and enters the root netns at vethxxx. It’s passed on to cbr0, which makes the ARP request to find the destination. 3a. Since nobody on this node has the IP address for pod4, bridge sends it to flannel0 because the node’s route table is configured with flannel0 as the target for the pod network range . 3b. As the flanneld daemon talks to the Kubernetes apiserver or the underlying etcd, it knows about all the pod IPs, and what nodes they’re on. So flannel creates the mappings (in userspace) for pods IPs to node IPs. flannel0 takes this packet and wraps it in a UDP packet with extra headers changing the source and destinations IPs to the respective nodes, and sends it to a special vxlan port (generally 8472). Even though the mapping is in userspace, the actual encapsulation and data flow happens in kernel space. So it happens pretty fast. 3c. The encapsulated packet is sent out via eth0 since it is involved in routing the node traffic. The packet leaves the node with node IPs as source and destination. The cloud provider route table already knows how to route traffic between nodes, so it send the packet to destination node2. 6a. The packet arrives at eth0 of node2. Due to the port being special vxlan port, kernel sends the packet to flannel0. 6b. flannel0 de-capsulates and emits it back in the root network namespace. 6c. Since IP forwarding is enabled, kernel forwards it to cbr0 as per the route tables. The bridge takes the packet, makes an ARP request and finds out that the IP belongs to vethyyy. The packet crosses the pipe-pair and reaches pod4 🏠 There could be slight differences among different implementations, but this is how overlay networks in Kubernetes work. There’s a common misconception that we have to use overlays when using Kubernetes. The truth is, it completely depends on the specific scenarios. So make sure you use it only when it’s absolutely needed.An illustrated guide to Kubernetes Networking [Part 3] Due to the every-changing dynamic nature of Kubernetes, and distributed systems in general, the pods (and consequently their IPs) change all the time. Reasons could range from desired rolling updates and scaling events to unpredictable pod or node crashes. This makes the Pod IPs unreliable for using directly for communications. Enter Kubernetes Services — a virtual IP with a group of Pod IPs as endpoints (identified via label selectors). These act as a virtual load balancer, whose IP stays the same while the backend Pod IPs may keep changing. The whole virtual IP implementation is actually iptables (the recent versions have an option of using IPVS, but that’s another discussion) rules, that are managed by the Kubernetes component — kube-proxy. This name is actually misleading now. It used to work as a proxy pre-v1.0 days, which turned out to be pretty resource intensive and slower due to constant copying between kernel space and user space. Now, it’s just a controller, like many other controllers in Kubernetes, that watches the api server for endpoints changes and updates the iptables rules accordingly. Due to these iptables rules, whenever a packet is destined for a service IP, it’s DNATed (DNAT=Destination Network Address Translation), meaning the destination IP is changed from service IP to one of the endpoints — pod IP — chosen at random by iptables. This makes sure the load is evenly distributed among the backend pods. When this DNAT happens, this info is stored in conntrack — the Linux connection tracking table (stores 5-tuple translations iptables has done: protocol, srcIP, srcPort, dstIP, dstPort). This is so that when a reply comes back, it can un-DNAT, meaning change the source IP from the Pod IP to the Service IP. This way, the client is unaware of how the packet flow is handled behind the scenes. So by using Kubernetes services, we can use same ports without any conflicts (since we can remap ports to endpoints). This makes service discovery super easy. We can just use the internal DNS and hard-code the service hostnames. We can even use the service host and port environment variables preset by Kubernetes. Protip: Take this second approach and save a lot of unnecessary DNS calls! The Kubernetes services we’ve talked about so far work within a cluster. However, in most of the practical cases, applications need to access some external api/website. Generally, nodes can have both private and public IPs. For internet access, there is some sort of 1:1 NAT of these public and private IPs, especially in cloud environments. For normal communication from node to some external IP, source IP is changed from node’s private IP to it’s public IP for outbound packets and reversed for reply inbound packets. However, when connection to an external IP is initiated by a Pod, the source IP is the Pod IP, which the cloud provider’s NAT mechanism doesn’t know about. It will just drop packets with source IPs other than the node IPs. So we use, you guessed it, some more iptables! These rules, also added by kube-proxy, do the SNAT (Source Network Address Translation) aka IP MASQUERADE. This tells the kernel to use IP of the interface this packet is going out from, in place of the source Pod IP. A conntrack entry is also kept to un-SNAT the reply. Everything’s good so far. Pods can talk to each other, and to the internet. But we’re still missing a key piece — serving the user request traffic. As of now, there are two main ways to do this: NodePort/Cloud Loadbalancer (L4 — IP and Port) Setting the service type to NodePort assigns the service a nodePort in range 30000-33000. This nodePort is open on every node, even if there’s no pod running on a particular node. Inbound traffic on this NodePort would be sent to one of the pods (it may even be on some other node!) using, again, iptables. A service type of LoadBalancer in cloud environments would create a cloud load balancer (ELB, for example) in front of all the nodes, hitting the same nodePort. Ingress (L7 — HTTP/TCP) A bunch of different implements, like nginx, traefik, haproxy, etc., keep a mapping of http hostnames/paths and the respective backends. This is entry point of the traffic over a load balancer and nodeport as usual, but the advantage is that we can have one ingress handling inbound traffic for all the services instead of requiring multiple nodePorts and load balancers. Think of this like security groups/ACLs for pods. The NetworkPolicy rules allow/deny traffic across pods. The exact implementation depends on the network layer/CNI, but most of them just use iptables. That’s all for now. In the previous parts we studied the foundation of Kubernetes Networking and how overlays work. Now we know how the Service abstraction helping in a dynamic cluster and makes discovery super easy. We also covered how the outbound and inbound traffic flow works and how network policy is useful for security within a cluster. ☞ Learn Kubernetes from a DevOps guru (Kubernetes + Docker) ☞ Learn DevOps: The Complete Kubernetes Course ☞ Kubernetes for the Absolute Beginners - Hands-on ☞ Complete DevOps Gitlab & Kubernetes: Best Practices Bootcamp ☞ Learn DevOps: On-Prem or Cloud Agnostic Kubernetes ☞ Master Jenkins CI For DevOps and Developers ☞ Docker Technologies for DevOps and Developers ☞ DevOps Toolkit: Learn Kubernetes with Practical Exercises! Guide to Spring Cloud Kubernetes for Beginners1.. In this tutorial, we’ll: In our example, we're using the scenario of travel agents offering various deals to clients who will query the travel agents service from time to time. We'll use it to demonstrate: Firstly, let's get our example from GitHub. At this point, we can either run the “deployment-travel-client.sh” script from the parent folder, or else execute each instruction one by one to get a good grasp of the procedure: 4. Service Discovery4. Service Discovery ###); } } 5. ConfigMaps5. ConfigMaps @RestController public class ClientController { @Autowired private DiscoveryClient discoveryClient; }: 6. Secrets6. Secrets kubectl edit configmap client-service Let's look at how Secrets work by looking at the specification of MongoDB connection settings in our example. We're going to create environment variables on Kubernetes, which will then be injected into the Spring Boot application.: 8. Additional Features8. Additional Features ribbon.http.client.enabled=true"; } We can take advantage of Spring Boot HealthIndicator and Spring Boot Actuator to expose health-related information to the user. In particular, the Kubernetes health indicator provides:. In this article, you’ll learn how to deploy a Stateful app built with Spring Boot, MySQL, and React on Kubernetes. We’ll use a local minikube cluster to deploy the application.Introduction In this article, you’ll learn how to deploy a Stateful app built with Spring Boot, MySQL, and React on Kubernetes. We’ll use a local minikube cluster to deploy the application. Please make sure that you have kubectl and minikube installed in your system. It is a full-stack Polling app where users can login, create a Poll, and vote for a Poll. To deploy this application, we’ll use few additional concepts in Kubernetes called PersistentVolumes and Secrets. Let’s first get a basic understanding of these concepts before moving to the hands-on deployment guide. We’ll use Kubernetes Persistent Volumes to deploy Mysql. A PersistentVolume ( PV) is a piece of storage in the cluster. It is a resource in the cluster just like a node. The Persistent volume’s lifecycle is independent from Pod lifecycles. It preserves data through restarting, rescheduling, and even deleting Pods. PersistentVolumes are consumed by something called a PersistentVolumeClaim ( PVC). A PVC is a request for storage by a user. It is similar to a Pod. Pods consume node resources and PVCs consume PV resources. Pods can request specific levels of resources (CPU and Memory). PVCs can request specific size and access modes (e.g. read-write or read-only). We’ll make use of Kubernetes secrets to store the Database credentials. A Secret is an object in Kubernetes that lets you store and manage sensitive information, such as passwords, tokens, ssh keys etc. The secrets are stored in Kubernetes backing store, etcd. You can enable encryption to store secrets in encrypted form in etcd.Deploying Mysql on Kubernetes using PersistentVolume and Secrets Following is the Kubernetes manifest for MySQL deployment. I’ve added comments alongside each configuration to make sure that its usage is clear to you.: polling: polling-app-mysql # Name of the resource labels: # Labels that will be applied to the resource app: polling-app spec: ports: - port: 3306 selector: # Selects any Pod with labels `app=polling-app,tier=mysql` app: polling-app tier: mysql clusterIP: None --- apiVersion: apps/v1 kind: Deployment # Type of the kubernetes resource metadata: name: polling-app-mysql # Name of the deployment labels: # Labels applied to this deployment app: polling-app spec: selector: matchLabels: # This deployment applies to the Pods matching the specified labels app: polling-app tier: mysql strategy: type: Recreate template: # Template for the Pods in this deployment metadata: labels: # Labels to be applied to the Pods in this deployment app: polling-app tier: mysql spec: # The spec for the containers that will be run inside the Pods in this deployment containers: - image: mysql:5 We’re creating four resources in the above manifest file. A PersistentVolume, a PersistentVolumeClaim for requesting access to the PersistentVolume resource, a service for having a static endpoint for the MySQL database, and a deployment for running and managing the MySQL pod. The MySQL container reads database credentials from environment variables. The environment variables access these credentials from Kubernetes secrets. Let’s start a minikube cluster, create kubernetes secrets to store database credentials, and deploy the Mysql instance: $ minikube start You can create secrets manually from a literal or file using the kubectl create secret command, or you can create them from a generator using Kustomize. In this article, we’re gonna create the secrets manually: $ kubectl create secret generic mysql-root-pass --from-literal=password=R00t secret/mysql-root-pass created $ kubectl create secret generic mysql-user-pass --from-literal=username=callicoder [email protected] secret/mysql-user-pass created $ kubectl create secret generic mysql-db-url --from-literal=database=polls --from-literal=url='jdbc:mysql://polling-app-mysql:3306/polls?useSSL=false&serverTimezone=UTC&useLegacyDatetimeCode=false' secret/mysql-db-url created You can get the secrets like this - $ kubectl get secrets NAME TYPE DATA AGE default-token-tkrx5 kubernetes.io/service-account-token 3 3d23h mysql-db-url Opaque 2 2m32s mysql-root-pass Opaque 1 3m19s mysql-user-pass Opaque 2 3m6s You can also find more details about a secret like so - $ kubectl describe secrets mysql-user-pass Name: mysql-user-pass Namespace: default Labels: <none> Annotations: <none> Type: Opaque Data ==== username: 10 bytes password: 10 bytes Let’s now deploy MySQL by applying the yaml configuration - $ kubectl apply -f deployments/mysql-deployment.yaml service/polling-app-mysql created persistentvolumeclaim/mysql-pv-claim created deployment.apps/polling-app-mysql created That’s it! You can check all the resources created in the cluster using the following commands - $ kubectl get persistentvolumes NAME CAPACITY ACCESS MODES RECLAIM POLICY STATUS CLAIM STORAGECLASS REASON AGE mysql-pv 250Mi RWO Retain Bound default/mysql-pv-claim standard 30s $ kubectl get persistentvolumeclaims NAME STATUS VOLUME CAPACITY ACCESS MODES STORAGECLASS AGE mysql-pv-claim Bound mysql-pv 250Mi RWO standard 50s $ kubectl get services NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE kubernetes ClusterIP 10.96.0.1 <none> 443/TCP 5m36s polling-app-mysql ClusterIP None <none> 3306/TCP 2m57s $ kubectl get deployments NAME READY UP-TO-DATE AVAILABLE AGE polling-app-mysql 1/1 1 1 3m14s You can get the MySQL pod and use kubectl exec command to login to the Pod. Deploying the Spring Boot app on KubernetesDeploying the Spring Boot app on Kubernetes $ kubectl get pods NAME READY STATUS RESTARTS AGE polling-app-mysql-6b94bc9d9f-td6l4 1/1 Running 0 4m23s $ kubectl exec -it polling-app-mysql-6b94bc9d9f-td6l4 -- /bin/bash [email protected]:/# All right! Now that we have the MySQL instance deployed, Let’s proceed with the deployment of the Spring Boot app. Following is the deployment manifest for the Spring Boot app - --- apiVersion: apps/v1 # API version kind: Deployment # Type of kubernetes resource metadata: name: polling-app-server # Name of the kubernetes resource labels: # Labels that will be applied to this resource app: polling-app-server spec: replicas: 1 # No. of replicas/pods to run in this deployment selector: matchLabels: # The deployment applies to any pods mayching the specified labels app: polling-app-server template: # Template for creating the pods in this deployment metadata: labels: # Labels that will be applied to each Pod in this deployment app: polling-app-server spec: # Spec for the containers that will be run in the Pods containers: - name: polling-app-server image: callicoder/polling-app-server:1.0.0 imagePullPolicy: IfNotPresent: polling-app-server # Name of the kubernetes resource labels: # Labels that will be applied to this resource app: polling-app-server spec: type: NodePort # The service will be exposed by opening a Port on each node and proxying it. selector: app: polling-app-server # The service exposes Pods with label `app=polling-app-server` ports: # Forward incoming connections on port 8080 to the target port 8080 - name: http port: 8080 targetPort: 8080 The above deployment uses the Secrets stored in mysql-user-pass and mysql-db-url that we created in the previous section. Let’s apply the manifest file to create the resources - $ kubectl apply -f deployments/polling-app-server.yaml deployment.apps/polling-app-server created service/polling-app-server created You can check the created Pods like this - $ kubectl get pods NAME READY STATUS RESTARTS AGE polling-app-mysql-6b94bc9d9f-td6l4 1/1 Running 0 21m polling-app-server-744b47f866-s2bpf 1/1 Running 0 31s Now, type the following command to get the polling-app-server service URL - $ minikube service polling-app-server --url You can now use the above endpoint to interact with the service - Deploying the React app on KubernetesDeploying the React app on Kubernetes $ curl {"timestamp":"2019-07-30T17:55:11.366+0000","status":404,"error":"Not Found","message":"No message available","path":"/"} Finally, Let’s deploy the frontend app using Kubernetes. Here is the deployment manifest - apiVersion: apps/v1 # API version kind: Deployment # Type of kubernetes resource metadata: name: polling-app-client # Name of the kubernetes resource spec: replicas: 1 # No of replicas/pods to run selector: matchLabels: # This deployment applies to Pods matching the specified labels app: polling-app-client template: # Template for creating the Pods in this deployment metadata: labels: # Labels that will be applied to all the Pods in this deployment app: polling-app-client spec: # Spec for the containers that will run inside the Pods containers: - name: polling-app-client image: callicoder/polling-app-client:1.0.0 imagePullPolicy: IfNotPresent ports: - name: http containerPort: 80 # Should match the Port that the container listens on resources: limits: cpu: 0.2 memory: "10Mi" --- apiVersion: v1 # API version kind: Service # Type of kubernetes resource metadata: name: polling-app-client # Name of the kubernetes resource spec: type: NodePort # Exposes the service by opening a port on each node selector: app: polling-app-client # Any Pod matching the label `app=polling-app-client` will be picked up by this service ports: # Forward incoming connections on port 80 to the target port 80 in the Pod - name: http port: 80 targetPort: 80 Let’s apply the above manifest file to deploy the frontend app - $ kubectl apply -f deployments/polling-app-client.yaml deployment.apps/polling-app-client created service/polling-app-client created Let’s check all the Pods in the cluster - $ kubectl get pods NAME READY STATUS RESTARTS AGE polling-app-client-6b6d979b-7pgxq 1/1 Running 0 26m polling-app-mysql-6b94bc9d9f-td6l4 1/1 Running 0 21m polling-app-server-744b47f866-s2bpf 1/1 Running 0 31s Type the following command to open the frontend service in the default browser - $ minikube service polling-app-client You’ll notice that the backend api calls from the frontend app is failing because the frontend app tries to access the backend APIs at localhost:8080. Ideally, in a real-world, you’ll have a public domain for your backend server. But since our entire setup is locally installed, we can use kubectl port-forward command to map the localhost:8080 endpoint to the backend service - $ kubectl port-forward service/polling-app-server 8080:8080 That’s it! Now, you’ll be able to use the frontend app. Here is how the app looks like -
https://morioh.com/p/58fcb9181410
CC-MAIN-2019-47
refinedweb
4,482
61.16
Part. 23 replies on “A Poetry Transformation Server” Hi, Great tutorial, it should be first part of Twisted documentation 😉 I have a question about code re-use when implementing UDP services. There are no factories for DatagramProtocol, so how should it be organized if, let’s say, we’d like to implement Poetry Transformation Server based on UDP protocol? Thanks in advance! Thank you! That’s an intriguing question 🙂 I think you would only be able to re-use the Service object for a UDP protocol. As you pointed out, there are no factories involved when you listen on UDP ports with Twisted (since there are no connections, just datagram packets). So the Protocol object you pass to listenUDP would have a reference to the Service object. And the Protocol itself would have to be rewritten entirely, as you would need to re-implement some of the features that TCP gives you, like order preservation and guaranteed delivery. I was not able to get any output from the netcat script ./twisted-server-1/transform-test Using Wireshark I could see the poem was actually returned in lower case. It seems that netcat is exiting before the transformed poem has been received. Using netcat with option -q -1 (-q secs quit after EOF on stdin and delay of secs (-1 to not quit)) it works. This is on Ubuntu 10.10 / Intel Atom CPU 330@1.60GHz. Thanks for the excellent tutorials! Hm, I’ll check it out, thanks! Fixed! I also discovered a rather embarrassing misspelling of the word ‘transform’ in quite a few places, including the name of a script 🙂 Is it possible to change protocol class during connection? My scenario is something like this: video player connects to 554 port. On this port there might be normal RTSP service or RTSP-over-HTTP thingy. I can discover this after first request from client (he will call me with HTTP GET or RTSP DESCRIBE). Handling both protocols in single class kinda sux. Any ideas? 😉 What you can do is provide a protocol that starts forwarding its calls to another protocol after the original protocol decides what to do. See twisted.protocols.policies.ProtocolWrapper for an example of what I mean, though that’s doing a little more than I think you need (providing ITransport calls in addition to IProtocol) and also a little less (it’s not switching to the wrapped protocol after it first figures out what the next protocol will be). See twisted.protocols. for a similar idea. […] 原文: 作者:dave 译者:notedit 时间:2011.06.25 […] Hi Dave, Great tutorial. I have managed to reach part 12. I am trying to implement the transform server on my own. In my transform server, every time there is a protocol error i.e. ‘.’ not sent in the request, I call transport.loseConnection(). The reactor returns an error code: “The connection was closed in n non-clean fashion”. Am I forgetting to do something here? Is there a clean way to close the socket from the server? You mean the server prints it out in its log, right? Could you post your code? I call the disconnect code after I make the check for a ‘.’ in the received message. def disconnect(self): self.logger.warning(“Disconnecting”) self.sessionState = ‘UNBOUND’ self.transport.loseConnection() Ok, thanks, but I actually meant the whole thing, so I can run it myself to recreate the error message. Could you post it as a github gist perhaps? It actually turned out to be something unrelated to the code. There was a firewall interfering with the code. Resolved when I tested on a personal computer. Glad you were able to solve it! I saw this PyCon demo on cooperative multitasking using twisted and it made me wonder: Let’s say the cummingsify() method actually has a lot of lines of code and takes longer to execute (but no IO involved). Does it make sense for the server app to yield to the reactor in the middle of execution or return only after transformation is finished? In a single threaded context, is there any use case where it is better to let the reactor service another transform request before the current one is complete? I am trying to understand if it is okay to have synchronous CPU bound code run to completion? If the performance is unacceptable what are the ways out in the reactor model? Yes, you raise a very good point. A cpu-bound task is going to block the reactor just like a blocking I/O call would. If such tasks are long and frequent enough then they could definitely reduce the performance of your server. At that point you have a few options: Excellent tutorial. I was cruising along pretty well but I’m having a heck of a time with example #4. I’m not wrapping my brain around how to make the methods on TransformService (ex: cummingsify()) return a Deferred and also actually do the transformation work, too, asynchronously. I’m failing to understand how to kick off the transformation but return the Deferred before it’s complete. The only solutions I can come up with using Deferreds are, I think, effectively the same in terms of synchronicity as the original. Can you give me any guidance on this? Thanks! Hey, glad you like the tutorial. So #4 is really more of a though experiment (just imagine .transform() returned a deferred — how would the main service need to change?). But one way to make a function return a deferred that fires later is with a nifty Twisted utility api: twisted.internet.task.deferLater. You call it like: d = deferLater(reactor, delay, function, *args, **kw) The first argument is the reactor object, and the second is the number of seconds to delay. After the delay, Twisted will call the given function with the given arguments and fire the deferred you got back from deferLater with the result. Make sense? That does make sense. I’m still having some trouble putting it together into the transformation server the way I thought I might, but that’s okay. What I’m doing with the exercise at this point is fairly contrived and pointless anyway; just seeing if I could do it. Your future Parts and the project I ultimately will use these skills on will guide me when it really counts. Thanks! […] A Poetry Transformation Server […] As of GNU netcat 0.7, -q option is not available. -n option for echo seems to prevent transform-test from sending correct data. I’m using Twisted 12.3.0 and bash 4 on Mac OS 10.8.2 […] 作者:dave@译者:杨晓伟(采用意译) […] […] 本部分原作参见: dave @ […]
https://krondo.com/a-poetry-transformation-server/
CC-MAIN-2022-33
refinedweb
1,119
65.42
Welcome to the second part of my Windows Presentation Foundation tutorial! If you’ve missed the first part you probably want to check it out here (link) since we’ll be building on what we did last. In this tutorial I’ll be covering creating a custom control for our Sudoku board and databinding it to the game logic. First, I think it would be a good idea to go over just what databinding in WPF means, since it’s used quite differently than in say Windows Forms or MFC. Hopefully this will give more insight in to why the internal classes are designed the way they are; you can databind anything but you can only easily databind some things. First off all, despite its name, databinding in no way involves databases, complex schemas, or any boring stuff like that. It’s really all about tying your UI to your code. We’ve all written that WinForms or VB code that synchronizes a control like a listbox or treeview with an internal array, collection, or other data structure and we all remember how painful it is. Why!? Why can’t the control just use my object for data storage instead of its own memory that I have to keep synced? Well, we don’t have to worry about that anymore because that’s how it works in WPF, in fact, controls only have their own storage if you explicitly request it and you’ll find if you write clean code you’ll almost never need it. So where am I going with this? How does it tie in? Well, if we structure our code correctly, we can have our Sudoku board control automatically display our Sudoku board object and easily enter and validate moves. To do this we are going to use a hierarchy of listboxes. Before you think I’ve gone off the deep end, it’s important to note that in WPF listboxes are controls that list anything not just strings. So, lets start hammering out the data structures by looking at a typical Sudoku board for a 9x9 game: 5 3 7 6 1 9 8 4 2 Actually it’s a 3x3 grid of 3x3 grids. But let’s abstract this to any size. Starting at the deepest level we have a cell itself. public class Cell{ public bool ReadOnly = false; public int? Value = null; public bool IsValid = true;} It’s simple, but gets the job done and maintains which cells are part of the original puzzle. Unfortunately this won’t work so well with databinding. First of all, databinding only works on properties, not fields and how can the control know when a property has changed? To make this work we have to implement the INotifyPropertyChanged interface and turn the fields into properties like this: public class Cell: INotifyPropertyChanged { bool readOnlyValue = false; public bool ReadOnly { get { return readOnlyValue; } set { if (readOnlyValue != value) { readOnlyValue = value; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("ReadOnly")); } } } int? valueValue = null; public int? Value { get { return valueValue; } set { if (valueValue != value) { valueValue = value; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Value")); } } } bool isValidValue = true; public bool IsValid { get { return isValidValue; } set { if (isValidValue != value) { isValidValue = value; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("IsValid")); } } } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; #endregion} Ok, before you run away screaming, bear with me for a second. First, you only have to do this for properties that will be databound then changed after they are initially read. Second, there are other methods such as dependency properties that accomplish something similar that I’ll discuss later. Dependency properties support animation, metadata, and all sorts other fun stuff but they have more overhead so this way is probably best if you just want the databindings to update. All that’s going on here is firing off the PropertyChanged event when one of the properties changes, pretty simple and a good candidate for a code snippet or good old copy and paste. Next, let’s define the inner grid: public class InnerGrid: INotifyPropertyChanged { ObservableCollection<ObservableCollection<Cell>> Rows; public ObservableCollection<ObservableCollection<Cell>> GridRows { get { return Rows; } } Here we initialize the collections in the inner grid cell and populate then with Cells. What’s neat here is that not only can the framework itself use the INotifyPropertyChanged interface but so can our code. We are adding a handler to the cell’s event in order to revalidate ourselves when one of our child cells is altered. public InnerGrid(int size) { Rows = new ObservableCollection<ObservableCollection<Cell>>(); for (int i = 0; i < size; i++) { ObservableCollection<Cell> Col = new ObservableCollection<Cell>(); for (int j = 0; j < size; j++) { Cell c = new Cell(); c.PropertyChanged += new PropertyChangedEventHandler(c_PropertyChanged); Col.Add(c); } Rows.Add(Col); } } void c_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "Value") { bool valid = CheckIsValid(); foreach (ObservableCollection<Cell> r in Rows) { foreach (Cell c in r) { c.IsValid = valid; } } isValidValue = valid; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("IsValid")); } } Here we cache the result of the last IsValid value. We can do this because we now have a notification event that is fired whenever there is a possibility of that value changing. bool isValidValue = true; public bool IsValid { get { return isValidValue; } } private bool CheckIsValid() { bool[] used = new bool[Rows.Count * Rows.Count]; foreach (ObservableCollection<Cell> r in Rows) { foreach (Cell c in r) { if (c.Value.HasValue) { if (used[c.Value.Value-1]) { return false; //this is a duplicate } else { used[c.Value.Value-1] = true; } } } } return true; } #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; #endregion} As you can see I’ve defined the class to store its data in collections of type ObservableCollection, this is because ObservableCollection already implements INotifyCollectionChanged and INotifyPropertyChanged and that’s great because I’m lazy. I’ve essentially defined an array of arrays containing the cells in the inner grid. This works great for databinding but it kind of sucks to access the cells from C# code. To solve this I also added an indexer to the class like so: public Cell this[int row, int col]{ get { if (row < 0 || row >= Rows.Count) throw new ArgumentOutOfRangeException("row", row, "Invalid Row Index"); if (col < 0 || col >= Rows.Count) throw new ArgumentOutOfRangeException("col", col, "Invalid Column Index"); return Rows[row][col]; }} The Board class is extremely similar to the InnerGrid except it stores InnerGrids instead of Cells so I wont list the entire thing here (you can check it out, and the IsValid implementations if you download the source). I also changed the constructor and the indexer to drill-down through the two levels of containers. If you’re not sure on how this would work you should probably check out the source before you continue just so we’re on the same page. Ok, so now we’ve written all these class it’s time to hit the XAML and make a custom control. So we need to add a new WinFX user control to the project. I’ve modified some of the properties of the user control, but basically we start with this: <UserControl x:<UserControl/> The basic idea here is that we’ll use a series of nested ItemsControls to display our board. An ItemsControl is a generic panel that contains any number of other items, for example the ListBox control inherits from ItemsControl and adds support for things like scrolling and selection but we don’t need those. We define the outer control that holds the rows on inner squares. <ItemsControl ItemTemplate ="{StaticResource OuterRowTemplate}" ItemsSource ="{Binding Path=GridRows}" x: <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <UniformGrid Columns ="1"/> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> </ItemsControl> Ok, so this is where the fun starts. Every item that can be databound has a DataContext property that specifies the object it’s bound to. We’ll set this later from C# code but it’s important to know that it’s there because it’s the basis for the binding syntax. When specifying a data binding, if no source is explicitly set the data context is used. In this code ItemsSource, the collection containing the child items is bound to the GridRows property of the data context, which will eventually be an instance of our Board class. Another thing of note is the use of the UniformGrid class. By default the items control lays out items by stacking them from top to bottom. Instead of this behavior we would rather have the items stacked in a single column and stretched to fill the entire space evenly. The UniformGrid container does this and so I’ve substituted it for the default using the ItemsPanel property, but in general you could use any kind of standard or custom panel here, for example to arrange the items in a ring. Also you’ll notice ItemTemplate points to a resource: <DataTemplate x: <ItemsControl ItemsSource ="{Binding}" ItemTemplate ="{StaticResource InnerGridTemplate}"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <UniformGrid Rows ="1"/> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> </ItemsControl></DataTemplate> A data template describes how each item in the source list is interpreted as an item in the ItemsControl. The data context is the current item, which is the list of blocks in the row, which we bind to the ItemsSource of another ItemsControl. Currently, we have a vertical list of horizontal lists. Then, we do this all over again for the cells inside each block. You can also add other controls in the template and I’ve added a border to the InnerGridTemplate to show the boundary between cells. Finally, we reach the innermost data template, the one for the Cell: <DataTemplate x: <Border x:<TextBlock HorizontalAlignment ="Center" VerticalAlignment ="Center" FontWeight ="Bold" FontSize ="16" Text ="{Binding Path=Value}"/> </Border></DataTemplate> Here, we draw a lighter border around the cell then display the Value property of the current cell, which is the data context of the template. Finally, we want the entire thing to stay square as it resizes. Normally this would require a few lines of C# code but thanks to the insanely flexible databinding available in WPF we can do this with no code! All you need to do it to bind the Width property of the UserControl to its ActualHeight property, which contains the final height of the control after it’s been laid out. We can do this with the RelativeSource property, to bind to object itself instead of the data context. This sounds complicated but it’s actually really simple: Width="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}" Now, we need to put the control onto our main window. First, we need to map out C# namespace, SudokuFX, to an XML namespace that we can reference from XAML. To do this we define a new namespace in the document root using this syntax: xmlns:clr="clr-namespace:SudokuFX" Where the xmlns:clr indicates the xml namespace. “clr” is in no way special an I could have called it xmlns:stuff="clr-namespace:SudokuFX" or whatever I wanted. Once that’s done I can use my control just like any other. I’ve replaced the stand-in canvas with our custom control tag: <clr:SudokuBoard If you run the app now you should see this: Not that amazing, but we haven’t bound any data yet. We can modify the C# component of the control to add a data source: public partial class SudokuBoard : UserControl{ public Board GameBoard = new Board(9); public SudokuBoard() { InitializeComponent(); MainList.DataContext = GameBoard; }} Now, it should look more like this (I’ve added the numbers just to show that it works): You can see it rebuilds correctly to match the data, when I change from a 9x9 grid to a 16x16 grid: Ok, so now that we’ve got that working, to close of this tutorial lets add the ability to change the numbers on the board. I’ve added a new collection property to the Cell class called PossibleValues that is populated with all the possible values when the class is created. Let’s add a context menu that’s bound to this new property so that the cell values can be changed. To do this the XAML needs to be changed like this: <DataTemplate x:<Border x: <TextBlock Focusable ="False" HorizontalAlignment ="Center" VerticalAlignment ="Center" FontWeight ="Bold" FontSize ="16" Text ="{Binding Path=Value}"> </TextBlock> <Border.ContextMenu> <ContextMenu> <ContextMenu.ItemContainerStyle> <Style TargetType ="{x:Type MenuItem}"> <Setter Property ="Template"> <Setter.Value> <ControlTemplate TargetType ="{x:Type MenuItem}"> <ContentPresenter x: </ControlTemplate> </Setter.Value> </Setter> </Style> </ContextMenu.ItemContainerStyle> <ListBox BorderThickness="0" Width ="35" Margin ="0" SelectedItem ="{Binding Path=Value,Mode=TwoWay}" HorizontalAlignment ="Stretch" VerticalAlignment ="Stretch" DataContext ="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=DataContext}" ItemsSource="{Binding Path=PossibleValues}"/> </ContextMenu> </Border.ContextMenu> </Border></DataTemplate> The key here is the binding of the listbox to our data source. Because the context menu exists in a separate hierarchy the data context isn’t automatically inherited. We can work around this by binding the new data context to the data content of the parent element just outside our sub-hierarchy. To do this we use the RelativeSource syntax to access our TemplatedParent. Next, we bind the ItemsSource property to the new property, which populates the listbox, and then we bind the SelectedItem property to the object’s Value property. Because we specify a two-way binding, when the value of Value changes, so will the selected item in the listbox, and, when the use selects a new item through the UI, Value will updated also. A listbox is needed because a menu doesn’t have the capability to retain item selections. To work around this I added the listbox to the menu as a single item, and then altered the MenuItem Template to remove all padding and selection logic. I haven’t covered altering control templates yet, so don’t worry about how exactly that part of the code works, we’ll revisit it in the next tutorial. Now, if you run the application, you’ll see that you can edit the displayed grid: This is really cool because, essentially, there is no code that ties the internal data classes to our UI! The UI automatically and dynamically displays and edits an instance of our custom class. How awesome is that? Don’t worry, we’re not done yet! Come back for my next article were we take a break from data and spiff up the coolness of the app’s look and feel. I’ll be covering cool stuff like: See you next time! If you would like to receive an email when updates are made to this post, please register here RSS where can I download this project (thus far) ? - or do I wait until the end ? thanks Even with updates for the released build of WCF, this project fails and my project fail to build. The statement : xmlns:clr="clr-namespace:SudokuFX" causes issues and adding the statement: <clr:SudokuBoard...> causes major issues with the DockPanel. How is anyone supposed to learn from this article when a) in your laziness you did not specify where to put the xmlns:clr statement and what you provide as an example will not build??? thanks a lot at least u gave me an idea on what to do Hey, I'm having trouble running through this tutorial in Visual C# 2008 Express. I can get about half way through it It looks like every time I use a StaticResource in a UserControl and then use that control in a window the window's designer bugs out. It displays a "Could not create instance of [UserControl]" error, even thought the project compiles and runs fine, and the UserControl looks fine in the designer. I found it when working through the tutorial and I assigned a LinearGradientBrush called ControlGradient to the App resources, used in in SodukuBoard.xaml, then tried to put the SodukuBoard on Window1 - the designer for Window 1 now throws a "Could not create instance of SodukuBoard" error. I've just found this article but I'd like to start from the beginning. Where is the link to part 1? Sudoku challenge: Part 1: Part 2: Part 3: Part 4: Part 5: Your code seems to have been chopped off on the right some how leaving many of the entries incomplete. Otherwise this is a very nice introduction to theese ideas in WPF @LagDaemon: True, I can go in and fix that. You can also download the source at the top of the page. Building this. However, when I click on the context menu, nothing comes up. I am not sure if I am missing something. I tried running your code in VS2008 it works fine. however mine does everthing expect the part where a number should appear in a cell, when you select the context menu. i did a comparison, and everything looks intact. I even copied your SudokuBoard.xaml and still did not work. I am stumped. i ran into similar issues when i downloaded the code for part 1. i couldn't even get the project file to load. as far as i can tell, the staticreferrences have been removed since the winfx days, so you can just remove that keyword (and whatever else you have to to get it to compile). since i couldn't get the csproj to load, i created an empty project and dropped the xaml and c# code into that project (remember to add existing item so the solution knows about it). you also must add referrences to windowsbase, windowscore, and presentationfoundationcore (vs will tell you which to add in the event that i forgot/misspelled those). finally, if you drop the code into a brand new project, vs will complain that you don't have a main method. you must add this to the "secret" .g.cs file. you can get to the file by viewing app.xaml.cs. put your cursor on the name of the class (i.e. App), right click, and select "go to definition". this should give you two choices, one of which is the .g.cs file. (there might be a better way to do all this, but this is all i could kludge together while watching tv ;) ) to this file, add something like: /// <summary> /// Application Entry Point. /// </summary> [System.STAThreadAttribute()] [System.Diagnostics.DebuggerNonUserCodeAttribute()] public static void Main() { SudokuGame.App app = new SudokuGame.App(); app.InitializeComponent(); app.Run(); } you may have to rebuild the solution to get it to work. also, i only got it to work with my release executable (run without debug). if anyone has anything to add to this, please feel free! good luck! ~domni The download link at the top is not working.. do we have a dump somewhere else??? @Nagaraj: The Ch9 update broke this. I fixed the link.
http://blogs.msdn.com/coding4fun/archive/2006/11/06/999781.aspx
crawl-002
refinedweb
3,110
61.46
Technical Support On-Line Manuals RL-ARM User's Guide (MDK v4) #include <net_config.h> void* tftpc_fopen ( U8* fname, /* Pointer to name of file to open. */ U8* mode ); /* Pointer to mode of operation. */ The tftpc_fopen function opens a local file for reading or writing. The argument fname specifies the name of the file to open. The mode defines the type of access permitted for the file. It can have one of the following values. The tftpc_fopen function is in the TFTPC_uif.c module. The prototype is defined in net_config.h. note The tftpc_fopen function returns a pointer to the opened file. The function returns NULL if it cannot open the file. tftpc_fclose, tftpc_fread, tftpc_fwrite void *tftpc_fopen (U8 *fname, U8 *mode) { /* Open local file for reading or writing. */ return (fopen ((char *)fname, (char *.
http://www.keil.com/support/man/docs/rlarm/rlarm_tftpc_fopen.htm
CC-MAIN-2019-43
refinedweb
132
70.09
In this blog post I want to show you How to avoid ViewBag and ViewData in ASP.NET MVC. It could be so easy: When passing data from the Controller to the View in MVC one can use ViewBag.MyProperty = “ThisIsTheContentOfMyProperty”; or ViewData["MyProperty"] = MyProperty; And in the view you can access the data with: @ViewBag.MyProperty or ViewData["MyProperty "] as ... But what about spelling problems? IntelliSense will not correct you if you would miss a character. Even the compiler does not give you any hint. @ViewBag.MProperty would not be wrong but won’t show any data in your View. Also spelling problems in the ViewData-String would not be noticed in code. In general: Using the MVC-Pattern is great. So when ASP.NET MVC gives us the possibility to use this pattern: Do so! A Viewbag (also Viewdata, Viewbag is only a wrapper around Viewdata) can be used like a bucket for your data. But this is not nice and it’s harming the Mvc-Pattern! The view knows its model and should not get any data from anything else. So to avoid using any pails for your data, use ViewModels to pass your data into the View. This could look like this: public class MyViewModel { public List MyModels { get; set; } public string Rooms { get; set; } public bool IsSomethingTrueOrNot { get; set; } ... } And in the View you can pass the complete ViewModel to your View public ActionResult MyMethod() { MyViewModel viewModel = new MyViewModel(); // Do anything with the ViewModel like filling it, etc. return View(viewModel); } With this technique you can keep all the data you need for creating a view separately from your MVC-Models. This can be tested well; it can be used easily and gives you more structure arrangement to your MVC-Projects. It’s so easy, isn’t it? Happy coding!
https://offering.solutions/blog/articles/2014/03/08/how-to-avoid-viewbag-and-viewdata-in-asp.net-mvc/
CC-MAIN-2022-21
refinedweb
305
66.03
Hello everyone, welcome to this new article where we are going to make a React Native Datepicker Example using UI Kitten . If you are not familiar with UI kitten, it’s a React Native UI Components library, with plenty of cool and custom UI. You can consider it top 5 React Native UI Libraries, and use it to make cool modern experience in your app. And it offers a really nice and simple global design system that you can switch the entire look of the app, eg Light mode, Dark mode… If you are an active user of my blog, you would notice that I usually use nativebase for my UI. I have been using nativebase for a long time, and I am trying to explore new UI libraries and other options. There are quite a lot, ant design, material design, UI kitten etc. I will try to explore each one of them by time and try to make good stuff with em. Without further talking, let’s get into the purpose of this article. Let’s Get Started Environment Setup Make a new project using React native and install UI kitten package npm i @ui-kitten/components @eva-design/eva react-native-svg You also need to complete installation for iOS by linking react-native-svg. cd ios && pod install If you have started the app by this time, you need to restart the bundler to apply the changes. Go back to the root application directory, shut down the current bundler process and call. npm start -- --reset-cache Configure Application Root Wrap the root component of your App into ApplicationProvider component. In your App.js; That was it, Now you are ready to use UI Kitten in your app Datepicker Example For this example, I will code directly in the app.js file. First let’s make a new state to handle our date picking const [date, setDate ] = useState(new Date()) Don’t for get to import the useState hook from react import React, { useState} from 'react'; If you are using a class component, you should be fine without the previous step, just setup your init state normally. in our render method, like we have seen in Configure Application Root we will need ApplicationProvider. Since I didn’t setup my example that way, I will need to include it in the app.js <ApplicationProvider mapping={mapping} theme={lightTheme}> <Layout style={styles.container}> </Layout> </ApplicationProvider> And now simply add Datepicker component from UI kitten to the app. <Datepicker date={date} onSelect={setDate} This should be fine to render the datepicker UI Component in our screen. Once you click on it Now, our Datepicker is fully functioning, once you select a date the date field in the state should be updated via the onSelect function of the datepicker component. There is still a lot to do to customize the datepicker, so let’s try some. Adding an Icon We can use the icon prop of the datepicker component, to render an icon for it. You can use UI Kitten Icon component, or any component really it would work. const DateIcon = (style) => ( <Icon {...style} ) <Datepicker date={date} onSelect={setDate} icon={DateIcon} /> Selectable days We can use the filter prop to filter the days that can be selected, using the select prop. const filter = (date) => date.getDay() !== 0 && date.getDay() !== 6; <Datepicker placeholder='Pick Date' date={date} onSelect={setDate} filter={filter} /> Now, only results of the filtered days will be selectable, and the rest will be disabled. More Options There are plenty of options you can use to customize your datepicker for your needs, Here is the list. Datepicker Properties Methods There you have it React Native Datepicker Example using UI Kitten. I hope you find it as informative as you have expected. Feel free to share it with your friends, and comment out your questions and concerns. Stay tuned for more, Happy coding It’s nearly impossible to find experienced people on this topic, but you sound like you know what you’re talking about!!
https://reactnativemaster.com/react-native-ui-kitten-datepicker-example/
CC-MAIN-2020-16
refinedweb
673
60.35
It's not the same without you Join the community to find out what other Atlassian users are discussing, debating and creating. issues = jira.search_issues('project=titan') print issues [] Just returns an empty list, why? No matter what I put in there it always returns an empty list. It works fine thru the gui. There are many issues. I can search for individual issues but cannot get anything from this method. jira version = 6.1.3 What language or script is jira.search_issues from? It's not java, so what actually is it? It's from python-jira. from jira.client import JIRA options = {'server': ''} jira = JIRA(options, basic_auth=('user', 'password')) issues = jira.search_issues('project=titan') print.
https://community.atlassian.com/t5/Jira-questions/jira-search-issues-returns-nothing/qaq-p/439968
CC-MAIN-2018-43
refinedweb
117
62.14
cv2.perspectiveTransform() with Python I am attempting to use the perspectiveTransform() function in Python to warp a set of points: import cv2 import numpy as np a = np.array([[1, 2], [4, 5], [7, 8]], dtype='float32') h = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype='float32') pointsOut = cv2.perspectiveTransform(a, h) However, all I get is an error: cv2.error: /build/buildd/opencv-2.3.1/modules/core/src/matmul.cpp:1916: error: (-215) scn + 1 == m.cols && (depth == CV_32F || depth == CV_64F) in function perspectiveTransform I assume I'm passing the arrays in the wrong format somehow, but I've tried quite a few different combinations of array shapes and data types with no success. What's the right way to do this?
https://answers.opencv.org/question/252/cv2perspectivetransform-with-python/
CC-MAIN-2019-35
refinedweb
128
65.01
perltutorial Juerd <h2>No include</h2> <p> Some simple languages, like PHP, offer an <tt>include()</tt> to include a file literally. Perl does not. Then how can you still load code from other files? </p> <p> There are many ways to do this in Perl, but there is no easy way to get close to what most people expect of an <tt>include()</tt>. People who want to include files usually come from simpler languages, or have no programming experience at all. The hardest thing they will have to learn is that <b>you should not want to include a file</b>. </p> <p> That may sound harsh, but it's a Perl reality. In Perl, we don't include or link libraries and code reuse isn't usually done by copying and pasting. Instead, Perl programmers use <b>modules</b>. The keywords [use] and [require] are meant for use with modules. Only in the simplest of situations you can get away with abusing [require] as if it were some kind of <tt>include()</tt>, but it's easy to get bitten by how it works: it only loads any given file <b>once</b>. </p> <h2>Creating a module</h2> <p> What is a module, anyway? [perlmod] defines it as: <em>just a set of related functions in a library file, i.e., a Perl package with the same name as the file.</em> </p> <p>, <tt>NameOfTheProject/SomeModule.pm</tt> is a good filename (in real life, use something a little more meaningful). The corresponding package is <tt>NameOfTheProject::SomeModule</tt>. Use CamelCaps like this, because everyone else does too. </p> <p> The file must be in a directory that is listed in <tt>@INC</tt>. To find out what your <tt>@INC</tt> is, run <tt>perl -V</tt>. The current working directory (listed as its symbolic name <tt>.</tt> (a single dot)) should be listed. To begin with, putting the module in the script's directory is a good idea. It is the easiest way to keep things organized. If you want to put the module somewhere else, you will have to update <tt>@INC</tt>, so that perl knows where to find it. An easy way to do get code like this in the main script: <code> use lib 'path/to/the/modules'; # The example module could be path/to/the/modules/NameOfTheProject/SomeModule.pm </code> </p> <p> What goes in the module itself doesn't require much explanation. I'll just give a complete example of a simple NameOfTheProject::SomeModule: <code> use strict; package NameOfTheProject::SomeModule; sub some_function { # put sane code here return 123; } 1; </code> Just list all the subs as you usually would, put a [package] statement at the top and a true value at the bottom (<tt>1</tt> will suffice). Obviously, [use] [strict] is a good idea. You should never code a module that does not have this. Beware: A <tt>use strict;</tt> statement in the main script has no effect on the module. </p> <p> A module runs only once. That means that for code to be reusable, it <b>must</b> be in a sub. In fact, it's considered very bad style to do anything (except declaring and initializing some variables) in the module's main code. Just don't do that. </p> <p> You can now load the module and use its sub, simply by doing: <code> use NameOfTheProject::SomeModule; print NameOfTheProject::SomeModule::some_function(); # prints 123 </code> </p> <p> You can have the module export its sub(s) to the caller's namespace (that is: the package the [use] statement is in. By default, this is <tt>main</tt>). For this, put after the [package] statement: <code> use base 'Exporter'; our @EXPORT_OK = ('some_function'); </code> Then, when [use]ing the module, you can request that <tt>some_function</tt> be imported to your namespace with: <code> use NameOfTheProject::SomeModule ('some_function'); print some_function(); # prints 123 </code> To have it exported automatically, use <tt>@EXPORT</tt> instead of <tt>@EXPORT_OK</tt>. This will eventually bite you if the function names are generic. For example, many people get bitten by [cpan://LWP::Simple]'s <tt>get</tt> function. It is not unlikely that you already have one. </p> <p> There are more ways to export functions. I of course prefer to use my own module [cpan://Exporter::Tidy]. Not only because it's smaller and often faster, but mostly because it lets the user of a module define a prefix to avoid clashes. Read its documentation for instructions. </p> <p> For the export/import mechanism, it is very important that the filename, the package name and the name used with [use] are equal. This is case sensitive. (Ever wondered why under Windows, <tt>use Strict;</tt> doesn't enable [strict], but also doesn't emit any warning or error message? It has everything to do with the case insensitive filesystem that Windows uses.) </p> <h2>Stubbornly still wanting to include</h2> <p>? </p> <p>: <code> # This is config.pl mirror => '', path => '/var/www/example', skip_files => [ 'png', 'gif', 'jpg' ], </code> (The last <code>,</code> is optional, but it's included to make adding a line easier.) <code> # This is script.pl use strict; my %config = do 'config.pl'; chdir $config{path}; ... </code> Error checking is left as an excercise. </p> <p> Because we used only the return value of the script, and never even touched a variable in <tt>config.pl</tt>, the inaccessibility of lexical variables is no longer a problem. Besides that, the code looks very clean and we have a very powerful config file format that automatically supports comments and all kinds of useful functions. How about <tt>interval => 24 * 60 * 60,</tt> for self-documentation? :) </p> <h2>Still not good enough</h2> <p> [do] updates <tt>%INC</tt>, which you may or may not want. To avoid this, use [eval] [cpan://File::Slurp|read_file] instead. To find out if you want this, read [perlvar]. </p> <p> There is a way to get an <tt>include()</tt>. </p> <p> If you read the documentation for [eval] (which you of course should (don't use an operator without having read its documentation first)), you see that if it is called from within the <tt>DB</tt> package, it is executed in the caller's scope. This means that lexical values are made visible and the file behaves as a code block. </p> <p> Here is an example to get an <tt>include()</tt> function that actually works the way most people expect: <code>; </code> Documentation for the <tt>#line</tt> directive is in [perlsyn]. </p> <p> To test this new module, save it as Acme/Include.pm and create: <code> # This is foo.pl use strict; use Acme::Include; my $lexical = 'set in foo.pl'; include 'bar.pl'; print $lexical; # Should print: set in bar.pl </code> and: <code> # This is bar.pl use strict; $lexical = 'set in bar.pl'; # There is no "my" here, because that would create a *new* lexical # variable, hiding the existing one. </code> and then run <tt>perl foo.pl</tt>. </p> <p> This example Acme::Include does not have any error checking. In practice, you will want to check <tt>$@</tt> somewhere (but you also want to retain the value returned by the included file, and context to propagate properly. Good luck!). </p> <h2>Learning more</h2> <p> I wrote this tutorial to have an answer ready for the <i>n</i>th time someone in EFnet's #perlhelp asks why [require] works only once, or asks how to really include a file. Explaining the same thing over and over gets annoying over time. This is not a good guide to writing modules. For that, read chapter 10 of [ Perl] and [perlmod] and [perlnewmod]. Of course, good code always comes with good documentation; so learn [id://252477]. </p> <h2>One last thing</h2> <p> If you name your module <tt>Test</tt>, don't be surprised if it doesn't work. The current working directory comes <b>last</b> in <tt>@INC</tt>, so the [perldoc://Test] module that is in the Perl distribution is probably loaded instead. This bites me at least once per year, this time while writing this tutorial :). </p>
http://www.perlmonks.org/index.pl/jacques?displaytype=xml;node_id=393426
CC-MAIN-2016-30
refinedweb
1,381
73.88
- 23 Apr, 2014 2 commits - 21 Apr, 2014 27 commits Some BSD socket functions don't return error numbers in errno namespace, but rather in other error namespaces. CPython resolves this by using OSError subclasses for them. We don't do that so far, so there's ambiguity here. Well, Python3 also defines an attribute for that, but that's bloat. Exact behavior of typecodes may be not yet enforced. :) This is a one-liner fix. It gets the class-super.py test passing, but is probably not a complete fix. modffi: Fix how we call `pkg-config` 11 commits TODO: Never "optimize" includes any more! The HAL handles for the I2C/SPI objects are rather large, so we don't want to unnecessarily include them.
https://gitrepos.estec.esa.int/taste/uPython-mirror/-/commits/4c6b375960098c6596541b1e48c1210b10198d98
CC-MAIN-2022-33
refinedweb
126
68.16
usethe __ versions is then relatively obvious without additional commenting.> > >> >>+ * is called.> >>+ *> >>+ * The double-underscore version must only be called if you know the task> >>+ * can't be preempted.> >>+ *> >>+ * __get_cpu_fpsimd_context() *must* be in pair with __put_cpu_fpsimd_context()> >>+ * get_cpu_fpsimd_context() *must* be in pair with put_cpu_fpsimd_context()> >> >"in pair" -> "paired with"?> > Sure.> > >> >I'd move each of these comments to be next to the function it applies> >to.> > Do you mean on top of {,__}put_cpu_ or {,__}get_cpu?It doesn't matter. It's the statement about get_cpu_fpsimd_context()next to the definition of __get_cpu_fpsimd_context() that I find a bitweird.Arguably we could solve this by just having less commenting: theexpectation that a "get" should be paired with a subsequent matching"put" is a common pattern (which was the reason for suggesting thosenames).> >>+ */> >>+static void __get_cpu_fpsimd_context(void)> >>+{> >>+ bool busy = __this_cpu_xchg(kernel_neon_busy, true);> >>+> >> >I don't mind whether there is a blank line here or not, but please make> >it consistent with __put_cpu_fpsimd_context().> > I will modify __put_cpu_fpsimd_context() to add a newline.> > >> >>+ WARN_ON(busy);> >>+}> >>+> >>+static void get_cpu_fpsimd_context(void)> >>+{> >>+ preempt_disable();> >>+ __get_cpu_fpsimd_context();> >>+}> >>+> >>+/*> >>+ * Release the CPU FPSIMD context.> >>+ *> >>+ * Must be called from a context in which *get_cpu_fpsimd_context() was> >> >Nit: Why *?> > Same as above, I can update to use {,__} instead of *.> > >> >>+ * previously called, with no call to *put_cpu_fpsimd_context() in the> >>+ * meantime.> >>+ */> >>+static void __put_cpu_fpsimd_context(void)> >>+{> >>+ bool busy = __this_cpu_xchg(kernel_neon_busy, false);> >>+ WARN_ON(!busy); /* No matching get_cpu_fpsimd_context()? */> >>+}> >>+> >>+static void put_cpu_fpsimd_context(void)> >>+{> >>+ __put_cpu_fpsimd_context();> >>+ preempt_enable();> >>+}> >>+> >>+static bool have_cpu_fpsimd_context(void)> >>+{> >>+ return (!preemptible() && __this_cpu_read(kernel_neon_busy));> >> >Nit: Redundant ()> >> >>+}> >>+> >> /*> >> * Call __sve_free() directly only if you know task can't be scheduled> >> * or preempted.> >>@@ -221,11 +274,12 @@ static void sve_free(struct task_struct *task)> >> * thread_struct is known to be up to date, when preparing to enter> >> * userspace.> >> *> >>- * Softirqs (and preemption) must be disabled.> >>+ * The FPSIMD context must be acquired with get_cpu_fpsimd_context()> >> >or __get_cpu_fpsimd_context()? Since this is effectively documented by> >the WARN_ON() and this is a local function anyway, maybe it would be> >simpler just to drop this comment here?> > I am fine with that.> > >> >>+ * before calling this function.> >> */> >> static void task_fpsimd_load(void)> >> {> >>- WARN_ON(!in_softirq() && !irqs_disabled());> >>+ WARN_ON(!have_cpu_fpsimd_context());> >> if (system_supports_sve() && test_thread_flag(TIF_SVE))> >> sve_load_state(sve_pffr(¤t->thread),> >>@@ -239,15 +293,22 @@ static void task_fpsimd_load(void)> >> * Ensure FPSIMD/SVE storage in memory for the loaded context is up to> >> * date with respect to the CPU registers.> >> *> >>- * Softirqs (and preemption) must be disabled.> >>+ * The FPSIMD context must be acquired with get_cpu_fpsimd_context()> >> >Likewise.> > Ditto.> > >> >>+ * before calling this function.> >> */> >> static void fpsimd_save(void)> >> {> >> struct fpsimd_last_state_struct const *last => >> this_cpu_ptr(&fpsimd_last_state);> >> /* set by fpsimd_bind_task_to_cpu() or fpsimd_bind_state_to_cpu() */> >>+ WARN_ON(!have_cpu_fpsimd_context());> >>- WARN_ON(!in_softirq() && !irqs_disabled());> >>+ if ( !have_cpu_fpsimd_context() )> >> >Nit: Redundant whitespace around expression.> > This hunk should actually be dropped. I was using for debugging and forgot> to remove it before sending the series :/.Ah, right. I didn't spot it -- yes, please remove.> >> >>+ {> >>+have ownership of the cpu FPSIMD context" to refer back to thecommenting for get_cpu_fpsimd_context(), that should cover the generalcase.> > >> *external caller, it might be worth adding a WARN_ON(preemptible()) hereif you want to stick with the __ functions.Otherwise, I don't have a strong opinion.Cheers---Dave
https://lkml.org/lkml/2019/4/17/562
CC-MAIN-2021-49
refinedweb
500
50.63
My segment is not getting set with the new value though It goes into the if statement. Am I doing something wrong? InterSystems Open Exchange Overview Webinar Hi Community! We're pleased to invite all the developers to the upcoming InterSystems Open Exchange Overview webinar on September 18 at 11:00 AM EDT. In this webinar you will learn about InterSystems Open Exchange – a gallery of solutions, tools and templates made with InterSystems IRIS, IRIS for Health and other InterSystems data platforms. What awaits you? In the webinar you’ll know: Hi Newbie question. Could you please help me implement the following using DTL only - no programming. We have a problem where our system sends longer addresses e.g. block of flats in an unexpected format e.g. address below: Hello! First of all, let me state that I am no senior InterSystems expert. In my organization, we have a HealthShare Health Connect setup where each namespace has one code database and one data database, which are both actively mirrored. We have two nodes in the mirror. I am trying to create a Procedure in Caché, but this message is showing: <UNDEFINED>frmit+118^%qaqpsq *mt("v",1) This is the procedure: CREATE PROCEDURE testebi.sp_cargainicial() BEGIN INSERT INTO testebi.Fato_Atendimentos ( PK_OsProcedimento ) SELECT ID from dado.TblOsProcedimento ; From my recent post, I uploaded a set of values into a global, and I am trying to compare the first field, and then $GLOBAL("123", "bone issue")="" $GLOBAL("234","joint issue")="" Now, I want to compare and see if the DG1:4.1 segment has the code $GLOBAL and then replace the DG14.1 segment with the code and the description so For Eg: if DG1:4.1 exists in $GLOBAL("123") then replace the segment with the code and description Can someone guide me on how I can achieve this? Is there a way to bulk load csv into a global? I have a csv with 283 lines in the following pattern 123, first text 234, second text 456, third text I want to load them into a global ^loader(code, text). Is there a way to upload them using code? This is a coding example working on IRIS 2020.2 It is also NOT serviced by InterSystems Support ! The demo is based on the raw class descriptions. The data classes used are Address, Person, Employee, Company For a more attractive demo, a JSONtoString method by ID was added. Hey Developers! We're pleased to announce the next competition of creating open-source solutions using InterSystems IRIS! Please welcome: ⚡️ InterSystems Full Stack Contest ⚡️ Duration: September 21 - October 11, 2020 InterSystems Full Stack Contest Kick-off Webinar Hi Community! We are pleased to invite all the developers to the upcoming InterSystems Full Stack Contest Kick-off Webinar! The topic of this webinar is dedicated to the Full Stack Contest. On this webinar, we’ll demo the IRIS Full Stack template and answer the questions on how to develop, build and deploy full stack applications in InterSystems IRIS. Date & Time: Monday, September 21 — 11:00 AM EDT Speakers: 🗣 @Evgeny Shvarov, InterSystems Developer Ecosystem Manager 🗣 @Raj Singh, InterSystems Product Manager - Developer Experience I have a class that has 2 different cursors for different queries, audit1 and audit2. which are in 2 different methods. The first query runs fine, but the second one generates a 102 error. Is there an issue with having more than 1 cursor in a class? Has anyone seen this before? Hi. Hi, Community! You know that your productions need to be monitored. But what should you be monitoring, and how? I see command shortcuts for getting journal details, like Status^JOURNAL for displaying the journal status. And, I'm using the shortcuts in my shell scripts. I'm not seeing/finding command shortcuts for getting database details. If anyone have those details, please share with me. Hello Developers, I am pretty new to developing using HealthShare, I am working on a project and need to create a custom DTL that will List multiple patients. Anyone have an idea on how to create this? Any help is much appreciated._1<<.png) .png) Example 2: Hello all How can I convert cache date to hijri date format in object secript. please help. Hi Community! Please welcome the new video on InterSystems Developers YouTube: ⏯ Get InterSystems IRIS from the Docker Store This is a coding example working on Caché 2018.1.3 and IRIS 2020.2 It will not be kept in sync with new versions It is also NOT serviced by InterSystems Support ! IRIS 2020 ;-) We are trying to make a document query from an HIE iti-43 on healthshare platform the full SOAP message is follows Hello! I do some http get request. And this is its response. Hi guys!! In the system that I work, I came across an iterator pattern that uses the %Resultset library without performing the close after executing the query. Does anyone know how to say what are the impacts of not performing such a procedure? If you have any model of iterator pattern made in caché to recommend as a good example, I will be grateful hehe :D Currently when 'Importing and Compiling' multiple files I have to click 'Overwrite on Server' for each file. Is there a way of choosing 'Overwrite on Server' for all files I have selected. Hello everyone Webcast in Portuguese - InterSystems IRIS for notification of Covid-19's test results for the Ministry of Health Hi Community! Join us for another InterSystems Brazil virtual event, this time in partnership with Shift. The topic of discussion led by Marcelo Lorencin on September 16 will be: "InterSystems IRIS for notification of Covid-19's test results for the Ministry of Health". Please register now with the link below, vacancies are limited: ✅ InterSystems IRIS for notification of Covid-19's test results for the Ministry of Health Date & Time: September 16 – 11:00 BRT Note: The language of the webcast is Portuguese. Join us!.
https://community.intersystems.com/
CC-MAIN-2020-40
refinedweb
1,001
64.3
Node:Programming with pipes, Next:Low-level file routines, Previous:Single-character input and output, Up:Input and output Programming with pipes There may be times when you will wish to manipulate other programs on a GNU system from within your C program. One good way to do so is the facility called a pipe. Using pipes, you can read from or write to any program on a GNU system that writes to standard output and reads from standard input. (In the ancestors of modern GNU systems, pipes were frequently files on disk; now they are usually streams or something similar. They are called "pipes" because people usually visualise data going in at one end and coming out at the other.) For example, you might wish to send output from your program to a printer. As mentioned in the introduction to this chapter, each printer on your system is assigned a device name such as /dev/lp0. Pipes provide a better way to send output to the printer than writing directly to the device, however. Pipes are useful for many things, not just sending output to the printer. Suppose you wish to list all programs and processes running on your computer that contain the string init in their names. To do so at the GNU/Linux command line, you would type something like the following command: ps -A | grep init This command line takes the output of the ps -A command, which lists all running processes, and pipes it with the pipe symbol ( |) to the grep init command, which returns all lines that were passed to it that contain the string init. The output of this whole process will probably look something like this on your system: 1 ? 00:00:11 init 4884 tty6 00:00:00 xinit The pipe symbol | is very handy for command-line pipes and pipes within shell scripts, but it is also possible to set up and use pipes within C programs. The two main C functions to remember in this regard are popen and pclose. The popen function accepts as its first argument a string containing a shell command, such as lpr. Its second argument is a string containing either the mode argument r or w. If you specify r, the pipe will be open for reading; if you specify w, it will be open for writing. The return value is a stream open for reading or writing, as the case may be; if there is an error, popen returns a null pointer. The pclose function closes a pipe opened by popen. It accepts a single argument, the stream to close. It waits for the stream to close, and returns the status code returned by the program that was called by popen. If you open the pipe for reading or writing, in between the popen and pclose calls, it is possible to read from or write to the pipe in the same way that you might read from or write to any other stream, with high-level input/output calls such as getdelim, fprintf and so on. The following program example shows how to pipe the output of the ps -A command to the grep init command, exactly as in the GNU/Linux command line example above. The output of this program should be almost exactly the same as sample output shown above. #include <stdio.h> #include <stdlib.h> int main () { FILE *ps_pipe; FILE *grep_pipe; int bytes_read; int nbytes = 100; char *my_string; /* Open our two pipes */ ps_pipe = popen ("ps -A", "r"); grep_pipe = popen ("grep init", "w"); /* Check that pipes are non-null, therefore open */ if ((!ps_pipe) || (!grep_pipe)) { fprintf (stderr, "One or both pipes failed.\n"); return EXIT_FAILURE; } /* Read from ps_pipe until two newlines */ my_string = (char *) malloc (nbytes + 1); bytes_read = getdelim (&my_string, &nbytes, "\n\n", ps_pipe); /* Close ps_pipe, checking for errors */ if (pclose (ps_pipe) != 0) { fprintf (stderr, "Could not run 'ps', or other error.\n"); } /* Send output of 'ps -A' to 'grep init', with two newlines */ fprintf (grep_pipe, "%s\n\n", my_string); /* Close grep_pipe, cehcking for errors */ if (pclose (grep_pipe) != 0) { fprintf (stderr, "Could not run 'grep', or other error.\n"); } /* Exit! */ return 0; }
http://crasseux.com/books/ctutorial/Programming-with-pipes.html
CC-MAIN-2017-43
refinedweb
689
75.13
Why the string is passed by reference here? Why the string is passed by reference here? Here if I only change the N to nine it gives no solution why ?? I have tried comparing the strings directly and it works. Why does the note says that comparing string directly does not work? I tried to understand this solution but couldn’t. In this code I was not able to input values several times and everything else was fine. Can any tell me if my code is right? This is the code I wrote: #include <iostream> using namespace std; string secret_s(){ srand(time(0)); int num; num =(rand()%10000); return to_string(num); } int cow(string ss,string sg){ int c=0; for(int i =0;i<4;i++){ here the array size is 5 so we can enter 4 numbers not 5
https://www.commonlounge.com/profile/0686ed9eceb341e2b0c5b56976402093
CC-MAIN-2021-43
refinedweb
141
82.34
tag:blogger.com,1999:blog-28621447226171944172020-02-28T11:17:46.755-08:00A Beginning Programmer's Guide to JavaJava Programming Mysteries Explained for Those Learning to Program for the First Time, and for Experienced Programmers Just Learning Javasaundby of Java Programming SkillsYou can program in Java (or are learning to.) That's great! But what else can you do with those skills? Are you trapped with Java?<br /><br /.<br /><br /><b style="color:#ff8800;">C# (C Sharp)</b><br /.<br /><br /.<br /><br /><b style="color:#ff8800;">C</b><br /.<br /><br />Modern versions of C, such as ANSI C/ISO C (C99) provide a version of C which makes it easier to write good code if you're coming from an object-oriented background.<br /><br />Another major hurdle will be dealing with memory management directly (C has no garbage collection), and learning how to use the various functions of C which are often not as predictable as the Java methods you are familiar with.<br /><br />The basics of C will already be familiar to you, but you should conduct some formal study of C and use its standard libraries extensively before seeking to start formal projects with it.<br /><br /><b style="color:#ff8800;">C++</b><br /.<br /><br />With C++, however, you'll find that while there are standard cross-platform libraries, most code will be best written to the platform to which it is being compiled.<br /><br /><b style="color:#ff8800;">Python</b><br /.<br /><br /.<br /><br /><b style="color:#ff8800;">Javascript</b><br />Javascript is also very similar to Java in many ways, but not as much as the name of the language might lead you to believe. Java has recently acquired many of the constructs that have been favorites of Javascript programmers for years.<br />.<br /><br /.<br /><br /.<br /><br /><b style="color:#ff8800;">Objective-C</b><br /.<br /><br /.<br /><br /><b style="color:#ff8800;">Swift</b><br /.<br /><br /><b style="color:#ff8800;">PHP</b><br /.<br /><br />You will need to learn the specifics of PHP's syntax and data structures, but after mastering Java, you will not find this difficult.<br /><br /><b style="color:#ff8800;">Summary</b><br /.<br /><br /.<br /><br /.<br /><br />I highly recommend, at least, spending some time with C# under Mono or .Net if you are currently a Java programmer. I think you'll find that you feel right at home. <br /><br /.<br /><br /><b style="color:#ff8800;">Mobile</b><br /.<img src="" height="1" width="1" alt=""/>saundby: A More Polished Android Application in JavaSince my post on my <a href="">first Android app</a>, I've done a lot. I went on from that first app to learn how to access a lot more of the device, deal with a wider range of circumstances, and generally get to know Android and the tools for developing for it better.<br /><br />Specifically, I have posted an app for Android called <a href="">DozCalc</a>.<br /><br /><div class="separator" style="clear: both; text-align: center;"><a href="" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="" /></a></div>DozCalc is a dozenal (base 12) calculator. It doesn't convert back and forth between dozenal and decimal, so be warned. Just like your normal four function calculator that works in base 10 and nothing else, DozCalc works in base 12 and nothing else.<br /><br /><b>Java</b><br /><br /.<br /><br /.<br /><br />Sometimes programming is less about the language, or the algorithm, than about just getting a solution that's accurate enough for the need, then moving forward.<br /><br /.<img src="" height="1" width="1" alt=""/>saundby First Android AppI ordered an Android phone about two weeks ago.<br /><br />Last Thursday, I installed the <a gref="">Android SDK</a>. It went smoothly, I've installed it under two versions of Windows 7, as those are my systems with the most RAM and CPU power (for the Android device emulator. My older Mac and Linux systems lug a bit when doing serious hardware emulation.)<br /><br />I started the online tutorials linked on the SDK's opening page. Since the SDK is based on <a href="">Eclipse</a> (my favorite full-fat IDE for Java), it was no problem getting started.<br /><br />I got a simple app, modified from the 'getting started' tutorial, running on an emulated Android device within an hour or so of starting.<br /><br />The next day--Friday, my phone arrived in the mail. It runs Android 4.1.1.<br /><br />After a busy day on Friday interleaved with charging and moving into the phone, I got the Android SDK talking to my phone today, downloaded an updated version of the app (a =very= simple character generator for my RPG, <a href="">RoonVenture</a>.) It ran just fine. It's very similar to my online <a href="">RoonVenture Character Generator</a>.<br /><br />That is, it's ugly, poorly designed, but bone-simple while producing the essential results.<br /><br />Nevertheless, I found my Java skills played right into Android development (so far):<br /><br />Android's native language is Java, with some unique libraries.<br /><br />The default IDE is Eclipse, a common Java IDE (and one I recommend, though I still do about half my code in something lighter, ranging from vi or vim to Arachnophilia or BlueJ.)<br /><br />It's a lot like Java ME development (which I've done to build apps for my older "feature phones".)<br /><br /.<br /><br />Now I'm taking a break from the computer and reading a hardcopy book, "Creating Android Applications" by Chris Haseman. It's written for the experienced Java programmer who doesn't need 250 pages on Java and Eclipse.<br /><br />That should help me make a better app next. :)<br /><br /><center><iframe src="<1=_blank&m=amazon&lc1=0000FF&bc1=FFFFFF&bg1=FFFFFF&npa=1&f=ifr" style="width:120px;height:240px;" scrolling="no" marginwidth="0" marginheight="0" frameborder="0"></iframe><br /></center><img src="" height="1" width="1" alt=""/>saundby Programmers Need Not Fear JavaWhile most of this blog focuses on assisting beginning programmers to learn Java as their first computer language, I also try to make it useful to those who are "old school" programmers, like myself, that want to make the transition to the newer language.<br /><br />I.)<br /><br /><b style="color:#ff7700;">Tools Getting in the Way of the Work</b><br /.<br /><br /.<br /><br /><b style="color:#ff7700;">Welcome, Fellow Dinos!</b><br / <tt>vi</tt> and <tt>make</tt> with <tt>cc</tt> and a system-appropriate linker behind it.<br /><br />In fact, I still do. There are a fair few nights I unwind by firing up my Ampro Little Board Z-80 system, which runs CP/M 2.2, and having at Turbo Pascal or ASM. Just for relaxation. <br /><br />It's like embroidery or quilting for aging nerds, I guess.<br /><br /><b style="color:#ff7700;">Java for Dinos</b><br />I'm good with being called a dino, so I hope it doesn't put you off if you're an old-timer, too. (Am I really an old timer now? Some folks say so.)<br /><br />Java is really awfully easy to use at the command line. Create a source file with your favorite text editor.* Open up a command line (no matter what OS you're on), <tt>cd</tt> to the directory where you saved the file, and compile it with:<br /><tt style="color:#00ddee;">javac <i>filename</i>.java</tt><br /><br />Replace <tt style="color:#00ddee;"><i>filename</i></tt> with your file's name, of course.<br />At this stage you need to include the <tt style="color:#00ddee;">.java</tt> file extension. It will produce a new file with the same name but a <tt style="color:#00ddee;">.class</tt> extension is on it now.<br /><br />Once it completes successfully (and if it doesn't, and old timer should be able to read the error messages and line numbers to fix the code), use the following to run your program:<br /><tt style="color:#00ddee;">java <i>filename</i></tt><br /><br />Note that even though you're running a <tt style="color:#00ddee;">.class</tt> file, you don't specify the file extension for the java runtime. You'll get an error that makes it look like there's something wrong with your file if you do:<br /><blockquote style="color:00dd00;background-color:black;"><pre>>java Howdy.class<br />Exception in thread "main" java.lang.NoClassDefFoundError: Howdy/class<br />Caused by: java.lang.ClassNotFoundException: Howdy:306)<br /> at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)<br /> at java.lang.ClassLoader.loadClass(ClassLoader.java:247)</pre></blockquote><br />And, if you go to compile your program and get really, really long lists of errors, don't be discouraged. Remember the old maxim--fix the first error. Chances are most or all of the rest are errors that cascaded from the first one.<br /><br /><b style="color:#ff7700;">Why Bother?</b><br /.<br /><br /.<br /><br /><b style="color:#ff7700;">Come In and Look Around</b><br />Have a look at my Basic Java Articles, listed in the right column. I strive to post actual working code in my examples, in the form of complete programs. So you don't have to guess about how to fit a snippet into your code.<br /><br />To do this, I often strip away code that would be <i>good</i> <a href="">my Java code repository</a> for this blog (also on the right side of every article here.)<br /><br />If my articles are of use to you, or you think I can improve things, drop me an email.<br /><br />Thanks.<br /><br />.<br /><br /><br /><img src="" height="1" width="1" alt=""/>saundby's Assignment OperatorsAn <a href="">assignment operator</a> is a way of putting a new value into a variable.<br /><br />I covered these briefly in <a href="">Doing Math in Java, Part 1</a>. Now I'll go into a bit more detail.<br /><br /><b style="color:#ff7700;">The Simple Assignment Operator</b><br /><br />The simple assignment operator is <tt style="color:#77ff00;">=</tt>.<br /><br />It places the value from the expression on its right side into the variable on its left.<br />This is covered in detail in <a href="">Left Becomes Right</a>.<br /><br />Also see the <a href="">Java Language Specification</a>: <a href="">The Simple Assignment Operator</a>.<br /><br /><b style="color:#ff7700;">The Compound Assignment Operators</b><br /><br />The compound assignment operators are:<br /><tt style="color:#77ff00;">+=</tt>, "plus-equals",<br /><tt style="color:#77ff00;">-=</tt>, "minus-equals",<br /><tt style="color:#77ff00;">*=</tt>, "times-equals" or "star-equals",<br /><tt style="color:#77ff00;">/=</tt>, "divided by-equals" or "slash-equals",<br /><tt style="color:#77ff00;">%=</tt>, "remainder-equals" or "percent-equals",<br /><tt style="color:#77ff00;">&=</tt>, "and-equals",<br /><tt style="color:#77ff00;">|=</tt>, "or-equals",<br /><tt style="color:#77ff00;">^=</tt>, "exor-equals" or "caret-equals",<br /><tt style="color:#77ff00;">>>=</tt>, "signed-shift-right-equals",<br /><tt style="color:#77ff00;"><<=</tt>, "shift-left-equals",<br /><tt style="color:#77ff00;">>>>=</tt>, "unsigned-shift-right-equals".<br /><br /><b style="color:#ff7700;">Commonality</b><br />Each of these operators has a variable to assign a value to before it, and an expression that results in a value after it:<br /><tt style="color:#0077ff;">variable</tt> <tt style="color:#77ff00;">operator</tt> <tt style="color:#ff0077;">expression</tt><br /><br />The expression has to result in a value that is compatible with <tt style="color:#0077ff;">variable</tt>'s type.<br /><br />Java will calculate the value of <tt style="color:#ff0077;">expression</tt>,<br /><br />perform the calculation <tt style="color:#0077ff;">variable</tt> <tt style="color:#77ffff;">optype</tt> <tt style="color:#ff0077;">expression</tt>, where <tt style="color:#77ffff;">optype</tt> is the assignment operator without the equals sign.<br /><br />Then it will place the result of that calculation into <tt style="color:#0077ff;">variable</tt>.<br /><br /><b style="color:#ff7700;"><tt style="color:#77ff00;">+=</tt>, "Plus-Equals"</b><br />Plus-equals adds the value after += to the original value of the variable, then puts the result into the variable.<br /><br /><b style="color:#ff7700;"><tt style="color:#77ff00;">-=</tt>, "Minus-Equals"</b><br />This subtracts the value after the operator from the original value in the variable, then stores the result in the variable.<br /><br /><b style="color:#ff7700;"><tt style="color:#77ff00;">*=</tt>, "Times-Equals"</b><br />Multiply the variable by the value on the right of the operator, put the result in variable.<br /><br /><b style="color:#ff7700;"><tt style="color:#77ff00;">/=</tt>, "Divided by-Equals"</b><br />Same as the above, but for division.<br /><br /><b style="color:#ff7700;"><tt style="color:#77ff00;">%=</tt>, "Remainder-Equals"</b><br />This finds the <i>remainder</i> of the variable's initial value divided by the value after the operator. That <i>remainder</i> is then put into the variable.<br /><br />See <a href="">Java's Modulo Operator--Wrapping Around</a> for more information on how the remainder (or modulo) operator <tt style="color:#77ff00;">%</tt> works.<br /><br /><b style="color:#ff7700;"><tt style="color:#77ff00;">&=</tt>, "And-Equals"</b><br />And-equals does a bit-wise AND of the value after the assignment operator with the original value of the variable, then puts the results in the variable.<br /><br /><b style="color:#ff7700;"><tt style="color:#77ff00;">|=</tt>, "Or-Equals"</b><br />Or-equals does a bit-wise OR of the variable and the value after the operator. The result is placed in the variable.<br /><br /><b style="color:#ff7700;"><tt style="color:#77ff00;">^=</tt>, "Exor-Equals"</b><br />Exor-equals is short of Exclusive-Or Equals (and it is often written xor-equals). It does a bitwise exclusive-or of the variable and the value after the assignment operator, then puts the result into the variable.<br /><br /><b style="color:#ff7700;"><tt style="color:#77ff00;">>>=</tt>, "Signed-Shift-Right-Equals"</b><br />This does a signed right shift of the variable a number of times equal to the expression after the assignment operator. The result is placed in variable.<br /><br /><b style="color:#ff7700;"><tt style="color:#77ff00;"><<=</tt>, "Shift-Left-Equals"</b><br />This does the same thing as signed-shift-right-equals, except it does a signed left shift (each bit in the variable gets moved to the left <i>expression</i> times.<br /><br /><b style="color:#ff7700;"><tt style="color:#77ff00;">>>>=</tt>, "Unsigned-Shift-Right-Equals"</b><br />This one moves all the bits, unlike the signed shifts which leave the sign bit (highest order bit) alone.<br /><br /><b style="color:#ff7700;">Not Quite the Whole Story</b><br />That covers how these operators behave with numerical and other simple values. These operators have other behaviors when used with Strings, Arrays, and other complex value types. That goes beyond the scope of this article, however, more on that can be found at the links given under "Additional Information".<br /><br /><b style="color:#ff7700;">Additional Information</b><br />See the <a href="">Java Language Specification</a>: <a href="">Compound Assignment Operators</a>, <a href="">Multiplicative Operators</a>, <a href="">Additive Operators</a>, <a href="">Bit-wise and Logical Operators</a>.<br /><br /><img src="" height="1" width="1" alt=""/>saundby's Modulo Function--Wrapping AroundI've previously discussed <a href="">operators</a> in Java, where I gave a brief introduction to the <b>modulo</b> operator, <b><tt>%</tt></b>.<br /><br />The percent sign is used in many computer languages as a brief, single-character symbol for the remainder of a division, not for a percentage of a number, as you might expect.<br /><br /><b style="color:#ff7700;">What's Left Over</b><br /><br />In many calculations in normal day to day life, the remainder of a division is not very important. It's just the odd change left over at the end of doing division. With computer programs, however, modulos can be very useful and powerful.<br /><br /.<br /><br /><b style="color:#77ff00;"><tt>limitedNumber = someNumber % 100</tt></b><br /><br /><tt>limitedNumber</tt> will never be higher than 99.<br /><br /><b style="color:#ff7700;">Real World Analogies</b><br /><br /.<br /><center><img src="" alt="Radio dial, image by John McComb of Oakland, CA." width="450" height="450" /></center><br />For example, a radio dial that goes up in frequency until you hit the top of the radio band, then starts tuning over again from the bottom of the band.<br /><br /><b style="color:#ff7700;">Computer Applications</b><br /><br / <tt>xLoc</tt> (short for x location):<br /><br /><tt style="color:#0077ff;">Class Asteroid{<br /> int xLoc, yLoc, xSpeed, ySpeed, size;<br /> .<br /> .<br /> .<br />}</tt><br /><br />We'll assume the class has all the methods it needs to do what Asteroids do. Our instance is:<br /><br /><tt style="color:#0077ff;">Asteroid asteroid = new Asteroid();</tt><br />(If this is unfamiliar to you, you may want to read <a href=">Creating a Java Variable, Two Steps</a>.)<br /><br /.<br /><br />We can move our asteroid from left to right as follows:<br /><br /><tt style="color:#0077ff;">xLoc = xLoc + xSpeed;</tt><br /><br />Where <tt>xSpeed</tt> is how fast we're moving across the screen.<br /><br />The problem is, what do we do when we hit the right edge of the screen? That is, what do we do when xLoc is higher than 799?<br /><br />If we want our asteroid to "wrap around" from the right side to the left side of our screen, the modulo operator is just what we want. We can do this to make it wrap around that way:<br /><br /><tt style="color:#0077ff;">xLoc = xLoc + xSpeed;<br />xLoc = xLoc % 800; // Hard-coded screen width, for now.</tt><br /><br />That will make xLoc always be from 0 (when there is a zero remainder) to 799 (the highest possible remainder when dividing by 800.)<br /><br />We might have a method in Asteroid like the following:<br /><br /><tt style="color:#0077ff;">public int moveHoriz(int howFar){<br /> // Moves the Asteroid horizontally by howFar pixels on an 800 pixel wide screen.<br /> // returns the new pixel location.<br /> return (xLoc + howFar) % 800;<br />}</tt><br /><br />This glosses over a few other problems (like going from the left edge of the screen to the right), but illustrates the use of modulo to bring the object around from right to left again.<br /><br /><br /><b style="color:#ff7700;">An Expanded Example</b><br /><br />Here's a more developed example that deals with speeds higher than the screen width, and wraps both ways:<br /><br /><tt style="color:#0077ff;">public int moveHoriz(int howFar){<br /> // Moves the Asteroid horizontally by howFar pixels on a screen.<br /> // It returns the new horizontal pixel location.<br /><br /> // We have a screen width available to us in member variable xWidth,<br /> // and our x location in xLoc.<br /> // Wraps from right to left, or left to right.<br /><br /> //Use modulo to trim speed if it's too high.<br /> if (howFar > xWidth) howFar %= xWidth; <br /><br /> // Calculate the new x location and return it.<br /> return (xLoc + howFar + xWidth) % xWidth;<br />}</tt><br /><br /><h6>Radio Dial image by John McComb.</h6><img src="" height="1" width="1" alt=""/>saundby Introspection and Using Collections without GenericsIn my prior article on <a href="">Generics</a> we looked at how to use Generics to associate at type with data stored in a Collection.<br /><br />You.<br /><br />But, once you pull that data back out of the Collection, how do you find out what it was?<br /><br />Fortunately, the object itself has that information stored with it.<br /><br />There are two easy ways to find out what it is. <tt>instanceof</tt> can test if it is a specific type of Object:<br /><pre style="color:#0033ff;"><br />if (anObject instanceof String) { aString = (String)anObject); }<br /></pre><br /><br />You can also have an Object tell you its type:<br /><pre style="color:#0033ff;"><br />Class myClass = anObject.getClass();<br /></pre><br />or<br /><pre style="color:#0033ff;"><br />String myClassName = anObject.getClass().getName();<br /></pre><br /><br />A look at the documentation for <a href="">Object</a> and <a href="">Class</a> gives all sorts of useful methods for dealing with classes of data objects in Java.<br /><br />Here's some sample code:<br /><pre style="color:#00dd33;"><br />import java.util.*;<br /><br />public class NoGenerics2{<br />// This is an example of using introspection<br />// to determine types of Objects stored in a<br />// Collection without a Generic declaration.<br /><br /> public static void main(String[] arg){<br /> ArrayList myList = new ArrayList(); // No Generic <String> declaration.<br /> Stringsaundby in JavaGenerics are an oddly-named thing in Java that associate objects stored in a Collection with a particular type. Let's take a look at a piece of code that uses a Collection to store some Strings. It uses an ArrayList. Here's the code:<br /><br /><pre style="color:#dd0000;"><br />import java.util.*;<br />public class NoGenerics{<br />// This is an example of what happens <br />// when you don't declare a class<br />// for a Collection using Generics. <br />// It won't compile!<br /><br /> public static void main(String[] arg){<br /> // No Generic <String> declaration.<br /> ArrayList myList = new ArrayList();<br /> StringFeel free to take the above code and try to compile it to see the error you'll get. It <em>is</em> instructive.</p><br /><br /><b style="color:#ff7700;">The Fix for Lost Types</b><br /><br />In Java version 1.5 "Generics" were added to fix this. Now Collections like the ArrayList can associate a type with the data put in them, and the compiler can do type checking. Here's the above code, with the Generic declaration <String> added:<br /><br /><pre style="color:#0033ff;"><br />import java.util.*;<br /><br />public class Generics{<br />// This is an example of what happens <br />// when you declare a data class<br />// for a Collection using Generics.<br /><br /> public static void main(String[] arg){<br /> // Generic <String> declaration.<br /> ArrayList<String> myList = new ArrayList<String>();<br /> StringGenerics = Typed Collections</b><br />So if you are going to use a collection on Objects all of a specific type (rather than mixing and matching), put on a Generic declaration.<img src="" height="1" width="1" alt=""/>saundby under Mac OS X 10.7 LionLion is the first version of Mac OS X that doesn't come with Java already installed. Earlier versions not only had the <a href="">Java Virtual Machine</a> or runtime element installed, but they also had the JDK installed, which is the part that lets you write your own Java programs.<br /><br />Once, Java was an important part of Apple's strategy. They maintained their own version of Java for the Mac and encouraged its use by developers every bit as much as they encouraged the use of Objective-C.<br /><br /.<br />.<br /><br />Simply use Finder to go to Applications=>Utilities. There, start Terminal. Once Terminal starts, type in the command 'javac'. Your Mac will tell you that Java isn't installed, and let you install it.<br /><br /.<img src="" height="1" width="1" alt=""/>saundby JavaEmbedded Java sounds almost like an oxymoron. Taking a high level, large, interpreted language like Java and using it in an application field dominated by assembly and C certainly seems odd. But it's a reality.<br /><br /.<br /> <br /><a href="">NanoVM</a> is a small, subscale Java-ish virtual machine that runs on tiny 8-bit microcontrollers like the AVR ATMega8. It's not a full Java, but it covers most of what's interesting to the microcontroller programmer.<br /><br />The <a href="">JStamp</a> is a Java development system for the aJile micros. It's also not a full Java SE implementation (what would you do with the extra bits, even if it was?), but it is a verifiable real-time Java system for embedded development.<br /><br />Also, <a href="">IS2T</a> has MicroEJ, another embedded Java for a number of processors. Everything from the basics of execution and I/O up to GUIs, SOAs, and safety-critical libraries are available.<br /><br /.<br /><br />It's all just a bunch of ones and zeroes in the end.<img src="" height="1" width="1" alt=""/>saundby JavaOne of the nice things about Java is that is supported on more than desktop platforms, and has been for a long time. This means there is not only a large library of existing software, but also well-tuned development systems to use with mobile platforms.<br /><br />By "mobile platform", I'm referring to smartphones and tablets. There are other mobile platforms, but these are the most common ones. Netbooks may also run a "mobile" operating system, or they may run a normal desktop OS. Those that run a normal desktop OS will run normal <a href="">Java SE</a> applications. Java SE is "Java, Standard Edition", the version that typically runs on a desktop or laptop computer.<br /><br /><a href="">Java ME<.<br /><br /.<br /><br />I have been writing small, simple applications for my cellphones for about ten years now. It's nice to be able to write your own little application for your own unique needs. I started writing Java applications for my <a href="">Nokia 3650</a>, called a "feature phone" at the time I got it. It was a Symbian Series 60 phone that ran an early version of Java ME with a very basic library of GUI features.<br /><br />My next phone was a step up the Java ladder. It was a <a href="">Sciphone G2</a>, a fake Android phone. I didn't mind that it was "fake", it ran a real version of Java ME with updated GUI capabilities, which made it far easier to write applications for.<br /><br />My current phone is a <a href="">Blackberry Curve 8900</a>. It runs Java ME with all the latest bells and whistles, plus a lot of Blackberry add-ons that make it easy to access the phone's features.<br /><br / <a href="">Eclipse</a>, a great Java <a href="">integrated development environment</a>. The version linked above is a version specific to Java ME.<br /><br />Now I'm back to having a <a href="">development environment</a>.<br /><br /?<br />.<br /><br /.<br /><br /.<br /><br />Java ME applets are easy to translate, though I write almost all of my Java software as applications now.<img src="" height="1" width="1" alt=""/>saundby Literal ValuesJava 7 has added a new feature, binary literals for integer number types (byte, short, int, and long.) Before we can get excited about this, we need to know what that means. In earlier versions of Java, we have had several other types of literal value.<br /><br /><b style="color:#ff7700;">Let's Get Literal</b><br /><br />What is a "literal"? A literal is an explicit value. For example, in this line:<br /><tt style="color:#0077ff;">int number=123;</tt><br />the value <tt style="color:#0077ff;">123</tt> is a "literal". Since it's a normal base-10 value, we might say it is a "decimal literal". Decimal values don't have to be marked in any special way.<br /><br />A hexadecimal literal looks like this:<br /><tt style="color:#0077ff;">int number=0x007b;</tt><br />The value <tt style="color:#0077ff;">0x007b</tt> is a hexadecimal (base 16) number that is expressed literally (stated explicitly.) The <tt style="color:#0077ff;">0x</tt> at the beginning is what marks it as a hexadecimal value. The leading zero shows that it's a numerical value, not a variable name or keyword or something like that. The x marks it as a hexadecimal number.<br /><br />Hexadecimal numbers take binary values four bits at a time (a bit is a single one or zero value) and puts them into a single digit. Octal (base 8) digits each represent the values of three bits.<br /><br />To tell Java you're using an octal value, place a leading zero in front of the number itself:<br /><tt style="color:#0077ff;">int number=0173;</tt><br />Here the number <tt style="color:#0077ff;">0173</tt>:<br /><tt style="color:#0077ff;">int number=0123;</tt><br />The value of the number will be interpreted as eighty-three, not one hundred twenty-three. So watch out for that.<br /><br /><b style="color:#ff7700;">New for Java 7--Binary Literals</b>.<br /><br />But now it's finally here.<br /><br />So you can define values as individual bits, like this:<br /><tt style="color:#0077ff;">int number=0b01111011;</tt><br />That's the binary for one hundred twenty-three, by the way. Why is this important?<br /><br /.<br /><br /:<br /><br /><tt style="color:#0077ff;">byte stick_up=0b00001;</tt><br /><br />In this case, we show it setting the lowest order bit. We might have another like this:<br /><br /><tt style="color:#0077ff;">byte fire_switch=0b100000;</tt><br />.<img src="" height="1" width="1" alt=""/>saundby Variable Value Assignment: Left Equals Right, Left Becomes RightOne of those things that vexes beginning programmers is assigning values to a variable in Java. Part of what makes it so vexing is that the problem is practically invisible to an experienced programmer. Another part of it is that we use the equals sign (=) to do the assignment.<br /><br />Take a look at these statements:<br /><br /><code style="color:#33ff33;">int i = 1;</code><br /><code style="color:#33ff33;">j=7;</code><br /><code style="color:#ff3333;">7+count=c;</code><br /><code style="color:#ff3333;">b+14=a+9;</code><br /><br />The first two are fine (assuming that 7 is a valid value for whatever type of variable <tt>j</tt> is), but the last two are wrong.<br /><br /><b style="color:#ff7700;">Remember All That Algebra We Taught You? Well, We Broke It.</b><br /><br />After you've gone to all the trouble to learn how to deal with things like <tt>7+count=c</tt> and <tt>b+14=a+9</tt> in algebra class, now we take what you know and turn it on its ear in programming class. Sweet, eh?<br /><br />The problem is that the <tt>=</tt> we use in programming has pretty much nothing to do with the <tt>=</tt> that you use in math. It's just close enough to be confusing. In Java, the equals sign is an <em>assignment</em> operator, not an indicator of equality between values as it is in math. There is a comparison operator for equality in Java, it's <tt>==</tt>, and we'll talk about it shortly. First, let's talk assignment.<br /><br /><b style="color:#ff7700;">Assignment</b><br /><br /.<br /><br />With Java, we can store all kinds of values, not just numbers. We can store sections of text, called <em>strings</em> in a <tt>String</tt>.<br /><br />But we're here to just look at assignment today, not the wide variety of things we can assign as values.<br /><br />To store a value on a calculator, you use some key sequence like <tt>M+</tt> or <tt>STO 00</tt> to store the value in the calculator's display to memory. With Java, we use the equals sign to store some value on the right into whatever is on the left side of the equals sign. We read from left to right like this:<br /><br /><tt>count = a;</tt><br />"count equals a"<br /><br />This means we take the value of <tt>a</tt> and place it in <tt>count</tt>. But a better way to read that equals sign is to use the word "becomes" instead of "equals":<br /><br /><tt>count = 9;</tt><br />"count <b>becomes</b> nine"<br /><br />This makes it more obvious that we're putting in a new value that changes the value of <tt>count</tt>. In this case, we're putting in a value of 9. The statement up above would be "count becomes a" or, better yet, "count becomes a's value." Because what we're doing in <tt>count= a;</tt> is taking the value in variable <tt>a</tt> and copying it into <tt>count</tt>. If we then print the value in <tt>count</tt>, it will be the same as whatever is in <tt>a</tt> at that time.<br /><br />We can also compute a value to put into our variable.<br /><br /><tt>count = a + 1;</tt><br />"count becomes a plus one"<br /><br />This makes the value in <tt>count</tt> be one more than the current value of <tt>a</tt>.<br /><br />What we <b>can't</b> do is change sides around the equals sign. In algebra, <em>c = a + 1</em> is the same as <em>a + 1 = c</em>. But in Java that doesn't work:<br /><br /><tt style="color:#ff3333;">a + 1 = count</tt><br />This is wrong in Java. Does not compute. Norman, Norman, help me Norman!<br /><br />We would be trying to make a+1 become the value in count. The problem is, you can't have a storage location named "a+1". Java doesn't see this the way your algebra trained eyes do.<br /><br /><b style="color:#ff7700;">Comparisons</b><br /><br /.<br /><br />Another use of equals in some math problems is to state that two things are equal when they may or may not be, then determine whether that statement is true or not. You remember those problems, they looked something like this:<br /><br /><tt>State whether each of the following is true or false.</tt><br /><tt>1. 11 = 6 + 5<br />2. 14 = 3 x 7<br />3 65 - 14 = 17 x 3</tt><br /><br />In Java, the equals sign is already used for assigning values to variables. How do we do a comparison to see whether it's true or not?<br /><br /><b style="color:#ff7700;">The == Operator</b><br /><br />In some languages, <tt>=</tt> does both jobs. But in Java, there's a second operator for doing equality comparisons, <tt>==</tt>, "equals equals". When we want to see if two values are the same, we compare them using a statement something like this:<br /><br /><tt>if (count == 100) then stop();</tt><br /><br />This compares <tt>count</tt> to the value <tt>100</tt>, and executes the method <tt>stop()</tt> if the result of the comparison is <tt>true</tt>.<br /><br /><br /><b style="color:#ff7700;">The Dangers of the = Operator</b><br /><br />Something to look out for is using <tt>=</tt> by accident in such a situation. Like this:<br /><br /><tt style="color:#ff3333;">if (count = 100) then stop();</tt><br />Don't do this if you want to compare count to 100!<br /><br />What this does is <em>assign</em> the value 100 to <tt>count</tt>. If the assignment is successful (which it almost certainly will be, if the program compiles), the program will then do <tt>stop()</tt> every time it hits this statement! Because the assignment was successful, so the result is considered to be <tt>true</tt>.<br /><br /><b style="color:#ff7700;">Summary</b><br /><br />The equals sign makes the variable on the left equal the computed value from the right side of the equals sign:<br /><br /><tt>saundby Math in Java part 2:FunctionsThe basics of math in Java using operators was covered in <a href="">Part 1: Operators</a>. There I went over the standard operations built into the language itself, rather than in its APIs (libraries).<br /><br />But that's hardly the end of useful math operations. Especially when doing graphics, where all those geometric and trigonometric functions come in so useful. Square root, cosine, absolute values, etc.<br /><br /.) <br /><br />What you really want is the <a href="">java.lang.Math</a> class, in the java.lang package.<br /><br />This has most of the standard math functions you're used to. They're defined as static methods, so you don't need to create a Math object to use them. You just call them like this:<br /><br /><pre style="color:#0077ff;"><tt> float distance = Math.sqrt(dx*dx + dy*dy);<br /> float speed = Math.abs(velocity);</tt></pre><br /><br />These call the square root function <code>Math.sqrt()</code> and absolute value function <code>Math.abs()</code>. There are a slew of others like degree to radian conversion, the standard trig functions, and so on.<br /><br /><b style="color:#ff7700;">Date Calculations</b><br /><br />Calculations with dates are another standard sort of math that's not covered by standard operators. In the package java.util we've got <a href="">the Calendar class</a>. The Calendar class itself is an abstract class. This means that it's a class used to build other classes with, not to use directly. The <a href="">GregorianCalendar</a> class is a concrete implementation of <code>Calendar</code> that you can use directly. The Calendar object's add() method will add or subtract some amount of time--days, minutes, hours, etc.--to or from a given date (the date that the object is set to:<br /><ol><br /><li>Create a GregorianCalendar Object</li><br /><li>Set its date</li><br /><li>Use its add() method to add or subtract the time difference.</li><br /></ol><br />Example:<br /><pre><tt style="color#00ff33;">GregorianCalendar myDate;<br />myDate = new GregorianCalendar(2011, 6, 7); //set the date to 07 June 2011.<br />myDate.add(Calendar.Date, 165); // add 165 days to that date.<br /></tt></pre><br /><br /><code>before()</code>, <code>after()</code> and <code>compareTo</code>.)<br /><br /.)<br /><br />So it takes a lot of code to do what should only take a line or two, when working with dates.<br /><br /);<br /><br />I'll be adding articles dealing specifically with dates myself at a future date.<img src="" height="1" width="1" alt=""/>saundby Math in Java part 1: OperatorsOne of the most valuable uses of a computer is...computing. That is, acting as a mathematical calculator. Java has a plethora of tools for doing computation.<br /><br /><b style="color:#ff7700;">Operators</b><br /><br />The standard math functions that are built into the Java language are called <em>operators</em>. These are the sort of math functions you would expect to find on a simple calculator, plus some extras:<br /><br /><b><tt><pre>+ - * / % ++ --</pre></tt></b><br /><br />There are other operators used for comparisons, these are the math operators. You can learn more about them in the <a href="">Java Language Specification</a>, specifically in <a href="">Integer Operations</a>, <a href="">Floating-Point Operations</a>, and more extensively through <a href="">Chapter 15, Expressions</a>.<br /><br /><tt>+</tt> and <tt>-</tt> do what you would expect, they add and subtract one value from another. <tt>*</tt> is the symbol used for multiplication, instead of the × used in math class. <tt>*</tt> is used because it's easier for the computer to recognize it as a math operator, × just looks like a letter 'x' to the computer. Similarly, <tt>/</tt> is used for division. The ÷ sign isn't on most keyboards, but / has been common on keyboards even before they were attached to computers.<br /><br /.<br /><br /><tt>++</tt> and <tt>--</tt> are the "increment" and "decrement" operators. Increment means "go up by one unit", and decrement "go down by one unit". So if you've got a variable like:<br /><br /><code>int i = 5;</code><br /><br />And you do <code>i++</code>, the value of <code>i</code> will become 6. Doing <code>i--</code> will take away 1. <tt>++</tt> and <tt>--</tt> can be placed either before or after the value they act on, for example:<br /><br /><code>number = i++;<br />count = --j;</code><br /><br />There will be different effects on your program depending on whether they come before or after the value. You can find information on that in the Java Language Specification as well, in sections <a href="">15.14</a> and <a href="">15.15</a> which cover the two ways of using these operators. In general, it's best to stick to using them <em>after</em> your value until you understand the differences.<br /><br /><b style="color:#ff7700;">Assignment Operators</b><br /><br />You can also do math as part of assigning a value. For example, let's say we want to add three to a value in our program. The obvious way to do this would be:<br /><br /><code>i = i + 3;</code><br /><br />This takes the prior value of <tt>i</tt>, adds 3 to it, then puts the result back into variable <tt>i</tt>. With an <em>assignment operator</em> we can do the same thing more tersely:<br /><br /><code>i += 3;</code><br /><br />We've combined the <tt>+</tt> with <tt>=</tt> to create an operator. This does the same thing as <code>i = i + 3;</code>. Your program doesn't care which way you type it. The same thing can be done with the other operators that take two values:<br /><br /><code style="color:#0077ff;">i *= 4; // Multiply i by four, store result back in i.<br />i /= 2; // Divide i in half.<br />i %= 3; // Put the remainder of i/3 in i.<br />i -= 7; //Subtract seven from i.</code><br /><br /><b style="color:#ff7700;">More Complex Math</b><br /><br />This is what we can do with the basic math operators built into the language. To get more operations, like those found on a scientific or programmer's calculator, we use methods of some of the standard packages of Java. Which I'll cover in a future article.<br /><br />Until then, have a look at <a href="">java.lang.Math</a>.<img src="" height="1" width="1" alt=""/>saundby Own Java ClassesTo use Java effectively, you want to create and use your own classes. This is one of the great powers of object-oriented languages--the ability to construct programs out of independent building-blocks that cut large problems down into small, easily solvable ones. There's a lot more that can be said, and much of it is elsewhere. So I'll get right into a very simple, very basic example here.<br /><br />We.<br /><br />Here's our class: <a href="">(download HelloClass.Java)</a><br /><br /><pre style="color:#0077ff;">public class HelloClass{<br /><br />/**<br /> * sayHello() prints "Hello!" to the Java console output.<br /> */<br /> public void sayHello(){<br /> System.out.println("Hello!\n");<br /> }<br /><br />/**<br /> * doHello() prints "Hello, hello!" to the Java console output.<br /> * It's static, so you don't need to instatiate a HelloClass <br /> * object to use it.<br /> */<br /> public static void doHello(){<br /> System.out.println("Hello, hello!\n");<br /> }<br /><br />} // End of HelloClass</pre><br /><br />The two methods we have to print messages are <tt>sayHello()</tt> and <tt>doHello()</tt>. To use <tt>sayHello()</tt>, we need to have a <tt>HelloClass</tt> object created, then call that object's <tt>sayHello()</tt> method.<br /><br /><tt>doHello()</tt>, however, is a <tt>static</tt> method. This means is belongs to the class, not to any object of the class. So we can use it without any <tt>HelloClass</tt> objects being created first.<br /><br />Here's a class that uses these methods as described: <a href="">(download UseHello.java)</a><br /><br /><pre style="color:#00ff77;">public class UseHello{<br /> public static void main(String[] arg){<br /><br /> // We can use doHello() without a HelloClass object:<br /> HelloClass.doHello(); // call the HelloClass's doHello() method.<br /><br /> // But we need to create a HelloClass object to use sayHello():<br /> HelloClass hello=new HelloClass();<br /> hello.sayHello(); // call hello's sayHello() method.<br /><br /> }<br />} // End of UseHello.</pre><br /><br />If we try to call <tt>sayHello()</tt> without first creating a HelloClass object, like this:<br /><tt>HelloClass.sayHello();</tt><br /><br />then we'll get the dreaded "calling a non-static method from a static context" error message. That's letting you know that you need to instantiate (or create) a HelloClass object first, then tell that object to call its method.<br /><br />Static methods are useful for things like general arithmetic and calculation or other methods that might be used in a way where state information is unimportant. But beware, it's easy to create static methods when what's really wanted is an object that does what you want.<br /><br />Files available for download through: <a href=""></a>.<img src="" height="1" width="1" alt=""/>saundby Java CSV File ReaderOne of the most common types of data file is a CSV (Comma Separated Value) file. They can be exported by many popular applications, notable spreadsheet programs like Excel and Numbers. They are easy to read into your Java programs once you know how.<br /><br />Reading the file is as simple as <a href="">reading a text file</a>. The file has to be opened, a BufferedReader object is created to read the data in a line at a time.<br /><br />Once a line of data has been read, we make sure that it's not <tt>null</tt>,.<br /><br />The delimiter for a CSV file is a comma, of course. Once we've split() the string, we have all the element in an Array from which our Java programs can use the data. For this example, I just use a <tt>for</tt> loop to print out the data, but I could just as well sort on the values of one of the cells, or whatever I need to do with it in my program.<br /><br /><b style="color:#ff7700;">The Steps</b><br /><br /><ol><li>Open the file with a BufferedReader object to read it a line at a time.</li><br /><li>Check to see if we've got actual data to make sure we haven't finished the file.</li><br /><li>Split the line we read into an <i>Array</i> of String using String.split()</li><br /><li>Use our data.</li></ol><br /><br /><b style="color:#ff7700;">The Program</b><br /><pre style="color:#0077ff;"><span style="color:#00ff77;">// CSVRead.java<br />//Reads a Comma Separated Value file and prints its contents.</span><br /><br />import java.io.*;<br />import java.util.Arrays;<br /><br />public class CSVRead{<br /><br /> public static void main(String[] arg) throws Exception {<br /><br /> BufferedReader CSVFile = <br /> new BufferedReader(new FileReader("Example.csv"));<br /><br /> String dataRow = CSVFile.readLine(); <span style="color:#00ff77;">// Read first line.</span><br /><span style="color:#00ff77;"> // The while checks to see if the data is null. If <br /> // it is, we've hit the end of the file. If not, <br /> // process the data.</span><br /><br /> while (dataRow != null){<br /> String[] dataArray = dataRow.split(",");<br /> for (String item:dataArray) { <br /> System.out.print(item + "\t"); <br /> }<br /> System.out.println(); // Print the data line.<br /> dataRow = CSVFile.readLine(); <span style="color:#00ff77;">// Read next line of data.</span><br /> }<br /><span style="color:#00ff77;"> // Close the file once all data has been read.</span><br /> CSVFile.close();<br /><br /><span style="color:#00ff77;"> // End the printout with a blank line.</span><br /> System.out.println();<br /><br /> } <span style="color:#00ff77;">//main()</span><br />} <span style="color:#00ff77;">// CSVRead</span></pre><br /><br /><b style="color:#ff7700;">Downloads</b><br /><br /><a href="">This program</a>, and <a href="">an example CSV file</a> to use it with (a section of a spreadsheed I use to keep track of my integrated circuits) are available at <a href="">my code archive</a>.<br /><br /><b style="color:#ff7700;">Writing to CSV Files with Java</b><br /><br />Writing to a CSV file is as simple as <a href="">writing a text file</a>. In this case, we write a comma between each field, and a newline at the end of each record.<br /><br />Give it a try, starting with <a href="">TextSave.java</a>, modify it appropriately, then see what your favorite spreadsheet program thinks of the results.<img src="" height="1" width="1" alt=""/>saundby File Save and File Load: TextWe've looked at <a href="">saving and loading objects</a> to files. If we need to exchange information for use by a different program than our own it will seldom be convenient to save objects. Text files are commonly used to do this.<br /><br />Text files are even simpler to deal with than Object files, thanks to classes in the java.io package. FileWriter gives us everything we need to write from our program to a text file. All we need to do is feed it String data.<br /><br />FileReader lets us access a file, but using a BufferedReader makes it a lot easier to handle reading data from a file as lines of text.<br /><br /><span style="color:#77ff00;">As with object files, the basic steps are:<br />1. Open a file.<br />2. Write or read data.<br />3. Close the file.</span><br /><br />Here are example programs, the first writes a simple text file. After you run it, you can take a look at the file it creates (in the same directory) using your favorite text viewer. You'll see normal text written line by line.<br /><br /.)<br /><br />As always, you can download the program files from <a href="">the Begin With Java Code Archive</a>.<br /><br /><h3><a href="">TextSave.java</a></h3><pre style="color:#0077ff;"><br />import java.io.*;<br /><br />public class TextSave{<br /><br /> public static void main(String[] arg) throws Exception {<br /> // Create some data to write.<br /> int x=1, y=2, z=3;<br /> StringTextRead.java</a></h3><pre style="color:#00ff77;"><br />import java.io.*;<br /><br />public class TextRead{<br /><br /> public static void main(String[] arg) throws Exception {<br /> int x, y, z;<br /> Stringsaundby File Save and File Load: Objects<a href="#restore"><tt>Jump to Reading Data from Files with Java>></tt></a><br /><br /><a name="save"><h3>Saving Data to Files with Java</h3></a><br /.<br /><br />To reiterate:<br /><span style="color:#77dd00;"><br />1. Open a file.<br /><br />2. Open an object stream to the file.<br /><br />3. Write the objects to that stream.<br /><br />4. Close the stream and file.<br /></span><br /><b style="color:#ff7700;">1. Opening the File</b><br /.<br /><br />Example:<br /><span style="color:#00aa00;">FileOutputStream saveFile = new FileOutputStream("saveFile.sav");</span><br /><br /><b style="color:#ff7700;">2. Open an Object Stream</b><br />To write objects to the FileOutputStream, we create an ObjectOutputStream. We give it the FileOutputStream object we've set up when we construct the new ObjectOutputStream object.<br /><br />Example:<br /><span style="color:#00aa00;">ObjectOutputStream save = ObjectOutputStream(saveFile);</span><br /><br /><b style="color:#ff7700;">3. Write Objects</b><br />When we write objects to the ObjectOutputStream, they are sent out through it to the FileOutputStream and into the file.<br /><br />Example:<br /><span style="color:#00aa00;">save.writeObject(objectToSave);</span><br /><br /><b style="color:#ff7700;">4. Close Up</b><br />When we close the ObjectOutputStream, it'll also close our FileOutputStream for us, so this is just one step.<br /><br />Example:<br /><span style="color:#00aa00;">save.close();</span><br /><br />Example Program:<br /><pre style="color:#0077ee;font-size:9pt;">import java.io.*;<br />import java.util.ArrayList;<br /><br />public class SaveObjects{<br /><br />public static void main(String[] arg){<br /><br />// Create some data objects for us to save.<br />boolean powerSwitch=true;<br />int x=9, y=150, z= 675;<br />String<h3>Reading Data Files with Java</h3></a><br />Now we need to know how to get data back from a file with Java. Since the data objects were stored using an ObjectOutputStream, they are saved in a way that makes them easy to read back using an ObjectInputStream.<br /><br /.<br /><br />The steps are practically the same as for writing objects to a file:<br /><span style="color:#77dd00;"><br />1. Open a file.<br /><br />2. Open an object stream from the file.<br /><br />3. Read the objects to that stream.<br /><br />4. Close the stream and file.<br /></span><br /><b style="color:#ff7700;">1. Opening the File</b><br />To open a file for <i>reading</i>,.<br /><br />Example:<br /><span style="color:#00aa00;">FileInputStream saveFile = new FileInputStream("saveFile.sav");</span><br /><br /><b style="color:#ff7700;">2. Open an Object Stream</b><br />To read objects to the FileInputStream, we create an ObjectInputStream. We give it the FileInputStream object we've set up when we construct the new ObjectInputStream.<br /><br />Example:<br /><span style="color:#00aa00;">ObjectInputStream restore = ObjectInputStream(saveFile);</span><br /><br /><b style="color:#ff7700;">3. Read Objects</b><br />When we read objects from the ObjectInputStream, it gets then from the file.<br /><br />Example:<br /><span style="color:#00aa00;">Object obj = restore.readObject();</span><br /><br /><b style="color:#ff7700;">3 and a half. Cast Back to Class</b><br />Step 3. only restores a generic Object. If we know the original class, we should cast the Object back to its original class when we read it. If we had stored a String object, we'd read it something like this:<br /><span style="color:#00aa00;">String name = (String) restore.readObject();</span><br /><br /><b style="color:#ff7700;">4. Close Up</b><br />When we close the ObjectInputStream, it'll also close our FileInputStream for us, so this is just one step.<br /><br />Example:<br /><span style="color:#00aa00;">restore.close();</span><br /><br />Here's an example program to read back information saved by the first example program:<br /><pre style="color:#0077ee;font-size:9pt;">import java.io.*;<br />import java.util.ArrayList;<br /><br />public class RestoreObjects{<br /><br />public static void main(String[] arg){<br /><br />// Create the data objects for us to restore.<br />boolean powerSwitch=false;<br />int x=0, y=0, z=0;<br />String<<Return to How to Save to a File with Java</a><br /><br />The example programs can be downloaded at:<br /><a href="">Begin With Java Code Downloads</a><img src="" height="1" width="1" alt=""/>saundby Out the Sun ReferencesToday I'm going to start cleaning out the references in old posts to Sun Microsystems. Sun is gone now, except for a page that tells you it's gone and points toward Oracle. Oracle bought Sun, and now owns Java.<br /><br />Many of my old articles point toward the previous Sun website. I'll be changing those to point to current locations for the same resources, mostly to be found on <a href="">java.net</a>.<br /><br />If you come across something I appear to have missed, feel free to email me with the article title so that I can fix it. Thanks!<br /><br /><b style="color:#ff7700;">One More Thing</b><br /><br />It's worth noting that since some of these articles were written, the official online resources have improved. I still think there are some major gotchas for new learners in Java, but things are definitely better than when I started this blog.<img src="" height="1" width="1" alt=""/>saundby's File Names and Class NamesJava is picky about the file names you use.<br /><br />Each source file can contain one public class. The source file's name has to be the name of that class. By convention, the source file uses a <b><tt>.java</tt></b> filename extension (a tail end of a file name that marks the file as being of a particular type of file.)<br /><br />So, for a class declared as such:<br /><pre style="color:#ff0000;"><br />public class HelloWorld{<br />...</pre><br />The file it is stored in should be named <b><tt>HelloWorld.java</tt></b>.<br /><br /.<br /><br />When you compile your file with javac, you pass the full file name to javac:<br /><br /><pre style="color:#00ff00;">javac HelloWorld.java</pre><br />Let's say we save the file under a different name. We write the following program:<br /><br /><pre style="color:#00ffff;">public class HelloThere{<br /> public static void main(String arg[]){<br /> System.out.println("Hello There.");<br /> }<br />}</pre><br />Then we save it as HelloWorld.java, and try to compile it:<br /><pre style="color:#ff0000; font-size: 9pt;"><br />>javac HelloWorld.java<br />FileName.java:1: class HelloThere is public, should be declared <br />in a file named HelloThere.java<br />public class HelloThere{<br /> ^<br />1 error</pre><br /><br />Java lets us know that it won't compile until we rename the file appropriately (according to its rules.)<br /><br />So let's rename the file. Let's call it <b><tt>HelloThere.javasource</tt></b>. Seems a bit more explicit than just <b><tt>.java</b></tt>, right? Let's run the compiler:<br /><br /><pre style="color:#ff0000; font-size: 9pt;"><br />>javac HelloThere.javasource <br />error: Class names, 'HelloThere.javasource', are only accepted <br />if annotation processing is explicitly requested<br />1 error</pre><br />Java's still not happy with us. Annotation processing? That's when we include extra information in the program about the program itself. We're not bothering with that just now. So we should just name the file <b><tt>HelloThere.java</tt></b>, and not get fancy with our file names.<br /><br />But, under the right circumstances, javac <i>does</i> allow file name extensions other than <b><tt>.java</b></tt>. That's why we always type in the full file name, including <b><tt>.java</b></tt>, when we use javac. We say 'javac HelloThere.java', not just 'javac HelloThere'. Javac can't assume that we mean a <b><tt>.java</b></tt> file, though that's what it will usually be.<br /><br /><b style="color:#ffff00;">The Class File</b><br /><br />Once we make javac happy with a proper file name, and a program with no errors, javac produces a new file. This file will have the original file name, but with <b><tt>.java</b></tt> replaced with <b><tt>.class</b></tt>. This is your <i>bytecode</i> file, the file that the Java Virtual Machine can run.<br /><br />When we run the program with Java, we're running the .class file. In the case of HelloThere, we're running the <b><tt>HelloThere.class</b></tt> file. But we don't type in the full file name. Why?<br /><br />Unlike javac, java <i>requires</i> a .class file. That's all it will work with. There's no opportunity to have a different extension to the file name. So it <i>assumes</i> the .class part of the file name. But that's not the whole story.<br /><br />If you add .class yourself, here's what you'll get:<br /><pre style="color:#ff0000; font-size: 9pt;"><br />>java HelloThere.class<br />Exception in thread "main" java.lang.NoClassDefFoundError: <br /> HelloThere/class<br />Caused by: java.lang.ClassNotFoundException: HelloThere:307)<br /> at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)<br /> at java.lang.ClassLoader.loadClass(ClassLoader.java:248)<br /></pre><br />Pretty ugly. What we're actually doing when we type "<tt>java HelloThere</tt>" is telling Java to run the <i>class</i> <tt>HelloThere</tt>. Java assumes that it will find this in a file called "<tt>HelloThere.class</tt>", so that's what it's looking for first. <br /><br />We're <i>not</i> telling Java to run the <i>file</i> <tt>HelloThere.class</tt>, we're telling it to run the <i>class</i> HelloThere, which it expects to find in the file <tt>HelloThere.class</tt>.<br /><br />But what if we ask for another class that doesn't have its own .class file?<br /><br />Just for fun, let's change HelloThere.java like this, and see what happens:<br /><pre style="color:#00ffff;">public class HelloThere{<br /> public static void main(String[] arg){<br /> System.out.println("Hello.");<br /> }<br />}<br /><br /><span style="color:#ffff00;">class HelloZoik{<br /> public static void main(String[] arg){<br /> System.out.println("Zoiks!");<br /> }<br />}</span></pre><br />After we edit it, we compile with '<tt>javac HelloThere.java</tt>' and hold our breath.<br /><br />Hurray! No errors!<br /><br />Now we have a second class, HelloZoik, in the <tt>HelloThere.class</tt> file. Can Java find it?<br /><br />Let's try:<br /><pre style="color:#00ff00;"> java HelloZoik<br />Zoiks!</pre><br />It worked! Java found our class inside <tt>HelloThere.class</tt>.<br /><br />This shows it's not the file name that we're calling with the 'java' command, it's the class name.<br /><br />If Java doesn't find the class inside a file with the same name as the class followed by .class, it'll look in the other .class files available.<img src="" height="1" width="1" alt=""/>saundby I Still Learn Java?With all the controversy surrounding Java thanks to the purchase of Sun by Oracle, the lawsuits flying back and forth over the Java Community Process, the Apache Foundation, Android, and all the rest, <i style="color:#00FF77;">does it still make sense to learn Java?</i><br /><br />After all, the demise and abandonment of Java is being predicted practically every day.<br /><br />I say <b>Yes</b>, now is the time to learn Java. No matter what your programming skill or background, Java is a valuable language to learn, it will be used and useful for a <i>long</i> time to come.<br /><br /><b style="color:#ff7700;">Never a Dull Moment</b><br /><br />The Java language has been a-swirl in controversy since its public announcement. It has not become "the" language in many of the areas it originally claimed to be "the" language to use, but yet it <i>has</i> become popular in many other areas. In fact, Java is neck and neck with the language C for being the most popular computer language:<br /><br /><a href="">TIOBE Software Community Index</a> (of most popular programming languages.)<br /><br /><a href="">langpop.com</a> Programming Language Popularity Rankings.<br /><br /><a href="">Devtopics.com</a> Most Popular Programming Languages.<br /><br /><b style="color:#ff7700;">Why Popularity Matters</b><br /><br /.<br /><br />When I was first learning to program, the big languages were assembly (the "<i>real</i>".<br /><br />But COBOL was re-invented in the late 80's. And there were a lot of big-money installations running on it. ADA failed to displace it. It's still here, and it's still a valuable part of a programmer's resume for many jobs.<br /><br /.<br /><br /.<br /><br /.<br /><br />The key to a programming language's longevity is popularity. Once a language becomes sufficiently popular, for all practical purposes it will never die.<br /><br />Java is that popular.<br /><br /><b style="color:#ff7700;">The Many Javas</b><br /><br />Java has become deeply ingrained into the modern computer infrastructure. Not only does the <a href="">Java Virtual Machine</a> support a lot more languages than Java itself, but Java has spawned other languages so close to itself that if you know Java you can pick up the other languages without significant effort. C# is the most popular of these spin off languages.<br /><br /.<br /><br /.<br /><br /><br /><b style="color:#ff7700;">The Most Important Reason</b><br /><br />The most important reason to ignore all the hullabaloo about Java's impending demise and not worry about learning it is that:<br /><ul><br /><li>it is a good language that's fairly easy to learn,</li><br /><li>expressive enough to do a lot of different things effectively, </li><br /><li>easy to develop sophisticated modern programs in</li><br /><li>without too much work for an individual or small group of developers,</li><br /><li>gives access to all the important parts of the machine (graphics, sound, filesystem, peripherals)</li><br /><li>and what you learn travels well to other languages when you go on to learn them.</li><br /></ul><br /><br /.<br /><br />If you learn Java now, you may still be using it 20 years from now. Or 30.<br /><br />When I sat down to a card punch to write my first program 38 years ago as I write this, the computer lab know-it-all came to look over my shoulder.<br /><br />"FORTRAN!" he said. "Why are you wasting your time with <i>that</i> language? It's a dead, old language. Did you know it's the <i>oldest</i> computer language? If you really want to be a programmer, you should start right out in BAL*! That's what real programmers use, and you're going to be behind if you waste your time on anything else."<br /><br /.)<br /><br />And learning FORTRAN never kept me from learning structured languages, AI languages, Object Oriented languages, and so on. Even though my first program included the "dreaded" GO TO statement.<br /><br />There's never been a better time to learn to program. And there's never been a better time to learn Java (the language is in the best shape it's ever been!)<br /><br />*Basic Assembly Language, a version of assembly language for IBM computers.<img src="" height="1" width="1" alt=""/>saundby Keyboard Input In Java: KeyListenersIn a console application, you can get keyboard input using the <a href="">Scanner</a> class, as described in <a href="">Keyboard Input for Console Apps</a>. In an graphical app, though, you can use one of the classes built to accept text input (e.g. <a href="">TextArea</a> or <a href="">JTextField</a>) or add code to your application to respond directly to the keyboard.<br /><br /><img src="" width="480" height="320" style="display: block; margin-left: auto; margin-right: auto; " alt="Keyboard input in the Java GUI made simple." /><h5 align="center">Playing with Today's Program</h5><br />There are two basic ways of doing this. One is to set up <a href="">Key Bindings</a>, which maps keystrokes to actions in your application similar to accelerator keys or menu keyboard equivalents. The other is to use a <a href="">Key Listener</a>, similar to the <a href="">Mouse Listener</a>, which I detailed in <a href="">Simple Mouse Interaction</a>.<br /><br />In this example we're going to use Key Listeners. There is less overhead to setting up a KeyListener when you just need to use a few keys. Key Bindings require more overhead to set up, but when you want to bind actions to a lot of different keystrokes, and manage the actions bound to particular keystrokes at a higher level, Key Bindings are better to use than a simple KeyListener.<br /><br />As its name implies, a KeyListener is an <a href="">Event Listener</a>. If you're not sure what that is, read my <a href="">article on Listeners</a> or follow the prior link to Oracle/Sun's description.<br /><br />Here's a program that demonstrates simple keyboard interaction. It's based on the <a href="">MousePanel</a> program I presented in <a href="">Simple Mouse Interaction</a>. It acts as a sort of "Etch-a-Sketch". You can <a href="">download the KeyPanel program source</a> from my <a href="">Java code site</a>.<br /><br /><pre style="font-family: sans; color:#ff7700; font-size:90%;">// Import the basic necessary classes.<br />import java.awt.*;<br />import java.awt.event.*;<br />import javax.swing.*;<br /><br />public class KeyPanel extends JPanel implements KeyListener{<br /><br /> public KeyPanel(){<br /> super();<br /> pointX=0;<br /> pointY=0;<br /> oldX=0;<br /> oldY=0;<br /> addKeyListener(this);<br /> }<br /><br /> int pointX, pointY, oldX, oldY;<br /> boolean erase;<br /><br /> public void paintComponent(Graphics g){<br /> // Erase the board if it's been requested.<br /> if (erase) {<br /> g.clearRect(0, 0 , getBounds().width, getBounds().height);<br /> erase = false; // We're done, turn off this flag now.<br /> }<br /><br /> // Draw gray where the pointer was..<br /> g.setColor(Color.GRAY); <br /> g.fillRect(oldX-2, oldY-2, 4, 4);<br /> // Draw "Cursor" at current location in black.<br /> g.setColor(Color.BLACK);<br /> g.fillRect(pointX-2,pointY-2, 4, 4);<br /> }<br /><br /> public void keyPressed(KeyEvent key){<br /><br /> // Copy the last clicked location into the 'old' variables.<br /> oldX=pointX;<br /> oldY=pointY;<br /> // Move the current point depending on which key was pressed.<br /> if (key.getKeyCode() == key.VK_DOWN){<br /> pointY=pointY+5;<br /> if (pointY > getBounds().height){<br /> pointY=getBounds().height;<br /> }<br /> }<br /> if (key.getKeyCode() == key.VK_UP){<br /> pointY=pointY-5;<br /> if (pointY < 0){pointY=0;}<br /> }<br /> if (key.getKeyCode() == key.VK_LEFT){<br /> pointX=pointX-5;<br /> if (pointX < 0){pointX=0;}<br /> }<br /> if (key.getKeyCode() == key.VK_RIGHT){<br /> pointX=pointX+5;<br /> if (pointX > getBounds().width){<br /> pointX=getBounds().width;<br /> }<br /> }<br /><br /> <span style="color:#dddd00;">// Set a flag to erase the screen if Space is pressed.<br /> if (key.getKeyCode() == key.VK_SPACE){<br /> erase = true;<br /> }</span><br /> keyTyped(KeyEvent key){ } <br /> public void keyReleased(KeyEvent key){ }<br /><br /> public static void main(String arg[]){<br /> JFrame frame = new JFrame("Use Arrows to Draw, Space to Erase.");<br /> frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);<br /> frame.setSize(640,480);<br /><br /> KeyPanel panel = new KeyPanel();<br /> frame.setContentPane(panel);<br /> frame.setVisible(true);<br /><br /> <span style="color:#dddd00;">// We *must* do this to see KeyEvents.<br /> panel.setFocusable(true);</span><br /><br /> // Initialize the drawing pointer.<br /> panel.oldX=panel.getBounds().width/2;<br /> panel.oldY=panel.getBounds().height/2;<br /> panel.pointX=panel.oldX;<br /> panel.pointY=panel.oldY;<br /><br /> }<br />}</pre><br />Using this technique with the <a href="">Simple Video Game Kernel</a> would be similar. The VGKernel would extend KeyListener, register itself, and implement the KeyListener methods. But in those methods, rather than performing the operations that result from the keypress, as in this program, you would want to simply set a flag to show that the key has been pressed. Then, in your core game logic you would test to see whether the key has been pressed, and perform the appropriate actions.<br /><br />That way the actions are performed at the appropriate time in your game, and not just whenever the key happens to get pressed. Reacting to a key when it is pressed is appropriate for a turn-based game, but not for a real-time game. In a real-time game the action happens according to the timing of the TimerTask that drives the game, which is why we just note that a key has been pressed, and wait until the TimerTask occurs to actually conduct the action related to that key. This would be similar to what we do with the space key here, which sets a flag to tell paintComponent() to erase the screen.<br /><br />Give this program a try, see if you can extend it to allow the user to select colors to draw with or change the size of the drawing pen.<img src="" height="1" width="1" alt=""/>saundby System Commands in JavaLet's suppose you want to run another program on your system from within Java. Personally, I first decided I wanted to do this for the sake of a prank. You may have more businesslike purposes in mind, yourself.<br /><br />It's not too hard to do this since Java 1.5, which added the <a href="">Process</a> and <a href="">ProcessBuilder</a> classes.<br /><br />Here's an example program that starts up Firefox at a particular website:<br /><pre style="color:#ff7700;">public class OpenSite{<br /> public static void main(String arg[]){<br /> try { Process p = new ProcessBuilder("firefox", <br /> "").start(); }<br /> catch(java.io.IOException io){ }<br /> }<br />}</pre><br />I've compressed the various parts of the action down to one line here:<br /><pre style="color:#ff7700;">Process p = new ProcessBuilder("firefox", "").start();</pre><br />I'm creating an "anonymous" ProcessBuilder object, calling its start() method, which returns a Process, which I name simply "p".<br /><br />The whole thing is wrapped up in a try...catch structure because javac wants to see us deal with any I/O errors that result. In this program, I just ignore them.<br /><br />So you'll want to make sure that you either catch those errors and deal with them, or that they will be unimportant enough that they don't matter.<br /><br />Also note that the Java program's process will last as long as the external program you call. So if you don't shut down this instance of the firefox process, you'll have Java still running.<br /><br />If you want to see something fun you can do with this on Mac, check out my article on <a href="">my other blog</a> about <a href="">adding speech</a> to the <a href="">Simple Video Game Kernel</a>.<img src="" height="1" width="1" alt=""/>saundby Game Controllers with JavaIn the past, I've covered using <a href="">mice</a> as input devices, and covered the general input mechanism of <a href="">Listeners</a>. I've also discussed <a href="">keyboard</a> input for console applications, and I'll soon be covering <a href="">Key Bindings</a> as a way of using the keyboard in GUI applications.<br /><br />But there's no facility in Java itself that deals with game pads easily. To date, it's been necessary to create your own ActionListeners from scratch. But not any more. Thanks to the <a href="">JInput</a> project, there's an easier way to hook up game controllers to your software.<br /><br /.<br /><br />It's multi-platform, Windows, Mac OS X, and Linux. So it doesn't have the limitations of a lot of the other gamepad code implementations that use native code, thus limiting themselves to one platform (usually Windows.)<br /><br />If you want to see an implementation using JInput, check out <a href="">Greenfoot with Gamepads</a>. It's a good, clear example of using JInput in a general fashion.<img src="" height="1" width="1" alt=""/>saundby
http://feeds.feedburner.com/ABeginningProgrammersGuideToJava
CC-MAIN-2020-40
refinedweb
12,722
56.45
Introduction When you start a program on your machine it runs in its own "bubble" which is completely separate from other programs that are active at the same time. This "bubble" is called a process, and comprises everything which is needed to manage this program call. For example, this so-called process environment includes the memory pages the process has in use, the file handles this process has opened, both user and group access rights, and its entire command line call, including given parameters. This information is kept in the process file system of your UNIX/Linux system, which is a virtual file system, and accessible via the /proc directory. The entries are sorted by the process ID, which is unique to each process. Example 1 shows this for an arbitrarily selected process that has the process ID #177. Example 1: Information that is available to a process [email protected]:/proc/177# ls attr cpuset limits net projid_map statm autogroup cwd loginuid ns root status auxv environ map_files numa_maps sched syscall cgroup exe maps oom_adj sessionid task clear_refs fd mem oom_score setgroups timers cmdline fdinfo mountinfo oom_score_adj smaps uid_map comm gid_map mounts pagemap stack wchan coredump_filter io mountstats personality stat Structuring Program Code and Data The more complex a program gets the more often it is handy to divide it into smaller pieces. This does not refer to source code, only, but also to code that is executed on your machine. One solution for this is the usage of subprocesses in combination with parallel execution. Thoughts behind this are: - A single process covers a piece of code that can be run separately - Certain sections of code can be run simultaneusly, and allow parallelization in principle - Using the features of modern processors, and operating systems, for example every core of a processor we have available to reduce the total execution time of a program - To reduce the complexity of your program/code, and outsource pieces of work to specialized agents acting as subprocesses Using subprocesses requires you to rethink the way your program is executed, from linear to parallel. It is similar to changing your work perspective in a company from an ordinary worker to a manager - you will have to keep an eye on who is doing what, how long does a single step take, and what are the dependencies between the intermediate results. This helps you to split your code into smaller chunks that can be executed by an agent specialized only for this task. If not yet done, think about how your dataset is structured as well so that it can be processed effectively by the individual agents. This leads to these questions: - Why do you want to parallelize code? In your specific case and in terms of effort, does it make sense to think about it? - Is your program intended to run just once, or will it run regularly on a similar dataset? - Can you split your algorithm into several execution steps? - Does your data allow parallelization at all? If not yet, in which way does the organisation of your data have to be adapted? - Which intermediate results of your computation depend on each other? - Which change in hardware is needed for that? - Is there a bottle neck in either the hardware, or the algorithm, and how can you avoid, or minimize the influence of these factors? - Which other side effects of parallelization can happen? A possible use case is a main process, and a daemon running in the background (master/slave) waiting to be activated. Also, this can be a main process that starts worker processes running on demand. In practice, the main process is a feeder process that controls two or more agents that are fed portions of the data, and do calculations on the given portion. Keep in mind that parallelization is both costly, and time-consuming due to the overhead of the subprocesses that is needed by your operating system. Compared to running two or more tasks in a linear way, doing this in parallel you may save between 25 and 30 percent of time per subprocess, depending on your use-case. For example, two tasks that consume 5 seconds each need 10 seconds in total if executed in series, and may need about 8 seconds on average on a multi-core machine when parallelized. 3 of those 8 seconds may be lost to overhead, limiting your speed improvements. Running a Function in Parallel with Python Python offers four possible ways to handle that. First, you can execute functions in parallel using the multiprocessing module. Second, an alternative to processes are threads. Technically, these are lightweight processes, and are outside the scope of this article. For further reading you may have a look at the Python threading module. Third, you can call external programs using the system() method of the os module, or methods provided by the subprocess module, and collect the results afterwards. The multiprocessing module covers a nice selection of methods to handle the parallel execution of routines. This includes processes, pools of agents, queues, and pipes. Listing 1 works with a pool of five agents that process a chunk of three values at the same time. The values for the number of agents, and for the chunksize are chosen arbitrarily for demonstration purposes. Adjust these values accordingly to the number of cores in your processor. The method Pool.map() requires three parameters - a function to be called on each element of the dataset, the dataset itself, and the chunksize. In Listing 1 we use a function that is named square and calculates the square of the given integer value. Furthermore, the chunksize can be omitted. If not set explicitly the default chunksize is 1. Please note that the execution order of the agents is not guaranteed, but the result set is in the right order. It contains the square values according to the order of the elements of the original dataset. Listing 1: Running functions in parallel from multiprocessing import Pool def square(x): # calculate the square of the value of x return x*x if __name__ == '__main__': # Define the dataset dataset = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] # Output the dataset print ('Dataset: ' + str(dataset)) # Run this with a pool of 5 agents having a chunksize of 3 until finished agents = 5 chunksize = 3 with Pool(processes=agents) as pool: result = pool.map(square, dataset, chunksize) # Output the result print ('Result: ' + str(result)) Running this code should yield the following output: $ python3 pool_multiprocessing.py Dataset: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] Result: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196] Note: We'll be using Python 3 for these examples. Running Multiple Functions Using a Queue As a data structure, a queue is very common, and exists in several ways. It is organized as either First In First Out (FIFO), or Last In First Out (LIFO)/stack, as well as with and without priorities (priority queue). The data structure is implemented as an array with a fixed number of entries, or as a list holding a variable number of single elements. In Listings 2.1-2.7 we use a FIFO queue. It is implemented as a list which is already provided by the corresponding class from the multiprocessing module. Furthermore, the time module is loaded and used to imitate work load. Listing 2.1: Modules to be used import multiprocessing from time import sleep Next, a worker function is defined (Listing 2.2). This function represents the agent, actually, and requires three arguments. The process name indicates which process it is, and both the tasks and results refer to the corresponding queue. Inside the worker function is an infinite while loop. Both tasks and results are queues that are defined in the main program. tasks.get() returns the current task from the task queue to be processed. A task value smaller than 0 quits the while loop, and returns a value of -1. Any other task value will perform a computation (square), and will return this value. Returning a value to the main program is implemented as results.put(). This adds the computed value at the end of the results queue. Listing 2.2: The worker function # define worker function def calculate(process_name, tasks, results): print('[%s] evaluation routine starts' % process_name) while True: new_value = tasks.get() if new_value < 0: print('[%s] evaluation routine quits' % process_name) # Indicate finished results.put(-1) break else: # Compute result and mimic a long-running task compute = new_value * new_value sleep(0.02*new_value) # Output which process received the value # and the calculation result print('[%s] received value: %i' % (process_name, new_value)) print('[%s] calculated value: %i' % (process_name, compute)) # Add result to the queue results.put(compute) return The next step is the main loop (see Listing 2.3). First, a manager for inter-process communication (IPC) is defined. Next, two queues are added - one that keeps the tasks, and the other one for the results. Listing 2.3: IPC and queues if __name__ == "__main__": # Define IPC manager manager = multiprocessing.Manager() # Define a list (queue) for tasks and computation results tasks = manager.Queue() results = manager.Queue() Having done this setup we define a process pool with four worker processes (agents). We make use of the class multiprocessing.Pool(), and create an instance of it. Next, we define an empty list of processes (see Listing 2.4). Listing 2.4: Defining a process pool # Create process pool with four processes num_processes = 4 pool = multiprocessing.Pool(processes=num_processes) processes = [] As the following step we initiate the four worker processes (agents). For simplicity, they are named "P0" to "P3". Creating the four worker processes is done using multiprocessing.Process(). This connects each of them to the worker function as well as the task and the results queue. Finally, we add the newly initialized process at the end of the list of processes, and start the new process using new_process.start() (see Listing 2.5). Listing 2.5: Prepare the worker processes # Initiate the worker processes for i in range(num_processes): # Set process name process_name = 'P%i' % i # Create the process, and connect it to the worker function new_process = multiprocessing.Process(target=calculate, args=(process_name,tasks,results)) # Add new process to the list of processes processes.append(new_process) # Start the process new_process.start() Our worker processes are waiting for work. We define a list of tasks, which in our case are arbitrarily selected integers. These values are added to the task list using tasks.put(). Each worker process waits for tasks, and picks the next available task from the list of tasks. This is handled by the queue itself (see Listing 2.6). Listing 2.6: Prepare the task queue # Fill task queue task_list = [43, 1, 780, 256, 142, 68, 183, 334, 325, 3] for single_task in task_list: tasks.put(single_task) # Wait while the workers process sleep(5) After a while we would like our agents to finish. Each worker process reacts on a task with the value -1. It interprets this value as a termination signal, and dies thereafter. That's why we put as many -1 in the task queue as we have processes running. Before dying, a process that terminates puts a -1 in the results queue. This is meant to be a confirmation signal to the main loop that the agent is terminating. In the main loop we read from that queue, and count the number of -1. The main loop quits as soon as we have counted as many termination confirmations as we have processes. Otherwise, we output the calculation result from the queue. Listing 2.7: Termination and output of results # Quit the worker processes by sending them -1 for i in range(num_processes): tasks.put(-1) # Read calculation results num_finished_processes = 0 while True: # Read result new_result = results.get() # Have a look at the results if new_result == -1: # Process has finished num_finished_processes += 1 if num_finished_processes == num_processes: break else: # Output result print('Result:' + str(new_result)) Example 2 displays the output of the Python program. Running the program more than once you may notice that the order in which the worker processes start is as unpredictable as the process itself that picks a task from the queue. However, once finished the order of the elements of the results queue matches the order of the elements of the tasks queue. Example 2 $ python3 queue_multiprocessing.py [P0] evaluation routine starts [P1] evaluation routine starts [P2] evaluation routine starts [P3] evaluation routine starts [P1] received value: 1 [P1] calculated value: 1 [P0] received value: 43 [P0] calculated value: 1849 [P0] received value: 68 [P0] calculated value: 4624 [P1] received value: 142 [P1] calculated value: 20164 result: 1 result: 1849 result: 4624 result: 20164 [P3] received value: 256 [P3] calculated value: 65536 result: 65536 [P0] received value: 183 [P0] calculated value: 33489 result: 33489 [P0] received value: 3 [P0] calculated value: 9 result: 9 [P0] evaluation routine quits [P1] received value: 334 [P1] calculated value: 111556 result: 111556 [P1] evaluation routine quits [P3] received value: 325 [P3] calculated value: 105625 result: 105625 [P3] evaluation routine quits [P2] received value: 780 [P2] calculated value: 608400 result: 608400 [P2] evaluation routine quits Note: As mentioned earlier, your output may not exactly match the one shown above since the order of execution is unpredicatble. Using the os.system() Method The system() method is part of the os module, which allows to execute external command line programs in a separate process from your Python program. The system() method is a blocking call, and you have to wait until the call is finished and returns. As a UNIX/Linux fetishist you know that a command can be run in the background, and write the computed result to the output stream that is redirected to a file like this (see Example 3): Example 3: Command with output redirection $ ./program >> outputfile & In a Python program you simply encapsulate this call as shown below: Listing 3: Simple system call using the os module import os os.system("./program >> outputfile &") This system call creates a process that runs in parallel to your current Python program. Fetching the result may become a bit tricky because this call may terminate after the end of your Python program - you never know. Using this method is much more expensive than the previous methods I described. First, the overhead is much bigger (process switch), and second, it writes data to physical memory, such as a disk, which takes longer. Though, this is a better option you have limited memory (like with RAM) and instead you can have massive output data written to a solid-state disk. Using the subprocess module This module is intended to replace os.system() and os.spawn() calls. The idea of subprocess is to simplify spawning processes, communicating with them via pipes and signals, and collecting the output they produce including error messages. Beginning with Python 3.5, the subprocess contains the method subprocess.run() to start an external command, which is a wrapper for the underlying subprocess.Popen() class. As an example we launch the UNIX/Linux command df -h to find out how much disk space is still available on the /home partition of your machine. In a Python program you do this call as shown below (Listing 4). Listing 4: Basic example to run an external command import subprocess ret = subprocess.run(["df", "-h", "/home"]) print(ret) This is the basic call, and very similar to the command df -h /home being executed in a terminal. Note that the parameters are separated as a list instead of a single string. The output will be similar to Example 4. Compared to the official Python documentation for this module, it outputs the result of the call to stdout, in addition to the return value of the call. Example 4 shows the output of our call. The last line of the output shows the successful execution of the command. Calling subprocess.run() returns an instance of the class CompletedProcess which has the two attributes named args (command line arguments), and returncode (return value of the command). Example 4: Running the Python script from Listing 4 $ python3 diskfree.py Filesystem Size Used Avail Capacity iused ifree %iused Mounted on /dev/sda3 233Gi 203Gi 30Gi 88% 53160407 7818407 87% /home CompletedProcess(args=['df', '-h', '/home'], returncode=0) To suppress the output to stdout, and catch both the output, and the return value for further evaluation, the call of subprocess.run() has to be slightly modified. Without further modification, subprocess.run() sends the output of the executed command to stdout which is the output channel of the underlying Python process. To grab the output, we have to change this, and to set the output channel to the pre-defined value subprocess.PIPE. Listing 5 shows how to do that. Listing 5: Grabbing the output in a pipe import subprocess # Call the command output = subprocess.run(["df", "-h", "/home"], stdout=subprocess.PIPE) # Read the return code and the output data print ("Return code: %i" % output.returncode) print ("Output data: %s" % output.stdout) As explained before subprocess.run() returns an instance of the class CompletedProcess. In Listing 5, this instance is a variable simply named output. The return code of the command is kept in the attribute output.returncode, and the output printed to stdout can be found in the attribute output.stdout. Keep in mind this does not cover handling error messages because we did not change the output channel for that. Conclusion Parallel processing is a great opportunity to use the power of contemporary hardware. Python gives you access to these methods at a very sophisticated level. As you have seen before both the multiprocessing and the subprocess module let's you dive into that topic easily. Acknowledgements The author would like to thank Gerold Rupprecht for his support, and critics while preparing this article.
https://stackabuse.com/parallel-processing-in-python/
CC-MAIN-2019-43
refinedweb
2,993
53.31
Feedback Getting Started Discussions Site operation discussions Recent Posts (new topic) Departments Courses Research Papers Design Docs Quotations Genealogical Diagrams Archives I do not mean to start a completely subjective navel-gazing thread. I mean to learn, "if I loved Scheme when I learned it (and I really did, back in college in 1989), what else could I look into in these modern times?" (apropos the other current Scheme thread.) If you have thoughts, please mention something like: The language name, the language web site, the bullet point reasons you think it is at all related to where Scheme comes from spiritually, the bullet point reasons you think it is "better" than Scheme, the bullet point cons (if any ha ha!) in the language. (Or tell me this is a very bad idea for a thread, and delete it...) Wishing to simultaneously learn and yet avoid any rat-holing flame-wars. :-) I spent a lot of time looking for a scheme like language that has the power of scheme and suits me better. I didn't find one, which is why I'm on Lambda the Ultimate and working on my own language. Our own John Shutt has an elegant language with more power than scheme, but I have my doubts that there will be an efficient implementation of it, and I'm not a fan of typing in s-expressions either. to write an efficient Kernel compiler when I'm done the interpreters and compilers I'm currently working on. I almost know how to do it. I have two insights and one open question: 1)Kernel allows you to do horribly confusing things, changing the interpretation of a symbol in the middle of use - no one will do that. 2) Environments can be described by hash values. If you make a large enough hash, then you can leave out actually checking the environment and just trust the hash - in some astronomically unlikely case you'll crash the machine, so what? 3) the hard part is to get the mapping of variables figured out as early as possible, to simulate having a compile process, even a jit one is earlier than is simple for Kernel. no one will do that. As I was just remarking over on the other thread (yonder), the Kernel philosophy calls for empowering programmers by providing generality that will work when used in ways that are allowed but not anticipated. The Kernel design is meant to allow stability of bindings to be proven in particular cases. The unanswered question being whether that facet of the design can be made to work as intended. because breaking that mapping between symbol and where it comes from on the fly is confusing and too inefficient. So optimizing as if no one will ever do that will be a win. I'm not saying leave out the super slow fallback if people do something weird. But they'll pay the price. And the question isn't "will the language be used as intended" the question is "if it's not optimized, will the language EVER be used" You didn't say the question is whether the feature will be USED as intended but whether it can be optimized as intended. Is there a formalism you could use that will prevent people from making unstable mappings. My own plan is to do fexprs where the mapping is immutable. You set the mapping once, then you can't change it. I've always disliked immutable variables, but this is immutable mappings in an environment. I've found my first case where I love immutability! Even just being immutable is deciding as late as possible, I originally was planning on making them so "you decide before hand" in some sense. But that would break the spirit of Kernel. REALLY late as possible would be: 1) every time a symbol comes up it gets a mapping 2) it is an error for the same instance of the same atom to get a different mapping next time it's evaluated, but it's legal for the same name/atom in the same s-expression to get a different mapping as long as it's stable 3) question, does saving a continuation before the mappings are instanciated mean that they can be reinstanciated differently from that continuation? 4) all this is BAD in that it's confusing. A symbol should mean the same thing every time it's used in an expression or block of code. It should be stable across space as well as time. AND if recursion is used for looping, then the mappings will never be stable in the loop. I REALLY like the idea that you have a different formalism. Something equivalent to letting the fexpr insert a lambda that names the variables for their mapping. How do you distinguish between bindings that are to be immutable and ones that are to be mutable? Perhaps things would be clearer with a somewhat more concrete example. Consider the standard binding of list. That's a binding in the ground environment. It is, in fact, a stable binding, because it's in the ground environment. When you mutate an environment (for example, via $define! or $set!, which are equi-powerful), you are altering its local bindings, with no effect on any ancestors of that environment. The ground environment is the parent of global environments; so even if you do change the binding of list in a global environment, the binding in the ground environment is untouched. And there is no way for a user program to acquire the ground environment itself as a first-class object, so there is no way for a user program to mutate the ground environment itself. Thus, no matter what you do to any global environment, the binding of list in the ground environment is stable, effectively immutable. Now, suppose you're using a Kernel interpreter — a read-eval-print loop that evaluates expressions in a global environment — and you $define! an applicative f whose body looks up list. What binding does it access? Well, if you created f with a call to $lambda at the top level of the REPL, its static environment is the global environment of the REPL, and that global environment could always be altered later by an other expression entered into the REPL; so f's statically visible bindings are not stable, even though the bindings of the static environment's parent, the ground environment, are stable. But suppose, instead, that you put the $lambda inside a call to $let-safe, like this: list $define! $set! f $lambda $let-safe >>> ($define! f ($let-safe () ($lambda ...))) This creates a fresh global environment (a child of the ground environment, with no local bindings), and this clean global environment becomes the static environment of f. Since this clean global environment is not accessible from anywhere else, it provably will not be mutated, and f inherits a provably stable set of ground-environment bindings from its static environment. If f provably does not alter its own local binding of list, then provably a local lookup of list will find the standard applicative list as bound in the ground environment. Is there anything more that could be done in the language design to further encourage binding stability? It seems to me the weakest point in all of this is that if f were to call another user-defined combiner q, and q unexpectedly mutates its dynamic environment, that would destabilize the local environment of f; so either we also have to prove that q is suitably well-behaved, or we have to be careful how the call is done. For example, if the call were written as (apply q ...), it wouldn't matter whether q mutates its dynamic environment because its dynamic environment would be a throw-away empty environment, protecting the local environment of f. At this point I'm not quite sure what to do, because as-is the language design isn't entirely living up to my slogan "dangerous things should be difficult to do by accident" — it's too easy to make a mistake here that destabilizes f's local environment — but we really want a solution that is non-restrictive and further enhances the simplicity as well as generality of the language. I've mused on whether some sort of "guarded environments" feature, dual to the existing guarded continuations feature, might provide a way out, but it would need to be marvellously simply to use, and I'm just not seeing it yet. q (apply q ...) Maybe we should have a Kernel thread. I've installed a Kernel in a linux vm to play with... But my thoughts were more about pathological functions like this. Say a fexpr gets code to run that has a free variable 'a'. Instead of adding a to an environment, it creates 5 environments, gives 'a' a different identity and value in each and then, while it's executing the code, switches between the environments at random. Or maybe it works with other pathological functions to create differently shaped environments with different tree structures and 'a' instanciated in different parts of the tree in each environment so that even the topology of the lookups are different. Then in some nested routine it switches between these environments at random. By the way the point of hashing environments is to save on creating stack topologies and code for them even in the case of pathological functions and to make it possible to have something like stacks instead of hashes to look up variables in, despite Kernal's crazy flexibility. I was talking about whether different environments could be applied to the same symbol. It's the mapping "symbol"-"environment to look it up in" that I want to be immutable. I'm thinking you mean, a particular instance of a symbol always maps to the same environment, rather than, all instances of a particular symbol always map to the same environment. It seems "a particular instance of a symbol always maps to the same environment" is another way of saying "strictly lexical scope". Lexical scope is not always wanted; sometimes it's essential to a combiner's purpose that it access its dynamic environment. Off hand, a couple of classes of such combiners come to mind. Modularity-engaging devices, such as $let-like operatives, $provide!, $import!. And control structures orthogonal to modularity, such as $cond. $let $provide! $import! $cond " all instances of a particular symbol always map to the same environment." All instances in the same block of code should always map to the same environment. And the way Kernel works, in a loop you keep asking the environment over and over on the same block of code, so you need consistency over time, even though the mechanism, running user code, doesn't insure that. An interesting thought. How do you define "block of code", for this purpose? Also, what if you have a combiner whose behavior is meant to depend on how some particular symbol is bound in the dynamic environment from which it's called? So this is just off the cuff but obvious. "How do you define "block of code", for this purpose?" All passed to the same fexpr. It's the same block of code if it intuitively LOOKS like the same block of code to a human being. In fact this seems quite reasonable, as far as it goes; the practical purpose is to not surprise a human being who looks at the code, therefore the sense of "same block of code" that actually matters for the practical purpose is the sense that bears on the expectations of that human being looking at the code. Practical, but without the sort of precision entailed by an implementation; so it does leave the question of implementation hanging. 1) if it's surrounded by let or lambda, it's the same block of code 2) if it's surrounded by a combiner that the user has been told is equivalent to a let or lambda, then it's the same block of code. The point was that since the interpreter of Kernel runs everything through a hook to user code to map the environment, there is no guarantee that any such stability will result. That is unless I misunderstood the way Kernel works, and that's possible since I haven't used it yet. And the big problem with unprovable stability is that you can't map to machine code that's within an order of magnitude of being efficient. since the interpreter of Kernel runs everything through a hook to user code to map the environment, there is no guarantee that any such stability will result. It's possible that you're understanding how it works in theory but... perhaps... underestimating its potential for stability in practice. Hm, let's see. You write a great big Kernel expression, perhaps ($provide! ...), and tell the Kernel compiler it's a program. In theory, the behavior of Kernel, or for that matter of any other Lisp, is defined by how the expression would be evaluated at runtime by an interpreter. That is, any compilation at all must be done in such a way that the behavior will be the same as (though hopefully much faster than) what a pure interpreter would do with the expression. In a Lisp with special forms rather than fexprs, there's a great deal a compiler can deduce about the interpretation of the expression. In Kernel, in the general case, all you can say for sure is that the interpreter would identify the expression as a combination, lookup the operator $provide! in the environment, and either generate an error if the result of the lookup isn't a combiner, or do whatever the combiner says to do with the (unevaluated!) cdr of the expression. But that's unrealistically general. For one thing, you actually know something about the initial environment in which $provide! is looked up, so the compiler can do that lookup ahead of time; and it'll never be looked up again, so that's that. And since you know what combiner the lookup is going to produce, you can use the definition of that combiner to do at least the first bit of the processing of the cdr of the expression. And so on, and so on. There's likely to be lots of steps, small and large, in the interpretation that you can deduce at compile-time. Not, perhaps, as much as you would have been able to deduce in the special-forms-instead-of-fexprs Lisp, and the worst case will start to look very like just running an interpreter without any compilation at all, but it seems a bit of an exaggeration to say of this that Kernel would have to resort to pure interpretation for "everything". The big unknown here is, how much of an exaggeration. ($provide! ...) "Also, what if you have a combiner whose behavior is meant to depend on how some particular symbol is bound in the dynamic environment from which it's called?" You mean it uses the outer environment? That's still stable. That's not pathological. If I write ($define! f ($let-safe () ($define! $lookup ($vau (s e) d (eval s (eval e d)))) (wrap ($vau () e ($lookup quux e))))) are all of these symbol-to-environment mappings stable? I don't know much about Kernel, but I vaguely understand first-class environments. It sounds to me that something like this could make sense: - What if you could not manipulate a currently active environment (so they are always immutable), but you could build a new environment inheriting from the current one and call functions with it (maybe this is how it already works). We would define a currently active environment as anything in the environment stack. When you call a function with an environment would get pushed onto the environment stack and become immutable. In this case whenever a function is called we know that all function calls are stable with regards to the current environment, and can JIT compile the function before calling it, memoising the current environment. As once we call a function with an environment it becomes immutable calling the same function with the same environment should always use the same function bindings. The JIT compiler would build a table of function IDs and environment IDs to determine if functions have already been compiled. However we are always free to make a copy of any environment and mutate it before calling a function with it as the environment, or as an argument. We prevent bindings changing for any function above us in the call-stack, which seems a sensible property. Write a gnu emacs replacement for the modern era in scheme, starting from an interpreter at about the complexity level of SIOD, but not necessarily the same techniques. Study SCM's implementation a little bit. Don't worry about benchmarks except for very specific things like display update. Postpone writing a generalized compiler as long as possible. Review everything you can find about Genera, Concordia, and the Symbolics documentation viewer. In the back of your mind imagine a future with some compilation, with a compositor attached as a back end to not rely on any existing widnow system. Build a scheme "lisp machine" environment, in short, but keeping it simple enough for a small team to pull it off by emphasizing simplicity rather than squeezing out every last cycle of performance. It's not easy but we have plenty of good evidence it can be done by a small team with little more knowledge than what people already knew 3 or 4 decades ago. I think a good design principle would be unlimited dynamism - the sort of thing that's absolutely impossible to write a compiler for in general - plus facilities for specifically enabling that dynamism if and only if you're going to use it. The enabling language becomes a warning for other programmers that such-and-such may actually happen, like redefining cons or whatever. Likewise specific facilities for disabling dynamic facilities that are on by default. The disabling language becomes a promise to other programmers, as well as a request/command to the system to signal errors if you fail to abide by the constraints, and finally a means of giving the compiler information it needs to create efficient code. ("well, we would have produced an error before this if the value had been anything other than an integer, so integer-specific code cannot possibly cause an error here...") It also becomes a means for controlling semantically-troublesome imports. For example saying that you're importing only variable-pure functions from such-and-such module should automagically prevent you from calling something that changes a variable scoped outside itself, and saying that you're importing only side-effect pure functions from such-and-such module will automagically prevent you from calling something that may throw an exception, open or close a file, do I/O, make non-GC memory allocations or frees, etc. All these optional limiting/enabling declarations should document what the code without them would be doing (or not doing) anyway, not changing the meaning of anything otherwise valid. It should be possible to strip them out and get code that as the same semantics as when they are present. (define cons (foo ...)), or importing anything that does it, may throw a compile-time error if you don't have #I_AM_AN_IDIOT declared, but if redefining primitives is enabled at all, then the semantics of 'define' should be exactly the same as for other variables. Likewise with limitations on dynamism such as type declarations. When you declare that an array will only ever be used to hold integers you're allowing the system to produce optimized code for that array, and requesting that the truth of your declaration get proved at compile time if possible. Or that you should get a warning at compile time and an error at runtime if the constraint is violated, otherwise. But you should still be using the same syntax for array references, etc, and they should still have the same semantics even if, under the hood, they're mapping to versions of the routines that would only work on integers. As far as I am concerned R5RS Scheme is perfectly fine. What the Scheme ecosystem really needs is some boring but better engineering. Something like: Any successor to Scheme would have a similar need. I enjoy writing code in Go (it feels like C with closures and concurrency) but so often I think if only such engineering was poured in a Scheme ecosystem.... We don't have a cross-implementation package system yet, though we have a plan for one. Most substantial Schemes have their own package systems. Gambit and Chicken are decently fast compilers that produce decently fast C. Most of the slowness in compilation is due to the gcc or clang back end. AFAIK nobody has tried to make them work with a Plan-9-style compiler, but it shouldn't be that hard. As for libraries, I'm working as hard as I can on them, but it's hard to overcome the curse of Lisp. I'll grant that List is easy to write software in. But it's also, despite denials, damn hard to read other people's code in Lisp because s-expressions are a bad idea for human comprehension - they're better for machine processing but how often do you need that? So Lisp hackers probably aren't good at working together because they can't read each other's code easily! Thus the scripting languages are more productive. Got any research to back that up, sonny-jim? that you called Perl "write only code" and can't see that for most people scheme is the same. Do you have "research" to back up what you said about Perl? (i do feel like my original hope as sketched in the op has sorta been lost, which is not too surprising, so i am a little wary of contributing to this thread, BUT in defense i do think syntax will always be a valid question wrt usability of programming languages.) I for one have gone full circleish. I do not like how macros are done in non-sexpr languages. It becomes too ugly and verbose and unattractive. Thus I would at least want sexprs and macros in that ilk to be the base, always available, and then the mexprs on top of that to be gravy for those who want to work that way. But things must round trip. This thread right here is sort of a larger version of the epic movie from the 50s called Tabs vs. Spaces when in fact all our code should be going through transformation steps so that we always see code how *we* want to see it, each and every one of us, and gordian-knot the whole argument. I personally do want static type checking, inference, annotations, etc. along with the sexprs. But this can become a rat hole subject for sure. I would like to suggest people rather talk about higher level things that are related like: "Thus I would at least want sexprs and macros in that ilk to be the base, always available, and then the mexprs on top of that to be gravy for those who want to work that way. But things must round trip" agreed. Round trip! I'm working on that in a language by the way, or planning on it. Static type checking: I'm happy to see a few languages that don't have that, since obsessions over typing is everywhere. I like seeing a few untyped languages. I want a powerful macro system, and I want the current system killed dead dead dead. I guess you have to take out the macro system before you can replace it. Immutability: If you don't want to change a field, then don't change it! I don't need it enforced. What I was trying to say is that IMHO the best successor to Scheme is Scheme + better engineering! Conversely, any new language will have the same issues. Still, in response to some of your questions: (const value) (copy value) (export name ...) export Now putting on an engineer's hat I'd like to see the following (not sure if these require any language level support): (parallel-apply closure args...) We should have a flexible encoding scheme and constructs that interact with their environment through well-defined interfaces. The meaning of an encoded program as a construct should be completely static (and thus, as bad as macros are, F-exprs look worse). Once you've gotten away from macros, there's not much reason to use S-expressions. I almost resisted posting this, because it's high on opinion and low on evidence, but oh well. This is great, the kind of stuff I think shows LtU in the best light. Looking at the paradigms and seeing if they really work, or if there's something even better. So even though I have no idea what you mean, I for one am glad you wrote it down here. Heck, can you start a new thread with concrete examples of what you mean? If you can walk us through things in a fake evolutionary style from pre-macro languages to macro languages to all the different kinds of macros (hygenic or not, sexpr or mexpr) to generalized multistage languages and then off to what you are talking about in response, that would be very interesting to read. Dijkstra or Knuth, where programs are totally static so that they can be analyzed. It's the view of a computer scientist, not an engineer who wants flexible tools. Knuth could do both. He could analyze software/hardware and write reports on the spacetime complexity of taking the square root of a number, as well as write a specialized macro programming language called TeX. Now we have category theorists which can do neither, for which I blame Dijkstra. I'm still hoping that LtU could somehow become an interesting place again. My current stance is to ask people for interesting content to post, advising that they do *not* try to read the comment sections. I personally have nothing against circles and circles of discussions on s-exprs for readability and whether macros are a good idea. I would be grateful if you could avoid gratuitously attacking people (here: category theorists) during the discussion, though. Being improductive is fine, being insulting is not. We already had this discussion. Nobody was insulted and you don't get to determine other people's opinions. I think there's value in making tools that have clean semantics. It leads to additional flexibility, not less. It also tends to align with tools that are amenable to static analysis, but I think you'd be surprised at how little I'm interested in static analysis myself. As an example, I've heard you complain about immutability. Haskell is a pain (I doubt you'll disagree), but it has the right general idea - model mutability. Once you get the semantics right, you can express things concisely that are verbose and annoying in current languages. That sounds like an invitation to violate site policies with a top level post with nothing more than my opinions on macro systems. :) I'll try to respond with a better explanation this weekend. Well, I was thinking about giving more details about a specific alternative, but I don't think I'm ready to do that. Composing language fragments is delicate. I think I'll just elaborate a little on my comment above, complaining about macros and hinting at an alternative. Hopefully this helps ... The basic principle that macros violate is this: every construct should be assigned a single semantic value as a construct at the appropriate level of abstraction. Syntactic encoding is not the right level of abstraction, but that's the level at which macros work. A macro might instantiate a syntactic block in several contexts, resulting in several semantic interpretations of the same syntax. This is analogous to #include polymorphism, which is terrible. This complaint applies to both hygienic and non-hygienic macros. But there are additional well known problems with whichever of those you pick. If you pick hygienic macros, you're limited in power because you can't interact with constructs that provide or consume an environment. Non-hygienic macros are just terrible, able to arbitrarily inspect encoding details of parameters. What we want is to be able to write something like this (in pseudocode): syntax while condition:Expr body:Block where ... semantics definition ... When the language encounters a while statement, it notices that the context for the first parameter is an expression, and uses the following encoding to build an expression construct, and similarly the next section of encoding is built into a Block. The semantics of this while construct then interacts with its sub-construct parameters through well-defined interfaces for Expr or Block. If this was a for-construct instead of while, the construct might explicitly accept a Symbol as its first parameter and feed that to the Block as an available binding. In other words, we need to split macros up into providing an environment in which their child encodings can be interpreted as constructs, and then an explicit interaction between those constructs. Because the latter interaction will deal only with constructs and not their encodings, S-expressions will lose most of their advantages. As suggested by the psuedo-code, all of this should be statically typed. Once you get to each piece of user entered syntax as belonging to a single construct, you can make an construct aware IDE. This leads to a powerful way to extend an IDE and I think would even make a nice OS interface. The hard part of this is designing good interfaces that can be extended in useful ways, but that seems unavoidable. General language features don't naturally compose. Picking construct protocols that are well-factored requires work. I want everything to start off from the perspective of the abstract semantic graph, I sometimes think. (Whither bloody Intentional Computing, anyway?) Have you seen anything that is along the lines of what you are writing here? What is the closest, if anything? Would you think you could take existing languages and "fix" them with this, or would you want it from whole cloth? Starting from the ASG doesn't solve the problem if macros are allowed to inspect that ASG. The idea here is to use interfaces (more or less OO stlye) between a syntax constructor and its children. It's very similar in some ways to the meta-object protocol used in CLOS (I have the book, but I haven't been though all of it). That system was obviously based on a macro system, though. I'm not a Lisp expert, but I think they could have built what I'm talking about instead. My knowledge of other languages also isn't as broad as some of the others around here, so maybe someone else has seen something along these lines. I'm planning this for my own language. You could probably do this in many languages, but I have a handful of things that I'm "fixing", so I'm starting from whole cloth. This sounds a lot like type traits and function traits in C++? You also solve the unevaluated argument problem with function objects, which actually allow better optimisation because C++ can inline them (as compared to function pointers). You mean the template idiom? You could maybe emulate what I'm talking about by building all syntax out of templates. I'm not sure. It sounds horrible. Function objects allow code to be passed into functions by separating creation from execution. Consider: class myfn { int x, y; myfn(int x, int y) : x(x), y(y) {} int operator()(int z) { return x * z + y; } } So this can be constructed on the stack and passed to other code, so it serves as "quoted" code. template <typename F> int test(F f, int b) { return f(b); } auto a = myfn(3, 4); auto c = test(myfn, 5); Of course this still has only lazy checking that the passed type 'F' is suitable. However function-traits allow checking the function is of the correct type. template<typename F, typename std::enable_if< F::arity == 1 && is_same<F::argument<0>::type, int> && is_same<F::return_type, int> >::type* = nullptr> int test(F f, int b) { return f(b); } The template stuff looks fairly bad, but is essentially just providing constraints on the type of function that is expected. The interesting part is that imperative languages there is a difference between the function (value) and the result if the function. 'f' means something different from 'f()'. In functional languages you can achieve the same by having a function that takes a single void argument, or that can be partially applied like this: f x y () z = z * x + y test g b = g () b test (f 3 4) 5 The void argument is only really necessary if there are no further arguments to apply. However you still need a primitive that only evaluates code blocks conditionally like an 'if' statement, and it depends on the semantics of partial application in such a way that optimisation might cause problems. In conclusion the imperative languages differentiation between a function name and executing the function seems to be the right way to do this that plays nicely with compilers and optimisation, rather than the functional way of making a function name and it's value indistinguishable unless you use special argument types (fexpr). To me it seems better to always see when a function is executed, rather than have it depending on the definition of the arguments in other functions. In both cases it is clear we want to distinguish function names (unexecuted functions) from their results. Quoted code is just an anonymous function "name". I'd rather handle inlining through representation selection, leaving the semantics with an ordinary function parameter. This is more about extensible syntax. I think evaluation semantics is can of worms. I'm trying to avoid tying operational semantics to value semantics. Optional named function arguments seems a good way to do that, so you can have optional additional arguments identified by names. For example "if a {then b {else c}}" would have allow "if (a > b) then a" etc... You just need a short hand way to declare function objects. Rust uses ||, so you could write something like "if (a > b) then (|| print 'a') else (|| print 'b')" and it would only print the chosen branch. I would be happy with 'if' behaving like a other functions. In case it was not clear above, I prefer the imperative approach of having explicit evaluation of functions, to the fexpr approach of having referential transparency, but functions that sometimes take unevaluated arguments. if (x > 1) then print "x > 1" So your language will print "x > 1" when x = 0? I predict that this will be unpopular. I'm a little lost on context. What are you saying optional function arguments are a good way to do? For functions with side-effects , I'm very explicit about when evaluation occurs (think Monads). For functions or values without side-effects, I have no concept of evaluation. Actually I think you wouldn't allow the example you gave, as functions would only accept expressions as arguments, and to pass a statement block you would have to wrap in a lambda anyway. Your example reminded me of smalltalk exp ifTrue: [ print 'this is a lambda without arguments'. ] ifFalse: [ print 'this is another one'. ] Which is syntactic sugar (but the grammar not a macro) for something (schemelike) (send exp ifTrue:ifFalse (lambda() (print ...)) (lambda() (print...))) I like that explicitness. Fexprs need a different kind of quoting than a lambda, they need one that captures the structure of the code as data and captures the environment like a lambda. There is no primitive in lisp that does that. I do like the explicitness, but implicit quoting as a kind of macro is also ok with me. That's yet another possibility. What if the quoting was known at compile time, what if a fexpr is a macro? If you want a first class function you explicitly quote, if you want syntactic sugar you use a non-first class macro. That won't kill anyone, especially if you made a first class version that needs explicit quoting available too! Though in the language I'm designing I'm leaning toward a real fexpr if I can do it with that runtime without too much slowness - but it might not be possible. In trying to avoid quoting I reduced it to the following problem. Say you have some combinators: P = 0 Q P = 1 Q x = x Now how does Q P reduce? You don't know, right? But what if I say that Q is a macro? Then you do know, right? Q P Q So, I am thinking of going for a scheme where expressions may be reduced in separate stages where in one stage, some code is data (isn't reduced), and in the next stage is code again (is reduced). That can be made very efficient since that simply needs a compiler where combinators are compiled to code, which either reduce or not (i.e., the subroutine the combinator is compiled to is called, or not.) Not sure how to make it work yet, though. John had the idea to name combiners differently than reducers but he didn't enforce it. What if you enforced the difference syntactically but still make combiners first class? People seem to call this sort of difference "lifting". Say a function application is F e but a combiner application is C:e I like that principle, lots more things should be lifted than are. Calling a function is different than applying a combiner is different than calling a function with a continuation.. All should have separate syntax. They're first class but they're not interchangeable. We can have 4 kinds of non-interchangeable calls call call with continuation call with environment and quoted arguments call with continuation, environment and quoted arguments I don't know (yet). John tries to fit in pretty abstract ideas into a very concrete operational model. I work from the opposite direction, start of with a very abstract view and then try to design a language and operational model around that. But I assume rewrite semantics, so I am not thinking about call stacks and continuations. Though I might have reduced the problem to an absurdity. No idea yet. of separating out calls that can save a continuation is: 1) they can come back through the same code multiple times - the change the meaning of the outer program 2) they are a nonstandard kind of call, not using the stack so the implementation may be different I think a notation that captures it is f<<parameters The double arrow << is to represent that the call can come back more than once! Look out trying to type double left arrow, this site won't display it and will not display text after it. You have to type << I for one am fascinated by... and wary of... this different-call-syntaxes idea. Seems like it might be a very cool way to avoid accidents; on the other hand, I'm wondering about two things that seem like potential sticking points: (1) the potential for sliding into syntactic complexity; and (2) how it interacts with dynamic typing. If I'm following, you'd write "(f ...)" for an applicative call (well, okay, maybe you have something else in mind re parentheses, though I favor them myself, but that seems a somewhat seperate issue); "(f : ...)" for an operative call; and "(f << ...)" for a call that can capture its continuation — I like the multiple-angles-to-indicate-multiple-values mnemonic. It would be a dynamic or compile time type error to make the wrong call. Part of the reason is as I've explained before: 1) calls that don't take a continuation can be normal stack based calls or inlined and therefore more efficient 2) this could be built by cps transform on any language with tail call elimination - only transforming the calls that can take a continuation 3) this gives you a kind of clarity for what a reifiable delimited continuation IS. If you want to call a chain that can use a continuation you make a new continuation (Continuation:new()) then start a chain on it. 4) Most importantly it solves the "this construct changes the meaning of the whole program around it" problem. If only we had a solution like that for the other such construct, threads. - Though I'm starting to imagine a partial solution for that is based on shipping data around instead of sharing it. Create different arenas of data that are distinct, then ship the whole arena from one thread to another atomically. Like the problem with cps transforms and stack, that idea came from an implementation problem, from the efficiency limitations of soon to be obsolete ARM v7 processors. There could also be a syntax for combined calls with the understanding that they would be less efficient and might have weird but hopefully well defined properties. I'm missing sleep so I'm not even up to the task of laying out the many possibilities of how to handle an implicit continuation in a function that wasn't passed a continuation vs. one that was. John Shutt: I take it a non-continuation-capturing call could have something buried somewhere inside what it does that captures a continuation? No it can't, not one that can escape it, and that's the point. In this model you are explicitly passing continuations - this is a model that works with conditional cps transformation on a language that doesn't implement continuations. It allows BOTH kinds of calls to coexist. And in this model, the USER has to create a continuation to pass to the first function in the chain that uses a continuation. In this model both ends of the continuation are reified (or more with branches)! Both ends have to be active to jump into the continuation. If no one is waiting on the return value, then to jump into the continuation, you better tell it where the other end is going or it has to be you. Abnormal transfer of control — call it continuations, exceptions, whatever — is something I'm still convinced we don't know how to do right. In such situations my usual suspicion is that we're using a seriously wrong conceptual framework for the whole context within which the question occurs. If I'm following you rightly, a continuation can only move outward through a function call if the function call syntax explicitly permits such. That raises the "trouble with monads" problem: in a "pure" functional language using monads to model side-effects, introducing a side-effect in a low-level function forces a change to the signature of all the functions that call it, all the way up the abstraction ladder. My own foray into such stuff in Kernel was guarded continuations, though what I found most interesting about guarded continuations was the deeper questions they suggested. It's a matter of PL design. Lisp writes (if (a) (b) (c)) meaning, evaluate A, then evaluate B or C depending on the outcome. Would it be meaningful to express the same thing with named arguments like (if test:(a) consequent:(b) alternate:(c)) Just so people who don't remember (or don't care) about argument ordering could instead write (if alternate:(c) consequent:(b) test:(a)) ? with something as frequently used as 'if' it makes nonsense that anyone wouldn't remember the argument order, but in general? Yeah, that happens. And would it make sense that another programmer, who completely trusts her own knowledge of the argument orders and finds the additional notation annoying, could just turn off the display of argument names in the calls and get (canonically ordered) arguments? Yeah, that could happen too if the language supports both syntaxes, depending on the IDE. In fact the argument names might not even exist as part of the source code at all: The IDE could munge them into the display, or accept them as a written form for code it would save to file differently. No, I don't see it. How are you going to implement a 'macro' system with your approach? I still think you're too concrete. The idea to reduce it to an absurdity is to show what properties we are studying. Again. P = 0 Q P = 1 Q x = x Q P? You immediately observe non-confluency (due to), reflection, different rewrite strategies. Roughly, probably, you can implement a macro system iff you know what combinators you're going to evaluate in a preceding pass. Which simply coalesces with a nonstandard rewrite strategy. But in the combination with introspection you get non-confluency too, which is either a) bad, b) neat, c) a requirement. I simply don't know yet. Certainly not thinking about continuations, yet. (edit: fixed a typo.) Addendum: Of course, you can also study hygiene which enters after the TRS is extended with nameless abstraction. P (\x . e) = (\x . P e) P (f a) = f P v = v Q (\x . x) = x P as to show that introspection is useful, Q as to show that introspection is problematic. confluency is never a problem. Macros aren't a probramming language they're a way to make code a little more terse. I find macros operate at the wrong level of abstraction, C++ templates are almost as bad, although better than 'C' macros. I would like a language that gives the expressive power of macros through first class functions, and does not need to provide macros. But maybe thats just me. In creating a lispy language with fexpr-like semantics, I simply did not find any very good semantics for quote. However, in a lispy language with fexpr-like semantics, I have never found a situation that requires quoting. I wound up sticking several subtly different versions of it in a library of procedures that are considered semantically problematic, but which I included specifically because my goal was to create a translation target for source code originating in many languages, and many languages do use problematic constructions. So why do I have libraries devoted explicitly to providing constructs I specifically consider to be problematic? My goal with the lisp was to provide a formalization that explicitly describes the complete semantics of code regardless of programming language, at the level of explicit formalisms. Down to the level of the libraries explicitly describing exactly the mathematics corresponding to binary operations of underlying hardware when and as they affect the language semantics, as in assembly language. My idea (still unrealized) is that when these things are made explicit in a translation target, code that depends on the semantics of different languages, different machines, or even different compilers, when FULLY described in that language, can be made fully interoperable. What I want to do is have code regardless of its origin expressible (via a simple structure-preserving automatic translation) in a single language and combined, as desired, in programs. And reasoned about, refactored, deduplicated and optimized in that language. what do you think of my idea of syntactically offsetting fexpr calls (and ones that can capture a continuation). Have 4 kinds of calls (for the four combinations) instead of one. It complicates things but it means you can't ever be surprised by different semantics. If an expression is captured, you know it from the call. If a continuation is captured and can come back again, you know it from the call. Every thing is still first class or maybe nothing is. I'm still thinking about it, actually. It violates my expectations that code following a procedure call could be executed twice without being visually distinct from code that will only cause the following code to be executed once, so calling it out with distinct syntax would definitely help reduce confusion. OTOH, the question doesn't come up because I find continuations annoying and don't use them hardly at all. As I said, they often violate my expectations. I'm considering them semantically questionable because they tend to expose too much of implementation details and often affect the semantics of code that was written without using them or thinking about the consequences of other code that uses them. And while fexprs can be used in equally confusing ways, they are relatively straightforward in application. I -- fear never being able to untangle the semantic problems that combining them could cause. The most use I make of continuations, is to pass some functions a choice of continuations to call - ie, in some cases return to this point, but in other cases return to that point. Which reduces them to a special case much easier to reason about. Under the hood, it's the same code that specializes functions which may return different types - if returning an integer, you continue at re-entry point A which is statically compiled to deal with integers, and if returning a character, you continue at re-entry point B, which is statically compiled to deal with characters. It's exactly the same case with something that looks up an item in a dictionary: If you find the item, return it to re-entry point A, and if you don't (you are returning a value of the "error" type) you return to re-entry point B. You could have an obfuscated-scheme contest. But if continuations and macros were both allowed - especially the new style macros that can violate hygiene - it would be like using a nuke for rabbit hunting. Throw in fexprs and/or implicit lazy evaluation, and it's more like a K/T impactor. I trust the good taste of programmers a lot - I'm providing a lot of sharp tools and if they write pathological things, the system will behave in pathological ways. But I'm trying to make it hard to write pathological things *accidentally*, and I think continuations combined with some of the other constructs I'm working with violate that rule. Ok, maybe to a certain extent I was playing rather than using, but I needed them to: To implement a logic language. To do search, satisfy constraints. To parse a grammar or generate from a grammar, or fill in the blanks from a grammar. It's a matter of what paradigms of programming you use. If you're in a continuation-rich setting, then maybe you'd like continuations but want them better controlled. Now for fexprs, I imagine them as: 1) an engine for code transformation - not trivially, but as a way of programming 2) As an engine for equation transformation. Symbolic math. Constraints. But the point of offsetting them isn't for the sake of the programmer, it's for the sake of the compiler and speed etc. Whether the programmer will like it, I'm not sure but I don't think it will be too harmful. One can always supply combined forms too, with the understanding that they will be less efficient - and they're offset from the rest of the code too. I think there's a principle "offsetting is good" In creating a lispy language with fexpr-like semantics, I simply did not find any very good semantics for quote. However, in a lispy language with fexpr-like semantics, I have never found a situation that requires quoting. As I explored various facets of Kernel's evaluation model, I found that pretty much every time I wanted to demonstrate bad hygiene, the easiest way to do it was to use an operative ($define! $quote ($vau (x) #ignore x)). With enough repetitions of that lesson, and recognizing that fexprs naturally favor an explicit-evaluation philosophy while quote naturally favors an implicit-evaluation philosophy, I eventually concluded that mixing fexprs and quote nurtures defective hygiene. ($define! $quote ($vau (x) #ignore x)) I'd bet a year's salary that we ran into the same kind of hygiene problems. There are multiple 'sets' of operations that make a complete and general model of computation - but if you have more than one such set available, some of the features essential to one or more can turn out to have remarkably poor interaction with others. 'quote' turns out to such a construct. It interacts very well with homoiconicity, lambda, apply, eval, and first-class procedures. But not with fexprs, first-class environments, and lazy evaluation. But the things it interacts poorly with create a different general model of computation, rendering it unnecessary. Very well put. I think evaluation semantics is can of worms. I'm trying to avoid tying operational semantics to value semantics. This doesn't make sense to me. You're talking about three different semantics. Operational semantics I get but what do you mean with the rest? I personally decided I am going to drop quotation and opt for a solution with an explicit rewrite order. But I didn't figure it out yet how I am going to do it. I was lumping in 'evaluation semantics' with 'operational semantics'. I don't have an evaluation order defined for the semantics of my values and functions. During representation selection, a calling convention will be adopted that's compatible with the semantics of the function. For example, if the parameter to a function is a non-bottom Integer, then you can use call-by-value to pass that value. Please post a new top post about it on LtU if/when appropriate and/or let me know where i can sign up for your newsletter (seriously). The meaning of an encoded program as a construct should be completely static (and thus, as bad as macros are, F-exprs look worse). Wouldn't completely static meaning preclude stateful variables? The question of macros-versus-fexprs is more about hygiene, which is of concern even if all symbol bindings are immutable; and of course which of macros or fexprs is "better" on hygiene depends on various other design priorities. I think I've had a misunderstanding of fexprs that you just caused me to find and clear up. Specifically, all fexprs in Kernel can in principle be evaluated at compile-time, correct? The only problem would be if separate compilation prevents you from understanding the environment in which something will be executed? I probably shouldn't have mentioned fexprs since my only knowledge of them comes by osmosis from listening to you, but hey, at least I provoked you to respond. I'll upgrade my assessment of fexprs to merely as bad as macros :). Stateful variables can be modeled fine in my system. I'll try to post more this weekend for raould. Alas, not necessarily. It is possible to write Kernel code such that at compile time it can't be known whether the combiner of a combination will be operative or applicative, therefore can't be known whether the operands of the combination will be evaluated. This is true even if environments are actually immutable. The simplest way of doing this is to simply specify an operator that you don't know the type of. The possible problems and possible solutions get a bit subtle, on this point. consider this definition: ($define! p ($lambda (f) (f ...big hairy operands...))) Even if parameter value f is a combiner (rather than, say, an integer, which would cause an error), it could still be either applicative or operative. If f is operative, then ...big hairy operands... will be passed to that operative unevaluated. Which is probably not intended. This is, of course, bad coding practice; if an argument is expected to be applicative one ought to apply it, so that passing an operative would cause an error: ($lambda (f) (apply f (list ...big hairy operands...))). One could imagine a number of approaches to minimizing this error, perhaps involving a compile-time warning (which one would then probably want to be able to spot-disable once the programmer has looked at the particular code and rendered a decision that yes, they really did intend to do this strange thing). apply ($lambda (f) (apply f (list ...big hairy operands...))) It is perhaps worth mentioning, in this regard, that when a compound combiner is constructed, the operands to $vau are preserved as immutable copies — thus, ...big hairy operands... is immutable; so even if f does access it unevaluated, at least f can't change it. $vau ...big hairy operands... My concern over these hygiene considerations is generally limited to how best to minimize the likelihood of accidental bad hygiene, rather than how severely pathological bad hygiene can get. It's possible to write pathological code in any serious language, so if the worse possible is even worse with fexprs I'm not too fussed. There are situations where it's desirable to guarantee certain pathologies can't occur, and I do have a weather out for possible future devices for that, such as guarded environments or first-class theorems; but in the meantime I simply accept that such guarantees are not within the design's current purview. Okay, that's the understanding that I had previously. You're calling that hygiene, which ... this isn't quite the way I understand hygiene issues around macros. Can I view it as the same issue of unintended capture? Is "container polymorphism" (ability to pass an operative and an applicative to the same kind of lambda) really useful for you? Why don't you have a separate namespace for operative variables? I strove to clarify a bunch of these basic terms in my dissertation; "first-class value", "reify", "side-effect"; but found "hygiene" especially slippery. What I came up with: Hygiene is the systematic separation of interpretation concerns between different parts of a program, enabling the programmer (or meta-program) to make deductions about the meaning of a particular program element based on the source-code context in which it occurs. (Fwiw, Kohlbecker et al. credit Barendregt for the term hygiene.) The idea of a separate namespace for procedures is a key point of disagreement between Scheme and Common Lisp. Most often nowadays when someone refers to "Lisp 2" they probably mean "Lisp with a separate namespace for combiners". I oppose segregation; I don't think it really supports first-class-citizenship, and this is poetically the same principle that leads me to oppose the logical segregation of compile-time macros from the run-time system. I did introduce the $-prefix naming convention in Kernel to help reduce accidents, but stopped short of enforced constraints. $ Examples of applicatives that work on both applicatives and operatives arise early amongst the Kernel primitives — wrap and unwrap. wrap unwrap " I did introduce the $-prefix " I really wish you'd picked a character nearer to the home row that didn't need a shift key, like '/' or even better ';' /lambda ;lambda lambda; or just plain lambda! I used a '$' prefix for a separate class of entities called 'sigils'. Sigils are tokens that can't be bound to any value, and I use them as argument-class separators etc to eliminate a lot of non-evaluation parens from the language. Having a separate namespace but using tokens that do not syntactically differ just seemed like asking for trouble and complication. When I did decide I needed a separate namespace (to call out dynamic as opposed to lexical scoping), I made it lexically distinct with *bracketing* *stars*, consistent with the way Scheme names its standard dynamically-scoped variables such as *current-input-port* etc. That's Common Lisp. Scheme has neither dynamic variables nor rabbit ears. It's within the lispy-language tradition, either way. I was using both for a long-ish while; looks like now I'm getting them mixed up. And I beg to differ about scheme. The semantics of current-input-port, etc, are most definitely those of dynamic-environment variables. Actually current-input-port itself is an ordinary lexical variable, typically bound in the global environment. What it is bound to is a first-class object, a box with dynamic scope behavior. Check out the implementation of SRFI 39. current-input-port Unfortunately, the dynamic-bind procedure given there, which binds a list of arbitrary boxes to new values during the execution of an arbitrary thunk, isn't exposed by either SRFI 39 or R7RS-small, which provide only the macro version that specifies a body rather than a thunk. It's analogous to Common Lisp progv, but with boxes instead of variables. First-class dynamically bound boxes are a resource that we haven't yet begun to figure out how to exploit properly. dynamic-bind progv on the question "it's easy to tell at a glance what code in this language does" Common Lisp is at the bottom of the list, but Scheme is at the top third point. Which makes me think that very few people have used Scheme, and they're partisan. That list (with some minor languages left out) goes Python (good choice for ease of understanding) C# (I would think there's some complexity there, but so popular it gets pushed up maybe) Go (designed to be simple to read) Java (designed to lack abstraction and be verbose) Smalltalk (right on!) Lua (great syntax, a few confusing constructs, but those are rarely used) Objective C Scala O'caml Ruby Scheme PHP TCL Fortran (I would have put at the top for easy to read, given what it's for) Javascript Delphi C R ... at the bottom C++ Common Lisp Cog Perl Prolog Forth For "I enjoy playing with this language but would never use it for real code" Scheme is the number one answer, followed by Prolog, R and Common Lisp "Lua popular, has a JIT option / 'tables' are weird" The great and horrible thing about Lua is that in order to simplify syntax they combined all data structures into one structure that leaks abstraction like mad. So tables are lists and arrays and queues and hash tables and classes (with weird symantics so that add and compare are meaningfully extendable) and objects and proxies and to some extent environments. And among all these weird additions you lose the ability to copy a table except when you know what combination of things it really is and what the additions are. But it sure gives you a simple syntax for building any data structure. In, say, 1990, Scheme served a variety of uses for different people. Depending on which of them you want, today there are different things to pick: - If you want a core language to express simple computational ideas on paper in, then Scheme remains an excellent choice. For example, the Reasoned Schemer is written in Scheme, and it's a fine choice for it. - If you want a Lisp with a sensible core design that you can use to get real work done in, there are several good choices -- I'd especially mention Racket and Clojure, depending on your needs and platforms, but Gambit, Guile, etc are also good. - If you want a highly reflective language in which you can write useful programs, I recommend Ruby, or maybe JavaScript (but less so). - If you want a simple PL to extend in your next academic paper, which your reviewers will have heard of, then JavaScript is your best choice. - If you want an untyped language that everyone already teaches to undergraduates, then Python is for you. - If you want a simple language to write an interpreter for, then Scheme continues to be a great choice. However, if you want a language to play the role that Scheme played 20 years ago, then no such language exists, and won't exist no matter what people do -- the world has changed, rather than Scheme. This relatively young language might be of interest here: extempore and xtlang Please expand upon that thought: the bullet point reasons you think it is at all related to where Scheme comes from spiritually, the bullet point reasons you think it is "better" than Scheme, the bullet point cons (if any ha ha!) in the language. This relatively old (1982) language may also be of interest: axiomatic language spiritual similarities: * (extremely) minimal * s-expr syntax * metalanguage capability pros: * pure specification language - one defines the external behavior of a program without giving an implementation algorithm * completely declarative * more general, in the sense that relations are more general than functions con: * implementation grand challenge - requires automatically transforming specifications to efficient algorithms I really like that idea. But specifying *ONLY* external behavior at the top level is sort of a non-starter. Specifying the behavior at the level of routines, or even going down into the guts and specifying at the level of individual clauses, though, could be the "right thing." It would be a *lot* easier though - perhaps even feasible - to take the behavior specification and transform it into acceptance tests. As for actually running programs, it would be the ultimate case of "The Language Is The Library." The users could make behavior specs, and the UI could tell them "oh, somebody already implemented that" and call in the appropriate library. Or not, and then when the user who specified it implements it, (and the system proves it) The UI asks permission to put it into the library in case anyone else ever calls for that behavior spec (or one proven equal to it) ever again. And the library grows (bloats!) incrementally via the magic of crowd-sourcing. And as it grows, people would gradually be able to specify behavior at a higher and higher level, until specifying only the external behavior will start to actually work in some cases. You'd need background threads running under every UI, at full speed to try to prove implementations against specs, or prove the equality of specs so that implementations of one could be used for the other. Things relevant to the local projects with first-priority of course, but never letting a cycle go by without working on something from somewhere. It would be a globally distributed compiler, running full speed on every user's system. Implementations could be proved by testing exhaustively in some cases, with cases distributed to thousands of users. Or if the testing is extensive but not yet exhaustive, you'd have a continually updated probability score that the implementation meets the spec, and some devs might choose to accept those library entries on the basis of six-nines probability or higher. To be replaced instantly by an upgrade if an implementation that is properly proven to comply with the spec becomes available. It would be a worldwide, distributed, crowd-sourced compiler, running 24/7 and simultaneously on every user's code. But 1982 wasn't ready for it, because it just plain wasn't possible then. Distributed libraries weren't possible without the internet, automated theorem proving wasn't ready for anything non-trivial, nobody had ever built a distributed application, and the compute power for proving things or attempting to test things as exhaustively as possible just plain didn't exist. It's kind of an awesome idea, actually. If you have behavior spec as a proof target, you might be able to stick some sort of automated implementation into the mix. Neural net eats the behavior spec, comes up with -- something -- and if it gets proven correct it gets added to the library (and the set of "positive" examples for the neural net's continuing self-training). Of course it would almost always be wrong. But worldwide, distributed.... it might be right enough of the time to matter.
http://lambda-the-ultimate.org/node/5325
CC-MAIN-2019-35
refinedweb
11,402
60.45
This chapter contains general information applicable to all of the C programming libraries of XML-RPC For C/C++ (libxmlrpc, libxmlrpc_server, etc). You will also find information of general applicability in the manual for libxmlrpc, because it includes basic services that you use with all the other libraries. The equivalent chapter for the C++ libraries is. Almost everything you need to know about XML-RPC is here. But you will find that the official specification of the protocol is riddled with ambiguity and other usability problems. This page adds to it and accurately describes most so-called "XML-RPC" clients and servers. A library function either succeeds or fails. The distinction might be a little fuzzy sometimes, but the documentation should make it clear what is considered successful. When a library function fails, it returns no information. Any return values or pointed-to return variables have arbitrary values when the function returns. A library function does not change the state of anything when it fails. For all practical purposes, it is the same as if the function had not been called. While a library function, when it fails, does return information specifying how it failed, you generally aren't supposed to call a function just to see how it fails and your program should not analyze the failure information. The failure information is primarily intended for forwarding to a human to diagnose a larger problem. There generally exist interfaces whereby you can learn from a successful execution whatever you would have learned from some failed execution. There are a variety of constants that the libraries use, often through their internal use of other libraries, which are too complicated for the library loader to set up. Therefore, a program must call a library function after the program is loaded and running to finish setting up the library code. For example, in some configurations, libxmlrpc_client uses the GNU TLS library internally to provide SSL connections, and inside that library there is an elaborate tree that describes the SSL protocol. Each library that uses such global constants has a global initialization and global termination function, and any program that uses the library must call them. For example, libxmlrpc_client has xmlrpc_client_setup_global_const() and xmlrpc_client_teardown_global_const(), and libxmlrpc_abyss has AbyssInit() and AbyssTerm(). The global initialization function sets up the global constants. This may allocate resources (e.g. the memory for the GNU TLS tree mentioned above), so the global termination function releases them. The basic rule for constructing a program that uses one of these libraries is this: Call the global initialization function immediately after the program starts, while it is still only one thread and before it uses the library at all. Call the global termination function immediately before the program exits, when the program is again only one thread and after its last use of the library. be using libxmlrpc_client the library is not the main program, but rather a modular piece of a program, e.g. another library. As a module, your code doesn't know about other parts of the program -- it doesn't know whether they use an Xmlrpc-c library or not. And its code doesn't necessarily run at the start and end of the whole program. A module like this must have global initialization and termination functions of its own. The module thus has control at the beginning and end of the program and has a place to call the Xmlrpc-c global initialization and termination functions. Note that if multiple modules in the program use a particular library, they all will separately call that library's global initialization and termination functions, and that's OK because only the first global initialization and last global termination in a program changes anything (the libraries use a reference count in static memory). Some libraries offer simplified interfaces in which the global initialization and termination are done for you under the covers; but such an interface has the same restrictions and the global initialization and termination functions: it isn't thread-safe. The manual for each Xmlrpc-c library tells you what its global initialization and termination functions are. The library functions are thread-safe. They do not use static variables. Functions that set up and tear down global constants are an exception (but not really a significant one, since it's easy to call those while the program is only one thread). The objects based on the libraries are generally not thread-safe, so you must make sure no two threads access a particular object at the same time. The xmlrpc_value structure in libxmlrpc and the xmlrpc_c::value class in libxmlrpc++ that is based on it deserve special mention. These are thread-safe in Xmlrpc-c 1.33 and later if you use them properly, but in earlier Xmlrpc-c they are not only thread-unsafe themselves but make many other objects thread unsafe because these other objects refer to them. See XML-RPC Values for details. The objects provided by libxmlrpc_client and libxmlrpc_client++ are mostly thread-safe, so you can have multiple threads using the same transport and talking to the same server. The libraries' thread safety depends of course upon thread-safety of all the libraries it uses. Your standard C library in particular must be thread-safe. As far as I know, all libraries that Xmlrpc-c uses in typical configurations are thread-safe. A function is "thread-safe" if you can call it from multiple threads simultaneously without causing something totally unacceptable like a crash, hang, or memory leak. A function which was written without threads in mind -- particularly a function written before multiple threads were possible -- may very well not meet this criterion. A thread-safe function might still cause a disaster when you call it from multiple threads if it's part of a larger thread-unsafe procedure. For example, a function that adds to a linked list is probably thread-safe. But if you call it to add to a linked list that some other thread is presently adding something else to, you have threading trouble. An object is thread-safe if you can call its methods simultaneously from multiple threads without screwing up the object or causing the totally unaccepted behavior mentioned above. If a linked list object is thread-safe, you can call its add method (i.e. its official designated add function) from multiple threads simultaneously without corrupting the list. A library is thread-safe if all its functions and all the object classes it defines are thread-safe. That's all thread safety is. You can use multiple threads without crashing your program. But people often expect more from a threaded program and incorrectly call their expectation "thread safety." You may be trying to use threads because you want the performance benefits of doing two things at once. But a thread-safe library won't necessarily give you that. The easiest way to make a library thread-safe is to use a big lock to serialize everything -- make sure no two threads are ever executing the meat of the library at the same time. You could have 100 threads, and one at a time does useful work while 99 wait for the library's lock. So while thread-safety is a good start, you may want to ask about actual concurrency. XML-RPC For C/C++ facilities implement a superset of the XML-RPC protocol. I.e. the set of messages and communications you can do with these facilities is a superset of those specified by XML-RPC. In the manual, we generally treat the extensions to XML-RPC as if they are part of XML-RPC, but where it matters, we point out the distinction. In particular, there are additional data types you can use for parameter lists and results. There are two popular versions of the XML-RPC extension data type nil. In one, its value is encoded into an XML-RPC message with an XML element named nil. In the other, the XML element name is ex:nil. (The "ex" is a namespace and is meant to make it clear that it is an extension data type). Similarly, some clients and servers use i8 for the 64 bit integer type, while others use ex:i8. We refer to these distinct versions of the protocol as dialects. Xmlrpc-c names the "ex" dialect "Apache", since it originated with the Apache Java XML-RPC facility. It names the other "i8," for lack of a better name. The two dialects are compatible enough that Xmlrpc-c facilities for interpreting XML-RPC messages can and do handle both all the time. But the Xmlrpc-c facilities that generate XML-RPC messages need to be told which dialect to use, because a partner that handles only one dialect (e.g. one based on the Apache Java XML-RPC facility) must be sent that dialect. So Xmlrpc-c lets you choose on a per-client and per-server basis which dialect to use. See xmlrpc_client_create() and xmlrpc_registry_set_dialect(). If it annoys you that there are two standards for this, which means you can't make a single Xmlrpc-c-based program that works with all XML-RPC partners, remember that you really can't use these data types at all if you want maximum interoperability, because many potential partners speak only original true XML-RPC. To refer to a dialect, Xmlrpc-c has the type xmlrpc_dialect. It is an enumerated type with these values, whose meanings are obvious: XML-RPC messages (calls and responses) are XML documents, which use Unicode characters. The character encoding of those characters is flexible. All XML-RPC messages Xmlrpc-c generates use UTF-8 character encoding and include an XML Processing Instruction ("<?xml ... ?>") that says so. When Xmlrpc-c interprets an XML-RPC message, it understands the following character encodings and respects the declaration made by an XML Processing Instruction ("<?xml ... ?>") of which of these is in use. If the encoding specified is anything else, the Xmlrpc-c facility that needs to interpret the message fails. If there is no XML Processing Instruction, Xmlrpc-c assumes UTF-8. The above is true if you use the normal built-in version of Expat as its XML library. If you use a special build of libxmlrpc that uses libxml2 or any other XML library, the character encoding behavior is determined by that library. In no case does libxmlrpc tell the XML library to use any particular character encoding. In XML-RPC, strings and structure member names are composed of Unicode characters; i.e. they can essentially contain any character known to man, from capital A to o-circumflex to euro sign. Therefore, many Xmlrpc-c library services take Unicode strings as inputs and produce Unicode strings as outputs. (Where possible, though, they always work in traditional ASCII). There are various ways of representing a Unicode character in bits. The one Xmlrpc-c uses most of the time is UTF-8. However, there are a few things you can do in UTF-16 if you prefer. This manual tells you wherever it refers to a string what kind of encoding is involved. If you stick to the subset of Unicode characters that can be represented in ASCII (plain English text), you don't have to worry about the complexity of Unicode and UTF-8. All ASCII text is UTF-8 Unicode text, so you can just use ASCII, with its simple one byte per character encoding and take it easy. Note that ASCII codes are all 7 bits -- the high order bit is zero. So make sure your strings never contain a byte with the high order bit set. If your program contains non-ASCII string literals, you may need to take special care to understand your editor and compiler and even filesystem to avoid surprises. What appears one way on your screen may not be what the compiler sees when it compiles the code. On Windows, you can save a character encoding attribute with a file. If that attribute of your source file doesn't match what is actually in that source file, your string literals don't say what you think they do.
http://xmlrpc-c.sourceforge.net/doc/libgeneral.html
CC-MAIN-2016-36
refinedweb
2,033
53.31
/ Published in: JavaScript Expand | Embed | Plain Text - $('input.valid-number').bind('keypress', function(e) { - return ( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) ? false : true ; - }) Report this snippet Tweet This code won't catch the alternate values on the numeric keys. For example, #, ! and @ will all be allowed as the key pressed for these is still the number key. I changed the code to account for this as follows: $('input.valid-number').bind('keypress', function(e) { return (e.which === 8 || e.which === 0 || (e.shiftKey === false && (e.which > 47 && e.which < 58))) ? true : false; } Forgive the lack of formatting, this was my first post and I'm not used to Markdown.
http://snipplr.com/view/8213/
CC-MAIN-2015-48
refinedweb
115
80.07
Angular is a popular front-end framework made by Google. Like other popular front-end frameworks, it uses a component-based architecture to structure apps. In this article, we’ll look at ways to style Angular components. Component Styles Angular components are styled with CSS. Everything about CSS applies to Angular components. We can also compound component styles with components, which allows for more modular designs than regular stylesheets. Using Component Styles We can define CSS styles in addition to template content in our components. One way to do it is to use the styles property in our component. For example, we can write that as follows: app.component.ts : import { Component } from "@angular/core"; @Component({ selector: "app-root", templateUrl: "./app.component.html", styles: [ ` h1 { font-size: 50px; } ` ] }) export class AppComponent {} app.component.html : <h1>Foo</h1> Then we should see ‘Foo’ that’s 50 pixels big on the screen. Styles in styles isn’t inherited by any components nested within the template or any content projected into the component. We can use CSS class names and selectors that make the most sense in each component. Class names and selectors don’t collide with class names and selectors in other parts of the app. Changes elsewhere in the app don’t affect changes in the current component. We can co-locate the CSS code of each component with TypeScript and HTML code of the component, which makes the project structure cleaner. Also, we can change or remove CSS code without searching through the whole app to find where else the code is used. Special Selectors Angular apps can use special selectors to style components. They come from selectors for styling the shadow DOM. :host The :host pseudoclass selector targets styles in the element that hosts the component rather than the elements inside the component’s template. For example, we can write: :host { display: block; border: 3px solid black; } We can style host styles with the given selector by using the function form as follows: :host(.active) { border-width: 1px; } :host-context We can use :host-context to apply styles on some condition outside of a component’s view. It works the same way as the :host selector, which can use the function form. It’ll look in ancestor components all the way up to the document root for the given selector. For example, we can write: :host-context(.theme-light) h2 { background-color: #fff; } /deep/, >>>, and ::ng-deep (Deprecated) We can use /deep/, >>>, and ::ng-deep to apply styles to outside of the component by disabling view encapsulation for the rule. For example, we can write: :host /deep/ h3 { font-weight: bold; } Style Files in Component Metadata We can set the styleUrls to point to a stylesheet file to style a component. For example, we can write the following: app.component.ts : import { Component } from "@angular/core"; @Component({ selector: "app-root", templateUrl: "./app.component.html", styleUrls: ["./app.component.css"] }) export class AppComponent {} app.component.css : h1 { font-size: 50px; } app.component.html ; <h1>Foo</h1> In the code above, we put our styles in app.component.css and point our styleUrls to that file in app.component.ts . We can specify more than one style file in both styles and styleUrls . Template Inline Styles We can put style tags in our templates to add template inline styles. For example, we can write: app.component.html : <style> h1 { font-size: 50px; } </style> <h1>Foo</h1> The code above will set the h1’s font size to 50 pixels. Template Link Tags We can add link tags to templates to reference other styles. For example, we can write the following code: app.component.ts : import { Component } from "@angular/core"; @Component({ selector: "app-root", templateUrl: "./app.component.html" }) export class AppComponent {} app.component.html : <link rel="stylesheet" href="./app.component.css" /> <h1>Foo</h1> We see that we removed the styleUrls from AppComponent and put a link tag to reference the CSS file. The styles should be applied from the file we referenced in the link tag. CSS @imports We can import CSS files with the standard CSS @import rule. For example, we can write the following code: foo.css : h1 { font-size: 50px; } app.component.css : @import url("./foo.css"); app.component.html : <h1>Foo</h1> External and Global Style Files We can add external global styles to angular.json to include them in the build. To register a CSS file, we can put in the styles section, which is set to styles.css by default. Non-CSS Style Files Angular CLI supports building style files in SASS, LESS or Stylus. We can specify those files in styleUrls with the appropriate extensions ( .scss, .less, or .styl) as in the following example: app.component.scss : h1 { font-size: 70px; } app.component.html : <h1>Foo</h1> View Encapsulation We can control how view encapsulation works by setting the encapsulation setting in out component code. The following are the possibilities for view encapsulation: ShadowDomview encapsulation uses the browser’s native shadow DOM implementation. The component’s styles are included in the Shadow DOM Nativeview encapsulation uses the now deprecated version of the browser’s native shadow DOM implementation Emulatedis the default option. It emulates the behavior of the shadow DOM by preprocessing and renaming CSS code to effectively scope the CSS to the component’s view Nonemeans that Angular does no view encapsulation. The styles are added to global styles. We can change the encapsulation setting as follows: app.component.ts : import { Component, ViewEncapsulation } from "@angular/core"; @Component({ selector: "app-root", templateUrl: "./app.component.html", styleUrls: ["./app.component.scss"], encapsulation: ViewEncapsulation.Native }) export class AppComponent {} Conclusion We can use CSS to style Angular components. In addition, it supports SASS, LESS, and Stylus for styling. By default, the scope of the styles is local to the component. However, we can change that to be different. We can also include inline styles in our templates via the style and link tags. Discussion (0)
https://practicaldev-herokuapp-com.global.ssl.fastly.net/aumayeung/a-guide-to-styling-angular-components-1m59
CC-MAIN-2021-10
refinedweb
996
50.12
Reproductive and Genetic Engineering: Journal of International Feminist Analysis Volume 5 Number 3, 1992 JOCELYNNE A. SCUTT Owen Dixon Chambers, 205 William Street, Melbourne, Victoria 3000, Australia On May 31, 1992 in Melbourne, Australia, the Sunday Age ran an “exclusive”: “Doctor Forced Abortion: Woman.” Written by Caroline Wilson, the article described a Melbourne woman’s allegation in the Supreme Court of Victoria that Australia’s “largest infertility program”: demanded that she have an abortion to cover up for “a terrible mistake” which saw her inseminated with incompatible sperm. (Wilson, 1992, p. 1) The woman told the court that she “underwent an abortion against her will after being threatened by [a doctor] from Monash University’s Infertility Medical Centre, which has been a world pioneer in in vitro fertilization [IVF].” Caroline Wilson goes on to say that the doctor, a consultant to the Donor Insemination Service at the center, “allegedly told her patient that because of a ‘mix-up with the straws’ she had been inseminated with the semen of a Spanish-Egyptian of an incompatible blood type” (Wilson, 1992, p. 1). The Australian-born woman, whose husband serves in the armed forces, was allegedly told by the doctor that she “would not be allowed back on to the fertility program unless she had an abortion” (Wilson, 1992, p. 1). The woman said she was “also told that she would be refused further treatment at any fertility clinic in Australia should she take legal action over the sperm mix-up because her name would appear in every newspaper across the country” (Wilson, 1992, p. 1). The court case is proceeding on the basis that the action can be lawfully brought, and that the doctor concerned denies insisting that the woman have an abortion. The doctor also denies that she threatened that the woman would be debarred from reentering the IVF program if she continued with the pregnancy. The woman (who remains anonymous in consequence of a suppression order granted by the court) said that although she underwent the abortion in 1983, the doctor was unwilling to allow her back onto the program in 1985. In court, she stated: “They weren’t going to let me back for a second try, and I said to [the doctor], ‘I’ve covered up for you.’”She went on to add that the hospital had kept as a donor the man who had provided compatible sperm for insemination leading to the birth of her first child: “They stored [the sperm], and [the doctor] wasn’t going to let me back on the program” (Wilson, 1992, p. 4). The woman’s claim is for damages on nine counts of medical negligence against the doctor, together with punitive damages on the basis that the doctor “showed a contumelious (insolent), arrogant and wanton disregard for the [woman] and [her] health” (Wilson, 1992, p. 4). The woman’s affidavit filed in the court said, amongst other matters, that she was “informed by [the doctor] there had been a terrible mistake . . . I was told by [the doctor] to have an abortion. [The doctor] stated I would not be able to pass off as my own a Spanish- Egyptian child” (Wilson. 1992, p. 4). The woman went on to state, in court: Reproductive and Genetic Engineering: Journal of International Feminist Analysis Volume 5 Number 3, 1992 I didn’t create any waves. I realised at that time when the mistake was made there was a lot of controversy, there was a lot of publicity, there were ethics committees being formed, and I guess [the doctor] knew that if I spoke out then obviously it would put the program in danger, and that was virtually what I had been threatened with. (Wilson, 1992, p. 4) She underwent the abortion 6 weeks after her pregnancy was confirmed, and has since given birth to two sons following donor insemination at the center. Nonetheless, she says, the abortion “has continued to haunt her, and she suffered from stress and anxiety and has undergone psychiatric counselling as a result” (Wilson, 1992, p. 4). In court, the woman referred to the doctor “virtually [telling] me that I had to have an abortion, that if I sued [the hospital] the publicity would be all over Australia, my name would be in every newspaper, and I would never get back on a program in Australia . . . ” (Wilson, 1992, p. 4). The Infertility Medical Centre running the program involved in the case is based at Epworth Hospital. The doctor concerned has been a consultant to the Donor Insemination Service at the center since 1978. According to Caroline Wilson’s report, in August 1991 the woman received a letter from a man who claimed to be a Roman Catholic priest, accusing her of being “an abortionist and a murderer.” This letter was followed by 10 anonymous phone calls early in 1992. Consequently, in February 1992 the woman called the doctor concerned and told her of her concern for the security of her medical file. The doctor assured her that the file was secure. However, the woman told the court, the letter and the calls “triggered off, obviously, the rebirth of the whole thing again. It has always been in the back of my mind, it’s not something that ever goes away” (Wilson, 1992, p. 4). The alleged sperm mix-up occurred in May 1983. Because it was so long ago, and outside the 6-year limitation-of-actions period, it was necessary to seek leave of the court to issue proceedings and take action under section 23A of the Limitation of Actions Act (1958). Under this act, an argument can be made by a prospective litigant that she can bring the action out of time, because her reasons for not doing so earlier are within the terms of the Act and can be excused. One of the most powerful philosophies underlying IVF and other new reproductive technology programs is that the “right” child should be the outcome of the technology. This ignores the reality that humans, and most specifically women, are at the center of any “successful” outcome of the programs (though are not responsible for the failures of technology). It is from women that the ova come that are used on any program. Without women, there could be no programs. It is women who, by reason of their physiological capacity, nurture and give birth. Without women, there would be no births. Yet the philosophy of the “right” child imports into the programs a notion that it is the technologists, the scientists, and the doctors (and sometimes veterinarians) who “create babies” through their efforts. It also gives rise to a belief, on the part of the women concerned, that they fail if the technology does not produce a child through laboratory failure. Now the woman fails by not being implanted with the “right” embryo, not producing the “right” child. It can hardly be surprising that, sometimes, in IVF programs or artificial insemination programs, something “goes wrong”: that “something” being the injection of the “wrong” sperm into the “right” ovum. (Or, no doubt, the “right” sperm into the “wrong” ovum.) In a very real sense, an important aspect and outcome of these programs is the Reproductive and Genetic Engineering: Journal of International Feminist Analysis Volume 5 Number 3, 1992 creation of confusion as to precisely what is a mother? What is it to be a mother? What is a father? What is it to be a father? Arguments begin to center around the questions: Whose sperm is it? Whose ovum is it?, as if these are the central questions in the “creation” of fatherhood and motherood. While the Women’s Movement works hard to develop a concept and practice of fatherhood that involves social parenting and commitment, the new reproductive technology movement works assiduously to demote the concept and practice of motherhood to the traditional notion of fatherhood: Biological relationship is all. As the Melbourne case is currently before the courts and thus sub judice, it must be put to one side: Because it has not yet been decided, no one is entitled to speculate upon the content of the case or its possible outcome. The totality of the evidence will be revealed in due course, and cannot now be the subject of critical comment. Yet there have been other cases, in other countries, where similar difficulties have arisen. Some years ago in the United States it was reported that a woman, a “client” of an IVF program, had given birth to a black American child. The woman was a white American, as was her husband. There had, it was reported, been an “error” in the selection of sperm for injection into the ovum that was finally transported back into her womb (Rowland, 1992, p. i). “Image bank” is a title given to the place where receptacles store sperm waiting to be injected into an ovum. The stated aim is that the “clients” will be “matched up” to the sperm available: If the “clients” are Caucasian, then the sperm with which they are provided will be Caucasian. More specifically, if Anglo- American (or white Australian), then the sperm should be Anglo-American or white Australian. If the woman does not produce an ovum (or according to medical determination her ova are no “good” enough) and therefore an ovum donor is necessary, the idea is that an ovum (or more often, ova) will be “matched up” to the “client” couple. “Human error” is inevitable: There can be no pretense that never will there be an incorrect “matching up”; a mistake as to which sperm is in what test tube; a “mix-up” of ovum; accidental destruction of sperm or ovum so that a substitute must be found, with attendant possibility for mistakes; wrong labeling; even deliberate “sabotaging”; or perhaps the desire to engage in experimentation, swapping and changing ovum, sperm, and “client” “receptors.” But there is an additional issue here: Built in to the program is confusion. And, we need to ask, is it deliberate or unconscious confusion? The confusion or “unknowing” of doctors and academics is illustrated clearly by two Melbourne professors, one a medical practitioner, the other an ethicist. Both take the position that, if a woman gives birth to a child following the implantation of a fertilized ovum, the ovum having been produced by another woman, the birth mother will not have a “relationship” or not as strong a “relationship” with the child as she would have had, had the originating ovum been from her own body. Professor John Leeton of Melbourne has said: IVF surrogacy [using the commissioning couples’ sperm and ova] is superior to any other surrogacy because the child will be totally theirs genetically – her egg, his sperm – and the risk of the surrogate [sic] mother bonding to the child after that pregnancy is less . . . this is the point that everyone is missing, the vital point. (John Leeton, quoted in Monks, 1989, pp. 12-13) Peter Singer of the Monash Bioethics Center says: The difference is, of course, that the surrogate who receives an IVF embryo has no genetic relationship to the child she Reproductive and Genetic Engineering: Journal of International Feminist Analysis Volume 5 Number 3, 1992 carries. Attachment may still, of course, occur; but it is plausible to suppose that the lasting effects of separation will be less severe when the surrogate has no reason to think of the child as “her” child, but rather as the child “looked after” for nine months of its life. (Monk, 1989, p. 13) Every woman has always had the certainty that the child she bears is “hers.” About that, there can be no mistake. Never could any man be certain beyond doubt that a child was “his.” Even in situations where women have been guarded, tied up in “chastity belts,” kept together in harems and thus presumably out of the presence of men other than the husband, or isolated by other means so to be away from interaction with men other than the husband, a man has never had the same certainty as does a woman that a child is the result of the injection of an ovum by his sperm. IVF and other new reproductive technologies now make this uncertainty real for women, too. Instead of working to create a world where “ownership” of children is not the basis for parenthood, those favoring new reproductive technologies and running the programs appear to have done more than the opposite. They have brought into use a technology, the essence of which is the creation of so-called certainty for men as to their fatherhood of a child: If the ovum is taken out of the body of their wives (or some other woman), and fertilized in vitro by sperm, then they can have control over what sperm is used. The possibility for men thus is (in theory) for as great a certainty as a woman of “parenthood” (defined in these terms). Their position is even more enhanced: Now the woman has an uncertainty she has never experienced before. Yet, ironically, as the American example shows, any aim of scientific certainty for men in the childbirth stakes has not achieved its goal. Even the scientists and medical fraternity have no absolute control or certainty over “fatherhood” defined in this limited (biological) way. Human error in sperm storage and utilization cannot be eliminated. The end result is that men do not have a fail- safe mechanism for determining the biological origins of children to whom their wives give birth. And women have become equally uncertain of whether the ovum that is fertilized by the sperm, then replaced as an embryo back into the uterus, is indeed that self-same ovum removed from the ovaries associated with that particular womb. If the aim of IVF programs is to enable a man to be certain about his paternity, then that goal remains elusive: Uncertainty has been created for both putative father and mother. If, on the contrary, the aim of IVF has been to duplicate for women as parents the uncertainty that men experience (or make women uncertain, men more certain), then on the one hand, the programs have succeeded, at least in the formal sense, while on the other, they have not. The process of developing and nurturing an embryo and fetus, and giving birth to a child, is not solely reliant on an ovum, nor on an ovum injected by sperm. This process requires nurturance, the giving of oxygen, the giving of nutrients, and the growth of the fetus for 9 months. Whether the ovum was produced by the woman in whose womb it is nurtured or not, her body, herself, is directly associated with the development of the child in an extraordinarily intimate way. For women, the confusion as to “whose ovum” is subsumed within the certainty that the ovum is nurtured and brought to term within the body of the particular woman – the childbearer. The developing embryo and fetus is herself. To say, as does Peter Singer, that it is “plausible to suppose that the lasting effects of separation” from a child born from a “foreign” ovum will be “less severe” than when the woman gives birth to a child from her “own” ovum, is to ignore the developmental process that occurs during pregnancy. It is only more “plausible” to those who have no conception of what it is to carry a fetus to term. As Reproductive and Genetic Engineering: Journal of International Feminist Analysis Volume 5 Number 3, 1992 Barbara Katz Rothman points out, for a woman, “bonding” (as it is called by the so- called experts) does not begin for a woman when she holds a child in her arms; rather, the connection between a woman and the fetus begins when the fetus is a part of her body. There is a parallel between IVF and developments in diagnostic technologies employed during pregnancy. Just as IVF and other reproductive technology programs import the idea that a woman can disassociate from a child she bears because it was conceived from an ovum not produced by her body, diagnostic technologies are used to affirm to a woman that the pregnancy is “real” and that the fetus is “normal”: Thus a woman is taught to disassociate from the developing ovum in her body, until she gets the “okay” from a higher authority (the doctor – and his technology) that she has a fetus she can appropriately bring to term. Barbara Katz Rothman writes: A diagnostic technology that pronounces judgements halfway through the pregnancy makes extraordinary demands on the women to separate themselves from the fetus within. Rather than moving from complete attachment through the separation that only just begins at birth, this technology demands that we begin with separation and distancing. Only after an acceptable judgement has been declared, only after the fetus is deemed worthy of keeping, is attachment to begin. Reality has been turned on its head. The pregnancy experience, when viewed with men’s eyes, goes from separation to attachment. The moment of initial separation, birth, has been declared the point of “bonding”, of attachment. As the cord is cut, the most graphic separation image, we now talk of bonding . . . viewed from men’s eyes, the movement of our babies from deep inside our bodies through our genitals and into our arms was called the “introduction” or “presentation” of the baby. Only when we touched our babies with the outside of our bodies were we believed to have touched them at all – using man’s language we say of women who’s babies died or were given away, that they “never touched the baby, never held the baby.” (Katz Rothman, 1986, pp. 114–115) Only a man could say that this is the “point that everyone is missing” (Monk, 1989, 12- 13). Rather, the point that is being missed is that an embryo and fetus are a part of a woman’s body until she gives birth to a child, and that an embryo and fetus grow within a woman’s body, intimately touching the innermost part of her; an embryo and fetus grow as a part of her body, solely as a consequence of her nurturance, her blood supply, and her oxygen supply. The embryo and fetus are an intrinsically incorporated “being” within her own being, a part of her being. What of the possibility of duress or coercion where women are IVF “clients” or “patients”? Women on IVF and other reproductive technology programs do not generally speak publicly about “coercion,” “undue influence,” or “pressure.” Yet, as Renate Klein found in her research involving women who had come off these programs, such coercive factors did play a part. Speaking of the “world view” that it is the woman with the “infertility problem” rather than the man, and which precipitates women into infertility programs and, ultimately, IVF, one woman said: Eventually I told more and more people that it was Norm’s problem because everybody assumed it was my fault and I felt very pressured by their patronizing approach [italics added] to me. (Klein, 1989, p. 13; see also Klein, 1988, pp. 11–13) Reproductive and Genetic Engineering: Journal of International Feminist Analysis Volume 5 Number 3, 1992 Another reported: In retrospect I realized it was a big mistake not to see a therapist before beginning IVF. I wasn’t at all sure whether I had the energy to try again – and to cope again with disappointment. But I felt everyone was pushing me into it . . . gently but steadily [italics added]. . . . my husband, my mother, my best friend, even a girl at work whom I had told about it. I felt really caught [italics added]. . . . When we went to the initial counseling there was no space to say any of this [italics added]. We were given the impression that it was a big privilege to be accepted – and we were – so we had to be grateful. I shut up and began three years of utter misery (Klein, 1989, p. 21) Doctors, too, are involved in coercive tactics, as one woman points out: When I first came with my list of questions, Dr. X patted me on my head and said, “Now don’t you worry your little head off. We know what’s best for you, so if you co- operate and stop worrying you’ll have a good chance [italics added].” Later, however, he stopped being so “nice” and once, when I complained about his assistant being too late for egg pick-up – which means that I had missed my chance that month – he commented sharply. . . . “Doctor’s wives always cause trouble,” and, “You want a child, don’t you? If you do, then give up your job, stop being a problem and co-operate.” So I felt I had to shut up or risk delay on the program [italics added]. (Klein, 1989, p. 39) In the law, originally “coercion” related only to actual violence or threats of violence, either directly or through an agent, to a person entering into a contract. This narrow notion of duress has been expanded to include other forms of pressure, such as economic duress (Starke, Seddon, & Ellinghaus, 1988, p. 317). Whether it will expand further to include duress of the type experienced by women who are “required” by doctors to be compliant and uncomplaining in order to remain in reproductive technology programs is a question not yet answered by the law. For an agreement to be nullified or set aside, a person can show she (or he) has been forced unwillingly into the contract (this is coercion or duress), or that she (or he) has been “only too willing” because one party has taken unconscientious advantage of a position of dominance or ascendency (this is undue influence) (Starke et al., 1988, pp. 318, 323). In Universe Tankships of Monrovia v. International Transport Workers Federation (1983, p. 614) it was said that duress in all its forms requires two elements: o pressure amounting to compulsion of the will of the victim, and o illegitimacy of the pressure exerted. Compulsion means “effective lack of choice which may be evidenced by protest, by lack of independent advice or by resort to legal process, though none of these is essential to prove compulsion” (Starke et al., 1988, p. 319). In Union Bank of Australia Ltd v. White- law (1906, p. 720) “undue influence” was defined as “the improper use of the ascendancy acquired by one person over another for the benefit of himself or someone else, so that the acts of the person influenced are not in the fullest sense of the word his [or her] free, voluntary acts.” Where a confidential relationship exists between the parties, then “the fact that the confidence is reposed in one party either endows him with exceptional authority over the other or imposes upon him the duty to give disinterested advice. The possibility that he may put his own interest uppermost is so obvious that he comes under a duty to prove that he has not abused his position” (Starke et al., 1988, p. 324). Reproductive and Genetic Engineering: Journal of International Feminist Analysis Volume 5 Number 3, 1992 Lena Koch’s Danish research illustrates how doctors can use their position of influence to extract “agreement” from women in IVF programs. Does this fit within the legal standard of “abuse of position”? There can be no doubt that the doctor-patient relationship fits squarely within the legal concept of a confidential relationship with consequent legal implications. Lena Koch writes of a woman who had been in an IVF program and participated in a special experiment carried out in the 1980s: Elizabeth is a woman who basically accepts the idea of IVF technology. But she has trouble when she considers what IVF research and experimentation implies. “I am worried about the experiments. I refuse to think that they experiment on my eggs. I know they fertilized some of my eggs and never transferred them. I don’t want to think that I might have reason to doubt them, and I believe them because of the power and authority they have [italics added]. (Koch, 1989, p. 108) Koch goes on to point out how Elizabeth’s feelings “oscillate between faith and doubt”: “Once you’re in the experiment, you have to have faith in them. We believed in them because we thought we were in their power. The ‘girls’ accepted a lot. Somehow you become dependent on them [italics added].” These women were treated and forced to behave like children: “When I came in to have my hormone levels tested I would ask: “Have I behaved properly since yesterday?” (Koch, 1989, p. 108) Brigitte Oberauer’s example of a woman undergoing “harvesting” of egg cells in an Austrian hospital illustrates the problem of undue influence involved in a confidential relationship of doctor to “patient,” and coercion or duress. She writes: Standing there watching, I . . . experienced the woman’s humiliation. She lay with her legs apart on the chair. Dr. M. sat between her legs and introduced the vaginal scanner. At each follicle puncture he retracted the needle and then drove it in hard – a movement very similar to the act of penetration. All the other students had their eyes fixed on the woman’s genitals. After the fifth follicle had been sucked out, the woman asked him to stop, because she was in great pain. But Dr. M. would have none of that: “There are still such beautiful follicles” and so the sixth and seventh follicles were punctured against her will [italics added]. And again she winced, again each puncture unmistakably resembled a penetration. Finally when all seven follicles were punctured, an eighth black dot appeared. Although she implored him to stop. Dr. M. insisted on continuing. After the puncture it was found that the black bubble was a cyst which was then immediately aspirated [italics added]. (Oberauer, 1989, p. 114) How real is a choice made by women involved in a power relationship in the situation in which they are said to exercise free will, consent, or choice? Wendy Savage acknowledges that birth and power is an issue arousing “strong emotions because birth is a profoundly moving experience for all those who participate in the drama, whether as the person who should be the central point of the whole event, the woman, or the person who should be in a supporting role, the midwife or doctor” (Savage, 1986, p. 175). She goes on: Birth arouses primitive and elemental feelings within us, reawakens unconscious or conscious memories in connection with our own beginnings and those of our siblings. It reminds us of death as well as Reproductive and Genetic Engineering: Journal of International Feminist Analysis Volume 5 Number 3, 1992 life, and the awareness of the tragedies which do still occur is not far from the surface. (Oberauer, 1989, p. 114) For women who are classed as “infertile,” or who effectively are placed in that category as a consequence of their husband’s infertility and resort to IVF and other new reproductive technology programs, the emotions and elemental feelings will be likely to be even more emphasized. Power is never absent in a situation where a woman makes the “choice” to become an IVF “patient.” The “choice” is rationalized in many ways. As Robyn Rowland points out, where a woman denies that she has maternal “feelings” for a child or children born of “surrogacy” where an ovum or ova not hers, biologically, are used, her words effectively reveal another dimension: A powerful example of selfless surrogacy is that of Pat Anthony, the South African grandmother who gave birth to triplets conceived using her daughter’s egg and her son-in-law’s sperm – although she had decided never to have any more children after the difficult birth of her son. At forty- eight, she faced considerable risks, particularly after it was discovered that she was carrying triplets, which were eventually delivered through Caesarian Section. She denied having any maternal feelings for her babies, often described as her grandchildren, saying: “I don’t feel any strong maternal instincts or urges. I am doing this because my daughter, not me, was desperate for children and unhappy because of it.” Ironically, while denying maternal feeling towards the babies, she is the epitome of maternal self-sacrifice with respect to her daughter [italics added]. (Rowland, 1992, p. 177) Doctors and ethicists advocating IVF surrogacy with “foreign” ova may see the words of Pat Antony as supporting their position: Pat Anthony denies feelings for children she has borne, on the stated basis that they are “not hers” – because the ova were not. Yet this again limits the notion of maternal feelings to the narrow dimension often given to paternal feelings: the idea that a father will feel deeply only if he can be sure that the children are “his” (the “result” of his sperm, that is). The question to be asked is whether the mother/ grandmother would have felt no maternal feelings toward the children had they been born not from her womb but from the womb of her daughter. The answer surely is that she would be more likely than not to experience caring, compassionate feelings that we in this world describe as “maternal” or “female” toward the grandchildren born under “normal” circumstances of conception and birth. Why, then, does she state so surely that she has no maternal feelings toward them when they have been born from her own body? The commonsense reality that a child is more than an egg is expressed by Mary Beth Whitehead, now known worldwide as the “surrogate mother” (but more properly the birth mother) of Sara Whitehead: I remember the inseminating doctor telling me that I was giving away an egg. I didn’t give away an egg. They took a baby away from me, not an egg. That was my daughter. That was Sara they took from me. (Klein, 1989, p. 142) It wasn’t until the day I delivered her that I finally understood that I wasn’t giving Betsy Stern her baby. I was giving her my baby. (Klein, 1989, p. 140) Similarly, Deborah Snyder of Michigan says: I was fine. Then I looked down at her – I went to get out of the car to give her to her Reproductive and Genetic Engineering: Journal of International Feminist Analysis Volume 5 Number 3, 1992 parents and I just collapsed, sobbing uncontrollably. I don’t know what did it; I wanted them to have her – I knew I couldn’t raise another baby – but something hit me . . . I wanted to leave first – I didn’t want to watch them drive away with her. I had a week off from work and some times during the day I would start crying for no reason . . . I’m not crying anymore – I still notice babies though and I try to imagine how big she’s getting – I don’t think that will ever stop . . . I made her and I made her life – it was worth it -but I wouldn’t do it again, because I now know how hard it is. (Grossman, cited in Rowland, 1992, p. 189. footnote 84) At the other end of the scale, making the choice not to become involved in IVF and other “treatments” for a condition classed as infertility is difficult. Alison Solomon writes: About a year after I’d started infertility treatment I became involved with the Women’s Movement. Even there I discovered that whenever I brought up the subject of my infertility, there would be a total lack of understanding. I would be told (by women who had children, or had made a conscious decision not to have children) that it shouldn’t be so central to my life. I felt that my feelings and my reality were being denied. Yet I felt that a feminist approach could be helpful to myself and other women and I began to think about the idea of a self-help group for infertile women. When I mentioned the idea to one of the women at the infertility clinic she said she had enough of her life revolving around her infertility without going to a group devoted to it. . . . (Solomon, 1989, p.175) That feminists pose questions about “choice” in the context of new reproductive technology programs leads to charges that feminists see women only as victims, without rational will, helpless, hopeless, and unable to engage in autonomous action. Yet to recognize power differentials is not evidence of a lack of recognition of the power women do have. Nor is it outside the ken of the legal system itself. The law recognizes many situations where people can be manipulated and unfairly dealt with as a consequence of differences in power, and as a result of existing relationships – whether familial, fiduciary, or confidential. The law of contract has developed various principles for recognizing that a person in the less powerful position may be taken advantage of, and “agree” to a contract or to contractual terms that are highly disadvantageous to her or him. “Unconscionable contract” doctrines specifically cover this situation. Statute law, passed by parliaments, has also stepped in to fill gaps where the law developed by the courts does not adequately acknowledge power differentials and the negative consequences they can have upon persons operating in the world as it is. In Australia, for example, laws exist dealing explicitly with consumer credit transactions. These laws acknowledge that an individual consumer can be overwhelmed by the superior knowledge, financial acumen, and economic power of the finance provider – such as a bank or finance house. Consumer credit contracts can be reopened and the courts or tribunals have the jurisdiction to alter the financial arrangements, the terms of the contract, and the relative rights of the parties in any way the court or tribunal considers is necessary to make the arrangement “fair.” The court or tribunal can set aside a contract or mortgage or guarantee completely, absolving the consumer from any further responsibility in relation to it. The matters that can indicate that the consumer has been unfairly dealt with include: o whether or not there was any material inequality in the bargaining powers of the parties; Reproductive and Genetic Engineering: Journal of International Feminist Analysis Volume 5 Number 3, 1992 o whether or not it was reasonably practicable for the consumer to negotiate for the alteration of, or to reject, any of the provisions of the agreement; o whether or not any of the terms of the agreement impose conditions that are unreasonably difficult to comply with, or not reasonably necessary for the legitimate interests of the finance provider; o whether or not the consumer was reasonably able to protect his or her interests; o whether or not, and when, independent legal or other expert advice was obtained by the consumer; o the form of the agreement and the intelligibility of the language in which it is expressed; o whether undue influence, unfair pressure, or unfair tactics were exerted on or used against the consumer by the finance provider or any person acting or purporting or appearing to act for the finance provider or any other party to the agreement; o the conduct of the parties in relation to similar agreements to which any of them has been a party; and o the commercial or other setting, purpose, and effect of the agreement. Anyone who might attempt to suggest that it is “wrong” for consumers to have available to them provisions of the Credit Act (1984) has little credibility. No one is taken seriously who asserts consumers, by reason of the existence of such laws, are being treated as perennial victims, unable to help themselves, hopeless, lacking dignity, and unable to engage in independent negotiations with others, whether individuals or large finance houses and banks. Why, then, when it comes to medical “treatment” such as IVF and its associated programs, should it be persuasive that women ought to be categorized as self-sufficient, in control, and with no right of recognition of differing authority and power? Rather than demanding that women live up to an artificial standard that is not required of others, where questions of choice, consent, and coercion arise, it is important to recognize the social, cultural, and political underpinnings of IVF and other new reproductive technologies. Women are vulnerable to coercion and duress in many of their forms. This vulnerability does not lessen when women take on the “patient” or “client” role in an IVF clinic. It is a vulnerability experienced by all who are in a less powerful position, whether the position of lesser power is dictated by sex, race, minority ethnic background, understanding of the dominant language, class, or economics. Often the vulnerability of women is magnified by the existence of more than one of these factors; that should not be a reason for excluding women from legal recognition of the vulnerability. Women must be wary of arguments that do not take into account the political nature of the world in which we live. We must beware of arguments that attempt to throw back on to women a responsibility that is not demanded of others. Arguments depending for their force solely on the notion that women are possessed of equal power as men, or should see ourselves in that light, are designed to disempower us further. Just as the “personal is political,” women must be ever mindful of the reality that the political is personal. Autonomy for women will not come about because those who have a stake in power differentials as they are assert that women are autonomous and that the choices women make are free of coercion. Credit Act, Parliament of Victoria, Australia (1984). Katz Rothman, Barbara. (1986). The tentative pregnancy: Prenatal diagnosis and the future of motherhood. New York: Penguin. Reproductive and Genetic Engineering: Journal of International Feminist Analysis Volume 5 Number 3, 1992 Klein, Renate. (1988). The exploitation of a desire: Women’s experiences with in vitro fertilization. Geelong, Victoria, Australia: Deakin University, Women’s Studies Summer Institute. Klein, Renate D. (1989). Infertility: Women speak out. London: Pandora. Koch, Lena. (1989). We are not just eggs but human beings. In Renate D. Klein (Ed.), Infertility: Women speak out (pp. 101–110), London: Pandora. Limitation of Actions Act, Parliament of Victoria, Australia (1958). Monks, John. (1989, September 15). “I’ll have your surrogate baby”: Twins’ amazing pact. New Idea, p. 8. Oberauer, Brigitte. (1989). Baby making in Austria. In Renate D. Klein (Ed.), Infertility: Women speak out (pp. 111–120). London: Pandora. Rowland, Robyn. (1992). Living laboratories: Women and reproductive technologies. Sydney, Australia: Sun/Pan Macmillan. Savage, Wendy. (1986). A Savage enquiry: Who controls childbirth?. London: Virago. Solomon, Alison. (1980). Infertility as crisis. In Renate D. Klein (Ed.), Infertility: Women speak out (pp. 169-187). London: Pandora. Starke, Joseph G., Seddon, Nicholas C., & Ellinghaus, M. Paul. (1988). Cheshire & Fifoot’s law of contract (5th ed.). Sydney, Australia: Butterworths. Union Bank of Australia Ltd v. Whitelaw, Vic. 720 (1906). Universe Tankships of Monrovia v. International Transport Workers Federation, 2 All England Law Reports 614 (1983). Wilson, Caroline. (1992, May 31). Doctor forced abortion: Woman. Sunday Age (Melbourne), pp. 1,
https://www.techylib.com/el/view/mustardnimble/reproductive_and_genetic_engineering_journal_of_..._finrrage
CC-MAIN-2018-17
refinedweb
6,549
57
This is your resource to discuss support topics with your peers, and learn from each other. 12-03-2010 01:57 PM Hey Everyone, I was stuck with a small formatting problem when it comes to qnx.ui.listClasses. I'm using a qnx list container to display items from an RSS feed into a list. However, some of the comments and text blocks being fed from the RSS feed into the list are long and the containers width is not long enough to show the whole message, which makes the message disappear at the list border. I was wondering if there is a way to format the content being fed into the list to start on a new line within the container as soon as it hits the edge, so it doesn't disappear at the border. Any help is appreciated. Thank you! Solved! Go to Solution. 12-03-2010 02:08 PM One more thing - I was also wondering if it is possible to clear the dataprovider contents fed into a list(text content). 12-03-2010 02:42 PM Try: mycontrol.dataProvider.removeAll(); 12-03-2010 06:53 PM - edited 12-03-2010 06:56 PM hey jimmy, the only thing that comes to mind is make a custom cellrenderer class and modify the look of each row in the list. once you are in the cellrenderer class you can wrap each of the text in a Label class and set a width to match the width of the list and then set each of their properites for wordWrap to true. Edit #1: Also i just want to make a note that you should look for the functions onAdded and onRemoved if you want to directly edit each of the rows of the list from your custom cell renderer class. here is a link to something me and jtegen were working on a couple of weeks ago in regards to cellrenderes: it deals with the dropdowncellrenderer but its the same concept. good luck! 12-04-2010 01:20 AM Thanks so much Jrab, as well as John! Jrab that post you and John made on cellrenderers is going to help me big time, so I appreciate it! John I did try the .dataProvider.removeAll(); function to get rid of text within the list, however that did not work. I was thinking I might have luck if I used a loop to delete text within the list while length > 0. I am also going to try the onAdded and onRemoved functions. I'll post my progress if I make any. Thanks again! 12-04-2010 01:45 AM hey jimmy, no problem at all! now in regards to removing all items from your list. try to invoke the removeAll() method on your list object. this should clear your list. for example: (...) listOfThings = new List(); (...) listOfThings.dataProvider = dp; (...) listOfThings.removeAll(); (...) the reason why when u invoke the method on the actual dataprovider object it doesnt work is because when you set the dataprovider on your list object it takes just the values of hte dataprovider versus taking the entire object as a reference. so when you do something to dataprovider object it does not effect the list's dataprovider property. so try it out and see how it goes. good luck! 12-06-2010 03:48 PM hey JRab, Thanks for the suggestion. I tried it out, however that did not work. What I did though is I set the dataprovider value to null when I wanted the list cleared. example: (Where content is the array dataprovider) content = null; content = new Array(); I made this call each time I needed to populate the list with new content. Thank you for the suggestions though - your help is always appreciated! 12-06-2010 03:54 PM hey Jimmy, thanks for the kudo! but i dont understand why it didnt work.. guess practice beats theory huh? hah. im gonna have to test this out and see. thanks for the update though ill let u know what i find. 12-06-2010 03:58 PM Ya I was surprised it didn't work as well. I'm guessing it has something to do with the fact that the list I was populating consisted of dynamic items. Not entirely sure though. Let me know if it ends up working for you, ty. 12-06-2010 04:12 PM hey Jimmy, so i ran the following program: package { import flash.display.Sprite; import flash.display.StageAlign; import flash.display.StageScaleMode; import flash.events.MouseEvent; import qnx.ui.buttons.LabelButton; import qnx.ui.data.DataProvider; import qnx.ui.listClasses.AlternatingCellRenderer; import qnx.ui.listClasses.List; import qnx.ui.listClasses.ListSelectionMode; [SWF(width="1024", height="600", backgroundColor="#CCCCCC", frameRate="30")] public class RandomTests extends Sprite { private var myList:List; private var dp:Array; private var myBtn:LabelButton; public function RandomTests() { myList = new List(); dp = new Array(); for (var i:int = 0; i < 10; i++) { dp.push({label: "Test Item " + i}); } myList.dataProvider = new DataProvider(dp); myList.width = 200; myList.height = 500; myList.selectionMode = ListSelectionMode.SINGLE; addChild(myList); myBtn = new LabelButton(); myBtn.label = "Click Me To Clear"; myBtn.setPosition(250, 0); myBtn.addEventListener(MouseEvent.CLICK, clearList); addChild(myBtn); } public function clearList(e:MouseEvent):void { myList.removeAll(); dp.splice(0); for (var i:int = 0; i < 10; i++) { dp.push({label: "New Test Item " + i}); } myList.dataProvider = new DataProvider(dp); } } } so it first populates a list of ten items and presents the orginal list. then you click on the clear button and it clears the list and re-populates the list with new items. so it works on my end. maybe you are populating your list differently like u said?
https://supportforums.blackberry.com/t5/Adobe-AIR-Development/Format-large-text-blocks-to-fit-qnx-list/m-p/664699
CC-MAIN-2016-44
refinedweb
951
75.4
This short tutorial will show you how to sort lists in Python. Several different sorting techniques will be shown: including basic, natural, case insensitive, alphabetically. Data used in this article: import calendar days = list(calendar.day_name) the unsorted list is: ['Friday', 'Monday', 'Saturday', 'Sunday', 'Thursday', 'Tuesday', 'Wednesday'] 1. Python sort list alphabetically with .sort() Here's how you can sort a list alphabetically with Python. We are going to use method sort(): days.sort() days result: ['Friday', 'Monday', 'Saturday', 'Sunday', 'Thursday', 'Tuesday', 'Wednesday'] Note that this method works on the data structure. No need to assign a new variable . Default sorting is ascending. In order to change the order parameter reverse can be used: days.sort(reverse=True) days result: ['Wednesday', 'Tuesday', 'Thursday', 'Sunday', 'Saturday', 'Monday', 'Friday'] 2. Python sort list alphabetically with sorted() To sort a list in Python without changing the list itself - use sorted(). sorted(days) result: ['Friday', 'Monday', 'Saturday', 'Sunday', 'Thursday', 'Tuesday', 'Wednesday'] But the list itself is unchanged: days result: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] 3. Python natural sort of list Natural sort is closer to human perception for order. Let's illustrate it with a simple example of days. Let's have a list of days: days = ['day5', 'Day1', 'day7', 'DAY9', 'day10', 'day_11'] Using the previous sorting methods will give result: ['DAY9', 'Day1', 'day10', 'day5', 'day7', 'day_11'] which is not what is the natural order of the days. As a human I would expect: ['Day1', 'day5', 'day7', 'DAY9', 'day10', 'day_11'] In order to achieve this we can use the Python package: natsort. Method natsorted will be used in combination with parameters: key or alg: from natsort import natsorted, ns natsorted(days, key=lambda y: y.lower()) You can change the algorithm by parameter alg: natsorted(days, alg=ns.IGNORECASE) which will produce the same output. If no parameter is used: natsorted(days) output: ['DAY9', 'Day1', 'day5', 'day7', 'day10', 'day_11']
https://blog.softhints.com/how-to-sort-list-in-python-3-examples/
CC-MAIN-2021-25
refinedweb
317
57.67
In Haskell, there is a datastructure called Maybe. Maybe is used where you would often use null pointers in languages such as C# or Python. Python doesn't have null pointers as such, but it does have the None object, which in many cases has the same kind of patterns and problems associated with it. Haskell needs Maybe because no data types are nullable -- unless you are writing code that interfaces to C, you never have the possibility of a null pointer. Here is a brief explanation why Haskell's Maybe is infinitely better than null pointers. First, a word about Maybe. It is defined, at its most basical level, something like this in Haskell: data Maybe a = Nothing | Just a deriving (Eq, Ord, Show, Read) On the left hand side, a stands for any type. This definition means that a variable x which is, for example, of the type Maybe String is either Nothing or a Just y, where y is the actual string. To work out which it is, we normally use pattern matching, or a utility function that uses pattern matching -- but either way, we can't use variable x as if it was a string, we have to explicitly unpack it. This might seem laborious, especially when in other languages you get 'nullability' for free for most variables. A few examples will highlight why Haskell's way is much better. (By the way, the deriving clause tells the compiler to automatically generate methods for Maybe for testing equality, ordering, printing as a string and reading from a string). Now, onto our examples. Suppose you have a function that is like the lookup function of a dictionary -- it takes a key, and may or may not return a value. I'll use 'K' or 'k' for the type of the key. In C# 2.0, using generics, the function signature might look something like this: interface ILookup<K, V> { V GetItem(K key); } The idea is that GetItem() will return a null if the item isn't found -- this is a typical in languages like C#, whereas Python would probably throw a KeyError. (In both languages, we might do foo[key] rather than foo.GetItem(key), which can be done easily in either). A more functional implementation (but less idiomatic) would be to use delegates. We would require a declaration like this: delegate V Lookup<K, V>(K key); In Haskell, the function would be typed like this: lookup :: (Eq k) => k -> Maybe v Haskell already beats both Python and C# for the following reasons: - The fact that the nullability is explicit in the signature means that you can't forget that there is a possibility the object is 'null'. Even if you do forget, the compiler won't. So all those NullPointerExceptions? You can say goodbye to them forever. If you have ever seen a NullPointerException (or NoneType object has no attribute 'blah' in python), and I'm sure we all have, then you have all the evidence you need that programmers, even good ones, do forget to do these checks. - Even better than not producing NullPointerExceptions etc. is the fact that you can forget about whether a certain function can return null or not. The compiler will always catch it for you, so you are free to concentrate on the programming. This is a different point -- the first means you aren't producing programs that will ever crash with this error, the second means that as you are actually programming, you have less things in your mind to distract you, so you can keep your registers full with things you need. But let's make things more interesting. First, let's say our dictionary is caching results of potentially expensive database queries. So, the key might be the SQL query string, and the value could be objects of various kinds. In this case, Nothing is a valid value that the dictionary might hold -- it means we have done the search already and found nothing. The 'lookup' function in this case would return Just Nothing. But what about the C#/Python versions? There is nothing to stop us putting a null value in against a certain key, but when we do the lookup, a null pointer or None object could now either mean 'we already did the search and we found nothing', or 'we haven't done the search'. Let's add another level. Suppose we are searching for a value in the database that is held in a column that can actually be NULL. For example, we might be doing a search for Mrs Jones's age, and come back with the result that, although we do actually have a record for Mrs Jones, we don't have a value for her age. In the C# version, we are really in trouble now. We have 3 possible meanings for 'null', with no way to tell them apart. In Python, we could solve this either by throwing different types of exceptions (as we could in C#), or by additional null objects -- in Python there is nothing to stop you creating singleton null objects and assigning them to any variable. We can then check for identity against these null objects to cope with our various errors. Our Python solution suffers some limitations -- both exceptions and additional null objects will give us headaches if we try to serialise and resurrect them (None will resurrect OK, but for other singleton null objects you need a significantly more sophisticated mechanism than the ones normally used -- try it). But we also have to remember to document and handle all the possibilities. And when it comes to writing generic code that can easily be reused and combined in novel ways, our hacks will get in the way. We could decide to use a tuple to return (success_boolean, actual_value_or_None) at one or more levels, but this would be seen as unpythonic when the vast majority of code out there will either throw exceptions or return None. By contrast, Haskell's Maybe mechanism is a breath of fresh air. You can just wrap as many layers of Maybe as you need. Our 'lookup' function would not need modifying, but would in fact be returning an object of type Just (Just (Just Int)). This could be: - Nothing, meaning we haven't got a cached result for the search, - Just Nothing to mean we have done the search, but not found a record for Mrs Jones at all, - Just (Just Nothing) to indicate we have already done the search, and the result was the database doesn't know the age of Mrs Jones, - or Just (Just (Just 43)), if Mrs Jones is 43 years old. We won't get confused with all these levels -- for a start, each bit of code that adds or removes a Maybe wrapper is likely to only deal with one layer. But the compiler will catch it for us anyway if we make a mistake. Furthermore, we don't have to learn various different ways to cope with null -- we only have one, and we can be sure that our code won't need hacks to keep it working in different scenarios. And, to add some icing to the cake, Maybe has been written as an instance of a Monad. We all know the common pattern in code that is basically "if the value I get at this point is null, then return null from this function". Using Maybe as a monad, we can eliminate a lot of that kind of stuff -- the monad encapsulates this pattern for us. Sometimes it will be clearer to explicitly check for Nothing or Just x, but often you will be able avoid doing that. Using monad notation what you effectively do is write a number of functions that are bound together using the 'bind' method of Monads (though these functions look more like imperative statements in monad notation). The Maybe version of 'bind' knows to abandon ship as soon as it gets a Nothing, and just return Nothing. Of course, this way of doing things is just as type-safe, but it just allows us to avoid some of the explicit null handling. In conclusion: this is one instance of Haskell's wonderfully designed type system. If languages like C#, C++, Java etc have put you off static typing, Haskell might be able to change your mind.
http://lukeplant.me.uk/blog/posts/null-pointers-vs-none-vs-maybe/
CC-MAIN-2014-35
refinedweb
1,403
66.37
In this section you'll find the API Reference for the Instant Games JavaScript SDK. If you're starting a new game, we recommend always using our latest version of the SDK. Click the button below to see the SDK reference for our most up-to-date version:Instant Games SDK ReferenceBundle Configuration Reference Leaderboard.getConnectedPlayerEntriesAsync()API, which fetches the score entries of the current player's connected players from the leaderboard. ConnectedPlayerConnected Player objects have been updated. They no longer have an 'id' property. Instead, they now provide the following properties: PlatformWe're introducing a new platform type - "MOBILE_WEB". While a mobile web player is not publicly available yet, it will use this platform type when released. Games should ensure that controls are properly set for this platform type in order to provide the best experience for all players. Custom Update TemplatesCalls to FBInstant.updateAsync() to send a custom update must now populate a "template" field with the id of the custom update type that is being sent, as defined in the game's Bundle Config file (). Context Choose Options- IN PROGRESS We're adding support for optional filters on FBInstant.chooseAsync() that will affect the set of contexts that we suggest to the player. The client implementations are still in progress, but developers may integrate these options into their games now. The initial set of supported options are: FBInstant.getSupportedAPIs()Provides a list of the SDK APIs that are supported by the client. Useful for only surfacing functionality that is available to the game. FBInstant.player.flushDataAsync()Immediately flushes any queued changes to the player data. Player data is normally persisted in the background, so this provides a way to explicitly know whether a change has been persisted or not. FBInstant.context.createAsync(playerID)Allows the game to specify a player that the active player should enter into a context with. The specified player must be a connected player of the active player. IMMEDIATE CLEARClears any pending update (such as those set by the "LAST" strategy). This is mainly useful when the game needs to send an important update, but has a pending update that is less valuable and should be cleared in order to prioritize the new update. FBInstant.updateAsync()Now we accept a parameter "notification" on CustomUpdatePayload to allow developers to explicitly set whether or not the update should trigger a push notification. See documentation for updateAsync for details. (Removed) FBInstant.game.setScore() We are now providing a flexible platform that allows the developer to keep a customizable leaderboard using their own backend. (Removed) FBInstant.takeScreenshotAsync() and FBInstant.sendScreenshotAsync() With the new flexible platform, sharing is not limited to a screenshot but can be any image. Replaced by FBInstant.shareAsync(). (Removed) FBInstant.endGameAsync() Replaced by FBInstant.quit() which yields control back to the player. (Removed) FBInstant.abort() Replaced by FBInstant.quit() which handles any exit conditions. (New) FBInstant.quit() Yields control back to the Facebook Messenger UI. Used when the game should exit or is an unrecoverable error state. (New) FBInstant.updateAsync() Sends a fully customizable message into a Messenger conversation. (New) FBInstant.getEntryPointData() Allows to get a generic data blob sent with the update message (New) FBInstant.onPause() Allows developer to set a handler for when the game is interrupted (e.g., app switch, phone call) (New) FBInstant.player.getConnectedPlayersAsync() Retrieves the IDs of players who are connected to the current player, either as a Facebook friend or as a Messenger contact. Only players who also play the Instant Game are returned. (New) FBInstant.context.chooseAsync() Presents the user an interface to change the current game context (e.g. to change Messenger threads). (New) FBInstant.context.switchAsync() Switches to an arbitrary context ID (e.g. to switch to a specific Messenger thread based on a known context ID). (New) FBInstant.shareAsync() Displays a share dialog for the user to share game content to their friends. (New) FBInstant.setSessionData() Allows the developer to set a custom payload for the current session in a particular context. May be used to populate bot webhooks. (New) FBInstant.logEvent() Logs an event to Facebook Analytics (New) FBInstant.context.getType() Returns the type of the context from where the game is being played. (Breaking change) public API properties updated to functions We have updated all our public API properties like FBInstant.locale to functions like FBInstant.getLocale(). This future-proofs the SDK interfaces for backward compatibility. These functions are all synchronous and return immediately. (New) FBInstant.player.getName(): FBInstant.player.getName returns localized display name of the current player. (New) FBInstant.player.getPhoto(): FBInstant.player.getPhoto returns a URL to the profile photo of the current player. (Update) FBInstant.takeScreenshotAsync(): It used to be FBInstant.takeScreenshot and is renamed to FBInstant.takeScreenshotAsync which returns a promise. The promise will reject if we failed to take a screenshot. (Update) FBInstant.sendScreenshotAsync(): It used to be FBInstant.sendScreenshot and is renamed to FBInstant.sendScreenshotAsync which returns a promise. The promise will reject if the image is not valid. (New) Context Identifier FBInstant.context.id Provides context about where the player started the match from. It's a unique identifier for Messenger Threads or Newsfeed Stories depending on where the game was started from. (New) Key-value storage FBInstant.player.getDataAsync and FBInstant.player.setDataAsync allow you to save information from the player on Facebook's backend. (Update) FBInstant.locale: It's now returning the actual locale for the user, instead of the default test value 'en_US' (Update) FBInstant.player.id: It's now coming from our backend, so should work across all apps and devices for the same user. Methods renaming: Previously we had namespaces for specific calls, now we are including the domain for these calls in the method names themselves. Some methods were also renamed to improve expressiveness. This effort resulted in the following renames: FBInstant.loading.setProgress()is now FBInstant.setLoadingProgress() FBInstant.loading.complete()is now FBInstant.startGameAsync() FBInstant.game.setScore()is now FBInstant.setScore() FBInstant.game.asyncYieldControl()is now FBInstant.endGameAsync() FBInstant.media.takeScreenshot()is now FBInstant.takeScreenshot() FBInstant.media.sendPicture()is now FBInstant.sendScreenshot() FBInstant.system.abort()is now FBInstant.abort() (New) Initialization: Added the method FBInstant.initializeAsync() that should return a promise that, when fulfilled, will set the correct information on the global object. In addition to that, the promise returned by FBInstant.startGameAsync() will only be resolved when the player actually starts to play. So by using this API, it's not necessary to have a "Tap to start" behavior on the game itself (New) Platform information: Added the FBInstant.platform property, that once initialized will be populated with one of 3 values: 'iOS', 'android' or 'web' (New) Locale information: Added the FBInstant.locale property, that once initialized will be populated with the user's locale code. (New) Player Id information: Added the FBInstant.player.id property, that once initialized will be populated with the player's anonymous id. Removed unimplemented methods: All methods previously tagged with [Not Implemented] have been removed. They will be re-added once implemented. Included API Versioning on SDK file name: This file is now accessible via fbinstant.1.0.js. Newer releases will always have the version appended to the filename. fbinstant.js will keep at its current version and not evolve. The latest version will always be available at fbinstant.latest.js, although it's not recommended to point to that path directly, as breaking changes might land there.
https://developers.facebook.com/docs/games/instant-games/sdk/
CC-MAIN-2018-26
refinedweb
1,240
51.44
longjmp (3p) PROLOGThis manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux. NAMElongjmp — non-local goto SYNOPSIS #include <setjmp.h> void longjmp(jmp_buf env, int val); DESCRIPTIONThe functionality described on this reference page is aligned with the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of POSIX.1‐2008 defers to the ISO C standard.: - * - They are local to the function containing the corresponding setjmp() invocation. - * - They do not have volatile-qualified type. - * - They are changed between the setjmp() invocation and longjmp() call.
https://readtheman.io/pages/3p/longjmp
CC-MAIN-2019-18
refinedweb
123
51.24
Help:Style (正體中文) 以下的風格規範鼓勵人們使用整潔、組織化且視覺效果一致的文章呈現方式。請在編輯ArchWiki的時候遵守這些規範。 Contents - 1 文章頁面 - 1.1 標題 - 1.2 格式呈現 - 1.3 特殊功能關鍵字 - 1.4 文章分類 - 1.5 跨語言連結 - 1.6 顯示文章狀態之樣板 - 1.7 相關文章 - 1.8 前言/簡介 - 1.9 章節標題 - 1.10 格式化程式碼 - 1.11 命令列文字 - 1.12 File editing requests - 1.13 Keyboard keys - 1.14 Package management instructions - 1.15 systemd units operations - 1.16 Notes, Warnings, Tips - 1.17 Shells - 1.18 Hypertext metaphor - 1.19 Coding style - 1.20 Supported kernel versions - 1.21 "Tips and tricks" sections - 1.22 "Troubleshooting" sections - 1.23 "Known issues" sections - 1.24 "See also" sections - 1.25 Non-pertinent content - 1.26 Language register - 2 分類頁面 - 3 重新導向頁面 - 4 使用者頁面 - 5 普遍原則 文章頁面 標題 - 文章標題應該要根據sentence case的風格規範,比方說"Title for new page"是正確的,而"Title for New Page"是錯誤的風格。若有一般的單詞是專有名詞或是縮寫的一部分則應該以大寫呈現字首,如ALSA應該是"Advanced Linux Sound Architecture"而不是"Advanced Linux sound architecture"。命名空間不是標題的一部分,因此"ArchWiki:Example article"是正確的,而"ArchWiki:example article"是錯誤的呈現方式。子頁面的名稱應該要以大寫字母開始,正確的例子是"My page/My subpage",而"My page/my subpage"則不對。 - 一個標題名稱應該要是單數的形式;在特殊的情況下,需要表示群體或是不同類別的可數名詞時,才需要表示成為複數形式。 - 若有一篇文章的主題其名稱與縮寫都廣為人知,則在這裡偏好使用全名作為該文章的標題。請勿在標題同時使用全名與縮寫(比方說將縮寫放在後製括弧之中),而是應當編輯一個以縮寫為名稱的重新導向頁面,並讓該頁面指向以全名為標題的主頁面。 - 參照Help:Article naming guidelines以了解為文章命名的原則。 格式呈現 - 請在一篇文章中,依照順序呈現如下項目: 特殊功能關鍵字 - 一般來說,特殊功能關鍵字會改變文章的顯示方式,但不改變文章的內容。這類的功能應該要放置在文章頂端。 這個規則尤其應該使用在 {{DISPLAYTITLE:title}}的功能,以及小寫樣板,因為後者使用了前者的功能。 文章分類 - 每篇文章都應該至少歸屬於一種既定的分類 - 一篇文章可以屬於多於一種的分類,只要那些分類之中沒有直接的上下階層的關係。 - 分類與第一行文字內容之間不應該有空白行(或是跨語言連結),因為這樣會導致文章頂端額外的空間浪費。 - 詳情請參考Help:Category文章。 跨語言連結 - 若是文章具有其他語言版本(無論是ArchWiki內部或外部連結),跨語言連結應該要緊接在文章分類之後,且在首行文字之前。 且需注意的是,這些跨語言連結在實際的呈現上會出現在頁面左方的窗格之中。 - 在跨語言連結與首行文字之間不應該有空白行,否則會導致文章頂端的額外空間浪費。 - 當在新增或編輯跨語言連結時,應該要在所有已經存在的翻譯版本也新增或修改那些連結。 - 請勿為了同一種語言的文章新增超過一個跨語言連結。 - 請勿在某種語言的文章新增其自身的跨語言連結。 - 跨語言連結應該要以語言標籤的字母順序排序,如 [[fi:Title]]應該要在 [[fr:Title]]之前。 - 詳情請參考Help:i18n及Wikipedia:Help:Interlanguage links等文章。 顯示文章狀態之樣板 - 文章狀態樣板可以緊接在分類的下方(或跨語言連結的下方),而且在文章介紹(或是相關文章)之上。 - 視情況,文章狀態樣板也可以用在文章內的章節。 - 在加入文章狀態樣板時,請在適當的地方加入說明。若是需要的話,請在討論頁面直接發起討論。 相關文章 - 提供簡明的內部文章列表。 - 若要提供相關文章欄位,它應該位在文章分類(或是跨語言連結、文章狀態)之後。 - 詳情請參照並使用以下樣板:Template:Related articles start、Template:Related以及Template:Related articles end。 - 非英語文章可以使用這個樣板轉換對應的文章。 - 若要提供更詳細的參考文章,請善用"See also"章節。 前言/簡介 - 描述文章的主題。 比起自行撰寫可能帶有偏差的描述,你可以使用該專案社群或作者對該專案的描述。MediaTomb就是一個例子。 - 位在文章的第一個章節之前。 - 請勿額外編輯 ==Introduction==或 ==Preface==的章節,因為簡介與目錄都會自動出現在第一個章節之前。 - 請參照Help:Writing article introductions以取得更多資訊。 章節標題 - 文章內的章節層級必須從第二級( ==)開始,因為第一級已經被文章標題所保留。 - 創建章節次標題時,請勿跳級。 - 標題的大小寫規則依照句子的寫法,比方說不是全字首大寫My New Heading,而應該是My new heading。 - 避免在標題使用超連結,因為這樣會產生不一致的排版風格。應該改用以下方式呈現: - - 基於一樣的理由,請勿在標題使用HTML或wiki特有的效果,包括排版樣板。請參照Help:Style/Formatting and punctuation。 - 請參照Help:Effective use of headers以取得更多資訊。 格式化程式碼 - 對於短短數行的程式碼、檔案名稱、指令名稱、變數名稱與一些可在文章中穿插使用的文字,使用 {{ic|code}}語法標示。舉例而言,你可以使用這個寫法: 在命令列中執行 sh ./hello_world.sh - 若要將程式碼或指令表示在獨立區塊之中,可以將那些指令部份的開頭加上一個空白,請參考Help:Editing#Code的內容。舉例而言: $ sh ./hello_world.sh Hello World - 對於多行的程式碼或檔案等文字內容,可以使用 {{bc|code}}樣板,以將之呈現在獨立區塊之中,舉例而言: #!/bin/sh # Demo echo "Hello World" - 想要呈現命令列輸入與輸出的時候,使用 {{hc|input|output}}樣板。舉例而言: $ sh ./hello_world.sh Hello World - 想要呈現檔案內容且需要展示檔案名稱時,使用 {{hc|filename|content}}樣板,例為: ~/hello_world.sh #!/bin/sh # Demo echo "Hello World" - 對於整個區塊的程式碼或檔案,請僅顯示相關的重點,不相關的則以( ...)省略不相關的內容。 - 參考Help:Template以獲得更多資訊,以及關於排版相關議題的的疑難排解,如 =或 |。 命令列文字 - 需要在內文引用程式碼時,不應加入命令列符號,但櫻明確描述相對應指令所需要的權限。 - 當使用程式碼區塊(或以空白格開頭的程式碼)時,應使用 $示意為一般使用者之命令列,而 #為root之命令列。需注意 #符號在文字檔中也代表註解的形式,請避免混淆的情況出現(這可以透過額外的說明「執行指令」或「寫入檔案」的情況)。 - 使用程式碼區塊之前的文字敘述應以冒號結尾。 - 除非有其必要,否則描述特權指令時,偏好使用: # command而非: $ sudo command - 請勿將root命令列與sudo指令混用,如: # sudo command唯一的例外是指定使用者功能( sudo -u),這個情況下必須符合同一個程式碼區塊中的其他指令用法,或是單純採用 $命令列指示字元。 - 請勿在同一個程式碼區塊添加註解。 - 請避免撰寫太長的程式碼;必要時當使用適當的斷行。 - 請勿假設使用者使用sudo或是其他取得特權指令如gksu或kdesu。 File editing requests - Do not assume a specific text editor (nano, vim, emacs, etc.) when requesting text file edits, except when necessary. - Do not use implicit commands to request text file edits, unless strictly necessary. For example, $ echo -e "clear\nreset" >> ~/.bash_logoutshould be: - Append the following lines to ~/.bash_logout: clear reset - Where it might be helpful, a link to Help:Reading#Append, add, create, edit can be added.. - Examples of pacman commands are nonetheless accepted and even recommended in the Beginners' guide. -, for example {]]. - Examples of systemctl commands are nonetheless accepted and even recommended in the Beginners' guide.. -. - Only link to a new article after creating it. In general, do not create links to non-existent articles. - For technical terms, such as system call, not covered by an article in the ArchWiki, link to the relevant Wikipedia page. - When linking to other articles of the wiki, do not use full URLs; take advantage of the special syntax for internal links: [[Wiki Article]]. This will also let the wiki engine keep track of the internal links, hence facilitating maintenance. See Help:Editing#Links for in-depth information and more advanced uses of interwiki links syntax. - Avoid implicit links whenever possible. For example, prefer instructions like "See the systemd article for more information" instead of "See here for more information". - Except in rare cases, you should not leave an article as a dead-end page (an article that does not link to any other) or an orphan page (an article that is not linked to. -. Supported kernel versions - Do not remove any notes or adaptations regarding kernel versions greater than or equal to the minimum version between the current linux-lts package in the core repository and the kernel on the latest installation media. "Tips and tricks" sections - Tips and tricks sections provide advanced tips or examples of using the software. - Use the standard title of Tips and tricks. - The various tips and tricks should be organized in subsections. "Troubleshooting" sections - Troubleshooting sections are used for frequently asked questions regarding the software or for solutions to common problems (compare to #"Known issues" sections). - Use the standard title of Troubleshooting. Common misspellings that should be avoided are Trouble shooting, Trouble-shooting, and TroubleShooting. - cleanup easier by reducing the effort involved in researching whether the reported bug is still an issue; this can even lead to greater autonomy if the reader finds new information and comes back to edit the wiki. "Known issues" sections - Known issues sections are used for known bugs or usage problems which do not have a solution yet (compare to #"Troubleshooting" sections). - Use the standard title of Known issues. - If a bug report exists for the known issue, it is very desirable that you provide a link to it; otherwise, if it does not exist, you should report it yourself, thus increasing the chances that the bug will be fixed. "See also" sections - See also sections contain a list of links to references and sources of additional information. - This should be a list where each entry is started with *, which creates a MediaWiki bulleted list. - Use the standard title of See also. Other similar titles such as. - Uploading files is disabled for normal users, and including the existing images in articles is not allowed. As an alternative you can include links to external images or galleries, and if you need to draw simple diagrams you may use an ASCII editor like Asciiflow.. 分類頁面 - Every category must be appropriately categorized under at least one parent category, except for root categories, which are); they should be in the plural form if the singular form can be used to describe one of its members ("set" categories). 重新導向頁面 - Redirect pages should contain only the redirect code and nothing else. In rare cases, they can also contain a flag such as Template:Deletion. - Redirect only to internal articles; do not use interwiki redirections. - Redirects using interlanguage links are exceptionally allowed in accordance with Help:I18n and upon authorization from the ArchWiki:Maintenance Team. 使用者頁面 - Pages in the User namespace cannot be categorized. - Pages in the User namespace can only be linked from other pages in the User or talk namespaces, unless authorization to do otherwise is given by Administrators. 普遍原則 Edit summary See ArchWiki:Contributing#The 3 fundamental rules. - Usage of HTML tags is generally discouraged: always prefer using wiki markup.
https://wiki.archlinux.org/index.php?title=Help:Style_(%E6%AD%A3%E9%AB%94%E4%B8%AD%E6%96%87)&oldid=409340
CC-MAIN-2019-30
refinedweb
1,154
50.23
Conor MacNeill wrote: > > On Tuesday, July 9, 2002, at 06:54 , Nicola Ken Barozzi wrote: > >> Who needs the proposal implementations? >> We can put that stuff in the Ant1 codebase. > > Really? I am interested to see that. :-) > > Ant1 is bit of a mess, really. I tried to give some pointer to this in > my Mutant doco. > > For example, You have suggested <import> for an include function (BTW > why not use <include> or <include-project>?). Well, more than suggested. There is a working patch in bugzilla. Why not include or include-project? Dunno, there's no reason, call it smurf, it ok for me as long as it smurf well ;-) > In 1.6 Stefan will enable top level tasks. > > But, if someone has their own <import> task, they can't use it at the > top level since you will effectively introduce a new keyword to Ant. > Mutant tries to solve this problem by using a namespace for this sort of > metadata. I believe Myrmidon uses a task for <include> although there > are issues with that approach which I'm not sure how they have addressed. Is mutant based on Ant or a complete rewrite? Because in the first case, it maybe can have pieces put into Ant progressively... I'll look into the code again, it's a while since I did it. >? >>> Again, my issue is that there doesn't *seem* to be a drive toward the >>> user requirements >>> ( ), other >>> than luck... >> >> >> Not really. >> The proposals try to make the requirements real. >> Ant1 codebase tries to assimilate as much as possible without >> snaturating. > > > Let me give an analogy. You live in the leaning tower of Pisa and you > see your neighbours are adding rooftop pools to their building. They > look pretty cool but putting one on your roof may leave you a little wet > :-) ;-P My impression is that my building can still get features till it resembles the neighbours'. But then, the neighbours can make theirs better still, while I can't. Only then I decide to use their building, now that I'm accustomed to living in something like>
http://mail-archives.apache.org/mod_mbox/ant-dev/200207.mbox/%3C3D2ACC93.4070904@apache.org%3E
CC-MAIN-2016-22
refinedweb
350
74.69
Row. Locking Your Models Since you're building your web application with Django it's most likely that you are using Django ORM to access database. However, in order to be able to perform locking queries we will have to write SQL queries ourselves. Which is much easier than you might think (unless you need some complex join across million tables). Assuming you have Article model you acquire row level lock as follows: article = Article.objects.raw("SELECT * FROM articles WHERE id = 123 FOR UPDATE")[0] When running the above query an instance of your Django web application will remain blocked until the instance that acquired the lock first releases it or lock wait timeout occurs. One thing to note here is that locking will only work if your code is executing inside of a transaction. Ultimately, you want to have something like this: from django.db import transaction from MySQLdb import OperationalError def hack_article(article): # Some magical code that does something with the article. pass @transaction.commit_on_success def function(): try: article = Article.objects.raw("SELECT * FROM articles WHERE id = 123 " "FOR UPDATE")[0] except IndexError: # Handle not found return except OperationalError: # Handle lock timeouts return hack_article(article) The write lock will get released once the transaction is committed or aborted, in the above case this happens once we leave the function. There is actually one case (maybe there are more, let me know if I am wrong) where the lock can get released before the transaction is committed or aborted -- when a new transaction is started inside of another transaction. So, the above example would be prone to race conditions if our hack_article function looked like this: @transaction.commit_on_success def hack_article(article): # Some magical code that does something with the article. pass The reason for this is that locks don't propagate through nested transactions in MySQL. Wrapping up Achieving row level locks in Django is simple: - Make sure that your tables use InnoDB engine. - Acquire locks inside of transaction. - Make sure that you are not creating new transactions inside of another transaction which holds the lock. That's all. Hut for macOS Design and prototype web APIs and services.
http://vilkeliskis.com/articles/row-level-locking-in-django
CC-MAIN-2017-26
refinedweb
361
52.09
Hello, Just a quick question If i got a class that implements ActionListener and it does my event handling for my textfields and stuff. How do i write my focusListener within my ActionListener class? I have already created a seperated class for my focusListener however i want to combined them into one class I've been scratching my head for a few hours. and i'm just stump. My program does what i want but i just want it in one neat file =(. i thought it be easy and be something like this? but i honestly don't know the grammar for implementing stuff. Quote: public class name implements ActionListener, FocusListener{ }
http://www.javaprogrammingforums.com/%20java-theory-questions/7350-actionlistener-focuslistener-same-class-printingthethread.html
CC-MAIN-2014-15
refinedweb
111
66.23
Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video. Git-ing Up and Running15:55 with Gabe Nadel Time to put your money where your mouth is! Let's use what we've learned about Git and Github in a live Xcode project. We'll cover: creating repos, making commits, exploring GitHub and pulling changes. - 0:00 Welcome back, it's time to put what we've learned about Git to use. - 0:03 In this video we'll take the basic steps to get you off and running with Git for - 0:07 your own projects, as well as share projects. - 0:10 As I mentioned before, there's much more to explore with Git and - 0:13 I've linked some of those resources below. - 0:15 For now, we'll tackle the basics by setting up a GitHub account. - 0:20 Creating a new repo, adding our new Xcode project, making commits, - 0:24 exploring GitHub, and pulling changes. - 0:28 In the next video, we'll use a different account to access our repo to show how - 0:32 this process looks from a collaborative perspective. - 0:35 When we do this will demonstrate how we, create a new branch, make commits, - 0:39 merge our branches, and resolve conflicts. - 0:43 So for starters, let's create a GitHub account. - 0:46 Some of you may already have one, but just in case, let's walk through that. - 0:50 We'll head to github.com, and we'll wanna pick a username. - 0:55 You'll want that to be something relatively professional as potential - 0:58 employers and teammates will be seeing it. - 1:00 I'll create one here. - 1:17 Then we'll choose our plan. - 1:20 As you can see, having public repositories, - 1:22 unlimited repositories in fact, is free. - 1:25 You can also get private repos too as per this chart here but - 1:28 we'll just go with free for now. - 1:30 By the way, the term private just means they aren't open to the public. - 1:34 Private repos can still be shared with others but only by invitation. - 1:39 Okay, there we go. - 1:40 We now have a GitHub account. - 1:42 Now we'll set up a repo here. - 1:46 But it looks like we need to verify our email address. - 1:48 I'll go do that offline and be back in a second. - 1:51 All, right we're back. - 1:54 We verified, so we can click on that button again to create our new repo. - 1:57 Okay, we'll enter a repo name. - 2:00 And we can make that, gitDemo, TH for treehouse. - 2:08 The description is optional but we'll add one. - 2:16 We're gonna leave it as public. - 2:18 We won't initialize this with a README but - 2:20 that is a good thing to do on a real project. - 2:23 And we'll create it. - 2:25 Okay, now on this page we see a few ways that we can get going with our repo. - 2:30 We can do a quick set up here and that's what we're going to do. - 2:33 I'm gonna copy this link right now. - 2:36 We could create a new repo on the command line, push an existing repository, or - 2:40 import code from another repo. - 2:43 Were not gonna talk about these two but - 2:44 let's talk about the command line just for a second. - 2:48 Using git via the command line or terminal on your Mac is a very common way to go. - 2:53 Many devs do much of their gitting via terminal and as you can see here, - 2:57 the commands you would use are pretty familiar, even already. - 3:00 Stuff like commit and push. - 3:02 Now, you don't have to use the command line for this stuff. - 3:05 But as you move forward, you may find yourself in situations where you'll be - 3:08 tackling an issue and the solution really requires you to. - 3:12 Don't be afraid when that happens. - 3:13 It's something you'll need to get comfy with eventually anyway. - 3:17 If you're really itchy to get acquainted with git from the command line, - 3:20 I've linked a comprehensive Treehouse course on git below. - 3:22 Which covers that, as well as a whole lot more about git. - 3:26 So we've got our link here, and we're gonna open up Xcode in a second. - 3:30 But before we do, I wanna make sure that this machine is configured correctly. - 3:36 It's a shared machine, and you might not need to do this at home, but - 3:39 it's a good thing to know. - 3:41 So we will go to the command line briefly and - 3:43 we're gonna type in the following command. - 3:49 And I'll put in my new username. - 3:55 We'll type in one more with my email. - 4:08 Okay, let's open up Xcode and - 4:12 we'll create a new project. - 4:16 We're gonna make that a single view, And we'll call it getDemoTH. - 4:24 We're gonna make it a Swift project, click Next. - 4:28 Now we have a choice, and we want this checked. - 4:31 Create Git repository on My Mac. - 4:34 Now note, doing this will just create a local Git repo. - 4:37 Remember, Git is the system that can track all our commits, branches, and the like. - 4:41 You can simply use Git locally if you want. - 4:43 But GitHub, the hosted service, will allow you to share your project very easily and - 4:48 we'll set that up in a minute. - 4:53 First, let's make a couple small changes to our project. - 4:57 We can hop into the storyboard. - 5:01 And let's change our background color. - 5:07 Let's make it, I don't know, dark gray. - 5:12 Then we'll jump into our ViewController and - 5:15 let's create ourselves just a little string constant here. - 5:19 We'll say let userName = "dummyUser". - 5:29 Now we aren't actually gonna do anything with this code, really. - 5:32 I just need to make some changes so we can commit them. - 5:35 Speaking of which, let's do just that. - 5:37 To commit you, go to Source Control and then Commit. - 5:43 As we can see now, in the left panel, there are a few files containing changes. - 5:49 The two we've seen are the storyboard changes, and here in ViewController.swift. - 5:55 These changes are happening just by virtue of us opening up the project. - 5:59 Let's look in Main.storyboard first. - 6:02 Now, this code probably looks a little cryptic to you. - 6:05 But if we scroll around, you're gonna see that we've got the backgroundColor here. - 6:12 And that's in this tinted area. - 6:16 Now, the tinted area joined by an oval bar here indicates that there's been a change. - 6:22 All the plain white area here is unchanged. - 6:25 In looking at the two panels, - 6:26 we see on our left, we've got the Local Revision that's AKA, - 6:31 the project containing the changes we just made but haven't yet committed. - 6:35 And on the right we have the previous committed state, - 6:38 which in our case is just what the project was when it was first created. - 6:43 If we head over to the ViewController file, - 6:46 we see the line with our string constant is highlighted. - 6:49 If we click on the little oval bar in the middle, we see we can choose not - 6:54 to commit it or we can discard the change if we feel like it. - 6:58 We won't do that now but you may want to someday, so - 7:01 it's good to know about that option. - 7:03 Sometimes you'll make a lots of changes to a file and - 7:05 then at commit time you realize you have some extra stuff hanging around. - 7:08 And this is a good chance to get rid of it before committing it. - 7:12 If you wanna cherry pick just a few of the files to commit, - 7:15 you can use these check boxes, on the left. - 7:20 Now down here, we need to enter a commit message. - 7:22 Let's say changed bgColor and - 7:28 added constant. - 7:35 Now it's worth mentioning that very often they'll be lots of changes in - 7:39 a single commit. - 7:39 So you wouldn't give it this level of detail, - 7:42 you'd more wanna describe the feature that you're working on or something like that. - 7:47 If you're addressing a bug, you might wanna insert the bug number. - 7:50 And if it's a large feature, perhaps the feature and - 7:52 what specific changes you made. - 7:53 But usually you aren't gonna wanna list individual constants or - 7:57 color changes like that. - 7:59 Now down here, we see a grayed out check box where we could push to remote. - 8:04 But, alas, no remote is available. - 8:06 That's because we haven't yet told Xcode about our GitHub repo. - 8:10 Let's commit our changes to the local repo, and - 8:12 then we'll work on hooking up the remote repo. - 8:17 But before we do that, - 8:18 let's look at a couple quick things to illustrate what's happening. - 8:22 First, let's just try to commit again. - 8:27 If we do, we see an empty pane. - 8:30 There are no new changes to commit. - 8:31 Even if we try typing something in here, our button is still gonna be grayed out. - 8:37 Now that's a good thing, - 8:38 Xcode won't let us commit since we haven't changed anything. - 8:42 Next, let's look at the menu again. - 8:45 And where it says hm, getDemo, I guess I misspelled that. - 8:49 Says getDemoTH- Master, that indicates we're working on the primary or - 8:55 master branch of this repository. - 8:58 Which, of course, is the only branch we have so far. - 9:01 Okay, now let's hook up that remote repo. - 9:03 To do that we also stay in the Source Control menu, and - 9:08 we're gonna go down here Configure getDemoTH. - 9:12 We go to Remotes > Add a remote. - 9:17 Paste in our link from before and Add Remote. - 9:21 And there we go, we can click Done. - 9:25 Now just for fun, let's look at GitHub. - 9:30 We'll refresh this, hm, it still looks the same. - 9:34 Why don't I see any commits here? - 9:37 Anyone, anyone? - 9:39 Well, we did commit it but we committed it locally and we never pushed it. - 9:45 Back inside Xcode we can do that pretty easily. - 9:47 Again we'll go to the Source Control menu and we're gonna push. - 9:53 It's gonna push the local changes to the master branch on the origin. - 9:58 And because we haven't created that on the origin yet, it's gonna create it for us. - 10:13 There we go, push successful. - 10:16 Now let's head back to GitHub, We'll hit refresh and, ooh, very nice! - 10:25 Some very familiar stuff here. - 10:27 We've got our file structure and the commit messages we entered a moment ago. - 10:32 Now, just to be clear, all this visiting of GitHub is just to illustrate the point. - 10:35 You don't actually have to check this stuff, Xcode has taken care of that. - 10:39 But I wanted to show you what's happening behind the scenes. - 10:42 So here we can see that we're viewing the master branch, which for - 10:45 now is the only branch we have. - 10:47 And we can see that in the dropdown. - 10:49 If we had other branches, they'd be listed down here. - 10:53 If we look at these folders, we see some commit messages. - 10:56 Two of them have the message we entered, and then two of them say Initial Commit. - 11:02 Well, that's because of these folders, - 11:04 not all of them had contents that were changed. - 11:07 So they'll display the commit message from their last committed change, - 11:10 which in the case of these two, was the initial set up. - 11:13 It It may not seem obvious, but this actually points to a powerful feature. - 11:18 You see, our remote repo not only has captured the state of our project now, - 11:23 as in when we created the remote or when we pushed to the remote. - 11:27 But it has the history before that. - 11:30 This isn't all that important since we haven't really done much. - 11:33 But imagine you create a local project with a local Git repo. - 11:37 You work on it offline for a few days, maybe even a few weeks. - 11:40 Maybe you're on a trip and you don't have Internet access. - 11:43 Once you finally do set up your remote repo, the entire history will be included. - 11:48 Similarly, when you join someone else's project, - 11:51 you'll have access to the commits that occurred before you joined. - 11:55 So there is a lot you can do on GitHub. - 11:57 Much more than we'll go into now. - 11:59 So I encourage you to view their tutorials and docs, but - 12:01 we'll touch on a few while we're here. - 12:04 First of all, you can navigate into the files as they exist now. - 12:08 If we head to our ViewController file, - 12:14 We can see that constant that we created here. - 12:18 Now, often you may have done some committing or pushing or merging or - 12:21 something else in Xcode or via the command line. - 12:24 And looking here in GitHub is a good way to see what actually made its way to - 12:28 the remote. - 12:28 By the way, I don't mean to insinuate that working with a command line or - 12:32 GitHub Isn't reliable, but at times you or a collaborator may commit but - 12:36 forget to push or something like that. - 12:38 And this is a good way to peep behind the curtain and - 12:40 figure out what has happened really easily. - 12:42 You'll also notice that up here, we could - 12:47 open this file in GitHub Desktop which is a utility you can download for Mac. - 12:52 You could edit the file right here, which isn't something you do all that often but - 12:55 we will just for fun in a minute, or you could delete it. - 12:58 So let's edit this. - 13:01 And we'll call this "dummyUserChanged". - 13:05 You scroll down and we say, the commit message could be, dummy user updated. - 13:12 And we'll commit it, oops, didn't put the right commit message but that's okay. - 13:16 By the way, it's worth mentioning that, if your commit message is getting too long, - 13:21 you can enter a longer commit description. - 13:23 Which might be useful to someone who may come back and look at your code months or - 13:27 years from now. - 13:28 It's like leaving bread crumbs and it's very helpful to other developers. - 13:31 You may be that developer one day and you'll certainly appreciate it. - 13:35 Now if we go back to the main page, - 13:39 we can see that now we have three commits up here. - 13:43 There used to just be two. - 13:45 If we click on them, We can see we have our initial commit, - 13:50 the one we made in Xcod,e and the one we made just now. - 13:54 Off to the right, we see two links for each commit, these are really important. - 14:00 Clicking the left button, this cryptic ID, will show us the changes that were made. - 14:06 Here we see a- sign signifying the line that was replaced and - 14:10 a + sign with the new line. - 14:12 Now of course, I didn't actually delete this part, let userName =. - 14:15 I just typed in the word change but - 14:17 this is how it shows us this line has been replaced with this line. - 14:22 If we head back to that list of commits, And click on the set - 14:27 of angle brackets over here, we can browse the repository at this point in history. - 14:32 Now that's our most recent commit, it doesn't seem all that exciting. - 14:36 But if you wanted to browse an old version of a project, - 14:40 especially a really big project, this could be really, really helpful. - 14:47 Remember in the last video we talked about how our cowboy coder added a feature, - 14:51 then deleted it, then the client wanted it back? - 14:54 Well, by viewing the state of our project at a past commit, we could hunt through - 14:58 the files, find the code we need, and pop it back into our project. - 15:01 Even if it's been completely deleted since. - 15:04 All right, let's head back to Xcode. - 15:08 Well, here we see we still have this old value for the constant. - 15:12 How would we get the new stuff from our remote branch? - 15:15 Well, we simply need to pull. - 15:17 We head up to Source Control and we Pull. - 15:25 And look at that, it updates right before our eyes. - 15:27 Now the same thing, of course, would have happened if a collaborator on a project - 15:30 had changed that and pushed it to remote. - 15:33 Wel,l if you don't think that's impressive now, maybe you will one day - 15:36 when you're pulling dozens or even hundreds of complex changes. - 15:40 Maybe made by several collaborators and it somehow just works. - 15:44 We've come to a nice stopping place but we aren't done yet. - 15:48 We haven't seen how to create a new branch and merge changes. - 15:51 In our next video, we'll wrap up the workshop by doing just that. - 15:54 See you real soon.
https://teamtreehouse.com/library/giting-up-and-running
CC-MAIN-2018-17
refinedweb
3,292
90.39
Bootstrap custom class during Jboss startupAnil Mathew Mar 1, 2011 9:27 PM Hi, We have a application running on Jboss 5.1 and I was wondering is there a way i can update the Jboss configuration to include a Java class so that it will get picked during the Jboss startup process (similar to bootstrap). Note that my Java class will be calling EJB methods as a part of process. Any thoughts? Thanks Anil Mathew 1. Bootstrap custom class during Jboss startupAnders Welen Mar 1, 2011 9:47 PM (in response to Anil Mathew) You could implement it in a JBoss lifecycle MBean (use it's startup callbacks). Put in it's own jar file togheter with a dependecies towards the jars that contains the EJB it will call. 2. Re: Bootstrap custom class during Jboss startupAnders Welen Mar 1, 2011 9:53 PM (in response to Anders Welen) Perhaps a simpler way is to use the @Singleton (or @Service in JBoss 5) and the standard callback annotations like @PostConstruct. 3. Bootstrap custom class during Jboss startupAnil Mathew Mar 2, 2011 2:59 AM (in response to Anders Welen) Thank you for sharing your thoughts. Yes, @Service along with @PostConstruct should work. But I really can't find the jar which has the @Service annotation. Like i said i am using Jboss 5.1. Does the jar comes with the Jboss 5.1? Thanks Anil Mathew 4. Bootstrap custom class during Jboss startupjaikiran pai Mar 2, 2011 3:04 AM (in response to Anil Mathew) @org.jboss.ejb3.annotation.Service comes in jboss-ejb3-ext-api.jar which you can find in JBOSS_HOME/client folder. And by the way, be sure to use our latest EJB3 plugin against JBoss AS 5.1.0 since there have been some @Service related fixes after JBoss AS 5.1.0 was released. 5. Bootstrap custom class during Jboss startupAnil Mathew Mar 2, 2011 10:01 PM (in response to jaikiran pai) Thank You Jaikiran. I was able to get the jboss-ejb3-ext-api.jar and also I created a class which has @Service and @PostConstruct. As you suggested i also ran the plugin (and I could see it ran correctly - which was really Awesome!). As expected the PostConstruct method is called during the Jboss startup (whowhoo..i was so excited). But when i updated my @PostConstruct method to call a EJB method to get records, it is failing with the below error: 17:46:27,511 ERROR [ServiceContainer] Encountered an error in start of PropertyRegistryServiceImpl java.lang.RuntimeException: javax.ejb.EJBTransactionRequiredException: public java.util.Collection com.tixx.persistence.properties.manager.impl.ApplicationPropertyManagerImpl.findAllApplicationProperties() at org.jboss.ejb3.interceptors.container.AbstractContainer.invokeCallback(AbstractContainer.java:262) at org.jboss.ejb3.EJBContainer.invokeCallback(EJBContainer.java:1161) at org.jboss.ejb3.EJBContainer.invokePostConstruct(EJBContainer.java:1170) at org.jboss.ejb3.service.ServiceContainer.lockedStart(ServiceContainer.java:265) at org.jboss.ejb3.EJBContainer.start(EJBContainer.java:905) at org.jboss.ejb3.service.ServiceContainer.start(ServiceContainer.java:846) It seems like the transaction (EntityManager) is null. I am using EJB3 with Hibernate. Below is my code snippet: @Service @Remote( { com.tickets.service.properties.PropertyRegistryServiceRemote.class }) @TransactionAttribute(TransactionAttributeType.REQUIRED) public class PropertyRegistryServiceImpl implements PropertyRegistryServiceRemote{ @EJB EntityManager entityManager; @PostConstruct public void applicationStartup() { System.out.println("Jboss Properties Initializing!!!!!"); try{ Collection<ApplicationProperty> props = this.entityManager.findAllApplicationProperties(AppContextHolder.getUserContext()); }catch(Throwable e){ System.out.println("Jboss Properties Initializing ERROR: "+ e); } } } Any idea what am i missing here? 6. Bootstrap custom class during Jboss startupAles Justin Mar 3, 2011 4:58 AM (in response to Anil Mathew) @EJB EntityManager entityManager; Shouldn't this be @PersistenceContext? 7. Bootstrap custom class during Jboss startupAnil Mathew Mar 3, 2011 3:14 PM (in response to Ales Justin) Thanks Ales for the reply. I was stupid and it was a code mix up and entityManager was the issue and i got ALL working yesterday night!!!! A wrap up of what I did to make it work: - Created a class with @Service and @Remote annotation. - The class has a method with @PostConstruct annotation and this method will call a EJB (via Hibernate) and get all my records (property name/values) from database. - Make sure to have jboss-ejb3-ext-api.jar and run the necessary plugin as mentioned by Jaikiran. Thank You all. I AM IN LOVE WITH JBOSS 5.1 Anil 8. Bootstrap custom class during Jboss startupjaikiran pai Mar 4, 2011 2:38 AM (in response to Anil Mathew) Good to know it's working! 9. Bootstrap custom class during Jboss startupAnil Mathew Mar 4, 2011 5:22 PM (in response to jaikiran pai) Thank you for the support. I do have a question in regards to the plugin which i ran for the Jboss 5.1. I was wondering what exactly does it do when i run the plugin? I mean are we adding new jar files to different directory under Jboss home? The reason i asked is i will have to do the same to my QA / Production environment. I am little hesistant to run this directory in production. Anil Mathew 10. Bootstrap custom class during Jboss startupjaikiran pai Mar 4, 2011 11:45 PM (in response to Anil Mathew) Anil Mathew wrote: I was wondering what exactly does it do when i run the plugin? I mean are we adding new jar files to different directory under Jboss home? The plugin replaces some of the JBoss EJB3 implementation jars with new ones containing bug fixes.
https://developer.jboss.org/thread/163385
CC-MAIN-2018-13
refinedweb
912
50.12
Add Full-Text Search to your Django project with Whoosh Whoosh is a pure-python full-text indexing and searching library. Whoosh was opensourced recently and makes it easy to add a fulltext search to your site without any external services like Lucene or Solr for example. Whoosh is pretty flexible, but to keep it simple let's assume that the index is stored in settings.WHOOSH_INDEX (which should be a path on the filesystem) and that our application is a Wiki and we want to search the Wiki pages. Indexing Documents Before we can query the index we have to make sure that the documents are indexed properly and automatically. It doesn't matter if you put the following code into a new app or an existing app. You only have to make sure, that it lives in a file, which is loaded by Django when the process starts, resonable places would be the __init__.py or the models.py file (or any file imported in those of course) in any app. The following code listing is interrupted by short explanaitions but should be saved into one file: import os from django.db.models import signals from django.conf import settings from whoosh import store, fields, index from rcs.wiki.models import WikiPage WHOOSH_SCHEMA = fields.Schema(title=fields.TEXT(stored=True), content=fields.TEXT, url=fields.ID(stored=True, unique=True)) At the top of the file a Schema is defined. The Schema tells Whoosh what data should go into the index and how it should be organized. In this example every indexed document is stored as three fields by whoosh: title: A title of the document is stored in the index. content: Content is the content of the document, Whoosh will not store the whole content in the index but will only use the data to build it's index. url: To make it easier to uniquely identify a document in the index and to link to the document on the search result pages without fetching the document from the database I decided to store the url to the document in the index. def create_index(sender=None, **kwargs): if not os.path.exists(settings.WHOOSH_INDEX): os.mkdir(settings.WHOOSH_INDEX) storage = store.FileStorage(settings.WHOOSH_INDEX) ix = index.Index(storage, schema=WHOOSH_SCHEMA, create=True) signals.post_syncdb.connect(create_index) To make sure the index, which is stored on the filesystem, is available the function create_index is called by Django's post_syncdb signal and creates the index if it is not already present. This method uses the Schema defined earlier. def update_index(sender, instance, created, **kwargs): storage = store.FileStorage(settings.WHOOSH_INDEX) ix = index.Index(storage, schema=WHOOSH_SCHEMA) writer = ix.writer() if created: writer.add_document(title=unicode(instance), content=instance.content, url=unicode(instance.get_absolute_url())) writer.commit() else: writer.update_document(title=unicode(instance), content=instance.content, url=unicode(instance.get_absolute_url())) writer.commit() signals.post_save.connect(update_index, sender=WikiPage) To make sure the index is automatically updated everytime a page on the Wiki changes, the function update_index is called whenever a WikiPage object sends the post_save signal via Django's signal framework. If the instance was created it is added as a new document to the index and if it was edited (but existed before) the entry in the index is updated. The document is identified in the index by it's unique URL. Query the Index At this point we have made sure, that Whoosh will always keep an up-to-date index of our WikiPage pages. The next step is to create a view, which allows querying the index. A single view and a template is all we need to let users search the index. The template contains a simple form: <form action="" method="get"> <input type="text" id="id_q" name="q" value="{{ query|default_if_none:"" }}" /> <input type="submit" value="{% trans "Search" %}"/> </form> By setting method to GET and action to an empty string we tell the browsesr to submit the form to the current URL with the value of the input field (named q) appended to the url as a querystring. A search for the term "Django" will result in a request like this: I've also added the parsed query back to the search form while displaying the results. Therefore the user-experience is further improved, because the user can now easily edit the query and submit it again. If you have a special search page (instead of a search box on every page) you might also consider giving focus to the input field to save the user an extra click. If you don't use a JavaScript framework a very simple solution would be to use the onload attribute of the body tag: <body onload="document.getElementById('id_q').focus();"> Now lets have a look at the view-code which handles the requests: from django.conf import settings from django.views.generic.simple import direct_to_template from whoosh import index, store, fields from whoosh.qparser import QueryParser from somwhere import WHOOSH_SCHEMA def search(request): """ Simple search view, which accepts search queries via url, like google. Use something like ?q=this+is+the+serch+term """ storage = store.FileStorage(settings.WHOOSH_INDEX) ix = index.Index(storage, schema=WHOOSH_SCHEMA) hits = [] query = request.GET.get('q', None) if query is not None and query != u"": # Whoosh don't understands '+' or '-' but we can replace # them with 'AND' and 'NOT'. query = query.replace('+', ' AND ').replace(' -', ' NOT ') parser = QueryParser("content", schema=ix.schema) try: qry = parser.parse(query) except: # don't show the user weird errors only because we don't # understand the query. # parser.parse("") would return None qry = None if qry is not None: searcher = ix.searcher() hits = searcher.search(qry) return direct_to_template(request, 'search.html', {'query': query, 'hits': hits}) The view imports the previously defined WHOOSH_SCHEMA and gets the index location from the settings. Most of the clutter is only there to improve the user-experience by tranforming some chars found in search queries into their Whoosh equivalents and by catching all exceptions raised by the Whoosh QueryParser. Displaying the search results in the template is pretty straight-forward: {% if hits %} <ul> {% for hit in hits %} <li><a href="{{ hit.url }}">{{ hit.title }}</a></li> {% endfor %} </ul> {% endif %} Conclusion With Whoosh and not more than 100 Lines of code (including the template) it is possible to add full-text search capabilities to your Django project. I've already added the code above to two projects and I'm pretty impressed by the ease of use and the performance of Whoosh. The result is that I can now make my Django powered sites a bit more awesome by adding full-text search (if applicable) and the best is: at ~100 LOC it comes almost for free. Related Projects For a different approach to add Whoosh to your Django project you might also want to have a look at django-whoosh by Eric Florenzano which is available on GitHub. Django-Whoosh is basically a Manager which is added to your objects and will take care of indexing and lets you fetch objects by querying the Whoosh index. The idea is clever but only works if you want to edit the Model classes to add the manager. My approach is completely based on signals and will therefore work with any reuseable app without editing the app itself. Another app which combines Whoosh and Django is djoosh, also available on GitHub but it seems as if it's not finished at the moment. Djoosh aims to provide a mechanism which allows registering of Models with the Indexing infrastructure in a similar way as contrib.admin does. Hi Arne, nice article. Thanks for this! Kai Geschrieben von Kai Diefenbach 8 Minuten nach Veröffentlichung des Blog-Eintrags am 17. März 2009, 10:11. Antworten Very cool stuff! I really like your approach, as it's explicit and exact. My approach was literally just a few hours of experimentation, so I wouldn't recommend it for anyone to use in production :) Geschrieben von Eric Florenzano 9 Minuten nach Veröffentlichung des Blog-Eintrags am 17. März 2009, 10:12. Antworten Thanks a lot, that is exactly what I was looking for! Do you know if there are options to handle accents and upper/lowercase? I mean, I'd like to search "héhé" and retrieve documents with "héhe", "hehe", "Hehe" and so on. Geschrieben von David, biologeek 2 Stunden, 20 Minuten nach Veröffentlichung des Blog-Eintrags am 17. März 2009, 12:23. Antworten Hi David, I think this is currently not implemented in Whoosh, but you may want to ask on the official Mailinglist: Additionally, this thread might be related to your question: Geschrieben von Arne Brodowski 2 Stunden, 24 Minuten nach Veröffentlichung des Blog-Eintrags am 17. März 2009, 12:27. Antworten Arne, thanks for this guide! I like this approach so much that I'm going to be implementing this on my own blog soon. I really appreciate the info, and I've passed this post along through Twitter under my 'adoleo' account. Thanks! Geschrieben von Brandon Konkle 7 Stunden, 47 Minuten nach Veröffentlichung des Blog-Eintrags am 17. März 2009, 17:50. Antworten Lots of neat stuff being done with Whoosh nowadays, it was just added as a backend for <a href="">django-haystack</a> which is a fork of djangosearch. Geschrieben von huxley 1 Monat nach Veröffentlichung des Blog-Eintrags am 19. April 2009, 00:58. Antworten Can someone help with the proper url pattern for the search view? I've tired a couple with no luck. Geschrieben von Nate 3 Monate, 1 Woche nach Veröffentlichung des Blog-Eintrags am 24. Juni 2009, 04:19. Antworten And if I want to search to be available on all pages in the masthead? Geschrieben von nate 3 Monate, 1 Woche nach Veröffentlichung des Blog-Eintrags am 24. Juni 2009, 04:34. Antworten that's right. Just point the form at /search/ and you can search from every page. The form can be plain html, no need to include a django form object in your master-template, just make sure that the field names are the same as on the form class. Geschrieben von Arne 3 Monate, 1 Woche nach Veröffentlichung des Blog-Eintrags am 24. Juni 2009, 13:55. Antworten Vielen Dank Arne! Geschrieben von Sergej 1 Jahr, 3 Monate nach Veröffentlichung des Blog-Eintrags am 5. Juli 2010, 18:53. Antworten hello arne, thanks ! i#ve read yor article. i like this one and im going to be implementing it. ill be sure our webmaster can do this for us. thanks for this! Geschrieben von Lena Smirnova 1 Jahr, 11 Monate nach Veröffentlichung des Blog-Eintrags am 20. Feb. 2011, 18:30. Antworten Danke, whoosh und django rocks Geschrieben von programy 2 Jahre, 1 Monat nach Veröffentlichung des Blog-Eintrags am 11. Mai 2011, 19:17. Antworten
http://www.arnebrodowski.de/blog/add-full-text-search-to-your-django-project-with-whoosh.html
CC-MAIN-2017-17
refinedweb
1,805
65.52
Write Twice, Run Anywhere Pages: 1, 2, 3 Let's start by setting up the basic framework. To help you keep track of where we're heading, when we're finished, the directory structure will look like this. Directory structure for basic framework. Create the first version of the MacJMenuBar. This just puts appropriately labeled JMenus into the JMenuBar. MacJMenuBar package MacGUI; import javax.swing.JMenuBar; import javax.swing.JMenu; public class MacJMenuBar extends JMenuBar{ public MacJMenuBar(){ add(new JMenu("File")); add(new JMenu("Edit")); add(new JMenu("Format")); add(new JMenu("Window")); add(new JMenu("Help")); } } The code for the WindowsJMenuBar is the same except for the labels for some of the JMenus. WindowsJMenuBar package WindowsGUI; import javax.swing.JMenuBar; import javax.swing.JMenu; public class WindowsJMenuBar extends JMenuBar{ public WindowsJMenuBar(){ add(new JMenu("File")); add(new JMenu("Edit")); add(new JMenu("View")); add(new JMenu("Insert")); add(new JMenu("Format")); add(new JMenu("Help")); } } Now we'll create the MainFrame class. This is a JFrame that contains the main() method for this application and chooses the correct JMenuBar for the current operating system. Other than add a name to the title bar and adjust the size of the JFrame, the constructor includes the key call to the method getCorrectMenuBar(). main() getCorrectMenuBar() In this method we check to see if we are running on a Mac by checking the value of the System property mrj.version. Note that this is the method recommended by Apple. This value is only set on the Mac so if it isn't null, we know our application is running on a Mac and can create the Mac version of the JMenuBar. Otherwise we'll create the Windows version. Incidentally, the initial version of Java shipping on Jaguar has this property set to 3.3. Here's the first version of the MainFrame class. mrj.version MainFrame import javax.swing.JMenuBar; import javax.swing.JFrame; import MacGUI.MacJMenuBar; import WindowsGUI.WindowsJMenuBar; public class MainFrame extends JFrame{ public MainFrame(){ super("Write Twice Run Anywhere"); setJMenuBar(getCorrectMenuBar()); setSize(400,400); setVisible(true); } private JMenuBar getCorrectMenuBar(){ if (System.getProperty("mrj.version")!=null){ return new MacJMenuBar(); } else return new WindowsJMenuBar(); } public static void main(String [] args){ new MainFrame(); } } Compile and run this program and you'll see this menu bar. Close, but no prize. The menu bar still isn't in the right place. Arrrrgh, that's not right. The menu bar isn't in the right place. It's inside of the JFrame not up in the system menu bar spot where it belongs. We need to set a system property. We can do that when we run the application, but let's go ahead a put it in the code. If we discover that the application is running on a Mac, we'll set the system property to display the JMenuBar in the correct location. Here's the revised version of the getCorrectMenuBar() method. private JMenuBar getCorrectMenuBar(){ if (System.getProperty("mrj.version")!=null){ System.setProperty("com.apple.macos.useScreenMenuBar","true"); return new MacJMenuBar(); } else return new WindowsJMenuBar(); } With this simple addition, as you can see below, the menu bar is moved when the application runs on a Mac. The menu bar stays at the top of the JFrame when the application runs on other platforms. Ahhh, that's better. Now things look right! Pages: 1, 2, 3 Next Page © 2016, O’Reilly Media, Inc. (707) 827-7019 (800) 889-8969 All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.
http://www.macdevcenter.com/pub/a/mac/2002/09/06/osx_java.html?page=2
CC-MAIN-2016-50
refinedweb
590
67.55
CCoinsView that brings transactions from a mempool into view. More... #include <txmempool.h> CCoinsView that brings transactions from a mempool into view. It does not check for spendings by memory pool transactions. Instead, it provides access to all Coins which are either unspent in the base CCoinsView, or are outputs from any mempool transaction! This allows transaction replacement to work as expected, as you want to have all inputs "available" to check signatures, and any cycles in the dependency graph are checked directly in AcceptToMemoryPool. It also allows you to sign a double-spend directly in signrawtransactionwithkey and signrawtransactionwithwallet, as long as the conflicting transaction is not yet confirmed. Definition at line 863 of file txmempool.h. Definition at line 919 of file txmempool 921 of file txmempool.cpp. Definition at line 866 of file txmempool.h.
https://doxygen.bitcoincore.org/class_c_coins_view_mem_pool.html
CC-MAIN-2021-17
refinedweb
137
56.55
Language analysis can be accomplished computationally in many different ways. Neural networks and deep learning, anyone? 😊As much fun as it can be to toss your documents into an algorithm and let it spit out important features for you, feature analysis at the word or sentence level can also be a great way to analyze text - especially if you are just getting started with natural language processing (NLP). We will be using Python's nltk library to analyze words using nltk's WordNet Corpus. What's WordNet? WordNet is a special kind of English dictionary. When you use WordNet to look up a word, it will not only return the appropriate definition of the word, but every sense associated with that word. These senses, grouped together, are called synsets. Each synset represents a distinct concept associated with the word. For instance, the word "bat" can be a noun and refer to a nocturnal creature; however, another sense "bat" might have is a verb, referring to an object used by a Red Sox player to hit a home run, perhaps! Now, let's get into some examples of how we can use the WordNet corpus in Python. Quick Installation Note If you don't have the nltk library installed, open up your terminal and type the command: pip install nltk Now that you have nltk installed, we can go ahead and import the WordNet corpus like so: from nltk.corpus import wordnet Looking Up Words Since we are working with a dictionary here, the next logical step would be to go ahead and look up a word. Since the wind is a-blowing and I'm feeling pretty positive, let's go ahead and look up the word "breezy." breezy_syns = wordnet.synsets("breezy") breezy_syns >>> [Synset('breezy.s.01'), Synset('blowy.s.01')] We can see that "breezy" has two senses. Let's dissect the first sense to get a better understanding of the kind of information each synset contains. We can do this by indexing the first element at its name. breezy_syns[0].name() >>> 'breezy.s.01' "Breezy's" first sense contains the same kind of information encoded in the WordNet dictionary online: breezy: the word associated with the sense (in this case, the literal and most common meaning of "breezy"). s: the part of speech of the word (i.e. adjective) 01: the order of the word in the synset (it's the first here, folks!) We can also look up the definition of that particular word sense as well as examples to go along with it. breezy_syns[0].definition() >>> fresh and animated breezy_syns[0].examples() >>> ['her breezy nature'] Synonyms and Antonyms Beyond just looking up words, WordNet can also be used to derive all synonyms or antonyms for a particular word. This definitely would have been useful for me while I was studying literature in college and trying to find the most preposterous adjective to describe my very mundane noun. Since breezy isn't as popular of a word, let's look up synonyms for a synset that may contain more variety such as the word "small." for sim in wordnet.synsets('small'): print(sim.name(), sim.lemma_names()) >>> small.n.01 ['small'] >>> small.n.02 ['small'] >>> small.a.01 ['small', 'little'] >>> minor.s.10 ['minor', 'modest', 'small', 'small-scale', 'pocket-size', 'pocket-sized'] >>> little.s.03 ['little', 'small'] >>> small.s.04 ['small'] >>> humble.s.01 ['humble', 'low', 'lowly', 'modest', 'small'] >>> little.s.07 ['little', 'minuscule', 'small'] >>> little.s.05 ['little', 'small'] >>> small.s.08 ['small'] >>> modest.s.02 ['modest', 'small'] >>> belittled.s.01 ['belittled', 'diminished', 'small'] >>> small.r.01 ['small'] In the above code, I'm iterating over every synset associated with "small" and returning its name representation and synonyms associated with those representations. "Small" certainly has a large vocabulary in this sense! Of course, we way want to take a look at "small's" antonyms as well. for opp in wordnet.synsets('small'): if opp.lemmas()[0].antonyms() != []: print(opp.name(),opp.lemmas()[0].antonyms()[0].name()) >>> small.a.01 large >>> small.r.01 big There certainly could be the case where no antonyms exist for a particular word sense, so we'd want to be careful to not return any empty lists (hence, the conditional above). Here, I am returning all antonyms associated with "small's" first and most common word sense. Word Similarities WordNet also takes it a step further by allowing you to perform simple word comparisons to detect the similarity between two word senses. This could be useful in NLP tasks such as word generation, similarity detection, or search/relevance. Let's try it out! dog = wordnet.synset('dog.n.01') cat = wordnet.synset('cat.n.01') collar = wordnet.synset('collar.n.01') dog.wup_similarity(cat) >>> 0.8571428571428571 dog.wup_similarity(collar) >>> 0.47058823529411764 We can see that "dog" and "cat" are quite similar since they likely appear in context besides one another. It could also be that they are in the same mammal or pet category, with dogs being the superior choice, of course! "Dog" and "collar," while seemingly associated with one another in conversation, aren't as similar given the actual meaning of the word. It's always interesting to see the probabilities returned from word comparisons in WordNet. If you try this out with some words, I'd love to see your results or hear your thoughts! Well, that's it for now! I hope I've encouraged you to explore some of what WordNet has to offer. I'm still working to learn about it myself and wanted to share with you what I've learned so far. 😊 Discussion (1) Nice article, thanks!
https://practicaldev-herokuapp-com.global.ssl.fastly.net/navierula/word-analysis-with-nltks-wordnet-corpus-54n7
CC-MAIN-2021-10
refinedweb
942
65.93
< SIGs | PowerManagement Contents Development Tips Oprofile It is often mentioned that running oprofile is more complicated than using gprof, because it has to start a daemon and load a kernel module. But gprof needs recompilation of an application and dependent libraries with -pg option, which could be worse in case you need to recompile also glib library. Setting and using oprofile: Best practices In every good course book problems with memory allocation, performance of some specific functions and so on are mentioned. The best thing to do is to buy a good book ;-) It doesn't make sense to thing about every line, but optimize only things which are bottlenecks for performance. Here is a short overview of techniques which are often problematic: - threads - Wake up only when necessary - Don't use [f]sync() if not necessary - Do not actively poll in programs or use short regular timeouts, rather react on events - If you wake up, do everything at once (race to idle) and as fast as possible - Use large buffers to avoid frequent disk access. Write one large block at a time - Group timers across applications if possible (even systems) - excessive I/O, power consumption, or memory usage - memleaks - Avoid unnecessary work/computation And now some examples: Threads It is widely believed that using threads make our application performing better and faster. But it is not true every-time. Python is using Global Lock Interpreter so the threading is profitable only for bigger I/O operations. We can help ourselves by optimizing them by unladen swallow (still not in upstream). Perl threads was originally created for applications running on systems without fork (win32). In Perl threads the data are copied for every single thread (Copy On Write). The data are not shared by default, because user should be able to define the level of data sharing. For data sharing the (threads::shared) module has to be included, then the data are copied (Copy On Write) plus the module creates tied variables for them, which takes even more time and is even slower. Reference: performance of threads The C threads share the same memory, each thread has its own stack, kernel doesn't have to create new file descriptors and allocate new memory space. The C can really use support of more CPUs for more threads. Therefore, if you want have a better performance of your threads, you should be using some low language like C/C++. If you are using a scripting languages, then it's possible to write a C binding. The low performing parts can be tracked down by profilers. Reference: improving performance of your application Wake-ups Many applications are scanning configuration files for changes. In many cases it is done by setting up some interval e.g. every minute. This can be a problem, because it is forcing disc to wake-up from spindowns. The best solution is to find a good interval, a good checking mechanism or check for changes with inotify - eg. act on event. Inotify can check variety of changes on a file or a directory. The problem is that we have only limited numbers of watches on a system. The number can be obtained from /proc/sys/fs/inotify/max_user_watches and it could be changed, but it is not recommended. Example: #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <sys/types.h> #include <sys/inotify.h> #include <unistd.h> int main(int argc, char *argv[]) { int fd; int wd; int retval; struct timeval tv; fd = inotify_init(); /* checking modification of a file - writing into */ wd = inotify_add_watch(fd, "./myConfig", IN_MODIFY); if (wd < 0) { printf("inotify cannot be used\n"); /* switch back to previous checking */ } fd_set rfds; FD_ZERO(&rfds); FD_SET(fd, &rfds); tv.tv_sec = 5; tv.tv_usec = 0; retval = select(fd + 1, &rfds, NULL, NULL, &tv); if (retval == -1) perror("select()"); else if (retval) { printf("file was modified\n"); } else printf("timeout\n"); return EXIT_SUCCESS; } Pros: - variety of checks Cons: - finite number of watches per system - failure of inotify In the case where inotify fails, the code has to fallback to different check method. That usually means lot of "#if #define" in the source code. Reference: man 7 inotify Fsync Fsync is known as an I/O expensive operation, but according to the references is not completely true. The article has also interesting discussion which shows several different opinions on using or not using fsync at all. The typical examples are Firefox freeze (fsync) vs. empty files (without fsync). What's happened in these cases? Firefox used to call the sqlite library each time the user clicked on a link to go to a new page. The sqlite called fsync and because of the file system settings (mainly ext3 with data ordered mode), then there was a long latency when nothing was happening. This could take a long time (even 30s), if there was a large file copying by another process in the same time. In other cases wasn't fsync used at all and there was no problem until the switch to ext4 file system. The ext3 was set to data ordered mode, which flushed memory every few seconds and saved it to a disc. But with ext4 and laptop_mode the interval was longer and the data might get lost when the system was unexpectedly switched off. Now the ext4 is patched, but still we should thing about design of our applications and use fsync carefully. Simple example of reading/writing into a configuration file shows how backup of a file can be made or how can data be lost. Bad example: /* open and read configuration file e.g. ~/.kde/myconfig */ fd = open("./kde/myconfig", O_WRONLY|O_TRUNC|O_CREAT); read(myconfig); ... write(fd, bufferOfNewData, sizeof(bufferOfNewData)); close(fd); Better example: open("/.kde/myconfig", O_WRONLY|O_TRUNC|O_CREAT); read(myconfig); ... fd = open("/.kde/myconfig.suffix", O_WRONLY|O_TRUNC|O_CREAT); write(fd, bufferOfNewData, sizeof(bufferOfNewData)); fsync; /* paranoia - optional */ ... close(fd); /* do_copy("/.kde/myconfig", "/.kde/myconfig~"); */ /* paranoia - optional */ rename("/.kde/myconfig.suffix", "/.kde/myconfig"); Reference: inside of fsync
https://fedoraproject.org/wiki/SIGs/PowerManagement/DevelopmentDocumentation
CC-MAIN-2018-43
refinedweb
1,002
55.24
I wanted to step a little bit deeper into instant messaging development by using the Jabber protocol. The first place where I looked for an introduction was The Code Project, but I couldn't find any article dealing with Jabber client development. So I thought it's my part to write an article on how to create a small Jabber client, after I got familiar with this stuff. In this article, I want to introduce Jabber development by a small example application that allows you to chat with one of your Roster contacts. The example is written as a Console Application, but it should be no problem to transfer the code into a small Windows Application. Jabber is an open protocol for instant messaging (like Skype). The advantage of Jabber is that as an XML based protocol, it is platform independent and clients can be developed under several operating systems. It also provides the possibility to connect to other instant messaging services like ICQ. Jabber is based on the protocol XMPP (a Jabber derivative) which was standardized in 2004. A simplified Jabber network looks like this: The most important Jabber terms used in this article are: JID: Jabber ID, looks like an Email address (e.g. Test@TestServer.com) where TestServer.com is the Jabber server (you can find a list of public Jabber servers here). In the network above, we would have the following JID's: Client1@Server1 Client2@Server1 Client3@Server2 Roster: List of contacts (friends, family). The Roster can be organized like a tree (as the Jabber protocol is XML based) with folders and the JIDs. A basic example for a TCP based XMPP stream can look like this:> Where C is the Client and S is the Server. This example is taken from here. C S As an open and standardized protocol, there are plenty of libraries for different programming languages and operating systems available. As I was looking for a C# library, I found the agsXMPP library dealing with the most important tasks like Jabber Client or even Jabber Server development. The agsXMPP is provided under two licenses, the GPL for open source project, and a commercial license for closed source projects. agsXMPP To get started with the agsXMPP library, you can download the SDK here. For more detailed information about Jabber/XMPP, you should have a look here and here and here. This example application is just a demonstration of how to create a Jabber Client; it does not store any connection data or provide creation of a new account. So if you would like to use the code to develop a real world client, you will have to add some more functionality to the code. So now we are prepared to develop our own Jabber Client. For this example, I have chosen a Console Application, because it makes the code more readable. As the agsXMPP library provides a lot of events to handle several functionalities that do not make a Console Application the first choice, I think a Windows Forms Application would make it all a little bit confusing on the first view. agsXMPP So what are the goals of this example application? So let's start. To use the agsXMPP in your own project, you have to add a reference to agsXMPP.dll in your project. For this example, you should also add the following using directives to the header: using using agsXMPP; using agsXMPP.protocol.client; using agsXMPP.Collections; using agsXMPP.protocol.iq.roster; using System.Threading; To connect to a Jabber server, we need a JID (Jabber ID) and the corresponding password. At first, we have to create a new JID object with the user's JID as a string parameter. After that, we can create a new XmppClientConnection object with the JID server property of the JID object as a constructor parameter. The code looks like this: JID XmppClientConnection Console.WriteLine("Login"); Console.WriteLine(); Console.WriteLine("JID: "); string JID_Sender = Console.ReadLine(); Console.WriteLine("Password: "); string Password = Console.ReadLine(); Jid jidSender = new Jid(JID_Sender); XmppClientConnection xmpp = new XmppClientConnection(jidSender.Server); Now we have to open the connection and wait until we are connected and authenticated. In the agsXMPP library, the XmppClientConnection.Open() method is executed asynchronously, so we have to register the OnLogin Eventhandler and wait until the OnLogin event is raised. This is a beautiful solution for a Win App, but it makes a Console App not so beautiful. The code should look like this: XmppClientConnection.Open() OnLogin OnLogin xmpp.Open(jidSender.User, Password); xmpp.OnLogin += new ObjectHandler(xmpp_OnLogin); I solved the wait for OnLogin to be raised by a simple do loop, I know there are more pretty solutions, but it just does what it should do: do Console.Write("Wait for Login "); _wait = true; do { Console.Write("."); i++; if (i == 10) _wait = false; Thread.Sleep(500); } while (_wait); So now we have to take a look at the xmpp_OnLogin method: xmpp_OnLogin static void xmpp_OnLogin(object sender) { _wait = false; Console.WriteLine("Logged In"); } We are just waiting until the OnLogin event is raised (which means we are logged in and authenticated) and then exit the loop to continue our program. Now we can get some information about the Connection and Authentication state of our XmppClientConnection object: Console.WriteLine("xmpp Connection State {0}", xmpp.XmppConnectionState); Console.WriteLine("xmpp Authenticated? {0}", xmpp.Authenticated); To show our Roster members we are online, we have to send our presence to the server. This little task works like this: Presence p = new Presence(ShowType.chat, "Online"); p.Type = PresenceType.available; xmpp.Send(p); Now they can see in their Roster that we are online and available for chat (this task is necessary to receive the presence of our Roster members). To receive the presence of our Roster members we have to register the OnPresence Eventhandler: OnPresence xmpp.OnPresence += new PresenceHandler(xmpp_OnPresence); Now we have to wait until the event is raised (it is raised now, and if the presence of a Roster member is changed). Attention: we can only see the Roster members where presence type is available. static void xmpp_OnPresence(object sender, Presence pres) { Console.WriteLine("Available Contacts: "); Console.WriteLine(<a href="mailto:%7B0%7D@%7B1%7D%20%20%7B2%7D">{0}@{1} {2}</a>, pres.From.User,pres.From.Server,pres.Type); Console.WriteLine(); } Now we can start with the most interesting part: Chatting! How does chatting work basically? We send messages to an available chat partner (we need his JID), and we handle received messages in a MessageCallBack method. To prepare for incoming messages, we have to execute the following statement: MessageCallBack xmpp.MesagageGrabber.Add(new Jid(JID_Receiver), new BareJidComparer(), new MessageCB(MessageCallBack), null); Now the MessageCallBack method is executed if a new message arrives: static void MessageCallBack (object sender, agsXMPP.protocol.client.Message msg, object data) { if (msg.Body != null) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("{0}>> {1}", msg.From.User, msg.Body); Console.ForegroundColor = ConsoleColor.Green; } } Sending messages is quite an easy task: xmpp.Send(new Message(new Jid(JID_Receiver), MessageType.chat, outMessage)); where the JID_Receiver is the JID object of our chat buddy. This code should be packed into a loop, to send more than one message (in the download example I have put it into a do loop, with the string q! as the exit criteria). When you are finished, you just need to close the XmppClientConnection object: JID_Receiver q! xmpp.Close(); That is all there is to creating a little Jabber Chat Client which looks like this: The corresponding screenshots of my chat partner using PSI: There are plenty more features of Jabber/XMPP provided in the agsXMPP library, like creating your own Jabber server or creating your own packages. I think for an entry into Jabber development under C#, it is best to start with client development. The agsXMPP SDK provides a few very detailed examples like a Windows based mini client and a server component. If you would like to dive deeper into this technology, I suggest you study these examples before you dive into the libraries'.
http://www.codeproject.com/Articles/21267/Creating-a-Jabber-Client-using-the-agsXMPP-Library?fid=773552&df=90&mpp=10&sort=Position&spc=None&tid=2480084
CC-MAIN-2014-52
refinedweb
1,344
56.25
14 December 2007 14:29 [Source: ICIS news] By Edward Cox ?xml:namespace> "Record high naphtha prices are a major part of price negotiations. Right now we are looking at negative cracker margins and need an increase of €80-90/tonne on ethylene," said one producer. Sellers had previously mentioned target ethylene target hikes of €100/tonne for the first quarter, with a similar aim for propylene. Whatever increase was achieved on ethylene, propylene was likely to rise less, however, following the trend seen in previous recent settlements, said a number of sources. Buyers were largely resigned to notable increases, but some drew attention to suggestions that upstream costs might ease later in the first quarter and hoped this would be factored into negotiations. One consumer said on Friday it expected both ethylene and propylene to increase €50-80/tonne and this broadly reflected price ideas of other sellers and consumers. Feedback was emerging from discussions held on the sidelines of the European Petrochemical Luncheon this week in Naphtha prices once again reached an all-time high this week, with a trade at $849/tonne CIF (cost, insurance and freight) NWE (northwest Naphtha prices have been volatile in the fourth quarter, moving well above levels anticipated by most olefins players, and up from the low $700s/tonne CIF NWE when fourth-quarter contracts were established. Most sources expected settlements to come in the week beginning 17 December, the last really active trading week of 2007. With the wide gap in ideas between some contract partners there were suggestions, however, that talks could take longer, and possibly run into the new
http://www.icis.com/Articles/2007/12/14/9087086/c2-c3-europe-sellers-bullish-on-q1.html
CC-MAIN-2013-48
refinedweb
270
53.65
Hi Guys, I have an question : let say i have 1 web server with 3 web application on it: Those 3 web application running in same server with 1 IP Public : 202.x.x.x If i just want to secure connection for domain : or subdomain : my.company.com in SA using core access, how to do this if the server just using 1 IP public ? Let say If user access domain : or my.company.com from internet, traffic will directed to SA, consider like i told before just using 1 IP public. Thanks Solved! Go to Solution.. Hi steve, continuing for this issue, i already config SA and using local DNS and it's run well. user can login through SA and access the web resource server, but the question is : after successfull login to SA and sometimes when access the web server is slow and sometimes is fast for the page show up. i see in logging that SA already sent traffics to Web server but the received is take longer time, i think this is cause the web page is takes longer time to show up. But if i access the web page directly from browser without using SA, the web page is show up fast. any idea ? Thanks Hi, So you mean is delete DNS entry on internal AD domain for secured web apps.. i think its clear for me. Thank you Spuluka Sorry for the lack of clarity. You delete the PUBLIC DNS entry of the SECURED application. Your public web sites have a firewall forwarding rule that allows the web server to deliver those sites to the public. This same rule and server will also allow the public to load that secured web site. You delete that public dns entry so the public no longer has the ability to resolve the address and use the existing host headers to access the site you are moving secure. You should also consider CHANGING the host header on the secured web site. Since the DNS entry was previously public a smart hacker can use that information to bypass the deleted DNS record by creating their own local host file. Then they still have access to the newly secured site. If you change the host header they will not know the new value and cannot do this. I suggest that the new host header be your internal AD dns name. securesite.mycompany.local. Then this will work for your internal domain computers and can be what you setup in the web bookmark on the SA. This also means the host files you use internally are no longer needed and users have a new bookmark to the secured site. Assuming you are running a windows internal domain, I would make use of this internal namespace that is not published outside you network. Create an internal dns entry for each site - - using the windows domain dns. These resolve to the internal ip address. Add this as a second host header in your IIS setup for each site. Use these internal names then when you setup the SA resource and be sure the SA is setup to use your internal DNS servers. Hi Spuluka, So do you mean, the most task is done in DNS internal server? So DNS server is a must, right? the flow like this: see the below diagram HQ (local user) or user from internet----------------------------------------------DC (web application location) There are 2 location : HQ and DC. web app is located in DC site, and this server accessed by local user in HQ site and external user from outside(internet/ the local user is mobile). The goal is to secure this WEB application for the local user and user form external. for now this domain:, or other domain is published using 1 IP Public. So the plan is: this web app is not to publish anymore. If user (local user/user form external) want to access this web app must via SA SSL VPN. How to accomplish this using SA in this environment? let say in the front is firewall. Just change NAT in Firewall : NAT IP public to internal SA' IP private or how? considering there are 3 web app using same IP public. sorry asking more, because i'm still not clear about this. Thanks do you have a unique IP for each application internally? how do you connect to each internally? Hi, after i gather information from them, the condition is: Local user using Host File define in their PC if they access their web apps. This host file is contain domain name and it's IP local of the server which located in other site(not at HQ). and for user from external site/internet to access this web apps is forwarding using web alias configured in web server( they said like that) for the local user, i have clear about that. I just not clear about external user/internet traffics flow. Let say is user from internet access this web apps, ex: abc.com : the flow is through ISP's DNS forwarding to Public IP of web apps server in which in this web app server contains 3 web apps using the same Public IP. If i want installed SA SSL VPN using the same domain : abc.com, so when user access this web apps is forwarding to SA SSL VPN and then access this web apps through SA SSL VPN. Any idea how is the flow or concept to accompish this ? for your info this web apps is plan to not publish into internet anymore if using SA SSL VPN. or the solution is to give the new public IP for this domain that will be using for SA? I think this can be okay, but need more time to update this domain with new public IP. Thanks Sorry for the confusion. I am not sure I understand your full scenario, but here is what I think you are saying.. What I am not clear on is: When you secure the sites behind the SA will user login be required? This is the typical scenario. You would setup the SA with either an LDAP user database or a local user database listing. Users authenticate to the SA then are presented with the resources that this user is allowed to see. You create a new DNS entry and public ip address to have your firewall direct to the SA. The login and authentication are setup on the SA. You create each web site as a resource using the DNS name. If the sites are no longer public you can just change the DNS entry to the internal ip address and use this in the SA. You create a role for each type of user that will login. This defines how many and which of the three web sites that kind of user can access. you map the role to the resources. Now when the user logs in they receive their role and the web page displays the resources allowed to that role. Hi Spuluka, yes, first what you are said is correct about: ." after discussion with them, they decide internal HQ users will be keep using the current condition (not via SA), but for the user from internet will be using SA. user must be login to their web apps, so just for 1 web apps will be securing through SA, the 2 others web apps will still publish on internet/not through SA. So the task just for 1 web apps want to be secured and not publish anymore on internet. The server uses host headers to sort out the three sites on the single ip address. this will keep like this using 1 public ip address. let say the current domain use for this web apps is my.abc.com, so currently when user access this domain firewall will direct to web server local ip address. If i want to keep using this domain but change firewall directing to local IP of SA, is it possible right? or is it better solution to change public IP for domain my.abc.com? one more question: i want to put the SA in HQ site(not in same location with web app server) and they have not internal dns server, like i mentioned before user in HQ using host-file define on their PC "override the DNS and use the same host names to the internal web server ip address and this will not change" question is: is it possible to configure host-file in SA, like on user's pc, because there is no internal dns server which can be configured on SA's DNS setting? Thank you
https://community.pulsesecure.net/t5/Pulse-Connect-Secure/1-web-server-with-1-ip-public-running-3-web-application/m-p/17716
CC-MAIN-2021-43
refinedweb
1,456
70.53
In this chapter, we will learn about If- Else If Statements and the Switch Case Statements. If – Else If Statements: When a condition is checked then there are two possible outcomes, either true or false. However, when a new condition needs to be checked depending upon the result of the previous condition, then we use the If- Else If Statements. For Example: If you want to go out for a movie, then you will first check if the weather permits you to go out or not. If the weather permits, then only you will search for an interesting movie, if you find something worth watching then you will book the tickets. Now, the above situation can be explained using the if-else if statements as follows: if(weather is not okay) { cout<< “Don’t Go”; } else if(weather is okay)// if-else if statements { if(good movie available) // nested if else statements { cout<< “Book Tickets”; } else { cout<< “Don’t Book Tickets”; } } The if-else statements can also be nested. Switch Case Statements: switch case statement is a multi-directional conditional control statement. It helps the user to evaluate a particular condition and on the basis of the result produced execute the statements. It can be used to execute statements based on different values. Syntax: switch(condition) { case 1: statement(s); case 2: statement(s); . . . . . . case n: statement(s); default: statement(s); } The cases include the possible values the condition can return and with the case, the value returned matches the statements included in that particular case are executed along with all the statements below it. This is called a fall-through case. To prevent it we use a jumping statement called break. We will learn more about jumping statements later on. The default case is executed if the value returned does not match with any case. Example: #include <iostream.h> void main() { int num; cout<< “Enter any number between 1 to 4”; cin>>num; switch(num) { case 1: cout<< “You have entered ONE”; break; case 2: cout<< “You have entered TWO”; break; case 3: cout<< “You have entered THREE”; break; case 4: cout<< “You have entered FOUR”; break; default: cout<< “You have not entered any number between 1 to 4” ; break; } } In the above example, the number entered by the user is checked against four cases. If the user enters 1 then case1 is executed, if 2 is entered then case2 is executed and so on. However, if none of the cases matches that is if the user has not entered any number between 1 to 4 then the default case is executed. Report Error/ Suggestion
https://www.studymite.com/cpp/decision-control-statements-in-cpp-part-2/
CC-MAIN-2021-39
refinedweb
436
67.18
> socks5.zip > regex.h /* * regex.h : External defs for Ozan Yigit's regex functions, for systems * that don't have them builtin. See regex.c for copyright and other * details. * * Note that this file can be included even if we're linking against the * system routines, since the interface is (deliberately) identical. * * George Ferguson, ferguson@cs.rochester.edu, 11 Sep 1991. */ #if defined(_AUX_SOURCE) || defined(USG) /* Let them use ours if they wish. */ #ifndef HAVE_RE_COMP extern char *regcmp(); extern char *regex(); #define re_comp regcmp #define re_exec regex #endif #else extern char *re_comp P((const char *)); extern int re_exec P((const char *)); #endif
http://read.pudn.com/downloads/sourcecode/internet/proxy/797/clients/archie/regex.h__.htm
crawl-002
refinedweb
102
67.15
Version 1.23.0 For an overview of this library, along with tutorials and examples, see CodeQL for Java . A loop statement, including for, enhanced for, while and do statements. for while do import java Gets the body of this loop statement. Gets the boolean condition of this loop statement.. This statement’s Halstead ID (used to compute Halstead metrics).. Locations. startcolumn startline endcolumn endline filepath Holds if this statement is the child of the specified parent at the specified (zero-based) position. Gets a printable representation of this statement. May include more detail than toString(). toString() Gets a textual representation of this element.
https://help.semmle.com/qldoc/java/semmle/code/java/Statement.qll/type.Statement$LoopStmt.html
CC-MAIN-2020-05
refinedweb
104
60.21
0 The Java book I'm using (Java Programming by Joyce Farrel, Thompson Course Technology), when explaining how to add components to an applet, uses the following code: import javax.swing.*; import java.awt.*; public class JHello extends JApplet { Container con = getContentPane(); JLabel greeting = new JLabel("Hello. Who are you?"); public void init() { con.add(greeting); } } However, it doesn't explain how a Container object can be created without using the keyword new and its constructor. I've looked in three books, several websites, and asked someone for an answer, but I haven't gotten one so far. It's really not impeding my progress through the book; I'm just curious about this.
https://www.daniweb.com/programming/software-development/threads/101407/something-i-don-t-quite-understand-about-the-container-class
CC-MAIN-2016-50
refinedweb
114
56.55
Accessing your Model's Data from a Controller create a new MoviesController class and write code that retrieves the movie data and displays it in the browser using a view template. Be sure to build your application before proceeding. Right-click the Controllers folder and create a new MoviesController controller. Select the following options: - Controller name: MoviesController. (This is the default. ) - Template: Controller with read/write actions and views, using Entity Framework. - Model class: Movie (MvcMovie.Models). - Data context class: MovieDBContext (MvcMovie.Models). - Views: Razor (CSHTML). (The default.) Click Add. Visual Web Developer creates the following files and folders: - A MoviesController.cs file in the project's Controllers folder. - A Movies folder in the project's Views folder. - Create.cshtml, Delete.cshtml, Details.cshtml, Edit.cshtml, and Index.cshtml in the new Views\Movies folder. The ASP.NET MVC 3 scaffolding mechanism automatically created the CRUD (create, read, update, and delete) action methods and views for you. You now have a fully functional web application that lets you create, list, edit, and delete movie entries. Run the application and browse to the Movies controller by appending /Movies to the URL in the address bar of your browser. Because the application is relying on the default routing (defined in the Global.asax. Create a couple more movie entries. Try the Edit, Details, and Delete links, which are all functional. Examining the Generated Code Open the Controllers\MoviesController.cs file and examine the generated Index method. A portion of the movie controller with the Index method is shown below. public class MoviesController : Controller { private MovieDBContext db = new MovieDBContext(); // // GET: /Movies/ public ViewResult Index() { return View(db.Movies.ToList()); } The following line from the MoviesController class instantiates a movie database context, as described previously. You can use the movie database context to query, edit, and delete movies. private MovieDBContext db = new MovieDBContext(); A request to the Movies controller returns all the entries in the Movies table of the movie database and then passes the results to the Index view. Strongly Typed Models and the @model Keyword Earlier in this tutorial, you saw how a controller can pass data or objects to a view template using the ViewBag object. The ViewBag is a dynamic object that provides a convenient late-bound way to pass information to a view. ASP.NET MVC also provides the ability to pass strongly typed data or objects to a view template. This strongly typed approach enables better compile-time checking of your code and richer IntelliSense in the Visual Web Developer editor. We're using this approach with the MoviesController class and Index.cshtml view template. Notice how the code creates a List object when it calls the View helper method in the Index action method. The code then passes this Movies list from the controller to the view: public ViewResult Index() { return View(db.Movies.ToList()); } By including a @model statement at the top of the view template file, you can specify the type of object that the view expects. When you created the movie controller, Visual Web Developer automatically included the following @model statement at the top of the Index.cshtml file: @model IEnumerable<MvcMovie.Models.Movie> This @model directive allows you to access the list of movies that the controller passed to the view by using a Model object that's strongly typed. For example, in the Index.cshtml template, the code loops through the movies by doing a foreach statement over the strongly typed Model object: > } Because the Model object is strongly typed (as an IEnumerable<Movie> object), each item object in the loop is typed as Movie. Among other benefits, this means that you get compile-time checking of the code and full IntelliSense support in the code editor: Working with SQL Server Compact.sdf file, click the Show All Files button in the Solution Explorer toolbar, click the Refresh button, and then expand the App_Data folder. Double-click Movies.sdf to open Server Explorer. Then expand the Tables folder to see the tables that have been created in the database. Note If you get an error when you double-click Movies.sdf, make sure you've installed SQL Server Compact 4.0(runtime + tools support). (For links to the software, see the list of prerequisites in part 1 of this tutorial series.) If you install the release now, you'll have to close and re-open Visual Web Developer. There are two tables, one for the Movie entity set and then the EdmMetadata table. The EdmMetadata table is used by the Entity Framework to determine when the model and the database are out of sync. Right-click the Movies table and select Show Table Data to see the data you created. Right-click the Movies table and select Edit Table Schema. Notice how the schema of the Movies table maps to the Movie class you created earlier. Entity Framework Code First automatically created this schema for you based on your Movie class. When you're finished, close the connection. (If you don't close the connection, you might get an error the next time you run the project). You now have the database and a simple listing page to display content from it. In the next tutorial, we'll examine the rest of the scaffolded code and add a SearchIndex method and a SearchIndex view that lets you search for movies in this database.
https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions/getting-started-with-aspnet-mvc3/cs/accessing-your-models-data-from-a-controller
CC-MAIN-2018-05
refinedweb
901
65.52
Type: Posts; User: peahead Thank you - that's perfect! How do I develop my code to listen for F5 and F10, so if F5 is pressed run 'runSQL(conn, sqlStatement.getText().trim());' otherwise if F10 is pressed run 'runUpdateQuery(conn,... It's okay - I figured it out. I was calling the getText value in the wrong place I have a database connection which works well when using static final Strings, i.e. DATABASE_NAME = "test"; I want to make this a little more dynamic so I created a text box on my JFrame ... This should get you started on connecting to a MS Access DB As for importing (not exporting) I can't help you... How do I create a global login so that when the user logs in with their username and password that information is retained? Here is my connection class. Currently, I am using static final... Apologies, I meant run jar not create. Anyway, thanks for the lead - I put the jar in the folder relative to the lib directory and it is now running :-) Thanks - hadn't noticed that 'forward slash'. Still can't create my jar file. 2 more screenshots 1)my layout in Eclipse and 2) the latest output from command Hi, The mysql driver is on the build path (as far as I can tell). I added it by right-clicking on the project in Eclipse/build path/configure and under Libraries I can see the mysql driver which... I am working on a java front-end with a mysql database back-end. It work's well in Eclipse, however, when I export it to a jar file I get the following 'class not found exception... If you want to use a free text editor for Java coding take a look at Notepad++. It's a powerful text editor with its own set of plugins etc and I use it for everyday text use - great for copying and... Thanks, figured it out. I had to add ResultSet.CONCUR_UPDATABLE to the createStatement method. rs = conn.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE... Hi, I am displaying the results of sql query (using com.mysql.jdbc.Driver) in a jtable. Here is the main part of the code package guidatabase1; import java.sql.Connection; import... Thanks! This is a tongue in cheek of way of doing the same thing ;-) Let me Google that for you Actually, being serious, I was thinking on the lines that members had some useful links which... I have to login and connect to a mysql database using a java front end. I am also required to write and run queries in Java using Statement, etc. Does anyone know of any useful links /... Thank you. This is exactly what I want to do. Now that I know it is possible I am happy to research this method. Cheers Sorry about that. I used Excel to sort the order but it removed the colon which I didn't notice. So, to clarify, this is my original list: -4: a7a5 -3: b7b6 -6: f7f5 1: c7c6 2: d7d6 12:... What would be the best way to sort this string into descending order by score, i.e: from: -4: a7a5 -3: b7b6 -6: f7f5 1: c7c6 2: d7d6 12: e7e6 13: d7d5 Norm & dlorde, I have studied this loop but I cannot for the life of me figure out how to print lines at the top of my list. I am trying method 1 proposed by Norm, i.e. Get the old text,... I tried your method previously - it doesn't work. I need to print the most recent line at the top of my JTextArea but instead the most recent line prints at the bottom. In effect I need the data... I was trying different methods with different techniques but none of my my methods prints the line at the top of the JTextArea. I left the code as was...aploogies for the confusion. This is the... I have tried many permutations to concatenate the data to insert the new line at the front v end with no luck so far. I am having problems concatenating old and new data inside a loop. This is... Yes, well summarised :-) I am not sure how to do it but I will research further on Internet I have the following routine: private void getEngineOutput(Process engine) { try { BufferedReader reader = new BufferedReader(new... Ok Norm, thanks for all your help. I can take it form here. ATB
http://forums.codeguru.com/search.php?s=b3e118385deb052ba1d427a1fd2ea3d0&searchid=1921513
CC-MAIN-2013-48
refinedweb
747
73.98
Question Discounted cash flow analysis techniques are used by managers to understand the impact of investment decisions in terms of “today’s dollars.” Two common techniques that use discounted cash flows are net present value (NPV) and internal rate of return (IRR). Like most analysis techniques, each of these methods requires us to make certain assumptions. Required Describe the assumptions underlying NPV and IRR. Required Describe the assumptions underlying NPV and IRR. Answer to relevant QuestionsArmstrong Company manufactures three models of paper shredders, including the waste container, which serves as the base. Whereas the shredder heads are different for all three models, the waste container is the same. The ...Briefly describe the decision-making model discussed in the chapter.Imagine that you are home during a break from school and are talking to a friend about classes. You tell your friend, who is not a college student that you are taking managerial accounting this term. Your friend says that ...Define sunk costs and opportunity costs, and discuss their importance in decision making.RCE manufactures radios and alarm clocks. RCE has just designed a new high-definition-radio alarm clock with added features. The primary cost of the new alarm clock is direct materials, with a cost of $25. Direct labor cost ... Post your question
http://www.solutioninn.com/discounted-cash-flow-analysis-techniques-are-used-by-managers-to
CC-MAIN-2016-50
refinedweb
214
59.09
Adding portal engine functionality to ASPX templates When developing or maintaining a website using. To learn more about portal engine features, please read the version of this tutorial dedicated to the portal engine. The following example demonstrates how to create an ASPX page template with zones that users can design via the portal engine: Writing the ASPX code - Open your web project in Visual Studio (using the WebSite.sln or WebApp.sln file). - Right‑click the CMSTemplates\CorporateSite folder in the Solution Explorer and select Add -> Add New Item. - Create a new Web form named: TwoZones.aspx - Check the Select master page box. - Click Add. The Select a Master Page dialog opens. - Choose the Root.master page from the CMSTemplates/CorporateSite folder and click OK. Open the Source view of the new ASPX page and> The CMSPagePlaceholder control creates an area on the page that behaves in a way similar to a portal engine page template. The <LayoutTemplate> element defines the layout of the area. This example uses a basic two column table structure, but setting a CSS‑based layout applied through HTML elements (for example <div>, <span>) is also a valid option. The table contains two CMSWebPartZone controls, which represent fully functional portal engine zones. Users can manage these zones when editing pages based on the page template on the Design tab of the Pages application.When web part or widget content is added to a zone, the system stores the information in the database along with the respective page template object, not in the actual code of the ASPX page. Communication with the database is ensured by the CMSPortalManager control, which is located on the Root.master page. Switch to the code behind file (TwoZones.aspx.cs) and add a reference to the CMS.UIControls namespace: using CMS.UIControls; Modify the class definition to inherit from the TemplatePage class: public partial class CMSTemplates_CorporateSite_TwoZones : TemplatePage - Save the web form's files. You can now use the web form as a page template in Kentico. This page is a part of a series, which is meant to be read sequentially, from the beginning to the end. Go to the Home page Previous page: Using master pages Next page: Walkthrough - Creating a new site using ASPX templates Registering the ASPX page as a page template - Log in to the Kentico administration interface and open the Page templates application. - Select the Corporate Site/Examples folder. - Click New template and type Two zone template into the Template display name field. - Click Save. The system creates the template and displays its General tab. - Select the ASPX + Portal page option for the Template type property. This is necessary in order for the Design tab to be available when editing pages using the template in the Pages application. Enter the following path into the File name field: ~/CMSTemplates/CorporateSite/TwoZones.aspx Save the changes. Switch to the Sites tab and use the Add sites button to assign the page template to the site that you are using (Corporate Site). Using ASPX + Portal engine templates We will modify the About Us page created in the previous example to use the new page template. - Open the Pages application. - Select the About Us page and switch to the Properties -> Template tab. - Click Select and choose the Corporate Site/Examples/Two zone template page template from the catalog. - Click Save to confirm the page template change. - Refresh your browser window and switch to the Design tab, which is now available for the About Us page. You can see two empty zones on the page as defined in the ASPX code of the template. To define the content of standard zones, add web parts. - Drag the Editable text web part from the toolbar into zoneRight - Double-click the web part header in the zone and set the following properties: - Design -> Editable region title: Right text - Design -> Editable region height: 400 - Click OK. This web part provides a text area on the page that users can edit on the Page tab of the Pages application, just like the editable regions in the previous example. The template allows you to build the design of the page using a browser‑based interface. Each web part zone may contain any number of web parts. You may also configure zones to use various types of widgets, which are objects similar to web parts, but allow page customization by different kinds of website users, not just the administrators or designers. - Expand the menu () of zoneLeft and select Configure. - Switch the Widget zone type property from None to Customization by page editor. - Click Save & Close. The zone now serves as a widget zone for page editors. - Switch to the Page tab - Type some content into the editable text region displayed by the web part on the right and click Save. - Open the menu of the editor widget zone (click) and click Add new widget. Select the Newsletters -> Newsletter subscription widget from the catalog and set the following values for its properties: - Newsletter name: Corporate Newsletter - Allow user subscribers: disabled (unchecked) - Widget container: Corporate site - Light gradient box - Widget container title: Newsletter subscription - Click OK to add the widget and then Save the page. The widget provides a form which users can use to subscribe to the site's newsletter. The example demonstrates how to use web parts or widgets to build the design of pages based on ASPX page templates. This approach combines the standard architecture and development process of ASPX templates with the flexibility and user‑friendliness of the portal engine.
https://docs.xperience.io/k8tutorial/creating-pages-using-aspx-templates/adding-portal-engine-functionality-to-aspx-templates
CC-MAIN-2021-39
refinedweb
924
63.39
hi, i have problem dealing with a string in a line, for example i have the following lines in a .txt file ussdserver link from host /127.0.0.1:38978(account smpp34) is up|smpp34|2012-10-28... hi, i have problem dealing with a string in a line, for example i have the following lines in a .txt file ussdserver link from host /127.0.0.1:38978(account smpp34) is up|smpp34|2012-10-28... ok thanks i will try no, i searched "send HTTP POST xml via java" yes i tried to search in google but found nothing, what is the package's name? it should be simple, i want to send HTTP post request that in java to URL, i have XML file that i want to send as HTTTP POST to specific url, how i can send the XML with java? thanks the protocol is HTTP, i have an application that run on web server, and i have API xml file that can run this application. so i want to send this XML via java hi i want to send XML request via java code to web server. i hava XML request that i should send to a web srver, i want to send it using java code how can i do it? i dont hava any idea how to... hi, i want to build simulator that send ussd message to a gateway, the problem is, i dont know how to start or what to do, please help. thanks ok i think i didnt explain my problem, im working with eclipse in windows, and i have application that i should test that works in linux server. usually i use the winscp and open putty and i send... thanks Voodoo, i know how to use socket, but how i can send get and posts requests?? hi i'm trying to connect to linux server via eclipse, i want to run tests on the linux server (like send wget requests). usually i'm using putty to make this tests, but i want to write java... ok, 1. i didnt solve the problem, just assist 2. dont care about academic dishonesty, i got my degree 3 years ago so who cares you should define array like this, lotteryarray[numtix][6] and insert the numbers in it. so if the user want 3 tickts the array will be 3*6 the number of the columns is the number of the tickts... try this: import java.util.*; public class LotteryTest { public static void main(String[] args){ Scanner input = new Scanner(System.in); { ArrayList<Integer> numbers = new... hi your fault is int the loop "for (int i=0; i<6; i++) { //loop for # of lottery tickets" here you say that you want to make a loop 6 times but what if the user want only 2 tickts? cause of... hi i want to make FF add-on i built the add-on as java code in my computer is there someone that knows how should i upload it to befirefox extension? should i also write javascript code??... thanks i think i solved the problem i read it and i don't know if i can use all the methods there beacuse in the homework they recomended that i can use onlt specific method so i think if i use str.length then i can go all over the... i have to put the text in link list and in the text i have onle letters and space if i get a text like "hello world my name is mike" how can i separated the text without using Tokenizer class?? what thats mean??? how can i connect my program to microsoft sql database??
http://www.javaprogrammingforums.com/search.php?s=ee6f8a7df9128a26aaa3b51ef16b0d17&searchid=1133338
CC-MAIN-2014-42
refinedweb
622
78.28
. is this stuff outdated? No. Hey, Alex I am Mechanical student 1st year. I don’t know 1,2,3… of programming… Programming is recently added to our course (JAVA and C++), you must be knowing that how college teaching is ? Actually worse and self-study is only way. I searched over internet for learning basics of programming from ZERO level…. found this site of yours at the last ….i have read the first lesson…. it’s really like i will learn basics of C ++ in 10 days if i will be persistent. Thanks to you BRO. You’re welcome. It’ll probably take you longer than 10 days unless you’re really dedicated. This tutorial covers a lot of material! This site is just the way too great to be true. Well-explained for difficult concepts. Can you replace OS X with macOS? 😉 I can. Done. Hi i am new to this and use a windows os laptop,what are the softwares i need to get started Please see the next lesson. Awesome step wise explanation. Alex, This tutorial is awesome! So well paced and highly informative. Thank you very much! I understand the place I am at is only the beginning but getting here is encouraging, nonetheless. I’m learning slowly how to make use of and benefit from as many programming tools available; in particular, tools made for the Android platform. While I’ve had trouble with the C++ app which led me here to your website, I’m ever grateful to that app for including a link to reach this tutorial directly. With the aide of a MOOC and the app mentioned above, I started writing very rudimentary code to familiarise myself with the syntax of the C++ language. As more issues with the app surfaced, I dug in earnest for ways in which Termux - a terminal emulator and provider of a Linux environment on Android >=5.0 - could be of help in terms of compiling and building executables that I can run on my devices. I knew the requisite tools were available from Termux’ repository. What I didn’t know - and only know now because of this excellent tutorial - was how to use g++ for what it was designed, . Nano is my editor of choice, for now. It handles line-numbering, syntax highlighting, indentation rather well. The brief exposure I’ve had to g++ in these pages led me to compile and build my first executable C++ programme. An unsuccessful first attempt found me editing, paring down my trivial code for clarity (can’t properly debug yet) and I was able to run the programme right from my prompt after a second compile, linker, build command - tiny programme; immensely satisfying! 1 #include <iostream> 2 using namespace std; 3 4 int main() 5 { 6 int a; 7 int b; 8 cout << "Enter a number: n"; //Get user input 9 cin >> a; 10 cout << "Enter another number: n"; //Get input 11 cin >> b; 12 if (a > b) { 13 cout << "a is greater than b." << endl; 14 } 15 else { 16 cout << "b is greater than a." << endl; 17 } 18 19 return 0; 20 } I have to say, my initial desire to learn the art, skill, and fundamentals of programming had some kindling added to it as of reaching this page. Again, many thanks! You’re welcome. Thanks for visiting, and I hope the site serves you well ongoing. Is this guide could make me develop programs on c++ language individually? 😐 Yes. claro Thanks a lot I took a C++ course in college 1 1/2 years ago and made a "D" it was very discouraging. I forgot about programming altogether to focus on other course work.. I recently had the itch to relearn programming again. Thank you to the creators of this site. You’re welcome. I hope you find more success here! Thanks for the tutorial but I have one question…. In the linking section you wrote -o prog for executing process. Meanwhile if you want to compile and execute them in the same time you still wrote -o prog. So my question is Why -o prog and not -c -o prog? Sorry for not using tags….. -c tells gcc not to link, just to compile. -o tells gcc what the output file is named. So we’d only use -c -o when we want to compile but not link to an object file with a specific name. Hi Alex. Just curious. This executable file named prog created by linking the other files will have automatically have an extension named "out"? prog.out? I don’t think so? Generally if you don’t supply an output filename g++ will create one for you (e.g. a.out). But if you supply one via the -o command, I think it should use that. My knowledge of g++ is rusty though. Im so excited. Thanks for making this guide. Helpful info given. Moving towards ide can you wright a C++ program in google docs? You can write a program in any text editor, but you’ll only be able to compile it in an IDE or using a standalone compiler. For that reason, I’d suggest using an IDE instead of Google Docs. thanks,Alex. Thanks am learning more Thanks, I’m learning more already. Among other things I now understand what an object file is. So far so good this leason is for windows too? The lesson is platform agnostic (although we’ll often show examples using Visual Studio since it’s popular). ok, thanks Its interesting to learn what I have been failing to understand Thank you very much. Typo under Step 3 - there’s an extra ‘the’ (currently starts with: "In order to the write the program") Fixed, thanks! i like it very much Thanks! This is so helpful. Thank you for this great tutorial. Its really great! sir i am beginner please guide me how to learn c language because i am little bit knowledge of computer Thanks for the tut alex, enabled ads just for you (adblock was up 🙂 ) This is the best tutorial for programming I’ve ever seen! Thanks, Alex. Thanks for clarifying, Alex. Hi, Alex I’m a bit confused about something. You say above that all programs should have the .cpp extension. With "programs" do you mean the project file or the files inside the project? Whenever I start a new project with CodeBlocks they ask me for a project title. When I give a name it then adds this name in the project file name box below with an extension .cbp . When I change .cbp to .cpp it saves fine. Only problem is that when I try to open it again, CodeBlocks does not find it unless I set file type to C++ files. Then when I open it it does not open as a project but as some file with lots of things written in that I don’t understand. I know that within a project I should give any new files I create the .cpp extension and then it gets grouped with the main.cpp file in the project. So what I need clarification on is whether I should use the .cpp extension on the project file when I start a fresh project(although I have a feeling this is not what you meant), or only to any new file I add to the existing project? I mean the code files inside the project. You can name the project whatever you want (don’t change the extension of the project though). Hi Alex, I always question myself that how something like photoshop is written in C++ ? I encountered a question in web that was my question : << what languages would be used to create something like adobe photoshop? I’ve created about 2 programs using c++, but they’re like those tutorial things where they run in DOS, and the most advanced one I did was adding two numbers. 🙁 But How would you make a program where it opens outside of DOS, with it’s own interface and things like that. Basically something like photoshop, or any program like excel or word >> C++ GUI libraries are not part of standard libraries, so I guess that they did not use them to write something like photoshop or Mozilla apps … So How ? (this question is making me crazy!) You’re correct, C++ GUI libraries aren’t part of the C++ standard. I think the main reason is because GUI applications are operating-system specific. The C++ library tends to stick to things that are operating system agnostic. Fortunately, there are external libraries to fill in the gaps. QT is a popular library for making cross-platform GUI applications. If you don’t mind being Windows specific, you can have your application interface with Windows directly and build a MFC application. There are plenty of other C++ GUI libraries as well. It’s just a matter of finding the right one for whatever you’re trying to do (and what you budget is). I’m not sure what library Photoshop uses (or whether Adobe writes their own code for each operating system). Hello again, I still don’t know what we can do with C++ ?! for example if we want to develop windows GUI applications, I think C# is a good choice. if we want to develop android applications Java is good. I mean nobody likes programs that runs in DOS or Terminal environment. what useful thing we can create with C++ (in DOS environment) ? I’m learning C++ but I’m not sure for continue learning … every body says C/C++ are powerful languages that can directly associate with hardware and manage memory | what we can do with this ?! Thanks. You can do just about anything with C++, including writing Windows GUI applications. C++ excels at high performance, low latency, and memory constrained (e.g. embedded) applications. It’s used in 2d/3d games and simulations, finance, manufacturing, embedded systems, operating systems, compilers, music players, server applications, search engines, and everything in-between. Unlike Java or C#, C++ doesn’t require a huge framework to be installed first (the JVM/.Net frameworks). Given a specific task, other languages may be easier or more suitable to use, so it really depends on what you specifically want to do, and what your performance requirements are. This tutorial teaches using the console environment because it’s easy and cross-platform. Once you know the fundamentals of C++, learning how to write GUI apps is a lot simpler than trying to learn how to do C++ AND write GUI apps simultaneously. Also, once you know C++, moving to Java or C# (or vice-versa) is easier, because they have similar syntaxes, and a lot of fundamental programming concepts are language agnostic. I was wondering if u could help me out on Skype or something I’m having lots of trouble ;( Hi Alex, What is your idea about Qt? Is that good? Is it very different with C++ console programming? Can you Compare Qt and C# ? which one is better? tnx 😉 I like Qt. It’s a solid, cross-platform library with a lot of useful functionality, including GUI components. I also like it because doesn’t require a bunch of dependencies to be installed first. You can distribute everything with your executable, which makes installing your app easy. And it’s efficient. I can’t speak to C#, as I don’t have much familiarity with it. Name (required) Website
http://www.learncpp.com/cpp-tutorial/04-introduction-to-development/comment-page-2/
CC-MAIN-2018-05
refinedweb
1,926
73.88
Marcel Ruff wrote: >>There are many variants of compression. -------------------------------------- [...] 2. Compress in the SOCKET protocol plugin This is your way. The SOCKET spec supports it with a compression flag and a 'lenUnzipped' field. + Simple ++ Compresses everything, Key+content+Qos and even MsgUnit[] in a bulk - The CPU overhead in the xmlBlaster server increases for each subscriber as the received message is uncompressed on arrival and needs to be compressed for each subscriber separately. 3. Compress in MessageUnit.setContent() Here the Key and Qos is transferred uncompressed and only the message content is compressed. We could support this in our C/C++/Java MessageUnit struct. We could use a ClientProperty "__gzip" to mark it. + The xmlBlaster server would never uncompress the content (as it never looks into it) when receiving it and forwarding it to the subscribers. + This runs with all protocol plugins. ++ No CPU overhead - Key and Qos are not compressed [...] The solutions 2 and 3 are probably our ways to go. Configuration: -------------- Typically only publish() and update() and get()-return (and their Array & Oneway variants) need compression. Other requests like connect(), disconnect(), subscribe(), unSubscribe(), ping() and erase() don't need compression. Your configuration switches on/off compression for a publisher as a whole. Updates for all subscribers are always delivered uncompressed OR compressed depending on the SOCKET plugin configuration in the server. In a future step we will add a <compress type="gzip"/> flag to PublishQos and to SubscribeQos to have fine grained control. OK, but this again is only easily implemented in the 3rd variant. Though it can be done with the 2nd variant, too. I don't understand this. Do you say that the message stream is compressed on the fly as bytes are pushed in? I'll look into the code you send to understand it. Exactly. Its just a filtered stream. regards, Balázs
http://www.xmlblaster.org/mhonarc-xmlBlaster/msg01982.html
CC-MAIN-2017-47
refinedweb
308
66.84
RNDR 1.1.8 A simple and powerful templating engine. RNDR is a simple templating engine that unleashes the full power of Python within templates. Deriving much inspiration from PHP’s templating system, RNDR aims to exploit Python’s inherent utility for templating in a manner that is simple, configurable, and requiring little to learn. Usage Syntax RNDR’s syntax is easy to learn as it involves little more than enclosing a single-line Python statement within a pair of tags. These tags, the start-tag and the end-tag, are by default @R and R@ respectively. >>> r = RNDR( ... "<xml>" ... "@R echo( 1 + 1 ) R@" ... "</xml>" ... ) >>> r.render() '<xml>2</xml>' The output function echo is used in-place of Python’s print as the latter appends a new line, which may or may not be desirable. Rather than calling the echo function one may also use the output tag: a start tag appended, by default, with an equal sign: >>> r = RNDR( ... "<xml>" ... "@R= 1 + 1 R@" ... "</xml>" ... ) >>> r.render() '<xml>2</xml>' The Python language groups the statement blocks of control structures through the use of indentation. Unfortunately, using indentation as a means for managing control-structures within templates is restrictive, fragile, and generally unpleasant. In its place RNDR allows control structures to be explicitly terminated by providing a control-structure termination statement: end<control-structure>. >>> r = RNDR( ... "<html>" ... " Hello" ... "@R if 1+1 is 2: R@" ... " World! " ... "@R endif R@" ... "</html>" ... ) >>> print( r.render() ) <html> Hello World! </html> The syntax described so far is akin to (and drew its inspiration from) the PHP templating engine. Much like the PHP templating engine, there is no esoteric or neutered templating language to learn: RNDR simply executes Python code placed within statement tags. >>> r = RNDR( ... "<html>" ... "@R for i in [1,2,3]: R@" ... "@R= i R@ " ... "@R endfor R@" ... "</html>" ... ) >>> print( r.render() ) <html>1 2 3 </html> >>> r = RNDR( ... "<html>" ... "@R i = 0 R@" ... "@R while True: R@" ... "@R i += 1 R@" ... "@R if i == 3: R@" ... " I'm finally three! " ... "@R break R@" ... "@R endif R@" ... "@R endwhile R@" ... "</html>" ... ) >>> print( r.render() ) <html> I'm finally three! </html> One can take this to great extremes: >>> r = RNDR( ... "<html>" ... "@R try: R@" ... "@R 1/0 R@" ... "@R except Exception as e: R@" ... " @R= e R@ is fun! " ... "@R endtry R@" ... "</html>" ... ) >>> print( r.render() ) <html> integer division or modulo by zero is fun! </html> With respect to the principle of concern separation, seldom could such practice be considered a good idea. Ideally, complex or sensitive functionality should be contained in a domain removed from presentation; logic delegated to the template should be the simplest kind able to perform the given task. Templates and Context RNDR accepts templates in the form of Python strings ( both bytestrings and unicode ), and file objects. >>> f = open('test.rndr.xml','w') >>> r = f.write( ... "<xml>" ... "@R= 1+1 R@" ... "</xml>" ... ) >>> f.close() >>> r = RNDR( open('test.rndr.xml') ) >>> r.render() '<xml>2</xml>' RNDR also accepts context variables: the variables that will provide the namespace for statements found in the template. >>> r = RNDR( ... "<xml>" ... "@R= my_var R@" ... "</xml>" ... ) >>> r.render( {'my_var': 'Hello'} ) '<xml>Hello</xml>' These context variables may be of any type. >>> r = RNDR( ... "<xml>" ... "@R= my_func('Moe') R@" ... "</xml>" ... ) >>> r.render( {'my_func': lambda x: "Hello " + x } ) '<xml>Hello Moe</xml>' File and Template Inclusion RNDR also supports the inclusion of files and other RNDR templates into a template. The content of a file inclusion statement takes the form: <include_tag_suffix> "filename" | filename_variable The include_tag_suffix is the tag leading the start_tag of a statement. By default, the include_tag_suffix is an opening angle bracket (‘<’). @R< "filename" R@ @R< filename_variable R@ Templates included into other templates will share the same context variables. To provide a complete illustration: >>> with open('plain.txt','w') as plain, open('renderable.rndr.txt','w') as renderable: ... plain.write( ... " Hello World. " ... ) ... renderable.write( ... "@R if name: R@" ... "Hello @R= name R@." ... "@R endif R@" ... ) >>> r = RNDR( ... "<x>" ... "@R< 'plain.txt' R@" ... "@R< 'renderable.rndr.txt' R@" ... "</x>" ... ) >>> print( r.render( context = {'name':'Moe'} ) ) <x> Hello World. Hello Moe.</x> Django Integration Some users may want to integrate RNDR into their Django projects. This can be done quite easily: simply insert the line "rndr.loaders.RNDRLoader" into the TEMPLATE_LOADERS list in your projects settings.py file. Note that the RNDR template loader will only load templates that contain the nested/secondary extension ‘.rndr’ (e.g. template.rndr.html ). TEMPLATE_LOADERS = ( 'rndr.loaders.FileSystemLoader', 'rndr.loaders.AppDirectoriesLoader', ... ) Command-line interface RNDR also includes a very simple console interface for rendering template in a command-line environment. There are two positional arguments that may be passed. The first is the path of the template file and the second is the file to which rendered content will be written to. $ python -m rndr template.rndr.html rendered.html They default to the standard input and output streams respectively, meaining they can be used in pipes and standard stream redirections. $ echo "@R if True: R@ Hello @R endfor R@" | python -m rndr Hello $ echo "@R for i in (1,2,3): R@ Hello @R endfor R@" | python -m rndr > rendered.html One may also provide the context variables for a template by creating a file containing an evaluatable Python dictionary expression ( e.g. {'context_var':123} ) or a JSON array (e.g. { "context_var":123 } ) and providing its file path as the value for the -c or --context arguments. python -m rndr template.rndr.html rendered.html -c context.py Finally, one may retrieve the version number by passing the -v and --version arguments, or the help message via -h and --help. Configuration RNDR permits the configuration of a few of its features: tags, control structure tracking, and the output function used to print rendered components. Control-structure tracking By default, RNDR tracks control structures: every time a control structure is initiated (e.g. if A == B: ) it will be recorded as being active until explicitly terminated (e.g. endif). This allows RNDR to determine exactly what control structures are active or unterminated, and how to manage the indentation of the virtual source built from the statements. This feature can be disabled. This will result in RNDR being unable to track the particular control structures active, and will require explicit block management through use of the block_start_tag and block_end_tag symbols. The start of a block is denoted by the block_start symbol, which is found at the end of a statement. The end of a block is denoted by the block_end symbol, which is found at the beginning of a statement. By default, both use the colon (‘:’). >>> rc = Config( cs_tracking = False ) >>> r = RNDR( ... "<html>" ... " Hello" ... "@R if 1+1 is 3: R@" ... " Fail" ... "@R :else: R@" ... " World! " ... "@R :end R@" ... "</html>", rc ... ) >>> print( r.render() ) <html> Hello World! </html> This syntax is similar to that of the Templite+ templating engine. Taking advantage of the configurable start_tag and end_tag values, RNDR can fully support a Templite+ template. >>> templite_config = Config( ... cs_tracking = False,>', ... ) >>> r = RNDR( ... "<html>" ... " Hello" ... "<< if 1+1 is 3: >>" ... " Fail" ... "<< :else: >>" ... " World! " ... "<< :endif >>" ... "</html>", templite_config ... ) >>> print( r.render() ) <html> Hello World! </html> - Author: Z. Alem - Keywords: templates,templating,templating engine,render templates,eval - License: MIT License - Categories - Package Index Owner: Alem - DOAP record: RNDR-1.1.8.xml
https://pypi.python.org/pypi/RNDR
CC-MAIN-2016-40
refinedweb
1,218
59.5
I am new to conneting to MYSQL through a C++ code; so this is what i did i installed MySQL Server 5.1 (it was a EXE), and thats it. i opened the MYSql command line client and created a DB, and added a table and values to it. This is my code in C++ (I'm using VS2008) #include "stdafx.h" #include <iostream> #include <mysql.h> #include <windows.h> int _tmain(int argc, _TCHAR* argv[]) { return 0; } I get an error that prints fatal error C1083: Cannot open include file: 'mysql.h': No such file or directory What have i done wrong.. can some one help me fix this ASAP.
https://www.daniweb.com/programming/software-development/threads/327717/c-mysql-code-error-beginner
CC-MAIN-2018-39
refinedweb
111
85.08
Command buttons display on screen Priety Sharma Ranch Hand Joined: Jun 10, 2008 Posts: 156 I like... posted Dec 26, 2009 22:23:44 0 I have a midlet with 2 screens. Screen one is a form which has 2 StringItems and 1 TextField in that sequence. The StringItems display simple text messages. The Textfield is a initialized as follows: private TextField tf01 = new TextField("Ph num",null,5,TextField.NUMERIC); I have added 2 Commands to the initial screen. One for exit to close the application. One "Ok" Command to go to the 2nd screen. One BACK command to the 2nd screen to return to the 1st screen. I have attached an image of the 1st screen when I have clicked on menu button and the menu is getting displayed. Since there are only 2 commands on this screen Exit and Ok. I want on command to be displayed at the bottom left corner and one on the bottom right corner insted of the menu getting displayed. How do I achieve this? My code is as follows: /* Currently this program does not do anything with numbers. It displays one screen with 2 StringItems following messages. Screen 01 also has a textfield on it to recrive a 5 digit number. Upon choosing next from the menu it stores this number in the record store "aRS" and changes the display to tne next form. This screen has 2 menus: 1 Exit and 2 next (Which displays another form) This new form has a back button functionality through which you can return to the previous form. */ //jad file (please verify the jar size) /* MIDlet-Name: storenumbers MIDlet-Version: 1.0 MIDlet-Vendor: MyCompany MIDlet-Jar-URL: storenumbers.jar MIDlet-1: storenumbers, , storenumbers MicroEdition-Configuration: CLDC-1.0 MicroEdition-Profile: MIDP-1.0 MIDlet-JAR-SIZE: 100 */.midlet.MIDlet; import javax.microedition.lcdui.TextField; import javax.microedition.rms.RecordStore; public class storenumbers extends MIDlet implements CommandListener { private Display display; private Form form; private Command exit = new Command("Exit", Command.SCREEN, 1); private Command ok = new Command("next", Command.OK, 1); private Command back = new Command("back", Command.BACK, 1); private TextField tf01 = new TextField("Ph num",null,5,TextField.NUMERIC); private RecordStore rs = null; public storenumbers() { display = Display.getDisplay(this); StringItem messages[] = new StringItem[] { new StringItem("Hello, ", "J2EE is good."), new StringItem("Hello, ", "Friend.") }; form = new Form("Display Form with Items", messages); //Adding a text box to the form for entering a number form.append(tf01); form.addCommand(exit); form.addCommand(ok); form.setCommandListener(this); } public void startApp() { display.setCurrent(form); } public void pauseApp() { } public void destroyApp(boolean unconditional) { } public void commandAction(Command command, Displayable displayable) { if (command == exit) { destroyApp(true); notifyDestroyed(); } if (command == ok) { System.out.println("inside command == ok if()"); //Call method to store number in record store storenumberinRS(); StringItem messages[] = new StringItem[] { new StringItem("Welcome, ", "way to go boy."), new StringItem("Hello rey, ", "Champ") }; Form form1 = new Form("Display Form with Items", messages); form1.addCommand(back); form1.setCommandListener(this); display.setCurrent(form1); } if (command == back) { display.setCurrent(form); } } public void storenumberinRS() { try { rs = RecordStore.openRecordStore("aRS", false); } catch (Exception e) { System.out.println("Exception while opening record store"); } //Adding number to Record store byte numberbytes[] = tf01.getString().getBytes(); try { rs.addRecord(numberbytes, 0, numberbytes.length); } catch (Exception e) { System.out.println("Exception while addring number to record store"); } finally { try { rs.closeRecordStore(); } catch (Exception e) { } } }// method storenumberinRS() ends. } Please help. storenumber.JPG Priety. Pramod P Deore Ranch Hand Joined: Jul 15, 2008 Posts: 629 I like... posted Dec 27, 2009 03:02:55 0 I think you can't do that in j2me. I am not very much sure, but it may possible on some mobiles one command may be display on bottom right and one at bottom left , but on some mobile it display as a menu. Life is easy because we write the source code..... Priety Sharma Ranch Hand Joined: Jun 10, 2008 Posts: 156 I like... posted Dec 27, 2009 09:44:17 0 Hi, Yeah when I put it on my sony ericsson W810i it showed as 2 different buttons, one at the left bottom corner and one at the right bottom corner. This is not happening with the emulator. Thanks! Gopinath Karyadath Ranch Hand Joined: Oct 14, 2009 Posts: 87 posted Dec 31, 2009 22:54:58 0 try with private Command exit = new Command("Exit", Command.EXIT,0); Regards Did you see how Paul cut 87% off of his electric heat bill with 82 watts of micro heaters ? subject: Command buttons display on screen Similar Threads System Information Code not running J2ME, servlet and database help.. NullPointerException Getting Live Data Problem Problem Retrieve occassion which is stored in RMS All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter JForum | Paul Wheaton
http://www.coderanch.com/t/476407/JME/Mobile/Command-buttons-display-screen
CC-MAIN-2013-48
refinedweb
802
58.99
A web application consists of multiple pages and each page has its own route. A route can be defined as a Django lets us route URLs however we want and with no framework limitations. In this shot, we will see how we can create our own URL in Django. As we can see, the user enters a URL in the search bar of the web browser. Then, that URL is passed to the url.py file where it tries to find a matching URL pattern. If a matching URL is found, the corresponding view function attached with that URL is invoked. Otherwise, it returns 404. The routes are defined in the url.py file that can be either at the project or application level. We will focus on creating our route at the project level. To create a route in Django, we will use the path() function that accepts two parameters: a URL and a View function. url.pyfile looks like this: from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), ] All the routes are created inside the urlpatterns list. Simply add a new path as below and a new route will be created. from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('about/', views.about), ] With this, the about path will become a possible extension to the website’s URL. Assuming we’re using localhost and a port of 8000, it would be 127.0.0.1:8000/about/ to access this new URL. When this new URL is entered in the browser, it will check for a matching route. In this case, it will invoke the about method from views.py. The views.py file may look something like this: from django.shortcuts import render from django.http import HttpResponse def about(request): return HttpResponse('<h1>This is about me!.</h1>') Note: We can also create nested routes or even hundreds of routes all into this single urlpatternslist. The steps above give a brief explanation of how URL routing works in Django. It is quite easy, provided that we know its structure and the flow of events that occur when a specific URL is to be accessed. RELATED TAGS CONTRIBUTOR View all Courses
https://www.educative.io/answers/how-to-perform-url-routing-in-django
CC-MAIN-2022-33
refinedweb
383
77.53
DevOps Certification Training - 54k Enrolled Learners - Weekend/Weekday - Live Class The first step towards Kubernetes Certification is installing Kubernetes. This blog is a step by step guide to install Kubernetes on top of Ubuntu VMs (Virtual Machines). Here, one VM will act as the master and the other VM will be the node. You can then replicate the same steps to deploy the Kubernetes cluster onto your prod. Note: For this installation, we recommend a fresh Ubuntu 16.04 image since Kubernetes can take up a lot of resources. If your installation fails at any time, then execute all the steps mentioned from the very beginning in a fresh VM, because debugging would take longer. To install Kubernetes, you have to diligently follow the 3 phases that come as part of the installation process: Since we are dealing with VMs, we recommend the following settings for the VMs:- Master: Slave/ Node: By this point of time, I have assumed you have 2 plain Ubuntu VMs imported onto your Oracle Virtual Box. So, I’l just get along with the installation process. The following steps have to be executed on both the master and node machines. Let’s call the the master as ‘kmaster‘ and node as ‘knode‘. First, login as ‘sudo’ user because the following set of commands need to be executed with ‘sudo’ permissions. Then, update your ‘apt-get’ repository. $ sudo su # apt-get update Note: After logging-in as ‘sudo’ user, note that your shell symbol will change to ‘#’ from ‘$’. Next, we have to turn off the swap space because Kubernetes will start throwing random errors otherwise. After that you need to open the ‘fstab’ file and comment out the line which has mention of swap partition. # swapoff -a # nano /etc/fstab data-src= Then press ‘Ctrl+X’, then press ‘Y’ and then press ‘Enter’ to Save the file. Run the following command on both machines to note the IP addresses of each. # ifconfig Make a note of the IP address from the output of the above command. The IP address which has to be copied should be under “enp0s8”, as shown in the screenshot below. data-src= Now go to the ‘hosts’ file on both the master and node and add an entry specifying their respective IP addresses along with their names ‘kmaster’ and ‘knode’. This is used for referencing them in the cluster. It should look like the below screenshot on both the machines. # nano /etc/hosts data-src= Then press ‘Ctrl+X’, then press ‘Y’ and then press ‘Enter’ to Save the file. Next, we will make the IP addresses used above, static for the VMs. We can do that by modifying the network interfaces file. Run the following command to open the file: # nano /etc/network/interfaces Now enter the following lines in the file. auto enp0s8 iface enp0s8 inet static address <IP-Address-Of-VM> It will look something like the below screenshot. data-src= Then press ‘Ctrl+X’, then press ‘Y’ and then press ‘Enter’ to Save the file. After this, restart your machine(s). Now we have to install openshh-server. Run the following command: # sudo apt-get install openssh-server Now we have to install Docker because Docker images will be used for managing the containers in the cluster. Run the following commands: # sudo su # apt-get update # apt-get install -y docker.io Next we have to install these 3 essential components for setting up Kubernetes environment: kubeadm, kubectl, and kubelet. Run the following commands before installing the Kubernetes environment. # apt-get update && apt-get install -y apt-transport-https curl # curl -s | apt-key add - # cat <<EOF >/etc/apt/sources.list.d/kubernetes.list deb kubernetes-xenial main EOF # apt-get update Now its time to install the 3 essential components. Kubelet is the lowest level component in Kubernetes. It’s responsible for what’s running on an individual machine. Kuebadm is used for administrating the Kubernetes cluster. Kubectl is used for controlling the configurations on various nodes inside the cluster. # apt-get install -y kubelet kubeadm kubectl Next, we will change the configuration file of Kubernetes. Run the following command: # nano /etc/systemd/system/kubelet.service.d/10-kubeadm.conf This will open a text editor, enter the following line after the last “Environment Variable”: Environment=”cgroup-driver=systemd/cgroup-driver=cgroupfs” data-src= Now press Ctrl+X, then press Y, and then press Enter to Save. Voila! You have successfully installed Kubernetes on both the machines now! As of now, only the Kubernetes environment has been setup. But now, it is time to install Kubernetes completely, by moving onto the next 2 phases, where we will individually set the configurations in both machines. Note: These steps will only be executed on the master node (kmaster VM). Step 1: We will now start our Kubernetes cluster from the master’s machine. Run the following command: # kubeadm init --apiserver-advertise-address=<ip-address-of-kmaster-vm> --pod-network-cidr=192.168.0.0/16 data-src= Step 2: As mentioned before, run the commands from the above output as a non-root user $ mkdir -p $HOME/.kube $ sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config $ sudo chown $(id -u):$(id -g) $HOME/.kube/config It should look like this: data-src= To verify, if kubectl is working or not, run the following command: $ kubectl get pods -o wide --all-namespaces data-src= Step 3: You will notice from the previous command, that all the pods are running except one: ‘kube-dns’. For resolving this we will install a pod network. To install the CALICO pod network, run the following command: $ kubectl apply -f After some time, you will notice that all pods shift to the running state data-src= Step 4: Next, we will install the dashboard. To install the Dashboard, run the following command: $ kubectl create -f It will look something like this: data-src= Step 5: Your dashboard is now ready with it’s the pod in the running state. data-src= Step 6: By default dashboard will not be visible on the Master VM. Run the following command in the command line: $ kubectl proxy Then you will get something like this: data-src= To view the dashboard in the browser, navigate to the following address in the browser of your Master VM: You will then be prompted with this page, to enter the credentials: data-src= Step 7: In this step, we will create the service account for the dashboard and get it’s credentials. Note: Run all these commands in a new terminal, or your kubectl proxy command will stop. Run the following You should get the token like this: data-src= 4. Copy this token and paste it in Dashboard Login Page, by selecting token option data-src= 5. You have successfully logged into your dashboard! data-src= It is time to get your node, to join the cluster! This is probably the only step that you will be doing on the node, after installing kubernetes on it. Run the join command that you saved, when you ran ‘kubeadm init’ command on the master. Note: Run this command with “sudo”. sudo kubeadm join --apiserver-advertise-address=<ip-address-of-the master> --pod-network-cidr=192.168.0.0/16 data-src= Bingo! Your Kubernetes Cluster is ready if you get something similar to the above screenshot. So that brings an end to this blog on how to install kubernetes on Ubuntu 16.04. Do look out for other blogs in this series which will explain the various other aspects of Kubernetes.
https://www.edureka.co/blog/install-kubernetes-on-ubuntu
CC-MAIN-2019-39
refinedweb
1,270
63.7
This article has been dead for over six months: Start a new discussion instead WondererAbu Newbie Poster 4 posts since Apr 2008 Reputation Points: 0 [?] Q&As Helped to Solve: 0 [?] Skill Endorsements: 0 [?] •Newbie Member #include <iostream> #include <fstream> #include "Teacher.h" using namespace std;// syntax error : missing ';' before 'PCH creation point' teacher::teacher(int tid,int cid,char *teachname) { this->tid=tid; this->cid=cid; strcpy(this->teachname,teachname); } void teacher::setTeacherId(int tid){this->tid=tid;} int teacher::getTeacherId(){return tid;} void teacher::setCourseId(int cid){this->cid=cid;} int teacher::getCourseId(){return cid;} void teacher::setTeacherName(char *teachname){strcpy(this->teachname,teachname);} void teacher::getTeacherName(char *teachname){strcpy(teachname,this->teachname);} PCH stands for 'Pre Compiled Header', so you've created a project that requires a PCH but you didn't include it. Just add #include "stdafx.h" as the very first line in your code. Or turn PCH off, but since you didn't tell which compiler (version) you're using, I can't help you with that. One more thing: if you post code here, please post it between [code=cpp] // code here [/code] tags. It makes your code easier to read and preserves formatting.
https://www.daniweb.com/software-development/cpp/threads/124494/pch-error
CC-MAIN-2015-32
refinedweb
201
55.74
Before you get started using Adafruit IO with your Arduino, you'll need to select a library. We provide and support both of these libraries, but try starting with the Adafruit IO Arduino Library below: The Adafruit IO Arduino Library is a simple library to send and receive feed data using the Adafruit IO REST API. We suggest using it before moving onto the more advanced features of the MQTT Library. The library supports the following network platforms and hardware: You can install the library through the Arduino Library Manager (click: Sketch -> Include Library -> Manage Libraries...) Alternatively, you can download the Adafruit IO Arduino Library from GitHub and install it manually.: For Ethernet, you will only need to change from the default WiFi constructor to the Ethernet Ethernet lines in config.h: #include "AdafruitIO_Ethernet.h" AdafruitIO_Ethernet io(IO_USERNAME, IO_KEY);")); } We also have a library to provide support for accessing Adafruit IO using MQTT. This is a general-purpose MQTT library for Arduino that's built to use as few resources as possible so that it can work with platforms like the Arduino Uno. Unfortunately platforms like the Trinket 3.3V or 5V (based on the ATtiny85) have too little program memory to use the library--stick with a Metro 328p or better! The MQTT library supports the following network platforms and hardware: - Adafruit CC3000 - Adafruit FONA - ESP8266 - Generic Arduino Client Interface (incl. ethernet shield and similar networking hardware) You can install the library through the Arduino Library Manager (click: Sketch -> Include Library -> Manage Libraries...).
https://learn.adafruit.com/welcome-to-adafruit-io/libraries
CC-MAIN-2019-13
refinedweb
254
60.75
> Hello everyone I am working on the HUD UI for my game. I am trying to display the current health to the player via a canvas that is set to screen space overlay to create the desired effect. So far I have a canvas that displays the health in world space for everyone to see. I thought I could simply change the canvas render mode to screen space overlay and adjust the position of the canvas. Everything works properly until the health on the HUD needs to change, when the health is changed the HUD shows the new health but behind that is the old health. So for example if you are at 50 and someone hits you with a projectile you should be at 40, instead it shows 50 with a 40 right on top of it, and if you are hit again the 40 goes away and a 30 is placed but the 50 remains. WHY DOES THE 50 REMAIN!? Why doesn't this respond the way the world space render mode does? That one works just fine. Here is some code.... using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.Networking; public class Health : NetworkBehaviour { public int maxHealth; public GameObject HealthPackPrefab; public Transform HealthPackTransform; public Vector3 colPos; [SyncVar(hook="OnHealthChanged")] public int currentHealth; public Text HealthScore; public Text HUDHP; void Start () { HealthScore.text = currentHealth.ToString(); HUDHP.text = currentHealth.ToString(); } void OnHealthChanged(int updatedHealth){ HealthScore.text = updatedHealth.ToString(); HUDHP.text = updatedHealth.ToString(); } Answer by nickg309 · May 29, 2017 at 09:28 AM I fixed the issue. I realized that what was happening when I launched the game on a network I had every player's health being reported to the same canvas, resulting in the overlap effect, and for some reason I had to clear the default text in the canvas or that would also show up with the health values. I fixed this by adding a simple return script before the HUDHP as fallows. void Start () { HealthScore.text = currentHealth.ToString(); if(!isLocalPlayer){ return; } HUDHP.text = currentHealth.ToString(); } void OnHealthChanged(int updatedHealth){ if(!isLocalPlayer){ return; } HealthScore.text = updatedHealth.ToString(); HUDHP.text = updatedHealth.ToString(); } Just wanted to put this put for people who are trying to look for answers to adding networking to their game and having UI issues. I. In which layer is drawn a Canvas with render mode - Screen Space Overlay - ? 0 Answers Major Issues with Camera Switching 1 Answer Canvas not rendered by camera 1 Answer Hololens HUD 0 Answers Camera ProjectionMatrix and Canvas Scaling - different results in 2018.3 0 Answers
https://answers.unity.com/questions/1358451/screen-space-overlay-canvas-problems.html
CC-MAIN-2019-22
refinedweb
431
64.3
Yesterday, I started my very first job as a software engineer! It’s been super exciting, slightly terrifying, and sometimes overwhelming. I think one of the trickiest parts of starting as a new engineer at a company is the onboarding process. It might seem kind of scary, but if you think about it, it’s actually pretty fun. You get to dive down a rabbit hole and look at production code that you didn’t write. It’s getting a new puzzle that you haven’t solved yet: you try to figure out how one thing connects to another, where modules and methods exist, how things are namespaced, not to mention learning about new frameworks and gems. I feel like I’m entering into new dimensions and travelling through a space-time continuum or something. This also might be attributed to the fact that I’ve been listening exclusively to the Interstellar soundtrack for the past two days, but whatever – you get the point. My favorite part of the onboarding process is how much I’ve been learning. Every new class or module definition brings a new piece of the puzzle that I’ve never seen before, but can’t wait to learn about. It’s kind of crazy that I get paid to read and learn all day, every day – that’s the dream, right? Anyways, all of this is to say that I’ve found and learned about some cool stuff! For example this little ditty: acts_as_paranoid. I saw this in a class definition and my first thought was literally: Damn, that’s a great name for a validation! But as it turns out, it’s not actually a validation – it’s Rails magic! Start acting paranoid! Okay, I lied: acts_as_paranoid not actually magic – it’s a Rails ActiveRecord plugin. But it’s still pretty magical, you guys! So, what does it do? Well, it helps you be less paranoid about deleting stuff by accident (hence the name). Essentially, acts_as_paranoid allows you to make soft deletes in Rails. That means that it gives you the flexibility to delete an object without actually deleting it from the database. Does this sound like black magic yet? Just wait, you’re about to see some real magic. So…how do I starting acting paranoid? In my example, I’ll be implementing acts_as_paranoid on some Book objects in my eCommerce bookstore app. Using acts_as_paranoid is relatively simple. You can break it down into two simple steps: First, add acts_as_paranoid to your class definition: Then, add a column to the database for that class called deleted_at, which is set to a datetime format: Ok, I’m getting paranoid now – how does this work? So, we have another column in our Books table that has a deleted_at column with a type of :datetime. Now, this is where the magic happens: the acts_as_paranoid plugin actually overrides ActiveRecord’s find, count, and destroy methods. So now when we call the destroy method on a Book object, instead of actually deleting the object, the object’s deleted_at field will be set to the current date and time. And, if we call the find method on all of our Book objects, the one we just “deleted” won’t show up! Instead, only the objects that don’t have a value in their deleted_at column will render. So, calling @book.destroy doesn’t delete a row from the database; it actually just updates the row by giving a datetime to the object’s deleted_at field. If you’re into SQL queries, this is what’s going on: UPDATE books SET deleted_at = '2015-01-27 19:36:16' WHERE (id = 50) The Book object with an id of 50 isn’t actually deleted from the database, even though it will appear so in all of our views, and to our users/admins. But who needs soft deletes, anyways? I actually didn’t realize the use case for soft deletes at first. But it turns out that they are incredibly helpful when building out large, more complicated Rails applications. It’s important to remember that Ruby is an object-oriented programming language. Any object that has an association with another object inherently relies upon it. In my bookstore app example, a Book object would belong to a Order object, and also be associated with a User object of some sort. If you think about the appliation on a broader, less granular level, you might realize that deleting any given Book object could actually have serious repercussions. For example, you might want to see a Book object that was ordered in the past, even if that Book has since been deleted from a store. Perhaps you want to view the details of a Shipment object, even if that shipment was cancelled. Or, you might want to see an order that was placed by a User who may have deactivated their account months ago. The acts_as_paranoid plugin helps you access all of this information, without keeping you up at night, wondering whether you deleted the wrong row from the database. Because honestly, who has time for that? Not this kitty, for sure: tl;dr? - The acts_as_paranoidplugin modifies ActiveRecord methods and allows you to implement soft deletes on your Ruby objects. Just remember to include it in your class definition and add a deleted_atcolumn to your migration, with a type of datetime. - Want to see another example of disabling records using acts_as_paranoid? Check out this blog post. - To read more about acts_as_paranoidand its many caveats, check out the easy-to-follow documentation.
https://vaidehijoshi.github.io/blog/2015/01/27/embrace-your-inner-paranoia-use-acts-as-paranoid/
CC-MAIN-2018-51
refinedweb
928
63.29
Distributed multiprocessing.Pool¶ Ray supports running distributed python programs with the multiprocessing.Pool API using Ray Actors instead of local processes. This makes it easy to scale existing applications that use multiprocessing.Pool from a single node to a cluster. Quickstart¶ To get started, first install Ray, then use ray.util.multiprocessing.Pool in place of multiprocessing.Pool. This will start a local Ray cluster the first time you create a Pool and distribute your tasks across it. See the Run on a Cluster section below for instructions to run on a multi-node Ray cluster instead. from ray.util.multiprocessing import Pool def f(index): return index pool = Pool() for result in pool.map(f, range(100)): print(result) The full multiprocessing.Pool API is currently supported. Please see the multiprocessing documentation for details. Warning The context argument in the Pool constructor is ignored when using Ray. Run on a Cluster¶ This section assumes that you have a running Ray cluster. To start a Ray cluster, please refer to the cluster setup instructions. To connect a Pool to a running Ray cluster, you can specify the address of the head node in one of two ways: By setting the RAY_ADDRESSenvironment variable. By passing the ray_addresskeyword argument to the Poolconstructor. from ray.util.multiprocessing import Pool # Starts a new local Ray cluster. pool = Pool() # Connects to a running Ray cluster, with the current node as the head node. # Alternatively, set the environment variable RAY_ADDRESS="auto". pool = Pool(ray_address="auto") # Connects to a running Ray cluster, with a remote node as the head node. # Alternatively, set the environment variable RAY_ADDRESS="<ip_address>:<port>". pool = Pool(ray_address="<ip_address>:<port>") You can also start Ray manually by calling ray.init() (with any of its supported configuration options) before creating a Pool.
https://docs.ray.io/en/master/multiprocessing.html
CC-MAIN-2022-05
refinedweb
297
51.55
This is a library for providing access to the Weather Underground API to Dart applications. It provides for asynchronous access to the REST API for dart:io based applications, support for dart:html is on the road map for release in June. You can add it to your project directly in the Dart Editor by including weather_underground_api in your project. You can also contribute to the project via github. WeatherUndergound wu = new WeatherUnderground("apikeyhere", "84096"); wu.getConditions().then((var val) { print(val.toString()); }); There are currently three exceptions that this API can throw. Unfortuantely, the WeatherUnderground API documentation does not define any error return values, though it does return some, so more may be added as I come across them. For now, the following exceptions may be thrown: To date, all code has been written by Ira Burton (@iburton), a very rookie Dart programmer. If something is not working correctly, it is likely because he made some sort of dunderheaded mistake. Please feel free to thoroughly bash him for all mistakes so he can learn the right way to do it. There is no pride of authorship here. Add this to your package's pubspec.yaml file: dependencies: weather_underground_api: ^0.1.5 You can install packages from the command line: with pub: $ pub get Alternatively, your editor might support pub get. Check the docs for your editor to learn more. Now in your Dart code, you can use: import 'package:weather_underground_api/weather_underground_api.dart'; We analyzed this package on Oct 10, 2018, and provided a score, details, and suggestions below. Analysis was completed with status completed using: Detected platforms: unsure Error(s) prevent platform classification: Error(s) in lib/weather_underground_api.dart: Target of URI doesn't exist: 'dart:json'. Fix lib/weather_underground_api.dart. (-86.65 points) Analysis of lib/weather_underground_api.dart failed with 7 errors, including: line 4 col 8: Target of URI doesn't exist: 'dart:json'. line 236 col 28: The constructor returns type 'dynamic' that isn't of expected type 'StreamTransformer<List<int>, dynamic>'. line 236 col 32: Undefined class 'StringDecoder'. line 238 col 28: The method 'parse' isn't defined for the class 'WeatherUnderground'. line 257 col 28: The constructor returns type 'dynamic' that isn't of expected type 'StreamTransformer<List<int>, dynamic>'. Fix platform conflicts. (-20 points) Error(s) prevent platform classification: Error(s) in lib/weather_underground_api.dart: Target of URI doesn't exist: 'dart:json'. Running dartdoc failed. (-10 points) Make sure dartdoc runs without any issues. weather_underground_api.dart.
https://pub.dartlang.org/packages/weather_underground_api
CC-MAIN-2018-43
refinedweb
414
50.84
None 0 Points Aug 28, 2018 01:15 PM|saravanangj|LINK Hi, According to our requirement, from asp.net page we need to communicate UNIX server and from there we need to get the image and then need to display in the asp.net web page. Howe we can achieve this task. Please help me on this. Thank you.. All-Star 47180 Points Star 9801 Points Aug 29, 2018 07:01 AM|Brando ZWZ|LINK Hi saravanangj, According to your description, I suggest you could conside using SSH.NET to conenct to the UNIX server, then you could run ssh command to get the file or something else. Install SSH.NET from Nuget: More details about how to run shh command on Unix in asp.net, you could refer to below codes: Article: Test Code: using Renci.SshNet; using System; namespace ConsoleApp { class Program { static void Main(string[] args) { try { using (var client = new SshClient("server ip address", "your user name", "your password")) { client.Connect(); Console.WriteLine("Connected"); string result = client.RunCommand("ifconfig -a").Execute(); Console.WriteLine(result); client.Disconnect(); Console.WriteLine("Disconnected"); } } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); } Console.ReadLine(); } } } Result: Best Regards, Brando 2 replies Last post Aug 29, 2018 07:01 AM by Brando ZWZ
https://forums.asp.net/t/2146099.aspx?How+to+communicate+with+Unix+Server+from+ASP+Net
CC-MAIN-2020-29
refinedweb
213
57.47
Crystal Space Guest . Please or . December 05, 2013, 01:09:06 am 1 Hour 1 Day 1 Week 1 Month Forever Login with username, password and session length Search: Advanced search 9444 Posts in 2360 Topics by 6634 Latest Member: Czawer23 Show Posts Pages: [ 1 ] 2 1 Crystal Space Development / Support / Re: Python and Pixmaps on: May 06, 2006, 03:59:48 am That's great! You see to understand this a lot better than I do. I've run into a few similar issues with Python that I've managed to get around, but where are we supposed to write down this sort of thing? 2 Miscellaneous / Article/Tutorial Discussion / Re: Writing Python tutorial... problem on: May 02, 2006, 01:35:55 am Well... here it is. I still haven't figured out the iGenMeshSkeletonControlState, so if anyone wants to correct that, please do! Likewise, I haven't figured out how to use the shift keys in Python, because the CrystalSpace constants for the shift keys are undefined. My purpose here was to take the isotest demo script included with CrystalSpace and rewrite it in Python. They are presented side by side, so the reader can compare the C code to the Python code. Suggestions for better presentation (I'd love to color it like an IDE) or fixes are appreciated. Here's the link . Should I upload this somewhere? Maybe the CrystalSpace Wiki I've heard about (but can't find)? 3 Crystal Space Development / Support / Re: Python and Pixmaps on: April 27, 2006, 05:13:19 am There's the python examples that come with the download. Although perhaps you already knew about those. I agree, the information available to Python users is often insufficient. I'm trying to remedy this by writing a few tutorials, but I'm still a beginner myself. As far as the csSimplePixmap() function, I can't help you. I've run into similar issues where the normal C functions just don't exist in Python. 4 Crystal Space Development / General Crystal Space Discussion / Re: Making Crystal Space Easier: Tutorials, documents, wiki, demos on: April 23, 2006, 02:38:35 pm Hmm... well, I don't have the latest CVS, so that might be the problem. Likewise, I'm using Python which seems to be a little finicky, since it demands the latest argument loading (it doesn't let you use deprecated functions). However, I've run into multiple cases where the documentation on the website was not exactly correct. The information was mostly there, but the specifics were insufficient. For instance, the HitBeamObject problem above. In the code, it is described as deprecated. The web documentation didn't make that clear. Or the CreateLight issue I mentioned over in the TutorialDiscussion forum. The web doc says I can give it a name of 0, which doesn't work. In both cases, I had to go to the actual code documentation and read that before I could figure out what was wrong. Then I had to use trial and error to figure out how to use these functions correctly. Considering the number of such issues I ran into while transcribing isotest, I imagine these aren't isolated occurences. Take this with a grain of salt. Isotest works just fine in C. However, the same functions used in Python were hanging for the reasons mentioned above. I think the problem may be that Python is just going to be more exacting. In any case, the documentation problem is a lesser concern. I believe if the other issues are improved, the documentation will begin to take care of itself. 5 Crystal Space Project Development / Feature Requests / Re: Distribution Resource Analyzer (which DLLs?) on: April 23, 2006, 02:24:36 pm Ah. Thank you! 6 Crystal Space Development / General Crystal Space Discussion / Re: Making Crystal Space Easier: Tutorials, documents, wiki, demos on: April 22, 2006, 10:27:38 pm I'm still a noob, but perhaps that is who you need to comment here. I'm very pleased with CrystalSpace. From my experience so far. You have an excellent set of tools, but they are very difficult to figure out. Just getting CrystalSpace to run the first time caused a bunch of frustration. At one point, I turned off the computer and just walked away. Most new users are not going to take that sort of treatment, but they don't have the experience to avoid it. Likewise, programming for CS has been rough. Over the last week, I've rewritten the isotest example script into Python. During that time, I've run into bunches of snags, some of them unavoidable. For instance, the HitBeamObject code is deprecated, and now ouputs a csHitBeamResult instead of a boolean (so the only choice using Python). This is not documented anywhere except in the code itself. I still have a one last snag that I haven't figured my way through. This is mentioned in the Tutorials Discussion forum since that was the intent of this endeavor. Making CrystalSpace easier is a multi-fold problem. First, consider who you are making it easier for. New users. What will be their primary complaint? Problems installing. My guess is that this should probably be goal number one. We can't lose users before they even get their feet wet. It's like a flower shop with a booby trap on the front mat. It looks pretty on the outside, but getting in the door... Second, if you compare the CrystalSpace website with other 3d engines (I'm thinking of Ogre), it isn't as well organized. When I installed Ogre, I ran into many similar issues, but their website was clear and put together well, so I was able to find help quickly without even asking anyone. Helpful information on the CS web is often hidden several layers deep, or only available on the forums. And getting from spot to spot can be a pain. For example (of many), you are currently reading my post. What do you have to do to get back to the CrystalSpace site? I've been biting the bullet and typing the URL in. Why isn't there a link there from here? Third, documentation. You've written all this great documented code, but the documentation on the website doesn't match. Basically, until the first two problems are beaten, we can't really expect much from the community. Without users, nobody is going to help you write documentation. And if the process is painful, they won't do it anyway. I want to help, but I don't know where to start, how much authority I have to make alterations, or even where the Wiki is that you mentioned. I see where I can put in comments in txt2html or doxygen. Is that what you are talking about? I'm a stupid noob, but unless you tell us what to do and how, we CAN'T help. Perhaps, a good "GoogleSummerOfCode" would be to get someone to read through the code (documenting as they go) and bring the website documentation up to match. Please don't take my comments negatively. I'm just trying to help, saying what I see from the "new user (but learning)" perspective. I really like the CS engine. I've tried some of the others. They may have been easier, but they just didn't generate the same sort of application appearance (or design philosophy) that I was looking for. I'm also trying to do my part. I'm writing a tutorial in which I translate the isotest code over to Python. I'll post it sometime soon, probably next week. I do have two additional suggestions: First, it would be nice if the Python users had our own forum for Python specific issues. "CrystalPy" or something. Mmm... Pie... with Crystals in it! *grin* If you look over at Ogre3d, the Python users have their own sub-website. Second, concerning tutorials. It would be really nice if the new users could work out some sort of "tutorial trade" with the more experienced users. New users don't understand advanced subjects such as shaders, but they want to learn. However, they CAN write basic tutorials (on basic subjects) to help out other new users! Such a trade encourages new users to get involved. It also helps them learn as they write their own tutorials. As they become more experienced, they add to the community, so the advanced users can spend more of their time NOT helping noobs. Plus, there would then be twice as many tutorials (and tutorial writers). Seems like a win-win proposal to me. 7 Crystal Space Project Development / Feature Requests / Distribution Resource Analyzer (which DLLs?) on: April 22, 2006, 09:34:06 pm The subject title is vague, because I don't know the correct words for what I'm trying to describe. I will explain: Yesterday, I put together a distribution of a CrystalSpace application to send to a friend for testing on their computer. They didn't need to see the code, they were just going to run it and tell me what they see. All I needed to send was the compiled programs and the DLLs (for a Windows compile), and various other small things like vfs.cfg, the world file and textures. Simple enough? Yes, but it ended up being 180 something meg. That's just silly. So, I started paring it down. Only about a third of the DLLs are actually used by my program. Unfortunately, the quickest way to figure out which ones was by trial and error (deleting one at a time, and seeing if the program still functions correctly). In the end, the program was down to 50 something meg (16 meg zipped). That's not half so bad. What would be nice is a way to output a script at the end of a CrystalSpace program that tells you exactly which DLLs the program loaded. That way, when it's time to write a distribution copy (or commercial copy?), you don't have to resort to trial and error. Maybe there is already something like this, but I didn't see it in the documentation. 8 Miscellaneous / Article/Tutorial Discussion / Re: Writing Python tutorial... problem on: April 20, 2006, 07:55:42 pm All right! I figured out and fixed the first problem. Since I've been copying the code from isotest.cpp to build isotest.py (so I can have a comparison), I used the line "actor_light=self.engine.CreateLight(0, csVector3(-3,5,0), 5, csColor(1,1,1))" as it was written in C. However, this doesn't work in Python. The first field MUST be given a name even if the name is an empty string. So, "actor_light=self.engine.CreateLight("", csVector3(-3,5,0), 5, csColor(1,1,1))" works. Now, if I can just figure out the second issue listed above with iGenMeshSkeletonControlState 9 Miscellaneous / Article/Tutorial Discussion / Re: Writing Python tutorial... problem on: April 20, 2006, 03:35:10 pm I'm still stuck on the last problem, but I kept going so I could find any more issues. Code: self.spstate = SCF_QUERY_INTERFACE (self.actor.GetMeshObject (), iGeneralMeshState) self.animcontrol = SCF_QUERY_INTERFACE (self.spstate.GetAnimationControl (), iGenMeshSkeletonControlState) The first line works fine, the second generates this Traceback: Quote File "C:\CS\isotest.py", line 190 in CreateActor self.animcontrol=SCF_QUERY_INTERFACE (self.spstate.GetAnimationControl (), iGenMeshSkeletonControlState) NameError: global name 'iGenMeshSkeletonControlState' is not defined Sounds like Python doesn't recognize the keyword for the 'iGenMeshSkeletonControlState' structure. Not sure how to approach this problem. I assume the isotest.cpp include for gmeshskel.h isn't loaded by cspace.pyd. Or it wasn't SWIGed properly. Any ideas on what to try next? You know, it'd be nice if we had a forum dedicated to Python users and issues. Maybe call it CrystalPy? Hehe... 10 Miscellaneous / Article/Tutorial Discussion / Writing Python tutorial... problem on: April 20, 2006, 02:51:11 am I'm trying to write a tutorial for newcomers. It's also for my own good, since I get good experience out of it. My goal is to translate several of the tutorial programs that come with CS into Python scripts. Other people would probably be more qualified, but it needs to be done, so I'll do my best. The tutorial would be a line-by-line comparison between the two languages so that new users can see how to build their own programs in Python. Right now, I'm working on a translation of the isotest program. I've gotten pretty far, but I've run into an odd snag. Specifically, it appears that you can't create a light in Python. Here's the chunk of code: Code: try: actor_light=self.engine.CreateLight(0, csVector3(-3,5,0), 5, csColor(1,1,1)) except: msg=traceback.format_exc() csReport (object_reg, CS_REPORTER_SEVERITY_ERROR,"crystalspace.application.isotest",msg) NOTE: for new Python users. It took me a long time to figure out a proper debug method in CS. I'm accustomed to just printing and reading error messages in the terminal window. If you haven't found your own method, the try/except clause above works quite well. I hope someone can help me. When I run the program, it fails to create the light. It also gives a very odd traceback message: Quote File "C:\CS\isotest.py", line 143, in LoadMap actor_light=self.engine.CreateLight(0,csVector3(-3,5,0),5,csColor(1,1,1)) File "C:\CS\cspace.py", line 4269, in CreateLight def CreateLight(*args): return _cspace.iEngine_CreateLight(*args) NotImplementedError: No matching function for overloaded 'iEngine_CreateLight' As said above, I'm probably not the best man for the job, because I don't know what to do about this. It sounds like cspace.py doesn't have a proper function for iEngine.CreateLight. However cspace.py was built by SWIG wasn't it? Any ideas? 11 Crystal Space Development / General Crystal Space Discussion / Re: py2app or py2exe with CS? on: December 15, 2005, 07:34:24 pm I got a spare moment today, so I put in a few minutes, and I got it to work. Big thanks to Sunshine for explaining what my problem was! For future users, here's what I did: Since CrystalSpace was using the same name for one of Python's modules, I copied the Python module (opcode.py) renaming it (disopcode.py). Then, I changed dis.py to import disopcode.py instead of opcode.py. This worked perfectly, although it's not the best solution because if I ever reinstall Python or future modules try to call opcode.py, I'll run into the same problem again. However, it works for now. I now have a finished proof-of-concept compiled into a finished .exe file. It's only 23kb, but comes with ~8 megs of DLLs and PYDs and compressed PYCs. I did try switching Python's path order as suggested, but this didn't achieve quick results, so I switched it back and moved on. I also looked at changing CrystalSpace's opcode module's name, but since I wasn't certain of all the spots that referenced it, I decided my method would be easier. 12 Crystal Space Development / General Crystal Space Discussion / Re: py2app or py2exe with CS? on: December 15, 2005, 04:20:08 pm Ah! That definitely explains the problem. Now that I understand better, I will try to fix it. I'm kinda busy for a while, so it may be a week or two before I can address it properly. Thank you! 13 Crystal Space Development / General Crystal Space Discussion / Re: py2app or py2exe with CS? on: December 15, 2005, 02:41:05 am Since I still haven't heard any py2exe success stories, I suspect that nobody has ever prepared a CrystalSpace (using Python) script into an exe file. This is an important issue for anyone wishing to use Python for CrystalSpace, because if you can't freeze it to an exectuble, you have to copy the whole thing (uncompiled, with all the libraries) to other users. I'm still stuck at the same error despite reinstall of Python (including older versions). py2exe has been able to handle any other file that I've thrown at it (including some test cases), so to me, it seems like the issue must be a failure to handle CrystalSpace's code. For example, I've used py2exe on some other games that I've made using the pygame libraries and a proof-of-concept using Ogre3d. However, I like the design philosophy and the visual results from CrystalSpace best, so I still want to follow it. Unfortunately, I do not have the background to approach this level of problem. Possibly, I'm just doing something stupid. However, I'm forced to proceed with my effort using other engines. But I'll definitely keep an eye here for any updates. 14 Crystal Space Development / General Crystal Space Discussion / Re: py2app or py2exe with CS? on: November 18, 2005, 09:38:01 pm I will try to explain, although I'm still very new and Grimventions clearly knows what he's doing better than I do. When you have finished a Python script, and you want to make it accessible to other users that don't have Python (and all the libraries) available on their machine, you compile it as an executable (in Windows) so it can be run on any computer. This is a critical step to making useful programs in Python, since you can't expect your users to go download (and install) Python before they can run your program. The problem arises in that we don't know how well py2exe will handle the complex CS environment. From his post, I think Grimventions is initially having trouble getting the executable to recognize where to look for the VFS. In my case, I'm stuck at a much earlier point, as I can't even get py2exe to start a compile. Here's the error message, unfortunately it doesn't reference any part of CS, so I don't know if the problem is even related to CS, or it's somewhere within py2exe itself. Though since py2exe can handle anything else I've thrown at it, I'm not really sure where to start. C:\CS>python gamesetup.py py2exe Traceback (most recent call last): File "gamesetup.py", line 2, in ? from distutils.core import setup File "C:\Python24\lib\distutils\core.py", line 21, in ? from distutils.dist import Distribution File "C:\Python24\lib\distutils\dist.py", line 13, in ? from copy import copy File "C:\Python24\lib\copy.py", line 65, in ? import inspect File "C:\Python24\lib\inspect.py", line 31, in ? import sys, os, types, string, re, dis, imp, tokenize, linecache File "C:\Python24\lib\dis.py", line 6, in ? from opcode import * ImportError: dynamic module does not define init function (initopcode) 15 Crystal Space Development / General Crystal Space Discussion / Re: py2app or py2exe with CS? on: November 18, 2005, 12:11:19 am I've been waiting to see if you would get any replies. I only started a few weeks ago, so I won't be much help. However, this is the last critical step in my decision whether to choose to continue with CrystalSpace. I've brute-forced my way through most of the other Python issues I ran into, but this problem is just too far over my head. I now have a few proof-of-concept apps built, but without the ability to compile and give the final application to someone that doesn't have CS and Python, there isn't much point in continuing. Eagerly awaiting any news on this front. Pages: [ 1 ] 2 | SMF © 2006-2007, Simple Machines LLC Page created in 9.494 seconds with 15 queries.
http://www.crystalspace3d.org/forum/index.php?action=profile;u=300;sa=showPosts
CC-MAIN-2013-48
refinedweb
3,330
66.54
Forget about peeling back the layers - today we're gonna talk about adding layers. When you find an API that looks interesting, you'll naturally want to try it out. I've tested and written quite a bit about APIs, and most of the time I start off with a tool like Postman. That's fine for playing around, but eventually you'll want to use it in your app. APIs come in all shapes and sizes. Some are dead simple; others are amazingly complex - even overly complicated at times. It takes time to implement it in a language - to figure out the right way to access any REST endpoint, then to figure out the right way to access a specific endpoint and get the data you're interested in. As long as you're doing all that work, why keep it to yourself? You can share the work you've done - maybe elaborating to cover all of an API's endpoints, or maybe letting others make pull requests to fill in the gaps. Hopefully the language you're using has some concept of a library, package, or some other way to bundle code up for easy sharing, but that's not necessarily necessary. Let's Wrap an API in Python Several weeks ago, I wrote a few one-off Python scripts to demo accessing the ISS Notify API. I won't repost them here, but go check them out before looking at how we can refactor them. Notice how much code is duplicated between them. What if we wanted to make another call to the same endpoint? Or a call to a closely related endpoint? Or 10 more calls with different parameters? And what if someone else wanted to make the same calls as you but wasn't sure where to start? Maybe we can help them out. What I call an API wrapper is really quite simple - just some nice, clean functions to access the API, published somewhere accessible like GitHub. Tada. Here's two of the Python scripts from the other post, refactored into a single file that I named iss_api_wrapper.py. import urllib2 import json import datetime def __call_api(endpoint): request = urllib2.Request('' %(endpoint)) response = urllib2.urlopen(request) return json.loads(response.read()) def show_roster(): result = __call_api('/astros.json') print "There are %d people in space:" % (result['number']), for i in range(result['number']): print result['people'][i]['name'] + ",", def show_next_pass(latitude, longitude): result = __call_api('/iss-pass.json?lat=%s&lon=%s' %(latitude, longitude)) print('The next ISS pass for %s %s is %s for %s seconds' %(result['request']['latitude'], result['request']['longitude'], datetime.datetime.fromtimestamp(result['response'][0]['risetime']), result['response'][0]['duration'])) Place the file in a directory called iss along with an empty file named __init__.py. Create another file outside the directory called use_iss.py (or whatever you want) and call the functions in your new module: (or just download the scripts from GitHub) import iss.iss_api_wrapper as iss iss.show_roster() print "\n" iss.show_next_pass('41.4984174', '-81.6937287') 2018-01-24 17:37:00 for 254 seconds Now you can share your nice module / API wrapper with the world. If the API endpoints change in the future, you can change the calls being made in your Python code, but anyone using your module will be none the wiser! Let's Wrap an API in C# Let's try the same thing one more time, in C# this time. I wrapped all three examples from the ISS Notify API post. This code depends on the RestSharp NuGet package (just discovered it; made accessing the endpoint simple) and some classes I had to defined but didn't want to paste below - you can find everything on GitHub. You can see the original JSON output from the API here. using System; using System.Collections.Generic; using System.Linq; using RestSharp; namespace ISS_Notify_Wrapper { public static class ISS { private static T GetResource<T>(string description, string resource, Tuple<string,string>[] parameters = null) where T : new() { var client = new RestClient { BaseUrl = new Uri("") }; var request = new RestRequest(resource, Method.GET); if (parameters != null) foreach (var param in parameters) request.AddParameter(param.Item1, param.Item2); var response = client.Execute<T>(request); var content = response.Content; if (response.ErrorException != null) throw new ApplicationException($"Unable to retrieve {description}.", response.ErrorException); return response.Data; } public static void ShowRoster() { var roster = GetResource<Roster>("roster", "astros.json"); var astronautNames = String.Join(", ", roster.People.Select(x => x.Name)); Console.WriteLine($"There are {roster.Number} people in space: {astronautNames}"); } public static void ShowUpcomingPasses(string latitude, string longitude) { var nextPass = GetResource<Passes>("next pass", "iss-pass.json", new[] { Tuple.Create("lat", latitude), Tuple.Create("lon", longitude) }).Response[0]; Console.WriteLine($"The next ISS pass for {latitude} {longitude} is " + $"{DateTimeOffset.FromUnixTimeSeconds(nextPass.Risetime)} " + $"for {nextPass.Duration} seconds."); } public static void ShowCurrentLocation() { var pos = GetResource<Position>("next pass", "iss-now.json").IssPosition; Console.WriteLine($"The current position is: {pos.Latitude} {pos.Longitude}"); } } } And now you've got a nice wrapper that anyone can download and use, without them having to know exactly how the ISS Notify API looks, or rethink the same logic you already spent time coding. ISS.ShowRoster(); ISS.ShowUpcomingPasses("41.4984174", "-81.6937287"); ISS.ShowCurrentLocation(); 1/25/2018 3:23:45 AM +00:00 for 563 seconds. The current position is: -47.0603 147.0037 Press any key to continue... What Now? What do you think? Are you working on an API wrapper, or thinking about it? I'd love to check it out - let me know below, or just share your thoughts!
https://grantwinney.com/what-is-an-api-wrapper-and-how-do-i-write-one/
CC-MAIN-2019-18
refinedweb
928
58.99
- Author: - eopadoan - Posted: - May 25, 2007 - Language: - Python - Version: - .96 - ajax newforms autocomplete - Score: - 7 (after 7 ratings) From here with litle improvements. More about Script.aculo.us and Django From here with litle improvements. More about Script.aculo.us and Django very useful, tks! ;) # To make this snippet work in my app, I had to replace the %(id)sin the big returnstatement with %(attrs)s. attrswasn't used anywhere else, so I think this makes sense. # I've modified a little the script, so the value if instancited isnt lost in the path: return (u'<input id="%(id)s" name="%(name)s" type="text" value="%(value)s"><div class="autocomplete" id="box_%(name)s"></div>' '<script type="text/javascript">' 'new Ajax.Autocompleter(\'%(id)s\', \'box_%(name)s\', \'%(url)s\', %(options)s);' '</script>') % {'attrs': flatatt(final_attrs), 'name': name, 'id': final_attrs['id'], 'url': self.url, 'value': value, 'options' : self.options} Basically, I've added value="%(value)s" in the html input and the corresponding param 'value': value, in the dictionary. Great snippet, BTW -charlie- # I added the following method to AutoCompleteField, so that when this field is required and left empty, it does not validate: # Please login first before commenting.
https://djangosnippets.org/snippets/253/
CC-MAIN-2017-47
refinedweb
199
50.43
. As of version 4.16, the tslib runtime library that contains all of the TypeScript helper functions must be installed as well. This can be installed via npm install --save tslib. For additional information on this, please refer to the tslib documentation.. If you're upgrading an app from a previous version of the API to the latest version you can run the following command in your TypeScript project. npm install @types/arcgis-js-api@latest --save-exact or if wanting to target a specific version, run npm install @types/arcgis-js-api@4.[subversion-number-here] --save-exact The web has an abundance of useful information regarding how to work with npm. An Absolute Beginners Guide to Using npm and How to Update npm Packages to their Latest Version are just a couple sites that discuss working with npm..18 from "esri/Map"; import MapView from "esri/views/MapView"; const map = new EsriMap({ basemap: "streets-vector" }); for JavaScript 4.x applications. { options of the tsconfig.json are the same as the options passed to the TypeScript compiler. Without going into too much detail, the important options to take note of are as follows: compilerOptions.esModuleInterop- When true, allows use of importsyntax such as import x from 'xyz'. compilerOptions.module- Will compile TypeScript code to AMD modules as needed by the JavaScript API. compilerOptions.target- Output to ES2019:
https://developers.arcgis.com/javascript/latest/typescript-setup/index.html
CC-MAIN-2021-10
refinedweb
228
57.77
Objective C Interview Questions and Answers Most Frequently Asked Objective C Interview Questions. Objective-C was created by Tom Love and Brad Cox at their company Stepstone in the early 1980s. Apple released Objective-C 2.0 at the Worldwide Developers Conference in 2006. It is its latest version. A protocol announces a programmatic interface that a class chooses to implement. It enables two classes that are related by inheritance to “talk” with each other in order to accomplish a goal.. #import function ensures a file is included only once so that you do not have a problem with recursive include. import is a super set of include and it ensures file is included once. NSMutableArray is the subclass of NSArray and they both manage collections of objects known as arrays. NSArray is responsible for creating static arrays, whereas NSMutableArray is responsible for creating dynamic arrays. The object is a collection of as an array or set of Cocoa classes that may include the collection classes. This collection of classes adopts the NSFastEnumeration protocol. This protocol can be used to retrieve elements that are held by an instance by using a syntax that is similar to a standard C for loop. Look at this instance: NSArray *anArray = // get an array; for (id element in anArray) { /* code that acts on the element */ } @synthesize creates getter and setter for the variables and allows you to specify attributes for variables. When you @synthesize the property to the variable, you generate getter and setter for that variable. This is how you call a function: [className methodName] For announcing methods in same class, use this: [self methodName] The dot syntax is a shortcut for calling getter and setter. You can use this: [foo length] foo.length are exactly the same, as are: [foo setLength:5] foo.length = 5 NSObject is the root class from which a lot of other classes inherit. When an object encounters another object, it interacts using the basic behavior defined by the NSObject description. Atomic is the default behavior that ensures the present process is completed by the CPU. Non-Atomic is not the default behavior and may result in unexpected behavior.. KVC stands for Key-Value-Coding. It refers to accessing a property or value using a string. id someValue = [myObject valueForKeyPath:@”foo.bar.baz”]; Which could be the same as: id someValue = [[[myObject foo] bar] baz]; KOC stands for Key-Value-Observing. It allows programmers to observe changes in property or value. In order to observe a property using KVO, you should identify the property with a string. The observable object must be KVC compliant. [myObject addObserver:self forKeyPath:@”foo.bar.baz” options:0 context:NULL]; You can dealloc for memory management. Once an object “retainCount” reaches 0, a dealloc message is sent to that object. Never call dealloc on objects unless you call [super dealloc]; around the close of a overridden dealloc. (void)dealloc { [ivar release]; //Release any retained variables before super dealloc [super dealloc]; //Only place in your code you should ever call dealloc } Blocks are language-level features that are added to Objective C, C, and C++. Blocks allow you to create segments of code that can be passed to methods or functions as values. Syntax to define a block uses the caret symbol (^): NSLog(@”This is a block”); } ^{ Responder chain is a series of responder objects that are linked together. A chain starts with the first responder and ends with the app object. However, when the first responder is unable to handle an event, it forwards it to the next responder in the chain. - Well-tested and mature language - Documented frameworks. - Strong online support. - Works smoothly with C and C++. - Stable language. It is a pointer to any type, but unlike a void *, it points to an object. For instance, you add anything of type id to an NSArray as long as those objects are responding to retain and release it. @interface A: NSObject; @end @interface B : A @end Here, the init method is inherited from A to B. However, the method has a different return type in both classes. No. Objective-C does not support overloading, so you will need to use a different method.. Because it is a synchronous process. The idea of dispatch_once() is to perform a task only once, no matter how violent the threading becomes. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];You would write: // Code benefitting from a local autorelease pool. [pool release]; @autoreleasepool { // Code benefitting from a local autorelease pool. }
https://www.bestinterviewquestion.com/objective-c-interview-questions
CC-MAIN-2022-21
refinedweb
750
57.06
Benson Margulies wrote: > Can you point me at some description of how to get off the ground as an > XEmacs contributor. stephen <at> xemacs.org wrote: > Please do it this way: > > #define DONT_CHECK_DIRECTORY_WRITABLE > #if !defined(MS_WINDOWS) || !defined(DONT_CHECK_DIRECTORY_WRITABLE) > /* code that does the wrong thing on windows */ > #endif > > and send a patch to xemacs-patches. Benson, feel free to take this on--I don't have the time or the expertise. Here's what I did on my system using the XEmacs 21.4.19 source: In src/fileio.c: DEFUN ("file-writable-p", Ffile_writable_p, 1, 1, 0, /* Return t if file FILENAME can be written or created by you. */ (filename)) { /* This function can GC. GC checked 1997.04.10. */ Lisp_Object abspath, dir; Lisp_Object handler; struct stat statbuf; struct gcpro gcpro1; CHECK_STRING (filename); abspath = Fexpand_file_name (filename, Qnil); /* If the file name has special constructs in it, call the corresponding file handler. */ GCPRO1 (abspath); handler = Ffind_file_name_handler (abspath, Qfile_writable_p); UNGCPRO; if (!NILP (handler)) return call2 (handler, Qfile_writable_p, abspath); if (xemacs_stat ((char *) XSTRING_DATA (abspath), &statbuf) >= 0) return (check_writable ((char *) XSTRING_DATA (abspath)) ? Qt : Qnil); // GCPRO1 (abspath); // dir = Ffile_name_directory (abspath); // UNGCPRO; // return (check_writable (!NILP (dir) ? (char *) XSTRING_DATA (dir) //: "") // ? Qt : Qnil); //AF The check_writable() method doesn't work correctly on NTFS so //we are going to lie return Qt; } With Stephen's suggestion, the commented out section would become: #if !defined(MS_WINDOWS) || !defined(DONT_CHECK_DIRECTORY_WRITABLE) GCPRO1 (abspath); dir = Ffile_name_directory (abspath); UNGCPRO; return (check_writable (!NILP (dir) ? (char *) XSTRING_DATA (dir) : "") ? Qt : Qnil); #else return Qt; #endif The "right" solution would be to fix the check_writable function in the same file: static int check_writable (const char *filename) { #ifdef MS_WINDOWS // Use correct access control for Windows // Needs to work for FAT, FAT32, NTFS and ??? // Filename can be a file, directory, junction point(?), shortcut(??) #else #ifdef HAVE_EACCESS return (eaccess (filename, W_OK) >= 0); #else /*, W_OK) >= 0); #endif #endif } If you don't plan to take this on, let me know and I'll try to submit a patch for the stop-gap solution. -- Tony Freixas Tiger Heron LLC tony <at> tigerheron.com _______________________________________________ XEmacs-Beta mailing list XEmacs-Beta <at> xemacs.org
http://article.gmane.org/gmane.emacs.xemacs.beta/23560.
crawl-002
refinedweb
348
65.73
README Breakpoint X (Crossing)Breakpoint X (Crossing) SummarySummary Define responsive breakpoints, which can fire JS callbacks; optionally apply CSS classes to designated elements. This zero-dependency project provides a means to define points along the horizontal axis of the window, breakpoints, which can fire JS callbacks when the width crosses those breakpoints. It provides a setting, which will apply CSS classes to designated elements. It provides a PHP class with a similar form, that can be useful if you're using, say, a CMS for coordinating breakpoints. A breakpoint is defined as a single point along the horizontal axis. To the left lies a segment, and to the right of the highest value breakpoint lies the ray. To the right of all but the highest value breakpoint, likes a segment. See the section below Breakpoint Theory. Visit for full documentation. InstallationInstallation Install using yarn add @aklump/breakpointx or npm i @aklump/breakpointx Quick StartQuick Start var bp = new BreakpointX([480, 768]); Get segment info using any point along the axis: bp.getSegment(200); bp.getSegment(480); bp.getSegment(1000); Named SegmentsNamed Segments It can be helpful to name your segments: var obj = new BreakpointX([480, 768], ['small', 'medium', 'large']); Then you can also retrieve segment info using a name, which includes items such as the width, from point, to point, media query, image width, name, and more. bp.getSegment(300); bp.getSegment('small'); var name = bp.getSegment('small').name; var query = bp.getSegment('small')['@media']; var imageWidth = bp.getSegment(300).imageWidth; CSS ClassesCSS Classes To cause CSS classes to be written on an element, pass the appropriate settings, where addClassesTo is a DOM object. It becomes a property of the instance as .el, so it can be accessed in callbacks, if necessary. The example shows adding classes to the html element. If you're using jQuery you could do addClassesTo: $('html').get(0). // Breakpoints only with settings. var obj = new BreakpointX([768], ['mobile', 'desktop'], { addClassesTo: document.documentElement, classPrefix: 'bpx-', }); The element will look like this when the browser gets larger and crosses 768px. <html class="bpx-desktop bpx-bigger"> Or when crossing 768px getting smaller. <html class="bpx-mobile bpx-smaller"> Callbacks When Breakpoints Are CrossedCallbacks When Breakpoints Are Crossed When the window width changes, and a breakpoint is hit or crossed, callbacks can be registered to fire as a result. this points to the BreakpointX instance. // When the window crosses any breakpoint in either direction bp.addCrossAction(function(segment, direction, breakpoint, previousSegment) { ... do something in response. }); // When the window crosses 768 in either direction bp.addBreakpointCrossAction(function(segment, direction, breakpoint, previousSegment) { ... do something in response. }); // When the window crosses 768 getting smaller bp.addBreakpointCrossSmallerAction(768, function (segment, direction, breakpoint, previousSegment) { ... do something in response. }); // When the window crosses 768 getting bigger bp.addBreakpointCrossBiggerAction(768, function (segment, direction, breakpoint, previousSegment) { ... do something in response. }); In Terms of DevicesIn Terms of Devices Here is an example which demonstrates how you might construct an instance when thinking in terms of physical devices. It's given in PHP, however the JS methods are exactly the same. <?php $obj = new BreakpointX(); $obj ->addDevice('iphone', 480) ->addDevice('ipad', 768) ->addDevice('desktop', 1024) ->renameSegment(0, 'small'); In terms of Media QueriesIn terms of Media Queries You can also generate an object if you have a list of media queries representing the segments and ray. The queries do not need to be in any specific order: var obj = new BreakpointX(); obj .addSegmentByMedia('(max-width:768px)') // This is the ray. .addSegmentByMedia('(min-width:480px) and (max-width:767px)') .addSegmentByMedia('(max-width:479px)'); PHP UsagePHP Usage While this is foremost a Javascript project, there is a PHP class that may be helpful to your use case. Browser-related methods do not exist, but other methods share the same API as the JS object. The class file is dist/BreakpointX.php or if installing with Node, node_modules/@aklump/breakpointx/dist/BreakpointX.php. <?php $bp = new BreakpointX([480, 768]); $name = $bp->getSegment(300)['name']; $query = $bp->getSegment(300)['@media']; $imageWidth = $bp->getSegment(300)['imageWidth']; AutoloadingAutoloading For PSR autoloading, the namespace AKlump\\BreakpointX should map to node_modules/@aklump/breakpointx/dist. Here's an example for a composer.json in the same directory as the package.json used to install BreakpointX. { "autoload": { "psr-4": { "AKlump\\BreakpointX\\": "node_modules/@aklump/breakpointx/dist" } } } ContributingContributing If you find this project useful... please consider making a donation. Breakpoint TheoryBreakpoint Theory This cheatsheet will familiarize you with the terms used in this project. Download this Cheatsheet by In the Loft Studios Common MistakesCommon Mistakes - By definition a breakpoint does not have a width, nor does it have a minimum or a maximum; it's just a point. - A CSS media query represents a segment or ray not a breakpoint.
https://www.skypack.dev/view/@aklump/breakpointx
CC-MAIN-2022-27
refinedweb
790
50.43
I am writing a game where a certain location will point to a creature which resides there and also the creature points to the location where it is located. I am running into problems however because when I declare the location class and add as one of its members a pointer to an as of yet undeclared class creature it gives me an error. Is there any way to make this work? I've rewritten the relevant code and posted it here. So the problem basically is that I'm trying to create a pointer to a class that doesn't exist yet. Anyone have any ideas? Gives the error message:Gives the error message:Code:#include <iostream> #include <string> #include <cstdlib> using namespace std; class location { public: int x; int y; creature *pCreature; // CLASS CREATURE IS AS OF YET UNDECLARED! // }newLocation; class creature { public: int health; int strength; location *pLocation; }dog; int main() { dog.pLocation = &newLocation; newLocation.pCreature = &dog; system("PAUSE"); return 0; } Code:12 C:\Dev-Cpp\newTemp.cpp ISO C++ forbids declaration of `creature' with no type 12 C:\Dev-Cpp\newTemp.cpp expected `;' before '*' token
https://cboard.cprogramming.com/cplusplus-programming/112037-class-pointers-other-classes-member-data.html
CC-MAIN-2017-22
refinedweb
189
56.96
Java is one of the most widely used programming languages today. According to Oracle, over 3 Billion devices run Java. Java is used in a wide variety of applications. For example, many Android applications are written in Java. Java is used in Web applications that power eCommerece stores that connect to databases or even other websites using technologies such as REST. Many people have written desktop Java applications that make schedules or handle payroll. I have even seen Java powered cash registers. The point is that anyone who grabs a solid understanding of Java will not struggle to find work in the foreseeable future. As of this writing, the Java platform is in its 8th version with JDK 9 on its way. Java development has a massive community of people who are happy to share programming techniques and help others improve their code. Companies such as Google contribute to Java by publishing software libraries to enhance the language. However, to get started in Java, we need to install our build tools. The Java Development Kit (JDK) can be downloaded from Oracle’s website here. Alternatively, you can also use OpenJDK which is a community drive version of Java. Install either of these software packages will install the Java Runtime Environment (JRE), the Java compiler, and related software libraries on your system that make Java development possible. Now let’s write our first Java application. To do this, you need to use a plain text editor (on Windows, that would be notepad. Apple users may use TextEdit). In the end, Java source files are files that end with the .java extension. Once you have your text editor open, start by typing the following code. public class HelloWorld { public static void main(String [] args){ System.out.println("Hello World"); } } Once you have this code inserted into your text editor, you should use the save as feature and save this file HelloWorld.java. This is a critical step because required the name of the file to match the name of the class (this is the name that follows the keyword class, so in our case, it’s HelloWorld). Once you have saved the file, you will need to open your system’s command prompt or terminal. At this point, you need to compile your java file. Java is a compiled language that relies on the Java compiler to turn your *.java into an *.class file. To run the java compiler, navigate to the folder (or directory) that you saved your HelloWorld.java file in and then type. javac HelloWorld.java If all goes well, you will have a HelloWorld.class file in that folder next to HelloWorld.java. To run the program type: java HelloWorld Your system will print: Hello World Congratulations! You have wrote, compiled, and ran your first Java program!
https://stonesoupprogramming.com/2017/04/27/getting-started/
CC-MAIN-2018-05
refinedweb
469
65.93
Convert a JavaScript application to Typescript JavaScript is good but, like me, if you come from statically typed languages then it becomes a bit annoying to deal with lack of types when the project grows big. Luckily there is Typescript but adding Typescript retrospectively may not be a very straight-forward job. Recently I successfully converted a sizable JavaScript project into Typescript, one file at a time. Converting one file at a time to Typescript is really powerful because then you can make the change incrementally without having to stop delivering the features that your product owner wants. I tried doing this different ways. Here, I will talk you through the one that worked. This a long-ish read. I have divided the content into three main sections - Adding typescript config and webpack - Adding Type declaration files - Convert the code into typescript The source code for this article is on GitHub. It is a very simple calculator application with just two files. I think that is enough files to demonstrate the approach. The initial javascript source is in master branch. the changed source code at the end of every section is in appropriate branches in the same repository. Let's drive straight in then. 1. Adding typescript config and webpack Any typescript code has to be transpiled down to JavaScript before it can be run. That is where webpack comes in handy. If you have never used Webpack before, then I recommend reading A detailed introduction to webpack before proceeding. We start by installing webpack using the following command npm install --save-dev webpack Note that we are adding webpack as a development dependency. This is because it's only used to convert typescript code into javascript. Next we need a webpack configuration. Add a new file named webpack.config.js at the root of the project and the following content to it var path = require('path'); var webpack = require('webpack'); module.exports = { entry: { index: "./index.ts" }, target: 'node', module: { loaders: [ { test: /\.ts(x?)$/, loader: 'ts-loader' }, { test: /\.json$/, loader: 'json-loader' } ] }, plugins: [ new webpack.DefinePlugin({'process.env.NODE_ENV': '"production"'}) ], resolve: { extensions: ['.ts', '.js', '.json'] }, output: { libraryTarget: 'commonjs', path: path.join(__dirname, 'lib'), filename: '[name].js' }, }; Let's quickly go over the contents of this file. We have imported path module to make it easy to do some path manipulation in the output section of the config. We have also imported webpack to define a plugin in the plugins section. Let's not worry about this just yet. The file is basically just exporting a JSON object which webpack uses as configuration. Webpack has a large number of configuration options but the ones we have configured here are minimal ones needed for a typescript project. Let's look into each of the configuration we have defined in this object entry This tells webpack where to begin transpiling. Webpack will start with the files specified in entry, converts them into JS (see module section next) and then goes through every module that these modules import till it has reached the end of the tree. We do not have to have a single entry point. We can provide any number of entry points we want here. We have specified index.ts as our entry point. This file does not exist yet. We will eventually convert our entry module index.js into index.ts. target Target tells webpack where you want to run the final Javascript code. This is important because the code that gets generated to be run on server side is different from the code that gets generated to be run in a browser. For this example we specify node which is for the code that gets run on the server side module This is where the most of the magic happens. We have specified on the loaders part of this object. Webpack uses different loaders to transpile files. In our case, we have a ts-loader to transpile any Typescript files and a json-loader which I have left there in case we add a json file later on. Loaders need to be installed separately and they come as their own NPM packages. For our config, we need to install ts-loader and json-loader usin the following command. npm install --save-dev ts-loader json-loader plugins Let's ignore that for a moment resolve This is where you tell webpack which file extensions to scan during its transpilation process. We have added .ts and .js both as we want to convert one js file to ts at a time. This means, we will have a mix of js and ts files in our project and we want webpack to consider both output This is where we tell webpack how do we want the output of the transpilation to appear. We are saying that we want the output files to be named after the key name we used for the file in the entry section. We want the output files to be copied into a folder named lib under the current directory. And we want webpack to use commonjs module system. Again, if this is the first time you are using webpack, then do not worry too much about the content of this file. This is a minimal config that just works for any server side code. Next we need a Typescript config. Add a file named tsconfig.json to the project. Again, the minimal contents for this file are as below { "compilerOptions": { "target": "es5", "module": "commonjs", "noImplicitAny": true, "lib": [ "es5","es2015", "es6", "dom" ] } } This is telling the Typescript compiler that we want the resulting JS to be ES5 compliant and we want to use commonjs as our module system. We have also added a noImplicitAny which is set to true. This forces you to declare any variable of type any instead of leaving the type declaration out and compiler marking the variable as any. This helps to catch cases where we forget to declare type for a variable. Next we need a way to invoke webpack. There are two ways you can do this. The webpack npm package that we installed earlier, you can install that globally and just run webpack from the console at the root directory of the project. Or you can add an NPM script in your package.json that uses the locally installed webpack version like below "scripts": { "build": "node_modules/.bin/webpack --config webpack.config.js" }, Note that I have padded a --config flag which is not really needed because webpack looks for a file named webpack.config.js by default. But if you prefer to name your webpack config file differently then make sure you pass the --config flag. The source code at the end of this section is in add-webpack branch. 2. Add Type declaration files We need to find the first module that we can safely convert to Typescript. This is usually the entry module of our project. In our example, that would be index.js. To use the full power of Typescript in our converted module, we need to have type declaration files for other modules that this module is dependent on. There are two concepts around type declaration files that we need to understand. I am assuming that you know what type declaration files are, if not, I would recommend reading the official guidance on this topic - We need to explicitly install type declaration files for any external module. In our example, we have an external module called prompt-syncfor which we will need to install type declaration files - For our own modules that we have not converted into Typescript yet, we need to write type declaration files ourselves as a stop-gap arrangement till the time we convert that module into Typescript Installing type declaration files for external modules Type declaration files for most NPM packages are already made available by the community. We can run the following command to install the Type declaration files for our prompt-sync package npm install --save-dev @types/prompt-sync If the type declaration file is available, it will get installed. If not, you will see an error. You will need to create the necessary type declaration files yourselves. Creating type declaration files for own modules Type declaration files for a module contain interface, function and type declarations for the bits that the module exports. They are declared in a file with extension d.ts and named after the module name or index.d.ts. For instance, the type declaration file for the prompt-sync module that we just installed is named index.d.ts and you can find it in node_modules/@types/prompt-sync folder. That is one of the known location that typescript compiler searches during module resolution. You can read more about the module resolution process that typescript compiler follows in the Typescript Handbook. One of the strategies used by the compiler to resolve modules is to look for a type declaration file matching the module name at the same location as the imported module. For instance, if we import a module like below import * as calc from './calculator' then typescript compiler will look for a calculator.ts or calculator.d.ts file in the current directory. We can use this mechanism to put our existing calculator.js file behind a type declaration by creating a file calculator.d.ts like below declare module calculator { export function add(a :number, b :number): number export function subtract(a :number, b :number): number export function multiply(a :number, b :number): number export function divide(a :number, b :number): number } export = calculator; Notice that this is exposing the same methods as our calculator module but has annotated arguments and return values with a number type. This file needs to be placed next to calculator.js. Creating Type declaration files for external modules We do not have any external module in this example that does not have Type declaration files available. But if that were the case with you, you can combine the knowledge from the above two points. First you build your own type declaration file and name it index.d.ts. This can include only the methods/interfaces from the external module that you are using in your code. This type declaration file file needs to be kept under the folder node_modules/@types/{module_name}/ I have never personally tried this so cannot vouch for reliability but this is what community defined Type declaration files are doing under the hood. The source code at the end of this section is in add-types branch. 3. Convert the entry module into TypeScript Finally we are ready to convert our first module into TypeScript. There is not much really in this step. Rename index.js to index.ts and start rewriting the module in typescript. If you use the import syntax for bringing in the dependent modules then TypeScript compiler will look at the type declaration files of the target module and enforce type checking in addition to usual Javascript compiler checks. Here is how my converted index.ts file looks like import * as p from "prompt-sync" import * as calc from "./calculator" let prompt = p(); function readInput() { console.log("Welcome to the calculator. Choose one of the following options"); console.log("1. add"); console.log("2. subtract"); console.log("3. multiply"); console.log("4. divide"); console.log("5. exit"); var option = prompt(">> "); if (option !== "5") { console.log("Enter the first number"); let a = parseInt(prompt(">> ")); console.log("Enter the second number"); let b = parseInt(prompt(">> ")); let c; switch(option){ case "1": { c = calc.add(a, b); console.log(`a + b = ${c}`); } break; case "2": { c = calc.subtract(a, b); console.log(`a - b = ${c}`); } break; case "3": { c = calc.multiply(a, b); console.log(`a * b = ${c}`); } break; case "4": { c = calc.divide(a, b); console.log(`a / b = ${c}`); } break; } readInput(); } } readInput(); console.log("Thank you for using calculator. Good Bye"); Yeyy. We converted our first module from javascript to typescript. If you run npn run build at this point, you will notice the webpack successfully gives us a packaged bundle in lib/index.js that is ready to use. The source code at the end of this section is in convert-entry-module branch. 4. Keep going Converting the first javascript file is a big win. You have basic plumbing in place now to take on the bigger task. You may want to expand your webpack configuration to include other types of files you may have in your project, add production build steps like minification, uglification etc. At the same time, you also need to keep converting more and more files from javascript to typescript. The next logical step is to get rid of our own type declaration files by converting the javascript modules into typescript. Let's change the calculator module to get rid of calculator.d.ts. There are a number of ways, you can rewrite calculator module using typescript. The simplest is to just export the four methods in the module like below. export function add(a: number, b: number): number { return a + b; } export function subtract(a: number, b: number): number { return a - b; } export function multiply(a: number, b: number): number { return a * b; } export function divide(a: number, b: number): number { return a / b; } Delete the calculator.d.ts file and re-run npm run build you would get your packaged bundle in lib/index.js. That's it. We have converted everything in this project from javascript to typescript. The source code at the end of this section is in keep-going branch. Discussion (10) what is a right way to declare ENVIRONMENT_CONFIG & DEBUG with webpack.DefinePlugin example: new webpack.DefinePlugin({ ENVIRONMENT_CONFIG: JSON.stringify(environmentConfig), DEBUG: JSON.stringify(DEBUG), }), cause I get: ERROR in ./src/app/utils/Utility.ts (11,26): error TS2304: Cannot find name 'ENVIRONMENT_CONFIG'. Are you able to provide complete code of utility.ts? not a big sense here, ENVIRONMENT_CONFIG used in several files, so errors in several places, this is example: if (ENVIRONMENT_CONFIG.FLAG_1 === '0') { ... } else if (ENVIRONMENT_CONFIG.FLAG_1 === '1') { ... } else { ... } I've found workable solution: stackoverflow.com/questions/460086... but I do not like "typings" folder use, cause "typings" expected to be vanished with typings lib use, imo. I have tried to follow this, but loads was missing. It started to go wrong here: npm install --save-dev webpack. warnings: npm WARN ts-loader@5.2.2 requires a peer of typescript@* but none is installed. You must install peer dependencies yourself. npm WARN ajv-keywords@3.2.0 requires a peer of ajv@6.0.0 but none is installed. You must install peer dependencies yourself. solved that using the following: npm install ajv@6.0.0 npm install typescript npm install ts-loader Now, when I run npm run build, I get the following failure: Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema. NormalModuleFactory). Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema. npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! playground@1.0.0 build: webpack --config webpack.config.jsnpm ERR! Exit status 1 npm ERR! npm ERR! Failed at the playground@1.0.0 build script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. had to change loaders to rules in webpack.config.js: module: { rules: [ { test: /.ts(x?)$/, loader: 'ts-loader' }, { test: /.json$/, loader: 'json-loader' } ] Thanks for an interesting article! :) I am a little uneasy about your (admittedly untested) suggestion for creating type declaration files for external packages. In my limited npm experience, I assumed it was a best practice for only the npm utility itself to make changes to the node_modules folder; that way, it is easy to retrieve your dependencies from any computer without adding them to source control. To keep the "purity" of the node_modules folder, would it be possible to create a specific folder for external type declaration files and make the TypeScript compiler aware of it? You are spot on. I completely missed on that. Since I have never done such a thing myself before I searched for the best options to deal with this properly and came across this wonderfully written SO answer which does a lot more justice to the problem than what I could have done. Wonderful find! Thank you! I don't understand how to run your initial JavaScript application. I'm used to seeing index.html, which I can run by double-clicking. How do I run your index.js without creating an .html file to do it? This is not a web application and hence there is no index.html. You simply run node lib/index.jsin order to run the transpiled code.
https://dev.to/suhas_chatekar/converting-a-javascript-project-to-typescript-one-file-at-a-time
CC-MAIN-2022-27
refinedweb
2,813
66.64
Project centennial or whatever the bridge was called to bring over win32 applications to the store is what the store really lacks. Why can't users buy real (existing) windows programs from the store? When is that coming? Project Centennial": Converting your Classic Windows App (Win32, .Net, COM) to a Universal Windows App for Distribution in the Windows StoreOct 30, 2015 at 10:28AM @jsheehan Wow, you are still answering questions all these months later? That's really cool. Is there any news on this "bridge"? I think its really the key to seeing the store pick up. Again...I haven't heard a good description of containers from anyone at MS. For anyone that's interested... containers are namespaces for files and processes. Docker provides the ability to specify the difference between the "base" os and what you've changed to get your app running. That's why getting a docker image from the hub up and running is so quick. It only fetches the difference from the base... then when it starts the container it creates a private view of all the system processes and files that are in the base plus the differences. Check out cgroups on Linux, jails in BSD, or zones in Solaris... very similar. You guys should open source orchestrator. Thanks for the response. I know you guys are busy, and I really appreciate you taking time to reach out. Is there any discussion about supporting DA in Azure IaaS going on internally? What is being discussed around adding DA features to VPN? Will the machine still be able to authenticate "transparently"...that is, without user intervention? Please add support for hosting DirectAccess servers in Azure VM's. EDIT* I hope that you guys actually read this. Administrators like DirectAccess because they want the machine to authenticate back to the corporate environment. Having that work over multiple protocols and being able to manage out to the clients is awesome. It's REALLY disturbing to hear that you guys aren't investing development in this feature anymore. If you are planning to move features to the VPN subsystem it needs to do EVERYTHING that DirectAccess currently does. The guy that asked a question about DirectAccess in Azure...this would be such a great feature for companies that are connected to Azure via S2S VPN tunnels or ExpressRoute. Being able to stand-up those DirectAccess servers in Azure VM's is a great idea for all the same reasons that standing any internet facing app in Azure VM's is... You're not listening...did you notice all the questions about DA from the audience? Did this guy actually not know who Snover was? He actually doesn't seem to have a clue. Wow. @RickyFr Whoa. It's not everyday that I read something that far off. Look man, no one is saying that PowerShell should be the only interface in Windows. Channel 9 has videos of Jeff Snover and Don Jones showing how to get started. The thing that is great about PS is that the things you learn in those videos are applicable to anything else in PS. It's so incredibly consistent. If you don't or haven't used other command line systems its hard to get across to you how innovative PS actually is. Trying to manage a large number of systems is just not doable with out some way to interact with them programmatically. PowerShell provides an environment that makes it really easy to do that by abstracting away the parts that are labor intensive. I'm not doing it justice here. I've been a UNIX and VMS administrator in the past for what, at the time, where a lot of servers. I promise there is nothing else like PowerShell out there. (Maybe Python...maybe. But its hard to use Python as a work-a-day shell.) If you don't have a need for lots of automation then bully for you! Some of us do and need tools like PowerShell very much.. This is great stuff. Thanks @saramgsilva.
https://channel9.msdn.com/Niners/B3NT/Comments
CC-MAIN-2015-48
refinedweb
680
75.4
On Sun, Aug 01, 2004 at 02:23:24PM -0400, Chris Gorman wrote: [Please do not cross-post between lists, especially cross-posting to subscriber-only lists like linux-arm is considered rude.] > I'm trying to set some architecture specific definitions in the > vorbis-tools package so that when building on arm it will use a different > library than on non-arm. The reason for this is I want to use a fixed > point vorbis decoding library and header files when building on arm. > > Is there a predefined definition passed by the gcc environment that I can > use? For example, if I use > > #include <stdio.h> > > int main (int argc, char ** argv) { > > #ifdef MAGIC_DEFINITION > printf("success\n"); > #else > printf("failure\n"); > #endif /* MAGIC_DEFINITION */ > return 0; > > } "gcc -dumpspecs" will tell you, look at "predefines". If vorbis use autoconf/automake, the trick is to define macros or compile certain libraries depending on the target selection and not to rely on gcc dependencies. Erik -- ---- Erik Mouw ---- ---- +31 15 2600 998 ----
https://lists.debian.org/debian-arm/2004/08/msg00007.html
CC-MAIN-2016-36
refinedweb
168
60.55
A while ago I proposed DaST as a new architectural pattern for building highly dynamic Web 2.0 apps. In short, a web page is rendered as a set of randomly nested rectangles where each rectangle is controlled individually and every combination of rectangles can be partially updated via AJAX. The concept is currently implemented for ASP.NET as the open-source ASP.NET DaST framework, Just recently I published the first stable version of the framework and completed the documentation. This article is a DaST Tutorial that sums up the work done since the project started. DaST technology is a big shift to web development paradigm. It was designed specifically to turn creating of highly dynamic Web 2.0 apps into a trivial task. ASP.NET DaST proves that tiny open-source toolset can accomplish the job of highest complexity, outperforming monsters like standard WebForms and MVC in simplicity, architecture, flexibility, performance, presentation separation, and many other important web development aspects. I know how this sounds, but I can promise that further in this article DaST approach will completely change your idea about web application design and development. First impression is important. I'm putting this 1-minute overview here, before the main article, in order to highlight some DaST features, so you can get a feeling of what this technology is and what you can achieve using it in your web applications. Framework ASP.NET DaST is contained in a single .dll file. This framework is not an add-on, but a complete alternative to the standard WebForms and MVC frameworks. In the same time, ASP.NET DaST does not deny any standard features and can be smoothly integrated into existing ASP.NET applications page by page. .dll Assume we have some user-order-item data that we want to output in tree-like form. The DaST template for this could the the following: <div dast: <b>Customer:</b> {CustomerName} <div dast: <div><b>Order:</b> {OrderID}</div> <div dast: <div><b>Item:</b> {ItemName}</div> </div> </div> </div> Normally, to output user-order-item data we would need 3 nested repeaters. DaST template has 3 nested scopes instead. Plus, this is clear and pure HTML, without any special markup or control-flow statements! The controller tells the system how to render the template. Here is a part of the controller for our previous template: public class NonsenseExample1aController : ScopeController { private void DataBind_CustomerRepeater() { var customers = DataLayer.GetCustomers(); // get customers CurrPath().RepeatStart(); // zeroize repeater foreach (var c in customers) // loop through customers { CurrPath().Repeat(); // repeat scope for current customer CurrPath().Replace("{CustomerName}", c.GetValue("Name")); // render name CurrPath("OrderRepeater").Params.Set("CUST", c); // pass to next scope } } private void DataBind_OrderRepeater() { ... } private void DataBind_ItemRepeater() { ... } } The DataBind_CustomerRepeater() handler controls CustomerRepeater scope in the template. It simply retrieves customer objects and repeats the scope for each of them replacing {CustomerName} placeholder with its real value on each iteration. Two other handlers, for OrderRepeater and ItemRepeater scopes would be analogical. DataBind_CustomerRepeater() CustomerRepeater {CustomerName} OrderRepeater ItemRepeater Actions mechanism is DaST substitution for events. Action is raised on the client-side using JavaScript DaST.Scopes.Action(..) function: DaST.Scopes.Action(..) <a href="javascript:DaST.Scopes.Action('...', 'SubmitInput', ['abc', 123])"> </a> This code raises SubmitInput action that will be processed by action handler implemented inside the controller class. Last parameter is some generic data passed along with the action: SubmitInput private void Action_SubmitInput(object arg) { string p1 = (string)((object[])arg)[0]; // "abc" int p2 = (int)((object[])arg)[1]; // 123 // processing goes here ... } One of the coolest DaST features is that you can raise actions in the opposite direction, from server to client, and handle them in your JavaScript! This mechanism is called Duplex Messaging and here is a sample: private void Action_SubmitInput(object arg) { // processing goes here ... CurrPath().MessageClient("InputSubmitted", new object[] {"abc", 123}); } This sends InputSubmitted message to the client along with the generic argument. On the page we use JavaScript to handle this message: InputSubmitted <script language="javascript" type="text/javascript"> DaST.Scopes.AddMessageHandler('...', 'InputSubmitted', function(data) { var p1 = data[0]; // "abc" var p2 = data[1]; // 123 // processing goes here }); </script> DaST has the simplest and most powerful area-based native AJAX support where we literally can update any page area we point at without extra code or markup. private void Action_SubmitInput(object arg) { // processing goes here ... CtrlPath("CustomerRepeater", 2, "OrderRepeater").Refresh(); } So, we simply point at some scope and call Refresh() on it - that's all! This causes the system to re-invoke necessary binding handler(s), generate partial output, and update the corresponding container on the client-side. Refresh() In general case, the DaST page consists of multiple controllers (and multiple nested templates) that can communicate between each other. This is where Controller Actions mechanism is used. Here is a sample how to raise actions to talk to child or parent controller: private void Action_SomeActionName(object arg) { // some processing can go here CurrPath().RaiseAction("HelloFromChild", new object[] { "abc", 123 }); CurrPath("SomeChildScope").InvokeAction("HelloFromParent", new object[] { "abc", 123 }); // other processing can go here } Same as for client actions, we can pass generic parameters along with controller actions. Then HelloFromChild and HelloFromParent actions can be handled inside parent and child controllers respectively: HelloFromChild HelloFromParent private void Action_HelloFromChild(object arg) // or Action_HelloFromParent for child controller { string p1 = (string)((object[])arg)[0]; // "abc" int p2 = (int)((object[])arg)[1]; // 123 // processing goes here } The syntax here is totally uniform with client action handlers. Surpassing WebForms in all respects, DaST also has important advantages over the most recent MVC frameworks. Just divide your page into nested rectangles and manipulate them to reach the desired output! That's what the web development should be. No need for tons of server controls, weird page lifecycle, bulky binding expressions, or anything like this. Pure HTML templates can be stored anywhere providing native CMS capabilities. Plus you get the simplest and most powerful area-based native AJAX support where you literally can update any page area you point at without extra code or markup. This concept is very fresh and unique and it’s just as simple as it sounds. And for those, who feel lazy about learning new framework, there's really NOT MUCH to learn about DaST. It will take you about 2 hours – just time of going through this tutorial – to learn absolutely all aspects of DaST development. It’s a simple concept, some theory, a dozen of API functions, and truly intuitive programming on the top – that’s all. Here is the list of helpful links that you may need: Now it's time to turn to the actual tutorial. It gives you all needed concept theory followed by coding walk-through with samples of real applications that you can download and run on your local machine. I hope you enjoy it! To demonstrate DaST technology in action, I created a LittleNonsense DEMO web application. As its name implies, this app does not make much sense in a real world; however, it perfectly demonstrates power of DaST pattern and all features of the framework. I suggest you download the source code and run this app on your local machine. Overall functionality of this demo app is fairly simple. It reads customer orders data from XML file and outputs it to the web page in a user-friendly form. Listing below shows a part of this source XML data file located in /App_Data folder: /App_Data Listing 0.1: Part of ../App_Data/Data/LittleNonsense.xml data source XML file 01: <?xml version="1.0" encoding="utf-8"?> 02: <LittleNonsense> 03: <Customer id="C01" name="John"> 04: <Order id="O01" date="2012-01-01"> 05: <Item id="I01" name="IPod Touch 16GB" /> 06: <Item id="I02" name="HDMI Cable" /> 07: </Order> 08: </Customer> 09: <Customer id="C02" name="Roman"> 10: <Order id="O02" date="2012-04-05"> 11: <Item id="I03" name="ASUS/Google Nexus 7 Tablet" /> 12: <Item id="I04" name="Nexus 7 Protective Case" /> 13: </Order> 14: <Order id="O03" date="2012-04-22"> 15: <Item id="I05" name="ASUS EEEPC Netbook" /> 16: <Item id="I06" name="8 Cell Battery" /> 17: </Order> 18: </Customer> 19: ............... 20: </LittleNonsense> As you can see, structure of XML data file is trivial. We have a set of customers. Each customer can have multiple orders. And each order consists of multiple order items. Each element has a unique id attribute and a second attribute carrying some meaningful data: customer name, order date, or item name. id I divided the LittleNonsense application into 2 separate parts: Example 1 and Example 2 implemented on NonsenseExample1.aspx and NonsenseExample2.aspx pages respectively. Example 1 is trivial and is used for concept explanation and Coding Basics part of this tutorial. Example 2 has much more stuff in it and demonstrates Web 2.0 and all advanced features of DaST framework. Example 2 is used for the Advanced Coding part of this tutorial and we'll come to it later. Now, let's introduce Example 1. NonsenseExample1.aspx NonsenseExample2.aspx This example was designed to give you a feeling of DaST Rendering mechanism and show you what is so different about DaST concept. Specifically, Example 1 covers the following topics: All this application does is reading some hierarchical data from XML file and outputting it using 3 nested repeaters. Below is a screenshot of Example 1 output: Fig. EX1: Screenshot of NonsenseExample1.aspx page output So, we just repeat customers, orders for each customer, and items for each order, displaying the result in the form of user-friendly hierarchical tree. The id attribute of each element from XML file is displayed in square brackets before actual text data. In further sections I’ll do a complete Example 1 source code walkthrough with all details and explanations. Right now I’d like start with some theoretical knowledge and explanation of DaST Concept. First of all, DaST is much more than a framework – it’s a whole new web development pattern and a unique application design concept. The ASP.NET DaST project is a .NET implementation of this pattern. But the pattern can be implemented for any other platform such as PHP (upcoming project), JSP, etc. The concept started from a very simple thought that every web page is nothing, but a bunch of data produced by server-side logic and presented to the user in the client browser. The entire page rendering process can be separated in two steps: To accomplish these steps, DaST uses a combination of template and controller. Controller is a back-end class that generates the values. Template is a W3C compliant and valid HTML file where the values get inserted. And it’s just as simple as it sounds: Besides obvious simplicity and flexibility of this approach, HTML templates give us theoretical maximum of presentation separation! The central question here is what happens in between the controller and the template during rendering and how the values are delivered to the specific spots within the HTML template... And this is exactly what DaST engine is for! DaST stands for data scope tree. You’ll see why in a second, but before going into more details, let me illustrate DaST rendering approach by a simple picture that you will use for your reference: Fig. 1.1: Top-level design of DaST rendering process This picture visualizes the whole point of DaST pattern and illustrates the use of template/controller combination to get page output. Now, I’ll explain Fig 1.1 and give the formal definition of the concept: DIV SPAN dast:scope {SomeValue} This is the top-level concept definition. Next we will take a closer look at the scope tree. Scope tree is essentially a mechanism that gives the developer full control over the page output. In the beginning of page rendering process, DaST builds the scope tree by parsing the HTML template. This tree structure is exposed to the developer via Scope Tree API, so developer task inside action and binding handlers of the controller class reduces to pointing at the specific scopes in the tree and manipulating them: bringing real values to placeholders, repeating scope content, and others. Scope tree structure is not constant. Once the tree is initially parsed from the HTML template, it may change during further rendering process. For example, when some scope gets repeated, the tree gets an additional branch coming from this scope. We will distinguish 2 primary states of the scope tree: initial scope tree and rendered scope tree. Initial scope tree is the one that is parsed from the HTML template in the beginning of rendering process. In other words, initial tree is a structural skeleton of the HTML template. Template defines the initial tree, and vice versa, having initial scope tree, we can build valid and fully functional HTML template consisting of only scope container elements. For better understanding I will depict all scope trees that I talk about. I’ll use the following notation: Let’s now create the initial scope tree for our Example 1. To achieve the UI shown on Fig EX1 in Example 1 Intro section, it’s obvious that we need 3 nested repeaters. In DaST terms this a tree of 3 nested scopes repeating their content. Fig 1.2 shows the initial scope tree that I came up with: Fig. 1.2: Initial scope tree for Example 1 part of LittleNonsense demo A couple of important things to note: NULL Now let’s talk about the rendered scope tree. Rendered scope tree is the one that initial tree turns into in the end of rendering process. In other words, rendered tree represents the resulting web page. It’s always bigger than initial tree, because of new branches appeared due to the repeated scopes. Recalling graph theory we can make a couple of observations: Back to our Example 1. Looking at the UI on Fig EX1 in Example 1 Intro section and the initial tree on Fig. 1.2, let’s now depict the rendered scope tree: Fig. 1.3: Rendered scope tree for Example 1 part of LittleNonsense demo The initial tree which is a sub-tree of the rendered scope tree is depicted in black color. Grey part is whatever is added after all needed scopes are repeated to get the desired output. Blue comments help you to understand how scopes in the rendered tree correspond to the resulting output of Example 1 page. There are 3 customers in the XML data file, so CustomerRepeater content is repeated 3 times for customers "John", "Roman", and "James". Customer "Roman" has 2 orders, so OrderRepeater content is repeated 2 times for "[O02]" and "[O03]" order IDs. And so on. As I mentioned earlier, the developer controls page output by manipulating the scopes via Scope Tree API. Before manipulating the specific scope, it must be selected using scope path. The scope path is simply a way of addressing scope in the tree. Every data scope is uniquely identified by its scope path. When web page is rendered, string versions of scope paths are used in id attributes of the corresponding scope container elements. Uniqueness of scope path guaranties uniqueness of scope container element id attribute. Scope path consists of segments. Segment is a combination of the 0-based repeating axis and the scope name. Repeating axis indicates the repeating iteration of the container scope. If parent container scope does not repeat its content, then repeating axis stays 0. In the source HTML of Example 1 resulting page, scope container elements look like the following: <div id="SCOPE$0-CustomerRepeater$1-OrderRepeater$0-ItemRepeater"> The id attribute contains the string representation of the path for this scope. The actual path follows after “SCOPE” prefix and segments are delimited by “$” sign. NULL scope is always the same, so we don’t include it in the scope paths. Looking at the id attribute above, we can immediately tell which scope this DIV corresponds to on Fig 1.3. Just follow the path: take 1st (axis 0) CustomerRepeater, then take 2nd (axis 1) branch to OrderRepeater, then 1st branch to ItemRepeater. So, this path points to the ItemRepeater scope with "[O02] 2012-04-05" text on it (see Fig 1.3). DIV CustomerRepeater OrderRepeater ItemRepeater Note that scope container id attributes always use absolute paths, but inside the controller callbacks, we can also use relative scope paths. Relative paths start from the current scope i.e. the one that current action or binding handler is executing for. Controller is a back-end class that tells the system how to render the scope tree. The scope tree is defined by the template associated with the controller. You can think of DaST controller and template combinations as a conceptual replacement for standard ASP.NET server controls or MVC views/controllers. Every controller can consist of other nested controllers, each of them responsible for its own part of the scope tree. To control the desired part of the tree, the controller needs to be attached to the specific scope in the initial scope tree. When controller is attached to the scope, it becomes responsible for rendering of the partial scope tree (or sub-tree) starting from this scope. The sub-tree is rendered by the rendering traversal procedure that visits scopes one after another, calls corresponding binding handlers, and generates output (more details in Page Rendering section). Attaching controllers to their scopes is a part of tree model building which happens in the very beginning of the rendering process, so we’re only talking about the initial scope tree here. This is done before any of action or binding handlers are invoked, so the scope tree still has its initial structure parsed from the template. By default, DaST page is driven by one top-level controller called root controller associated with the root template. Root controller is always attached to the NULL scope of the tree defined by this template. If there are no other controllers, root controller becomes responsible for rendering the entire scope tree. For example, in Example 1 app for simplicity I used a single top-level root controller responsible for the entire scope tree. But if I attached some child controller to the OrderRepeater scope on Fig 1.2 and rendering traversal went beyond the OrderRepeater, then the responsible controller would be the one attached to OrderRepeater rather then the root controller attached to the NULL scope. And this controller would be used to execute action and binding handlers. All corresponding coding techniques are explained in depth in Controller Class section. Scope Tree API is the interface for talking to the scope tree from inside action and binding handlers in the controller class. In order to get the desired page output, our task reduces to manipulating specific scopes in the tree. After scope is pointed using scope path (see Scope Paths), we can perform certain manipulations on it such as: For more details go to Scope Tree API Reference. DaST page rendering process is the period from client request hitting the page until the response is sent back to the client. In standard ASP.NET we used to call it a “page lifecycle”, but I intentionally do not use this term here to emphasize the difference. There is no weird sequence of page and child control events where execution goes back and forth, no questions which event to use to do the certain task, no ambiguity at all. DaST rendering process is defined with mathematical precision and it is the most beautiful part of DaST pattern. Let’s start from looking at the top-level picture of client-server interaction and request processing flow. Below is the diagram showing this flow step-by-step: Fig. 1.4: Top-level request processing flow So, page loads initially, then reloads multiple times in response to some events on the client side. Overall workflow looks pretty standard except for having DaST page instead of the regular page. Below is the more detailed descriptions of steps marked with red circles on Fig 1.4: There is a couple of important things to note here. First, there is no such thing as full page postback in DaST. Every client action in DaST results in partial refresh of the specific scopes on the page. Whatever you wish to update, needs to be wrapped into the data scope. Second, in terms of code-behind design, DaST partial update has huge advantage over the standard AJAX based on UpdatePanel control. The standard async postback re-executes all your code unless surrounded by ugly IsAsyncPostBack conditionals. DaST re-executes binding handlers for the refreshed scopes only! All details are in the next section. UpdatePanel IsAsyncPostBack Now let’s delve into the page rendering process and see what happens behind the scenes. Like everything else in DaST, rendering process is based on the scope tree defined by the template. Note that rendering process illustrated on Fig 1.1 is a bit simplified, because there is only a single root controller responsible for the entire scope tree. In real apps, one page is usually rendered by multiple nested controllers, each of them responsible for its own part of the scope tree i.e. scope sub-tree (see Controller section). So, let’s formalize the rendering process now. On the top-level, it can be divided into 3 steps: Now let’s elaborate what system actually does during these steps. This has to be done separately for initial and subsequent page loads (see Workflow section), because there are some differences in how steps are executed in these two states. So, first, assume we’re on the initial page load. Rendering steps for this case are below: Now, assume we’re on the subsequent page load. Then rendering steps look like the following: And this is it! Sounds unbelievable, but this simple, clear, and transparent approach renders any page no matter how complex it is! Just look how clean, uniform, and well-defined DaST rendering process is in comparison with standard ASP.NET rendering, weird page lifecycle, event precedence, tons of server controls with nested data binding delegates, and so on! Even MVC, being is a huge step ahead of the WebForms, and being very well organized on the server-side, uses control flow and code generation constructs in views and partial views that immediately kills every hope for proper presentation separation. DaST pattern does not have any of these problems. It just dumps all this complexity at once! Since the developer deals only with the controller class, we also want to look at rendering process from the controller point of view. Inside the controller class, execution can be divided into 3 separate stages: Based on these simple stages, we always know the exact order of execution for all functions inside the controller. You’ll see how this works in coding walkthrough sections that follow. For now, we’re done with concept theory! At this point we know enough to start going through the real coding examples and talk about DaST development techniques. There is a bit more theory left, but we will learn the rest as we go through the code samples in this tutorial. To learn basics of DaST programming, we will walk through the code of Example 1 part of LittleNonsense demo application. For deeper understanding I suggest you download the source code and have it in front of you for all explanations. Also, all functions in this tutorial belonging to Scope Tree API are followed by "[*]" link that take you directly to API Reference for this function. So, let’s get started with coding now. Before doing anything we need to reference DaST framework. ASP.NET DaST is contained in a single AspNetDaST.dll and you have to drop this DLL into the /Bin folder of your web application. All classes from Scope Tree API are located in the AspNetDaST.Web namespace. AspNetDaST.dll /Bin AspNetDaST.Web The request URL in DaST leads to a physical .aspx page, which is similar to WebForms and different from MVC’s pattern based request routing. The content of .aspx file is ignored – this page is needed only as a request entry point. After hitting the page, the request processing workflow goes to DaST rendering engine. In other words, DaST framework overrides the entire rendering of the standard ASP.NET page. .aspx Look at Example 1 now. The request hits NonsenseExample1.aspx page and the purpose of the corresponding code-behind is to transfer the flow to the specific DaST controller. The source code of the code-behind is below: NonsenseExample1.aspx Listing 2.1: NonsenseExample1.aspx.cs file 1: public partial class NonsenseExample1 : AspNetDaST.Web.DaSTPage 2: { 3: protected override AspNetDaST.Web.ScopeController ProvideRootController() 4: { 5: return new NonsenseExample1Controller(); 6: } 7: } So, to turn regular.aspx page to DaST page you do the following: AspNetDaST.Web.DaSTPage System.Web.UI.Page ProvideRootController() This is it! Now you have a DaST page driven by the specified root controller. The question you might have at this point is why not to use URL pattern-based request routing directly to the controller, just like the way it is done in MVC and what is the purpose of having that intermediate.aspx page that does nothing? Ok, the main reason and a huge benefit of this design is that DaST pages can coexist with standard ASP.NET pages in one application without any extra settings! This allows the developers to smoothly transition existing ASP.NET apps to DaST-based apps page by page. I tried to smoothly integrate DaST into the existing ASP.NET infrastructure, so we can still use all standard features like HTTP context, session handling, cache management, etc. without changes. Template is passed to the controller as plain text, so the physical location of the template can be anywhere: files, database, remote server, etc. For LittleNonsense app all templates are stored as .htm files under /App_Data/Templates/ folder. Let’s now build the template for Example 1. .htm /App_Data/Templates/ In ASP.NET and MVC we built pages and views by reverse-engineering the desired page look into the set of server controls. Same thing in DaST – we take the desired UI and reverse-engineer it into the data scope tree. In Scope Tree section we’ve already found that Example 1 UI on Fig EX1 can be achieved with 3 nested data scopes. The initial scope tree is on Fig 1.2 and the corresponding template is on the listing below: Listing 2.2: ../App_Data/Templates/NonsenseExample1.htm 01: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> 02: <html xmlns=""> 03: <head> 04: <title>ASP.NET DaST - Little Nonsense | {TodayDate}</title> 05: .................... 06: </head> 07: <body class="some-class-{TodayDate}"> 08: .................... 09: <div dast: 10: <b>CUSTOMER:</b> [{CustomerID}] {CustomerName} 11: <div dast: 12: <div><b>ORDER:</b> [{OrderID}] {OrderDate}</div> 13: <div dast: 14: <div><b>ITEM:</b> [{ItemID}] {ItemName}</div> 15: </div> 16: </div> 17: </div> 18: </body> 19: </html> You can see our 3 scopes represented by nested DIV containers with dast:scope attributes and placeholders. On the rendering output stage (see Rendering section), the scopes are repeated and placeholders are replaced by the corresponding values giving us the desired output. dast:scope You might notice the {TodayDate} placeholder in the BODY tag class and in the TITLE. It’s there just to demonstrate that values can be inserted anywhere in the template including HEAD section. However, we cannot put scopes into this section, because container elements like DIV are not permitted in the HEAD tag. Whatever markup this tag has, it is considered as a part of NULL scope content. {TodayDate} BODY TITLE HEAD Designing the HTML template is a creative process. Templates can get more complex depending on the kind of UI your are trying to achieve. In the same time, it is always a way less complex than MVC views or, moreover, stardard .aspx markup pages, because template always stays just the valid HTML with scope containers, no matter how sophisticated your UI is. Since the entire DaST processing revolves around the data scope tree, it is important that the initial scope tree is properly parsed from the template (see rendering step 3.1.2 in Rendering Process section) . Due to this, DaST engine is very sensitive to bad-formed HTML in your templates. It is the responsibility of the developer to make sure that HTML template is well-formed (all tags are properly closed, attributes have name/value format, etc). If DaST is not able to parse your template, the engine will throw the exception with more detailed explanation of the problem. Currently I use a grammar-based HTML parser to extract data scope tree from the template. Later on this might be changed to the regex-based parser, so DaST will be more forgiving to syntax errors in the templates. After template from Listing 2.2 is completely rendered, we have the desired Example 1 page shown on Fig EX1. From this moment the control flow returns back to .aspx page that completes the output. In other words, DaST does not just output the resulted page as is, but does this via standard Web.UI.Page facilities. Behind the scenes the following happens to the resulted page: Web.UI.Page body There are some good reasons for mimicking the standard .aspx page. First, we need the seamless DaST integration into the standard ASP.NET. Second, in order to save implementation time and make my life easier, it was decided to use standard MS AJAX library with DaST add-on instead of creating my own AJAX layer, because it already has all those postback client scripts and everything else. Creating the dedicated light-weight DaST AJAX layer is on the development list. In the beginning, I wanted to prove the concept ASAP, obviously, and did not bother with my own AJAX. Now, when fully functional library is released, it’s time to clean, polish, and add more features. It is possible that PHP DaST framework gets the jQuery based AJAX library from the beginning and then I will port it for ASP.NET DaST. Controller is where the serious programming starts. From the DaST Concept section you should already have a good top-level picture of what controller class is and what it is for. In LittleNonsense demo all controllers are stored in .cs files under /App_Code/Controllers/ folder. From Listing 2.1 we see that NonsenseExample1.aspx page uses root controller class called NonsenseExample1Controller for processing all client requests. Let me give full source code for this class first, and then in the rest of the section I will explain this code line by line: .cs /App_Code/Controllers/ NonsenseExample1Controller Listing 2.3: ../App_Code/Controllers/NonsenseExample1Controller.cs 01: public class NonsenseExample1Controller : ScopeController 02: { 03: public override string ProvideTemplate() 04: { 05: return Utils.LoadTemplate("NonsenseExample1.htm"); // load temlate content from anywhere 06: } 07: 08: public override void InitializeModel(ControllerModelBuilder model) 09: { 10: // use one binding handler to bind all nested scopes (except for root scope) 11: model.SetDataBind(new DataBindHandler(DataBind_ROOT)); 12: model.Select("CustomerRepeater").SetDataBind(new DataBindHandler(DataBind_CustomerRepeater)); 13: model.Select("CustomerRepeater", "OrderRepeater").SetDataBind(new DataBindHandler(DataBind_OrderRepeater)); 14: model.Select("CustomerRepeater", "OrderRepeater", "ItemRepeater").SetDataBind(new DataBindHandler(DataBind_ItemRepeater)); 15: } 16: 17: // 18: private void DataBind_ROOT() 19: { 20: CurrPath().Replace("{TodayDate}", DateTime.Now.ToString("yyyy-MM-dd")); // output some example values 21: } 22: 23: private void DataBind_CustomerRepeater() 24: { 25: var customers = DataLayer.GetCustomers(); // get all customers 26: 27: CurrPath().RepeatStart(); // zeroize repeater 28: foreach (var c in customers) // loop through customers 29: { 30: CurrPath().Repeat(); // repeat scope for current customer 31: CurrPath().Replace("{CustomerID}", c.GetValue("ID")); // bind customer id 32: CurrPath().Replace("{CustomerName}", c.GetValue("Name")); // bind customer name 33: CurrPath("OrderRepeater").Params.Set("CUST", c); // pass customer to next scope 34: } 35: } 36: 37: private void DataBind_OrderRepeater() 38: { 39: var c = CurrPath().Params.Get<object>("CUST"); // customer passed in params 40: var orders = DataLayer.GetOrders((string)c.GetValue("ID")); // customer orders 41: 42: CurrPath().RepeatStart(); // zeroize repeater 43: foreach (var o in orders) // loop through orders 44: { 45: CurrPath().Repeat(); // repeat scope for current order 46: CurrPath().Replace("{OrderID}", o.GetValue("ID")); // bind order id 47: CurrPath().Replace("{OrderDate}", o.GetValue("Date")); // bind order date 48: CurrPath("ItemRepeater").Params.Set("Order", o); // pass order to next scope 49: } 50: } 51: 52: private void DataBind_ItemRepeater() 53: { 54: var o = CurrPath().Params.Get<object>("Order"); // order passed in params 55: var items = DataLayer.GetOrderItems((string)o.GetValue("ID")); // order items 56: 57: CurrPath().RepeatStart(); // zeroize repeater 58: foreach (var i in items) // loop through items 59: { 60: CurrPath().Repeat(); // repeat scope for current item 61: CurrPath().Replace("{ItemID}", i.GetValue("ID")); // bind item id 62: CurrPath().Replace("{ItemName}", i.GetValue("Name")); // bind item name 63: } 64: } 65: } As I already mentioned, Example 1 is driven by a single root controller whose code is on listing above. This controller is responsible for the entire scope tree starting from the NULL scope. Before delving into actual code, I want to talk about controller implementation structure. Let’s look at the structure of the controller on Listing 2.3. On the top-level, functions inside the controller class can be split into 3 categories that strictly correspond to 3 rendering stages (see Controller Rendering section): ProvideTemplate() InitializeModel() Action_SubmitInput() DataBind_ROOT() DataBind_OrderRepeater() DataBind_ItemRepeater() Next, before taking closer look, let's learn some basic APIs that we use to control scope tree. Before we delve into the controller source code, let’s learn some basic APIs. I already mentioned that the entire Scope Tree API consists of just a couple of classes with a dozen of functions in total. Knowing these, you’ll be able to create apps of any complexity level. In this section I’m going to highlight the most important APIs that we need to understand the code on Listing 2.3. First, ControllerModelBuilder [*] class is used for working with initial scope tree and to setup tree model on Stage 1. Instance of this class is passed to InitializeModel() [*] callback in model parameter. Following is usage example: ControllerModelBuilder model model.Select("CustomerRepeater", "OrderRepeater").SetDataBind(new DataBindHandler(SomeHandler)); This call consists of 2 steps: 1) pointing the scope with Select() [*] function, and 2) calling one of model setup functions. Function Select() [*] takes scope path specification as parameter and moves the scope pointer accordingly. Path consist of scope names only, because we work with the initial scope tree. Path specified is relative to the controller root scope. Then SetDataBind() [*] function associates handler function with the pointed scope. You can also call HandleAction() [*] to bind action handler or SetController() [*] to attach the child controller to the selected scope. I chose to force chained function call syntax everywhere because it looks very compact and readable. And this is all we need to setup tree model on Stage 1. SetDataBind() HandleAction() SetController() Second, ScopeFacade [*] class is used for working with the rendered scope tree and manipulate the scopes from inside your action and binding handlers on Stage 2 and Stage 3. It has a few functions and properties and throughout this tutorial all these members will be explained in greater details. ScopeFacade Same as for initial tree, before calling any member of ScopeFacade [*], the specific scope has to be selected. This is done by CurrPath() [*] and CtrlPath() [*] functions that take scope path (see Scope Paths) specification as optional parameter and return an instance of ScopeFacade [*] pointing at the selected scope. The difference between these 2 functions is that CurrPath() [*] starts from the current scope i.e. the scope for which current binding handler is executed, and CtrlPath() [*] starts from the controller root scope. So they are just like a Select() [*] function for model setup stage, but work in the rendered scope tree. Following is usage example: ScopeFacade CurrPath() CtrlPath() CurrPath() CurrPath("CustomerRepeater", 2, "OrderRepeater").Replace("{SomeValue}", "Hello World!"); Again, chained syntax is used. First call is to point the specific scope, and next call is one of ScopeFacade [*] members. In our case it’s a Replace() [*] function that takes placeholder name and a replacement value. Replace() [*] function has several overloads allowing different combinations of parameters. Note that this time I specified path with repeating axis for OrderRepeater scope. If axis is not specified, it’s considered 0. Replace() Finally, frequently used APIs are Params [*] and StoredParams [*] properties of ScopeFacade [*] class. These two allow us to associate some generic parameters with scopes. Essentially Params [*] is a way of passing data between the scopes during the rendering process. StoredParams [*], as it follows from its name, allows us to persist parameters between subsequent postbacks. Read the API description for these properties for more info. It is important to understand that DaST uses same controller instance to process the entire sub-tree that it’s responsible for and we should not create any instance members inside the controller to store any data. All data must be stored outside and if there is a need for passing objects between scopes, Params [*] property should be used. Params [*] property is of ParamsFacade [*] type that has a set of overloaded functions to get and set scope parameters. Params StoredParams Params StoredParams ParamsFacade Ok, now we know enough to start digging into the code. The order in which controller functions are executed is strictly defined by the rendering process and traversal flow (see Rendering Process). As the system goes through this process and traverses the scope tree, the callback functions inside responsible controllers get invoked one after another until page output is complete. In this section I’ll explain all controller functions in the order of their execution. Before reading further, you need to recall Rendering Process and Controller Rendering sections, because I’ll frequently reference them. Below I’ll follow the controller rendering stages, list callbacks in execution order, and describe what they do and how they work. It all starts with client request hitting the NonsenseExample1.aspx page. Example 1 does not use actions, so we only talk about initial page load here. Code-behind logic on Listing 2.1 transfers all further processing to NonsenseExample1Controller class given on Listing 2.3. NonsenseExample1Controller Execution begins from Stage 1: Controller model preparation. As I mentioned on step 3.1 of rendering process, controller preparation is executed ONCE per controller whenever traversal procedure hits the scope whose responsible controller model is not setup yet. So, for our controller whose model is not setup yet, DaST needs to call 2 setup functions: The purpose of overriding this function is to return the specific template as plain text. On line 5 I use utility function to read template by name from directory on the site and return it. Such simple approach is cool, because we can store our templates anywhere and build flexible CMS engines. Once template is returned, system proceeds with the next function call: This function has the important task to associate scope tree with the controller. In the previous sub-section I explained how ControllerModelBuilder [*] class is used for setting up the tree model. So, on line 11 we associate DataBind_ROOT() with the controller root scope which is the same as NULL scope in our case. Notice that I omitted Select() [*] call, so pointer stays at the controller root. Next, on line 12 we associate DataBind_CustomerRepeater() handler with CustomerRepeater scope. To point at the CustomerRepeater scope, we use Select() [*] function passing relative path to it. On lines 13-14 we do the same for OrderRepeater and ItemRepeater scopes. This time paths consist of multiple segments. ControllerModelBuilder At this point, model setup is complete and the system turns to Stage 2: Action processing. In Example 1 we don’t have any actions, so this stage is simply skipped. No callbacks get invoked here. Actions is more advanced topic and you’ll see how it works in second part of this tutorial. Finally, system comes to Stage 3: Scope tree rendering output. This is the stage where actual rendering happens and our scope tree turns into the rendered scope tree on Fig 1.3. During this stage the traversal visits scopes one by one, invokes binding handlers, and outputs the result. So, traversal starts from visiting the NULL scope of the tree: DataBind_ROOT() SCOPE For better understanding, I will always specify the current scope path i.e. the one that CurrPath() [*] points to if called without parameters. This time current path is SCOPE meaning that CurrPath() [*] points to the NULL scope. The DataBind_ROOT() handler has only a single line of code. In the previous sub-section I explained how ScopeFacade [*] class is used to manipulate scopes from inside action and binding handlers. So, on line 20 we use CurrPath() [*] without parameter to point at the current scope which is the root scope. And then we call Replace() [*] on it to output formatted date into the {TodayDate} placeholder. Recall that this placeholder is used in our template on Listing 2.2 inside TITLE and BODY tags that belong to the NULL scope. And we’re done here. Next traversed scope is CustomerRepeater: SCOPE TITLE SCOPE$0-CustomerRepeater The content of CustomerRepeater scope needs to be repeated for every customer. The {CustomerID} and {CustomerName} placeholders need to be replaced on every iteration with appropriate customer data. So, on line 25 we retrieve the list of customers. We do it using data layer utility that returns entities from XML. Then we call RepeatStart() [*] on the current scope to reset repeating axis counter to 0. This function must be always called before repeating scope content, because by default there is always 1 axis for every scope. On lines 28-34 we loop through all customer objects, repeat the scope, and replace the placeholder. The loop iterates 3 times for customers “John”, “Roman”, and “James”. On line 30 the Repeat() [*] function is called instructing the system to repeat content of the pointed scope once. This function has to be called before anything else on the current iteration. On line 31-32 we use already familiar syntax to paste values into {CustomerID} and{CustomerName} placeholders in the current scope. On line 32 we point to the OrderRepeater scope and use Params [*] property to pass customer object to this scope as parameter. In the previous sub-section I explained how Params [*] property works. The customer saved on this step will be retrieved when execution comes to OrderRepeater binding handler, and we will know whose orders to display. So, our next scope visited by traversal is OrderRepeater: {CustomerID} RepeatStart() Repeat() SCOPE$0-CustomerRepeater$0-OrderRepeater Here we need to do pretty much the same as before, but for customer orders. On line 39 we start from retrieving the customer object passed from the previous traversal step. Current customer object is for “John”. After we get the customer, we use data layer to get the list of his orders. Then, on line 42 we prepare the scope for repeating again by calling RepeatStart() [*]. Finally, on lines 43-49 we do the loop analogical to previous binding handler, but this time for customer orders, replacing placeholders with specific order ID and date values. In the end of iteration, we, again, use Params [*] to save order object for ItemRepeater scope. We’re done here and traversal continues to ItemRepeater scope: SCOPE$0-CustomerRepeater$0-OrderRepeater$0-ItemRepeater Everything is the same here as before, but now for ItemRepeater. First, we retrieve order object from scope parameters. Then get order items from XML. Then loop through them, repeat the scope, and replace the placeholders with item values. This time we don’t need to save anything in Params [*], because there are no more scopes. Now look at the scope tree on Fig 1.3. At this point we have completely traversed the first branch, and the traversal would stop here if we had only one customer. But since we have multiple repeated customers, the traversal has to travel all branches. So, our next visited scope is OrderRepeater again, but on the next repeated branch: DataBind_OrderRepeater() SCOPE$0-CustomerRepeater$1-OrderRepeater Notice the repeating axis of OrderRepeater scope in the current path – it is 1, not 0, because we’re on the second branch now! The customer object retrieved on line 39 is now for “Roman” i.e. the one saved on the 2nd repeating iteration of the previous CustomerRepeater scope. Everything else is the same – get the list of orders for current customer and repeat the scope to display them. Continuing traversal on the same branch, next visited scope is ItemRepeater: SCOPE$0-CustomerRepeater$1-OrderRepeater$0-ItemRepeater As before, first, we retrieve the saved order object for “O02”. Then get its items with “I03” and “I04” IDs. Then repeat the scope for every item and replace placeholders. Next visited scope is ItemRepeater again: SCOPE$0-CustomerRepeater$1-OrderRepeater$1-ItemRepeater It’s the same scope again, but with the different scope path. We are here, because customer “Roman” has 2 orders and we need to output items for order “O03” now. So, order object saved at the current path corresponds to “O03” and we repeat it 2 items. This branch is complete and traversal goes back to OrderRepeater: DataBind_OrderRepeater SCOPE$0-CustomerRepeater$2-OrderRepeater The repeating axis for current scope is 2, because we are now on the 3rd branch for customer “James”. Everything else is the same as before and next scope is ItemRepeater: DataBind_ItemRepeater() SCOPE$0-CustomerRepeater$2-OrderRepeater$0-ItemRepeater Again, except for different path, functionality is analogical to previously visited ItemRepeater scopes. And finally, traversal visits ItemRepeater again, because "James" has one more order: SCOPE$0-CustomerRepeater$2-OrderRepeater$1-ItemRepeater And we’re DONE! Our tree is completely rendered and output is ready. In our simplified Example 1 of LittleNonsense where the page is driven by a single top-level controller, you might get a feeling that traversal cannot go anywhere until it finishes work in the current controller. It’s not true. In case of multiple controllers, the traversal can go beyond the current controller at any time. The traversal simply travels the rendered scope tree and for every visited scope system executes functions inside the currently responsible controller. For example, look at the scope tree on Fig 1.3 and imagine that there is a nested controller attached to ItemRepeater scope. If this were a case, then instead of executing DataBind_ItemRepeater() inside the root controller, the system would execute this handler inside the controller, attached to ItemRepeater. Moreover, the system would have to run the model preparation stage for this nested controller before calling any binding handlers. After it’s done, the traversal would return back to calling DataBind_OrderRepeater() on root controller for the repeated axis. So, execution can go beyond the bounds of the current controller and then come back again. LittleNonsense Look how clear and intuitive your controller code is! No matter how big your scope tree grows – the rendering part of the controller always consists of a plain list of binding handlers. This means that structural complexity of your code does not grow even for sophisticated Web 2.0 designs! This, in its turn, results in simple and readable source code as well as slim application architecture. At this point the first part of this tutorial is completed. We’ve learned basics of DaST design and development and it’s time to delve into true Web 2.0 programming world and see the full power of DaST in action. In this part of the tutorial we will learn the rest of DaST features needed for building highly complex and dynamic Web 2.0 sites. To demonstrate all these new features, I designed Example 2 part of LittleNonsense demo. Further in this section I’ll walk through the source code of this app with all necessary explanations. I’ll start from giving the complete source code for all templates and controllers that participate in Example 2 implementation. This section will be used as code reference for all explanations throughout the rest of this tutorial. At the moment you can skip through it quickly. First of all, this time the request entry point is NonsenseExample2.aspx page. In NonsenseExample2.aspx.cs file everything is simple and analogical to what we’ve seen already in the previous example (see DaST Page section). The system is told to use NonsenseExample2Controller for processing all requests coming to this page. NonsenseExample2.aspx.cs NonsenseExample2Controller Now, as before, I'll give all code listings of Example 2 and will explain everything line by line throughout the rest of this article. Let's start from NonsenseExample2.htm file containing template for the root controller: NonsenseExample2.htm Listing 3.1: ../App_Data/Templates/NonsenseExample2.htm 01: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""> 02: 03: <html xmlns=""> 04: <head> 05: <title>ASP.NET DaST - Little Nonsense | {TodayDate}</title> 06: <link href="res/CSS/common.css" type="text/css" rel="stylesheet" /> 07: <script type="text/javascript" src="res/jQuery/jquery-1.7.1.min.js"></script> 08: </head> 09: <body class="some-class-{TodayDate}"> 10: 11: <div style="font-size: x-large; background-color: Gray; color: White; padding: 10px;">Little Nonsense | ASP.NET DaST Application DEMO</div> 12: <div style="margin: 0 10px;"><a href="NonsenseExample1.aspx">Example 1</a> | <a href="NonsenseExample2.aspx">Example 2</a></div> 13: <div style="margin: 20px; font-size: x-large; font-weight: bold;">Example 2: Partial Update, Actions, and Messages</div> 14: 15: <div dast: 16: <div dast:</div> 17: <div dast: 18: <div dast:</div> 19: <div class="txt"><b>CUSTOMER:</b> [{CustomerID}] {CustomerName}</div> 20: <div dast: 21: <div dast:</div> 22: <div dast: 23: <div dast:</div> 24: <div class="txt"><b>ORDER:</b> [{OrderID}] {OrderDate}</div> 25: <div dast: 26: <div dast:</div> 27: <div dast: 28: <div dast:</div> 29: <div class="txt"><b>ITEM:</b> [{ItemID}] {ItemName}</div> 30: </div> 31: </div> 32: </div> 33: </div> 34: </div> 35: </div> 36: 37: <script language="javascript" type="text/javascript"> 38: 39: function markScopeUpdated(scopeID) 40: { 41: $("div[id='" + scopeID + "'].gizmo").addClass("updated bold") 42: .find(".gizmo").addClass("updated"); 43: } 44: 45: function hideRepeaterHeaders() 46: { 47: // leave only first gizmo header in case of repeater gizmos 48: $(".gizmo").each(function () { $(this).find("> .headerScope:not(:nth-child(1))").hide(); }); 49: } 50: 51: // add server message handler 52: DaST.Scopes.AddMessageHandler("{ScopeID}", "RefreshedFromServer", function (data) 53: { 54: markScopeUpdated(data.ScopeID); 55: hideRepeaterHeaders(); 56: }); 57: 58: // some initial load UI setup 59: $(document).ready(function () 60: { 61: $("form").attr("autocomplete", "off"); 62: hideRepeaterHeaders(); 63: }); 64: 65: </script> 66: </body> 67: </html> Next listing is for child controller template used to display the header section of all scopes: 01: <div class="hdr"> 02: <span class="high-on-update"><b>Updated:</b> Next listing is root controller class itself: Listing 3.3: ../App_Code/Controllers/NonsenseExample2Controller.cs 001: public class NonsenseExample2Controller : ScopeController 002: { 003: public override string ProvideTemplate() 004: { 005: return Utils.LoadTemplate("NonsenseExample2.htm"); // load temlate content from anywhere 006: } 007: 008: public override void InitializeModel(ControllerModelBuilder model) 009: { 010: // scope binding handlers 011: model.SetDataBind(new DataBindHandler(DataBind_ROOT)); 012: model.Select("CustomerRepeater").SetDataBind(new DataBindHandler(DataBind_CustomerRepeater)); 013: model.Select("CustomerRepeater", "Customer").SetDataBind(new DataBindHandler(DataBind_Customer)); 014: model.Select("CustomerRepeater", "Customer", "OrderRepeater").SetDataBind(new DataBindHandler(DataBind_OrderRepeater)); 015: model.Select("CustomerRepeater", "Customer", "OrderRepeater", "Order").SetDataBind(new DataBindHandler(DataBind_Order)); 016: model.Select("CustomerRepeater", "Customer", "OrderRepeater", "Order", "ItemRepeater").SetDataBind(new DataBindHandler(DataBind_ItemRepeater)); 017: model.Select("CustomerRepeater", "Customer", "OrderRepeater", "Order", "ItemRepeater", "Item").SetDataBind(new DataBindHandler(DataBind_Item)); 018: 019: // set child controllers 020: model.Select("CustomerRepeater", "Header").SetController(new ScopeHeaderController()); 021: model.Select("CustomerRepeater", "Customer", "Header").SetController(new ScopeHeaderController()); 022: model.Select("CustomerRepeater", "Customer", "OrderRepeater", "Header").SetController(new ScopeHeaderController()); 023: model.Select("CustomerRepeater", "Customer", "OrderRepeater", "Order", "Header").SetController(new ScopeHeaderController()); 024: model.Select("CustomerRepeater", "Customer", "OrderRepeater", "Order", "ItemRepeater", "Header").SetController(new ScopeHeaderController()); 025: model.Select("CustomerRepeater", "Customer", "OrderRepeater", "Order", "ItemRepeater", "Item", "Header").SetController(new ScopeHeaderController()); 026: 027: // handle client actions 028: model.Select("CustomerRepeater", "Header").HandleAction("RaisedFromChild", new ActionHandler(Action_RaisedFromChild)); 029: model.Select("CustomerRepeater", "Customer", "Header").HandleAction("RaisedFromChild", new ActionHandler(Action_RaisedFromChild)); 030: model.Select("CustomerRepeater", "Customer", "OrderRepeater", "Header").HandleAction("RaisedFromChild", new ActionHandler(Action_RaisedFromChild)); 031: model.Select("CustomerRepeater", "Customer", "OrderRepeater", "Order", "Header").HandleAction("RaisedFromChild", new ActionHandler(Action_RaisedFromChild)); 032: model.Select("CustomerRepeater", "Customer", "OrderRepeater", "Order", "ItemRepeater", "Header").HandleAction("RaisedFromChild", new ActionHandler(Action_RaisedFromChild)); 033: model.Select("CustomerRepeater", "Customer", "OrderRepeater", "Order", "ItemRepeater", "Item", "Header").HandleAction("RaisedFromChild", new ActionHandler(Action_RaisedFromChild)); 034: } 035: 036: // 037: #region Action Handlers 038: 039: private void Action_RaisedFromChild(object arg) 040: { 041: if ((string)arg == "parent") 042: { 043: CurrPath(-1).Refresh(); // refresh parent scope of the root scope of header controller 044: CtrlPath().MessageClient("RefreshedFromServer", new { ScopeID = CurrPath(-1).ClientID }); // notify client of refreshed scope 045: } 046: else if ((string)arg == "child") 047: { 048: // find name of the next scope depending on current scope 049: string nextScope = null; 050: string currScope = CurrPath(-1).ClientID.Split('-').Last(); 051: switch (currScope) 052: { 053: case "CustomerRepeater": nextScope = "Customer"; break; 054: case "Customer": nextScope = "OrderRepeater"; break; 055: case "OrderRepeater": nextScope = "Order"; break; 056: case "Order": nextScope = "ItemRepeater"; break; 057: case "ItemRepeater": nextScope = "Item"; break; 058: } 059: // invoke action on Header scope of the first child scope 060: if (nextScope != null) 061: { 062: CurrPath(-1, nextScope, "Header").InvokeAction("InvokedFromParent", null); 063: } 064: } 065: } 066: 067: #endregion 068: 069: // 070: #region Binding Handlers 071: 072: private void DataBind_ROOT() 073: { 074: CurrPath().Replace("{TodayDate}", DateTime.Now.ToString("yyyy-MM-dd")); // output some example values 075: CurrPath().Replace("{ScopeID}", CurrPath().ClientID); // bind scope client id 076: } 077: 078: private void DataBind_CustomerRepeater() 079: { 080: var customers = DataLayer.GetCustomers(); // get all customers 081: CurrPath().RepeatStart(); 082: foreach (var customer in customers) // repeat scope for each customer 083: { 084: CurrPath().Repeat(); 085: CurrPath("Customer").StoredParams.Set("CustomerID", customer.GetValue("ID")); // pass customer ID to each child Customer scope 086: } 087: } 088: 089: private void DataBind_Customer() 090: { 091: var customerID = CurrPath().StoredParams.Get<string>("CustomerID"); // get customer ID set in previous binding handler 092: var customer = DataLayer.GetCustomer(customerID); // get customer object by ID 093: CurrPath().Replace("{CustomerID}", customer.GetValue("ID")); 094: CurrPath().Replace("{CustomerName}", customer.GetValue("Name")); 095: } 096: 097: private void DataBind_OrderRepeater() 098: { 099: var customerID = CurrPath(-1).StoredParams.Get<string>("CustomerID"); // get customer ID from parent Customer scope 100: var orders = DataLayer.GetOrders(customerID); // get orders by customer ID 101: CurrPath().RepeatStart(); 102: foreach (var order in orders) // repeat scope for each order 103: { 104: CurrPath().Repeat(); 105: CurrPath("Order").StoredParams.Set("OrderID", order.GetValue("ID")); // pass order ID to each child Order scope 106: } 107: } 108: 109: private void DataBind_Order() 110: { 111: var orderID = CurrPath().StoredParams.Get<string>("OrderID"); // get order ID set in previous binding handler 112: var order = DataLayer.GetOrder(orderID); // get order object by ID 113: CurrPath().Replace("{OrderID}", order.GetValue("ID")); 114: CurrPath().Replace("{OrderDate}", order.GetValue("Date")); 115: } 116: 117: private void DataBind_ItemRepeater() 118: { 119: var orderID = CurrPath(-1).StoredParams.Get<string>("OrderID"); // get order ID from parent Order scope 120: var items = DataLayer.GetOrderItems(orderID); // get order items by order ID 121: CurrPath().RepeatStart(); 122: foreach (var item in items) // repeat scope for each item 123: { 124: CurrPath().Repeat(); 125: CurrPath("Item").StoredParams.Set("ItemID", item.GetValue("ID")); // pass item ID to each child Item scope 126: } 127: } 128: 129: private void DataBind_Item() 130: { 131: var itemID = CurrPath().StoredParams.Get<string>("ItemID"); // get item ID set in previous binding handler 132: var item = DataLayer.GetOrderItem(itemID); // get item object by ID 133: CurrPath().Replace("{ItemID}", item.GetValue("ID")); 134: CurrPath().Replace("{ItemName}", item.GetValue("Name")); 135: } 136: 137: #endregion 138: } And final listing is for the child controller used for all scope headers: 01: public class ScopeHeaderController : ScopeController 02: { 03: public override string ProvideTemplate() 04: { 05: return Utils.LoadTemplate("ScopeHeader.htm"); // load template content from anywhere 06: } 07: 08: public override void InitializeModel(ControllerModelBuilder model) 09: { 10: // scope binding handlers 11: model.SetDataBind(new DataBindHandler(DataBind_ROOT)); 12: 13: // handle client actions 14: model.HandleAction("RefreshFromClient", new ActionHandler(Action_RefreshFromClient)); 15: model.HandleAction("InvokedFromParent", new ActionHandler(Action_InvokedFromParent)); 16: } 17: 18: // 19: #region Action Handlers 20: 21: private void Action_RefreshFromClient(object arg) 22: { 23: // client call was DaST.Scopes.Action(scopeID, 'RefreshFromClient', [input, target]); 24: string input = (string)((object[])arg)[0]; // 1st elem of passed JSON array 25: string target = (string)((object[])arg)[1]; // 2nd elem of passed JSON array 26: 27: switch (target) 28: { 29: case "self": break; 30: // notify parent scope by rasing action passing string target as parameter 31: case "parent": CtrlPath().RaiseAction("RaisedFromChild", "parent"); break; 32: case "child": CtrlPath().RaiseAction("RaisedFromChild", "child"); break; 33: default: throw new Exception("Unknown target"); 34: } 35: 36: CtrlPath().Params.Set("PostedData", input); // set posted data parameter 37: 38: CtrlPath().Refresh(); // refresh control root scope 39: CtrlPath().MessageClient("RefreshedFromServer", null); // notify client of refreshed scope 40: } 41: 42: private void Action_InvokedFromParent(object arg) 43: { 44: CtrlPath().Refresh(); // refresh control root scope 45: CtrlPath().MessageClient("RefreshedFromServer", null); // notify client of refreshed scope 46: } 47: 48: #endregion 49: 50: // 51: #region Binding Handlers 52: 53: private void DataBind_ROOT() 54: { 55: CurrPath().Replace("{Updated}", DateTime.Now.ToString("HH:mm:ss")); // bind update time 56: CurrPath().Replace("{ScopeID}", CurrPath().ClientID); // bind scope client id 57: if (CurrPath().Params.Has("PostedData")) // if PostedData param is set for the scope ... 58: { 59: var data = CurrPath().Params.Get<string>("PostedData"); // retrive posted data containing user input 60: 61: CurrPath().Replace("{PostedData}", data); // bind input value to output it 62: CurrPath().AreaConditional("data-posted", true); // display data-posted conditional area 63: } 64: else 65: { 66: CurrPath().AreaConditional("data-posted", false); // hide data-posted conditional area 67: } 68: } 69: 70: #endregion 71: } As you can see, there is lots of interesting stuff in the code. Below I’ll do the quick introduction into the Example 2 demo, then I’ll talk about nested controllers and new features in binding handler, and finally, I’ll turn to the most exciting part which is actions, AJAX partial updates, and duplex messaging. I designed Example 2 application to demonstrate all DaST programming techniques that you might possibly need for creating complex Web 2.0 designs: AJAX partial updates, multiple nested controllers, event handling, duplex messaging, and others. In the same time this demo is quite simple and straightforward. As you might have already guessed, DaST partial update mechanism is based on the scope tree just like everything else in DaST world. Putting it simple, every scope in the tree can be refreshed independently. Main idea in Example 2 is to visualize physical scope containers of the rendered scope tree on the resulting page and allow partial updates of random scopes, so that you can actually see how scope tree works, how scopes get updated, how data is passed, how controllers communicate, feel the workflow, and feel the real power of DaST pattern. In Example 1 our initial scope tree consisted of 3 repeater scopes (see Scope Tree section). Such structure allows us to update the entire repeaters, but not individual repeated items. In Example 2 we wrap repeated items into separate scopes so that partial updates can be also applied to these individual items. As a result, in addition to CustomerRepeater, OrderRepeater, and ItemRepeater scopes, our tree gets Customer, Order, and Item scopes. Next, for better scope visualization I want to output a special info header for each scope in the tree. This header will be displayed on the top of every scope container and will show scope client ID, last updated timestamp, and link buttons to raise actions and do partial update. I want to enclose header into a separate Header scope that will be a first child scope of every other scope in our tree. The resulted initial scope tree for Example 2 is shown below: Customer Order Item Fig. 3.1: Initial scope tree for NonsenseExample2.aspx page of LittleNonsense demo Having this structure of the scope tree, I get the control over every possible part of the page. I can apply partial updates or pass data anywhere I want in any scope combination. Now let’s see the UI output of this demo. A part UI output of this demo is shown below on Fig EX2: Fig. EX2: Part of Example 2 output As you can see, it is essentially the same hierarchical structure as in Example 1 based on the same XML data file of customer orders, but with more functionality and more sophisticated UI. Main thing I do to visualize the scopes is a dotted border around every scope container. Now we can actually see the scopes and ensure that their nesting configuration strictly corresponds to the initial scope tree on Fig 3.1. Also, the border around the scopes that were partially updated due to the last postback will have a red color. Scopes updated directly will have a bold red border, and scopes updated as result of parent scope update will have a regular red border. Shortly you’ll see how this looks. Second, all output of the actual data values from XML input file, is marked with blue background. This is done just to visually distinguish it from other markup on the page not related to values in XML file. And finally, every scope has a header highlighted with yellow background. The header section, as I said before, is wrapped into its own Header scope, so you can see the dotted border around header as well. Let’s take a closer look at the header now. Header Info header not only has its own scope, but also its own controller! Using this example I demonstrate working with multiple controllers, all related techniques, and APIs. If we tried to implement scope tree from Fig 3.1 using single controller with single template (as we did before in Example 1), we would end up duplicating header section code in both template and back-end controller. It is very intuitive to factor header section out into the separate controller with partial template and reuse it every time a scope needs header section. SCOPE$0-CustomerRepeater$0-Header The most interesting part of the scope header is the input box and 3 link buttons. These are needed to demonstrate data input and all Web 2.0 related mechanisms. The idea is that you enter random text in the input field and click one of the links on the left. This raises client action which passes your input data to the server, processes it, applies partial update to the specific scopes, and initiates duplex reply message, handled on the client side. The whole process will be explained in details through the rest of tutorial. Right now I’ll just describe the functionality of these 3 link buttons. So, let’s pick the scope header and enter “Hello World!!!” in it. Now click 1st “HeaderOnly” link. The result will be the following: Here you see the bold red border around the header meaning that scope was directly updated. When we clicked the link button, the action was raised and our input text was passed to the server side along with the action. On the server side we tell the system to display this text within the scope and apply partial update to this scope to reflect the changes. This is a typical interaction workflow for all Web 2.0 apps. As a result, you see your input text output in the “Passed” field on the right and the scope is highlighted. So “Header Only” link means pass the text and update only the header. Now input “Hello World 2!!!” in the same field and click the 2nd link “Parent Scope”. There result is below: This time the header and the parent scope were updated directly. Directly means that we will explicitly ask the system to update these scopes. All child scopes are also updated as result parent scope update, so they have a regular red border. The meaning of updating the parent scope is to show you how nested controllers communicate using controller actions. Since header has its own controller and ItemRepeater is in responsibility of the root controller, in order to update ItemRepeater we will have to notify the root controller. I will explain this interesting process in depth in the further sections. Finally, input “Hello World 3!!!” and click the 3rd link “First Child Scope”. You’ll see the following: Now we see that header of the current scope is updated as well as the header of the first child scope. This is even more sophisticated controller communication, we need to notify the root controller first, and the root controller needs to access current scope’s first child and notify its header. So it’s two steps: from child controller to parent, and from parent to another child controller. Now it’s time to delve into the code and see how this all actually works. And we will start from going through rendering and binding handlers part of the controllers which is already familiar to us from the previous example. Before reading further, please recall all theory from Controller section. In the current section we will walk through the source code of Example 2 controller binding handlers as well as controllers setup. From the Controller Class section in the previous example we already know how binding handlers work and what they are for. But this time the example application has much richer functionality and there are some new features to highlight in connection with rendering process. And, of course, the main difference is that now we have multiple nested controllers with multiple templates, so we want to see how everything works in this case. In Example 2 we use two different controllers and separate templates for each of them. The root controller is NonsenseExample2Controller on Listing 3.3 and its template is in NonsenseExample2.htm on Listing 3.1. The other controller is ScopeHeaderController on Listing 3.4 and its template is in ScopeHeader.htm on Listing 3.2. This controller is needed to display header section for every scope on the page. ScopeHeaderController ScopeHeader.htm Now look at the scope tree on Fig 3.1. We will need to attach child ScopeHeaderController to every Header scope in the tree to make it responsible for outputting the header. Attaching child controllers is a part of the model preparation rendering stage (recall Controller Rendering section). From HTML template point of view, the container element for the scope, to which you’re going to attach the controller, must be empty i.e. contain no markup. This is natural, because every child controller has its own template whose rendered result gets populated into that empty container during rendering traversal. Rendering traversal is not impacted by presence of child controllers anyhow. It still goes through the scope tree in the same traversal order executing binding handlers inside appropriate controllers. So, for currently traversed data scope, system finds the responsible controller and attempts to execute the corresponding binding handler inside it. Recall Traversal Between Controllers section above where I mentioned how execution can go back and forth between parent and child controllers. Now it’s time to touch some source code starting from HTML templates. Our root template is on Listing 3.1. It is responsible for the entire UI except header section. Root templates always look like a complete web page with <HTML> and <BODY> tags, while child templates only contain partial HTML fragments. <HTML> <BODY> All scope containers defining the data scope tree are on lines 15-35. Nesting structure is similar to our previous example, but we have more scopes this time. The multiple Header scopes (lines 16, 18, 21, 23, 26, and 28) are the ones to which ScopeHeaderController will be attached. In the template these scopes look like the following: 16: <div dast:</div> So, as I already said, if we want to attach the controller to the scope, its container must be empty; otherwise, the error is thrown. Child controller has its own template populated into this empty container after rendering. There is also a JavaScript block on lines 37-65. Most of this JavaScript is needed just for fancier output except for lines 52-56 where I use one of the coolest DaST features to handle message sent from the server side. In combination with client actions, this mechanism is called duplex messaging and I’ll talk about all this in depth in our next sections. Now look at the child template on Listing 3.2. On lines 1-11 it has some markup to output the header section UI. Note that there are no nested scopes here, so the scope sub-tree that child ScopeHeaderController is responsible for a single Header scope which is also a root scope of this controller in the same time. The markup is trivial. There are some placeholders to display updated timestamp and scope ID and link buttons to raise actions on lines 5-7. Actions will be explained in depth in Actions section. On lines 8-10 we use another DaST feature called conditional area. I’ll explain this feature in one of the next sections. Child template also includes a JavaScript block on lines 13-56. I use typical jQuery syntax to create a $.ScopeHeader plugin to prepare data and raise actions. This all will be explained in Actions section. Notice the if condition on line 17 – it is needed to avoid plugin class redefinition, because there are multiple Header scopes on the resulted page so this script will be pasted multiple times. I could simply place it in the parent template and the problem would disappear, but I just wanted to show how to write fully independent templates containing mix of markup and scripts. $.ScopeHeader if Now let’s turn to the source code of our controllers. Look at the new scope tree on Fig 3.1. First thing we need to do in the root controller is to attach the child ScopeHeaderController to all Header scopes to make it responsible for rendering the header section. Child controller should be attached in the InitializeModel() [*] override of the parent controller using SetController() [*] API where the instance of the desired child controller is passed. So, on lines 20-25 of our top-level controller on Listing 3.3 we attach ScopeHeaderController to every Header scope in the scope tree. Every call in InitializeModel() [*] follows the same idea all the time – the target scope is selected using Select() [*] and the desired setup API is called on it. So, the typical call to attach the child controller looks like the following: 20: model.Select("CustomerRepeater", "Header").SetController(new ScopeHeaderController()); The SetController() [*] expects an instance of the controller class to be passed as parameter. We can pass the same instance everywhere or use the new one every time like I did – it does not matter, because by design inside the controller we do not rely on instance anyway and use context-dependent facilities like Params [*] collection and others. Now, after controllers are attached, our scope tree is ready for traversal. Leaving all actions related stuff for the future sections, let’s just do a quick overview of binding handlers inside both controllers. From the Controller Class section we already know how binding handlers work and what they are for. So, let’s start from the root controller on Listing 3.3. On lines 11-17 of Listing 3.3 we do some boilerplate code to associate binding handlers with the scopes in the tree using SetDataBind() [*]. Here we have more scope binding expressions than our previous controller in Example 1, simply because there are more scopes this time. We bind all scopes that we have in the scope tree on Fig 3.1 except for Header scope, because this scope has an attached child controller that becomes responsible for rendering this scope. Binding handler implementations are on lines 72-135. In the previous example we only had handlers for 3 nested repeaters. Now we have to add more handlers for Customer, Order, and Item scopes wrapping individual items inside the corresponding repeaters. Other than that, the idea is pretty much the same: retrieve items, repeat scope in a loop, save current item in params, etc. Let’s go through some of the binding handlers really quick. Item First binding handler is DataBind_ROOT() on line 72 for the controller root scope which is also a NULL scope. Nothing special about it. Just replace some placeholders in the root scope. DataBind_ROOT() Next one is DataBind_CustomerRepeater() on line 78. This is already familiar to us: we get the list of customer objects, loop through them, and repeat the current scope. Unlike previous example, we don’t have to replace any placeholders here, because for each item in this repeater we have a dedicated Customer scope whose binding handler should do all replacements. The only thing we need is to pass the customer object to the next traversed scope using scope parameters. Customer And here is the interesting moment. On line 85, to pass customer to the next scope I use StoredParams [*] collection instead of Params [*]: 85: CurrPath("Customer").StoredParams.Set("CustomerID", customer.GetValue("ID")); This time instead of the complete customer object, I pass the ID that can be used to retrieve this customer directly. Why I cannot use Params [*] to do this? Params [*] work only when we need to pass data between the handlers executed on the same traversal run. But since in Example 2 every scope can be randomly refreshed, causing the traversal to re-execute binding handlers starting from this scope, I cannot rely on Params [*] anymore – the customer ID simply will not be there unless DataBind_CustomerRepeater() is executed on the current traversal run. Using StoredParams [*] instead solves the problem easily, because values saved in StoredParams [*] persist during consequent actions and postbacks. I would advice against heavy use of StoredParams [*], because its idea is similar to the standard ASP.NET VIEWSTATE which adds some overhead between Ajax requests. All you can do with StoredParams [*], you can also do without it by just passing parameters along with actions. For our example I just want to demonstrate how to use StoredParams [*] if you really need to. VIEWSTATE Next handler is DataBind_Customer() on line 89. Its implementation is trivial. On line 91 we retrieve previously saved customer ID. Even if traversal starts from current binding handler (partial update), the StoredParams [*] will still contain the needed customer ID value saved there on the initial page load when traversal went through the entire tree. On line 92 we get the customer object using customer ID. And on lines 93-94 we replace the placeholders. DataBind_Customer() Next one is DataBind_OrderRepeater() on line 99. And here we see one more interesting thing – negative number in the scope path: 99: var customerID = CurrPath(-1).StoredParams.Get<string>("CustomerID"); Read the CurrPath [*] API description and refer to the Example 2 scope tree on Fig 3.1. Current scope is OrderRepeater and negative -1 tells the system to go 1 scope backwards i.e. point at the previous Customer scope. Since customer ID was saved with the Customer scope, we can always retrieve this ID by pointing at this customer scope. CurrPath -1 Everything else in this handler is the same as for previous repeater. We retrieve a list of orders by customer ID, repeat scope in a loop, and pass current order ID to Order scope on each iteration. Order And so on. Other binding handlers in NonsenseExample2Controller are analogical. Now let’s see what’s going on in the child ScopeHeaderController on Listing 3.4. The Header scope that this controller is attached to, becomes the root scope of this controller. Except the root scope, there are no more scopes in this controller. So we only need one binding handler for the root scope. The handler is set on line 11 and the callback function DataBind_ROOT() is on line 53. This binding handler will render the entire header UI. First of all, on lines 55 and 56 we replace {Updated} and {ScopeID} placeholders with current timestamp and ClientID [*] of the current scope respectively. Take a look at the template on Listing 3.2 where all these values are inserted. Next, on line 57, we use Params.Has() [*] to check if parameter named "PostedData" is set. If yes, then this data is output to the {PostedData} placeholder; otherwise, we hide the entire output area. On the initial load, "PostedData" parameter is not set. On the subsequent loads, it is set for the current scope by the action handler in response to user input in the text box within the scope header. This will be explained in depth in our next Actions section. For now, last thing in binding handlers that needs explanation is usage of AreaConditional() [*] API on lines 62 and 66. {Updated} {ScopeID} ClientID Params.Has() "PostedData" {PostedData} "PostedData" AreaConditional() Take a quick look at the AreaConditional() [*] API. This is simply a way to hide or show a fragment of your HTML code depending on some condition. This fragment has to be wrapped into a special comment tag with the special syntax. In our child controller template on Listing 3.2 we have such conditional on lines 8-10: AreaConditional() 08: <!--showfrom:data-posted--> 09: <b>Passed:</b> <span class="passedData">{PostedData}</span> 10: <!--showstop:data-posted--> This area is controlled from the binding handler using AreaConditional() [*] API. On line 66 of Listing 3.4 we have the following statement: 66: CurrPath().AreaConditional("data-posted", false); This tells the system to remove specified area from the resulting page. On line 62 we pass TRUE for the second parameter meaning that area needs to be added to the resulted page. Same thing we could achieve by wrapping conditional area in the scope and hiding it when necessary, but we don’t want to flood our scope tree with unnecessary scopes. Conditionals are the light-weight approach to toggling different UI areas on the page. TRUE Area conditionals can be nested to achieve logical AND or put beside each other for logical OR. You can combine conditions in many different configuration to achieve your UI requirements. One thing to remember about conditionals is that they should not contain nested scopes. It will not break anything, but from the design point of view, it does not make sense to hide scopes using parent conditional area. In such case a parent scope should be used to maintain a clear scope tree. Actions and duplex messaging mechanism in combination with partial updates is another outstanding feature that makes DaST different from other frameworks. Main asset of DaST concept is that simplicity and flexibility of the core features design are both at the maximum level in the same time, while other modern server-page engines usually have to sacrifice one for the sake of the other. Actions mechanism is a DaST replacement for event handling. The typical action workflow is the following: In our Example 2, action is raised when user inputs some text into the textbox located in the header area of every scope and clicks one of the link buttons on the right. In Intro section I’ve already described the differences of those 3 link buttons and the resulting action top-level workflow. Let’s go though this process from the very beginning and explain everything in details. Action is raised in the client browser using DaST.Scopes.Action() [*] API. The scopePath passed to this function is the ID of the scope whose responsible controller should be used to handle the event. The actionName parameter identifies the action within the controller. Finally, actionArgs is a generic data parameter passed along with an action. The DaST.Scopes.Action() [*] function can be called from anywhere within your web page. You can put it in the onclick attribute of HTML element or call it from your JavaScript – there are no limitations. Now back to our example on Listing 3.2. Assume we input “Hello World!!!” and clicked “Header Only” link button as described in Example 2 Intro section. The result of this action is also described in Example 2 Intro section. Now let’s follow the code and see what happens and how exactly it works. The “Header Only” link button is on line 5 of Listing 3.2 and it looks like the following: DaST.Scopes.Action() scopePath actionName actionArgs onclick 5: <a href="javascript:$.ScopeHeader('submit', '{ScopeID}', 'self')">Header Only</a> All 3 buttons call the same submit method of $.ScopeHeader plugin (I use jQuery plugin syntax just because I like it) passing different parameter to it depending on which button is clicked. The method is implemented on lines 23-36. Even though it’s not directly related to actions, I’ll give a bit of explanation here. The purpose of submit method is to get input text from the corresponding text box, prepare some values, and raise action passing the text and the prepared values as parameters. Since “Header Only” is clicked, the target parameter equals “self”. On line 26 I clear all bolded and red borders bringing them to the initial state before Ajax call. On line 29 I use passed scopeID value to find the current scope container where button is clicked. Note that jQuery will not accept DaST id specification with “$” delimiters, so I have to use attribute selector. I’ll change the delimiters in the future to solve the problem. Next, on line 30 I get the currently input text. Next, we have an if clause on line 31 and warning message display on line 35 in case of the invalid input. Finally, if input is valid, we come to line 33 where all interesting stuff happens: submit target scopeID 33: DaST.Scopes.Action(scopeID, 'RefreshFromClient', [input, target]); This is our long waited call to DaST.Scopes.Action() [*] API to raise a client action. The scopeID param is reused here to point at the scope whose responsible controller should handle an action. Recall that we’re currently in the template for one of the Header scopes, so scopeID will point to one of Header scopes depending on where we clicked the button. And the controller attached to this scope is ScopeHeaderController, so the system will use its instance to handle current action, which is the desired behavior. Second parameter is action name and I chose "RefreshFromClient". It’s self-explanatory telling that “this is a refresh request coming from client”. Note that action name has to be unique for the entire controller, not for the target scope. Last parameter is the generic data value that will be passed to the action handler on the server side. This value has to be a JSON-serializable object. In our case we pass the JSON array where we put input text and a target (whose value is "self" in our case). Now action is raised. Let’s see how to handle this action on the server side. ScopeHeaderController "RefreshFromClient" "self" In the controller class, actions are bound to their handlers inside the InitializeModel() [*] method using HandleAction() [*] API. There is no need to point at the specific scope using Select() [*], because client actions are bound on per-controller basis. The action handler function must have a generic object argument that equals the data value passed to DaST.Scopes.Action() [*] on the client side. Inside action handler, CurrPath() [*] always points to the scope specified by scopePath parameter in DaST.Scopes.Action() [*] call. Back to our example. As we know from previous section, the system chooses ScopeHeaderController attached to Header scope to process our "RefreshFromClient" action. The code for this controller is on Listing 3.4. First thing we have to do is to bind the action to its handler and this is done on line 14 as following: CurrPath() "RefreshFromClient" 14: model.HandleAction("RefreshFromClient", new ActionHandler(Action_RefreshFromClient)); So, you pass action name and the handler function. Implementation of Action_RefreshFromClient() handler is on lines 21-40. Let’s go through the source code of this handler and explain what it does. The purpose of this handler is to take the text input by the user, save it in the "PostedData" param for the scope that submitted this data, and then refresh certain scopes to make them re-render. Since we used “Header Only” button, we only need to refresh the current Handler scope (target is equal to "self"). From section Child Control Binding section we already know how DataBind_ROOT() binding handler on lines 53-68 works. On re-render, this handler is called again. This time "PostedData" value is set and the conditional area reveals the HTML snippet with actual input data, so you see your “Hello World!!!” output in red rectangle (see Header Action Links section). Action_RefreshFromClient() Handler "self" "PostedData " First of all, handler function has a generic arg parameter which is set to the JSON value passed to DaST.Scopes.Action() [*] from the client side. JSON objects are represented in .NET as combination of arrays and name-value dictionaries so it’s quite simple to work with them. Recall that I passed array of two values: input text and target. On lines 24 and 25 I retrieve these values into local variables. Next, on line 27, we switch on target value which does nothing in our case, because target equals "self". All other cases will also be explained in further tutorial sections. CurrPath() [*] points to the controller root i.e. the Header scope. On line 36 we save our “Hello World!!!” text under "PostedData" name to the current Header scope, so that it will be picked up inside the DataBind_ROOT() on re-rendering. Finally, we notice two more interesting expressions in the end of the action handler. On line 38 we see the DaST partial update used to refresh the current Header scope. And line 39 demonstrates DaST duplex messaging mechanism used to notify the client side of the event and pass data to it. Both these cool features are explained in depth on the next two sections. arg In DaST partial update can be applied to any scope or multiple scopes inside the tree. If scope is refreshed, its child scopes are refreshed as well. DaST does not refresh any scopes on a postback unless it is explicitly instructed to do so. There are no things like UpdatePanel triggers or similar stuff from standard ASP.NET. To refresh the scope in DaST, you need to point it using CtrlPath() [*] or CurrPath() [*] and call Refresh() [*] function. If you do this on multiple scopes, all of them are refreshed. It’s just that simple. When Refresh() [*] is called on the pointed scope, this scope is placed into the refresh queue. After completion of Stage 2: Action processing, the Stage 3: Rendering output starts (see Controller Rendering section). This time, instead of traversing the scope tree from the NULL scope, the tree is traversed partially starting from the scopes in the refresh queue. The resulting output for each sub-tree is sent back to the client and is applied to the corresponding scopes on the web page. It’s important to understand that during partial update, DaST executes binding handlers for the refreshed scopes ONLY! This is a mathematically correct approach to partial update, when partial UI refreshing results it partial code execution on the back-end. Compare to ugly UpdatePanel based updates in standard ASP.NET, where every partial update executed the entire page lifecycle. Now back to our sample code on Listing 3.4. The refresh is done on line 38 by the following instruction: CtrlPath() 38: CtrlPath().Refresh(); The “Header Only” link refreshes only one scope which is a Header scope corresponding to the header where the link button is clicked. Due to this instruction, the DataBind_ROOT() on line 53 will be re-executed during rendering traversal and the newly generated output will be applied to the corresponding scope on the web page. The resulting UI from clicking “Header Only” link was shown in Header Action Links section. To highlight the specific scope with red borders I need to be able to detect on the client side whether this scope was refreshed. For this purpose I can use one of my favorite DaST features – duplex messaging. Putting it simple, client messaging mechanism is like actions, but in the opposite direction. While action is raised on the client side and handled on the server side, the message is raised on the server side and is handled by JavaScript in the client browser! Actions and client messages complement each other allowing true both-ways duplex communication between the client and the server. This mechanism is something that DaST can be really proud of, because with all its simplicity, it brings unmatched Web 2.0 capabilities to your apps. The syntax is uniform like everything else in DaST: to send message to the client browser you need to point at the scope and call MessageClient() [*] function on it passing message ID and JSON data object. In the client script we use DaST.Scopes.AddMessageHandler() [*] JavaScript API to add handler for the specific scope and message ID combination. Back to our code on Listing 3.4. On the last line 39 of our action handler we see the following instruction: MessageClient() DaST.Scopes.AddMessageHandler() 39: CtrlPath().MessageClient("RefreshedFromServer", null); Here I send the "RefreshedFromServer" message to the client side, so that client code can handle this message and update the desired scope borders accordingly. The second parameter to MessageClient() [*] is some generic data value that have to be JSON-serializable object as before. This object is passed to the client and is given to the JavaScript message handler as argument. In our case we don’t need to pass any data, so just pass null. Let’s now see how the message is handled on the client side. In Listing 3.2 on lines 51-54 we see the following: "RefreshedFromServer" null 51: DaST.Scopes.AddMessageHandler("{ScopeID}", "RefreshedFromServer", function (data) 52: { 53: markScopeUpdated("{ScopeID}"); 54: }); And this is a JavaScript handler for our message! The {ScopeID} is replaced by the actual value pointing at the current Header scope. Recall that inside our action handler, the "RefreshedFromServer" message was also sent for the Header scope. Third parameter of DaST.Scopes.AddMessageHandler() [*] is a callback function with data param that gets the JSON representation of the value, passed to MessageClient() [*]. I love JSON, because it’s consistent everywhere. Note that this code is not a part of if(!$.ScopeHeader) condition starting from line 17. This condition need to avoid $.ScopeHeader plugin redefinition, because it’s always the same for all Header scopes. But code on lines 51-54 is always different due to different values of {ScopeID} and in our case message handler needs to be added for every Header scope on the page. Next, inside the callback function on line 53 I call a helper markScopeUpdated() function to give our scope the updated look and feel. This helper function is implemented inside the root template on Listing 3.1 on lines 39-43. You can see that I simply select the updated scope container and assign CSS classes to it so it becomes red and bold. Also I make all child containers red, but not bold, so that only the directly updated scope becomes bold. This achieves the UI we could see in Example 2 UI section. And this is it! Our scope gets updated, message is handled, UI is adjusted. Now it's time to see what other two link buttons do. data if(!$.ScopeHeader) $.ScopeHeader markScopeUpdated() Last topic that we need to learn is controller-to-controller communication. In DaST controllers talk to each other using controller actions. One of the biggest DaST assets is that syntax of controller actions is absolutely uniform with actions raised on the client. Assume we entered “Hello World 2!!!” into the header of ItemRepeater as shown in Header Action Links section. We already know how “Header Only” button works, but the other two buttons require a bit more programming. Main difference is that for “Header Only” button both action handling and scope refreshing were done in one ScopeHeaderController, because we only needed to refresh the Header scope. For “Parent Scope” and “First Child Scope” buttons we also need to refresh the parent ItemRepeater scope that root NonsenseExample2Controller is responsible for. So, what we need to do here is to refresh the Header scope and then tell the parent controller to refresh the ItemRepeater. To communicate between controllers DaST provides controller actions mechanism. The child controller can raise action that can be handler in the parent controller. Actions are raised using RaiseAction() [*] function where we pass action name and generic argument. This action can be handled on a parent controller using HandleAction() [*] API with syntax uniform with client actions handling. The only difference is that data item does not have to be JSON-serializable this time, because object is passed on the server side. Also, when handling client action, there is no need to point the scope before calling HandleAction() [*], but in case of controller action, we must point at the scope to which the desired child controller is attached. Back to our example. Assume we input “Hello World 2!!!” as shown in Header Action Links section and clicked “Parent Scope” button. The action is raised again by line 33 on Listing 3.2, but this time target equals "parent". Our action handler on line 21 of Listing 3.4 is executed again and this time switch clause on line 27 chooses case for "parent": RaiseAction() "parent" 31: case "parent": CtrlPath().RaiseAction("RaisedFromChild", "parent"); break; This is where we raise our "RaisedFromChild" action to be handled in a parent controller. I pass “parent” as generic data parameter because I’ll need to use this value later. After this line is executed, the action is raised and becomes visible to the parent controller which is in our case a root NonsenseExample2Controller on Listing 3.3. First thing we need to handle this action is to associate the action handlers. This is done on lines 28-33 of Listing 3.3 where I point all Header scopes (to which ScopeHeaderController is attached) one by one and associate the Action_RaisedFromChild() action handler with "RaisedFromChild" action. So, Action_RaisedFromChild() on line 39 gets called in response to the "RaisedFromChild" action with arg equal to "parent". The if clause on line 41 gets satisfied and lines 43 and 44 are executed. CurrPath() [*] still points and the Header scope, so, to refresh the ItemRepeater, we must go 1 step back in the scope tree first and then refresh. This is done on line 43. On line 44 we send a duplex "RefreshedFromServer" message to the client passing scope ID as parameter to notify our UI about the scope refresh. In the root template on Listing 3.1 this message is handled using the following code on line 52: "RaisedFromChild" Action_RaisedFromChild() 52: DaST.Scopes.AddMessageHandler("{ScopeID}", "RefreshedFromServer", function (data) 53: { 54: markScopeUpdated(data.ScopeID); 55: hideRepeaterHeaders(); 56: }); And this calls markScopeUpdated() helper function already familiar to us from the previous section. This function takes the ID of the refreshed scope as a parameter and I use the data.ScopeID that I passed to the previous MessageClient() [*] call. Could it be simpler? Ok, cool, but this is not it. After Action_RaisedFromChild() handler completes, the execution returns to Action_RefreshFromClient() handler on Listing 3.4 to line 36. The statements on lines 36, 38, and 39 get executed and I've already explained them in the previous section. So, as a result, the Refresh() [*] is called on both ItemRepeater and Header scopes. Since this Header is a child of ItemRepeater, it does not really matter if we call Refresh() [*] on the Header scope, because it is updated anyway as a child of the refreshed scope. Next thing to note is that we send two duplex messages to the client during current action handling procedure: on line 44 of Listing 3.3 and on line 39 of Listing 3.4. This, in its turn, means that both message handlers will be invoked on the client side: one on line 52 of Listing 3.1 and the other on line 51 of Listing 3.2. As a result, both Header and ItemRepeater scopes get the bold red borders. markScopeUpdated() data.ScopeID Action_RefreshFromClient() Now the other way around – parent controller can also raise action handled in its child controller. Or it’s more precise to say invoke action on a child controller. Actions are invoked using InvokeAction() [*] function where you pass action name and generic data item. Before calling this API, you have to point at the scope to which the desired controller is attached. Everything else is very similar to raised controller actions in the previous section. Action is handled using uniform syntax and HandleAction() [*] API (no need to point at the scope, because action is invoked per controller). Now let’s see how the last button works. Assume we enter some “Hello World 3!!!” into the header of ItemRepeater and click “First Child Scope” link as shown in Header Action Links section. This one is the most complex case. Here, instead of updating the parent ItemRepeater scope, we want to update Header scope of the first direct child of the ItemRepeater. There is no real meaning in this operation – I just want to demonstrate various updating and controller communication techniques here. So, in this case, the child ScopeHeaderController still notifies the parent NonsenseExample2Controller, and instead of updating ItemRepeater scope, the controller pushes notification further to the header of its first child scope i.e. to another child ScopeHeaderController. Let’s see how this looks in the code. The action is raised same way by line 33 on Listing 3.2, but this time target equals "child". Our action handler on line 21 of Listing 3.4 is executed again and this time switch clause on line 27 chooses case for "child": InvokeAction() NonsenseExample2Controller "child" 32: case "child": CtrlPath().RaiseAction("RaisedFromChild", "child"); break; So, we raise "RaisedFromChild" controller action again similar way we did for the previous button, but now passing "child" as data. Action_RaisedFromChild() callback on line 39 on Listing 3.3 is executed and this time flow goes to the second if branch on lines 46-64. Now look at the scope tree on Fig 3.1. For all explanations here I assumed we used buttons from header of ItemRepeater. So, action is raised from the controller attached to the Header scope whose parent is ItemRepeater. Our purpose is to access header of the first child Item scope of ItemRepeater passing appropriate path to CurrPath() [*] and notify it of the event. So the task reduces to finding the right path. Knowing that CurrPath() [*] points to the original Header scope and looking at the tree on Fig 3.1 it’s not hard to see that relative path will be -1$0-Item$0-Header i.e. one step back to ItemRepeater and then to first Item and its Header. The problem is that in general case we don’t know which Header raised the action and we have to build the desired path based on the current path. This is what I do on lines 49-58. Basically, I take the last segment on the scope ID and depending on the scope name, I take the proper next scope. That switch is a bit ugly, but this is just a quick and dirty solution. As a result, we have our path and use it to invoke action on the child controller on line 62: Action_RaisedFromChild() -1$0-Item$0-Header Header 62: CurrPath(-1, nextScope, "Header").InvokeAction("InvokedFromParent", null); I point at the desired Header scope that ScopeHeaderController is attached to and call InvokeAction() [*] API passing "InvokedFromParent" for action name and null for generic data item. In ScopeHeaderController on line 15 this action is bound to the Action_InvokedFromParent() handler defined on line 42. The code of this handler is trivial – first, we refresh current scope (which is a Header scope pointed for previous InvokeAction() [*] call) and send another "RefreshedFromServer" message to the client. So, this time we also updated 2 scopes and sent 2 corresponding duplex messages: one for original Header and the other for the Header of the first child scope. The UI result of this operation is on the last picture in Header Action Links section. Only 2 Header scopes are updated and not anything else. "InvokedFromParent" null Action_InvokedFromParent() "RefreshedFromServer" Congratulations! This tutorial is complete and now you're DaST expert! I know it's unusual that such limited set of tools can replace standard frameworks like WebForms or MVC, but it really can. Design your web page UI, divide it in scopes, and use DaST to control you markup areas individually – this is all. That's how web development should look like – simple and intuitive. No need to learn tons of server controls, weird page lifecycle events, grid/repeater/whatever binding expressions, etc. And a huge benefit of DaST is fully separated presentation – the HTML design group can work on real templates while developers work with skeleton templates. Also, whenever existing app needs UI changes, the HTML designer can do it without interrupting programmers. Of course, the ASP.NET DaST framework is still on the early stage. At the moment, we have a well defined pattern, proven concept, and working rendering core that already allow us to do a lot. But there are still some features that will be added in the near future. Within the next couple of months I want to accomplish the following: FORM If you wish to join the project (or PHP DaST) - do it right now! If you have any bright ideas/suggestions, please share with me. Watch for updates and follow @rgubarenko on Twitter. I'm open to any type of questions and will be glad to hear your feedback. Please drop me few lines what you think about all this. All useful links are below..
http://www.codeproject.com/Articles/560364/ASP-NET-DaST-to-wrestle-with-MVC-and-WebForms?fid=1829182&df=90&mpp=50&noise=3&prof=False&sort=Position&view=Normal&spc=Relaxed
CC-MAIN-2015-32
refinedweb
17,003
56.25
Code Reference¶ USE THE NAMESPACE (OPTIONAL)¶ using CognitiveVR; Session Name¶ You can set a custom name for a user's session. This can be useful for organizing sessions in SceneExplorer. If you do not provide a session name, one will be generated for you. This can be changed on the dashboard. You can set a session name before or after the session is initialized. CognitiveVR_Manager.SetSessionName("JohnSmith_001"); Custom Events¶ For an explanation about Custom Events, refer to the Custom Events page. new CognitiveVR.CustomEvent("Some Event Happened").Send(); Lobby¶ A LobbyId connects multiple user sessions together to display a multiplayer experience. Please get in contact to discuss your implementation details. To see more info on this, go to the Lobby System page. Users¶ Recording a user name for a user allows you to see how they experience multiple sessions, potentially across multiple devices. This will not set the Session Name that you can see on the dashboard. Think of this as a unique User ID that you might set for a logged in user. This can be added at Initialization: //YourClass.cs void Start() { var UserProperties = new Dictionary<string,object>(); CognitiveVR_Manager.Instance.Initialize("John Smith", UserProperties); } Or this can be added while your application is running: //some function in your app when you know who has logged in void OnPlayerLogIn(string UserName) { Core.UpdateSessionState(new Dictionary<string, object> { { "PremiumUser", true }, { "SignUpPromotionUsed", "FreeMonthTrial" } } ); }
https://docs.cognitive3d.com/unity/code-reference/
CC-MAIN-2019-13
refinedweb
232
50.12
In BGMC26, I wanted to be able to read the pixels from a rendered image. The image was 128x128 pixels, and so had some 16 thousand color vectors. In a somewhat naive attempt, I converted all of those into mathutils.Vectors. The result was 12 frames per second with nothing else in the scene. After coding a small DLL to allow the image to be dealth with in C, the time went from the 10’s of milliseconds to the 1’s of milliseconds - about a 10x improvement. Where is this applicable? Writing your code in C is not what you want to do. You want as much of your code to be in python as possible. Why? Because in python you don’t have segfaults, you can access the BGE API, and use high level languages. In all the time I’ve been using BGE, this is the first time I have had a single piece of logic “heavy” enough to consider porting it to C. So unless you’re doing image processing, neural networks or some other system handling a lot of data, you do not need to write code in C Limitations - Overhead in passing values into C - so writing a C function to add two numbers is pointless - Have to consider cross platform support - Can only work with C “primitives” (you can use custom C structs in python, but you cannot use python classes in C) - C is harder to debug than python - C can segfault - and so on. One caveat in BGE is that the python ctypes module caches the compiled C file, so you have to quit and re-open blender each time you recompile. Hopefully by now I have dissuaded some 90% of the people hoping to use this to build MMORPG’s or minecraft clones. If you didn’t get the message: Writing your code in C instead of python is probably a waste of your time. But for the few other people out there who want to learn about how to use C in BGE, or just generally want to run C from python, I shall continue. Getting Set Up You will need: - A C compiler. I used gcc on linux, and mingw-64 on windows. I also used Make to automate the build process on linux, but that isn’t necessary - Something to write in C that is more worthwhile than writing it in python - Both C and Python skills. I ain’t going to teach you how to use either of these languages ***A Trivial Example - And how to handle cross platform The most basic thing you can do is run a print statement in C, calling it from python. So here is our c file. It should be named “simple.c”: #include <stdio.h> #include "simple.h" DLLSPEC void test(void) { printf("Tada "); } You may notice that there’s a weird DLLSPEC in front of the function definition. This is because windows has a flag to declare that a function should be accessible externally from a DLL. And so in the header file (simple.h) we need: #ifndef __SIMPLE_H__ #define __SIMPLE_H__ #ifdef _WIN32 #define DLLSPEC __declspec(dllexport) #else #define DLLSPEC #endif DLLSPEC void test(void); #endif This defines the variable DLLSPEC depending on operating system. On windoes it becomes __dexlspec(dllexport), but on linux (or any other platform) it is left as an empty string. Compiling on Linux gcc -c -Wall -Werror -fPIC simple.c gcc -shared -o simple.so simple.o The first line has the -fPIC flag, which makes the code position-in-executable independant. This is useful if the .so file is going to be compiled into another C exectuable. Technically it shouldn’t make a difference here, but I didn’t see the point to risk it. The -Wall and -Werror flag are enabled because they always should be. This first line produces a fairly normal .o file. The second line produces the .so file that we will work with from python Compiling on Windows It’s a bit different on linux, and I’m not sure if this is the best way (Windows is not my platform of choice), but it worked. I ran the following: gcc -c -Wall -Werror -fPIC -DBUILDING_EXAMPLE_DLL simple.c gcc -shared -o simple.dll simple.o -Wl,--out-implib,libsimple_dll.a I am not sure at all what the stuff on the second line means. But without it it was producing invalid DLL’s. Perhaps someone more enterprising than me could explain it. I think the .a file isn’t needed here (indeed, you can delete it and it still runs), but eh, I’m not to sure. Running it in python import ctypes import platform import os # Discover the OS folder = os.path.split(os.path.realpath(__file__))[0] if platform.system() == 'Linux': _accel_path = os.path.join(folder, "simple.so") print("Detected Linux: ", end='') elif platform.system() == 'Darwin': _accel_path = os.path.join(folder, "simple.so") print("Detected Mac OSX: ", end='') else: _accel_path = os.path.join(folder, "simple.dll") print("Detected Windows: ", end='') #Load the library print("Loading C functions from {}".format(_accel_path)) ACCELERATOR = ctypes.cdll.LoadLibrary(_accel_path) # Run our function ACCELERATOR.test() Whowhee. So first we had to figure out what os we’re running, and then load the correct library. Finally, we can call the function. ***Function arguments All useful functions I can think of make use of function arguments. And so we need to know how to pass things into or out of the functions. Fortunately the ctypes module allows us to do this, as well as working with structs and array. If we had the function definition: DLLSPEC void test(int a) Then in python we can just use: ACCELERATOR.test(5) And something somewhere takes care of the magic for us. But for more complex things we have to declare their types from python. So if I were doing: DLLSPEC void test(int* someArray, int arrayLength) Then in python you’d have to use: array_type = ctypes.c_int * 3 array = array_type(0, 1, 2) ACCELERATOR.test(array, len(array)) And here you start seeing the overhead come to bite. Will transferring all the data into a c-type array be faster than just doing the operation in python? In my case in BGMC26, I was working with the output from a camera, and I had it in a python bytearray. As such I could run: array.from_buffer(some_buffer) And the data never went through python at all - both pythons bytearray and C’s arrrays are just pointers at the start of the data and some information about their type. As such, there was minimal overhead as the values were never looked at. in typical C fashion, you can use arrays passed into the function arguments as outputs - which is exactly what I did in the BGMC game. I could have returned a struct, but that would have required working with structs. Working with structs is posisble, and is documented in the ctypes documentation - but I did not need to do it so I didn’t.
https://blenderartists.org/t/accelerate-your-python-with-c/699149
CC-MAIN-2021-04
refinedweb
1,181
73.17