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
|
|---|---|---|---|---|---|
Before you start getting mad at me first a disclaimer: I really think you should adhere to the DRY (don’t repeat yourself) principle. But in my opinion the term “code duplication” is too weak and blurry and should be rephrased.
Let me start with a real life story from a few weeks ago that lead to a fruitful discussion with some fellow colleagues and my claims.
The story
We are developing a system using C#/.NET Core for managing network devices like computers, printers, IP cameras and so on in a complex network infrastructure. My colleague was working on a feature to sync these network devices with another system. So his idea was to populate our carefully modelled domain entities using the JSON-data from the other system and compare them with the entities in our system. As this was far from trivial we decided to do a pair-programming session.
We wrote unit tests and fixed one problem after another, refactored the code that was getting messing and happily chugged along. In this process it became more and more apparent that the type system was not helping us and we required quite some special handling like custom
IEqualityComparers and the like.
The problem was that certain concepts like AddressPools that we had in our domain model were missing in the other system. Our domain handles subnets whereas the other system talks about ranges. In our system the entities are persistent and have a database id while the other system does not expose ids. And so on…
By using the same domain model for the other system we introduced friction and disabled benefits of C#’s type system and made the code harder to understand: There were several occasions where methods would take two
IEnumerables of
NetworkedDevices or
Subnets and you needed to pay attention which one is from our system and which from the other.
The whole situation reminded me of a blog post I read quite a while ago:
Obviously, we were using the wrong abstraction for the entities we obtained from the other system. We found ourselves somewhere around point 6. in Sandy’s sequence of events. In our effort to reuse existing code and avoid code duplication we went down a costly and unpleasant path.
Illustration by example
If code duplication is on the method level we may often simply extract and delegate like Uncle Bob demonstrates in this article. In our story that would not have been possible. Consider the following model of Price and Discount e-commerce system:
public class Price { public final BigDecimal amount; public final Currency currency; public Price(BigDecimal amount, Currency currency) { this.amount = amount; this.currency = currency; } // more methods like add(Price) } public class Discount { public final BigDecimal amount; public final Currency currency; public Discount(BigDecimal amount, Currency currency) { this.amount = amount; this.currency = currency; } // more methods like add(Discount<span data-</span>) }
The initial domain entities for price and discount may be implemented in the completely same way but they are completely different abstractions. Depending on your domain it may be ok or not to add two discounts. Discounts could be modelled in a relative fashion like “30 % off” using a base price and so. Coupling them early on by using one entity for different purposes in order to avoid code duplication would be a costly error as you will likely need to disentangle them at some later point.
Another example could be the initial model of a name. In your system Persons, countries and a lot of other things could have a name entity attached which may look identical at first. As you flesh out your domain it becomes apparent that the names are different things really: person names should not be internationalized and sometimes obey certain rules. Country names in contrast may very well be translated.
Modified code duplication claim
Duplicated code is the root of all evil in software design.
— Robert C. Martin
I would like to reduce the temptation of eliminating code duplication for different abstractions by modifying the well known claim of Uncle Bob to be a bit more precise:
Duplicated code for the same abstraction is the root of all evil in software design.
If you introduce coupling of independent concepts by eliminating code duplication you open up a new possibility for errors and maintenance drag. And these new problems tend to be harder to spot and to resolve than real code duplication.
Duplication allows code to evolve independently. I think it is important to add these two concepts to your thinking.
|
https://schneide.blog/category/year/2019/
|
CC-MAIN-2020-05
|
refinedweb
| 760
| 51.58
|
Introduction ( ‘test.txt’, ‘w’ )
The “w” indicates that we will be writing to the file, and the rest is pretty simple to understand. The next step is to write data to the file:
fileHandle.write ( ‘This ( ‘test.txt’, ‘a’ )
fileHandle.write ( ‘nnnBottom line.’ )
fileHandle.close()
Now let’s read our file and display the contents:
fileHandle = open ( ‘test.txt’ )
print fileHandle.read()
fileHandle.close()
This will read the entire file and print the data within it. We can also read a single line in the file:
fileHandle = open ( ‘test.txt’ )
print fileHandle.readline() # “This is a test.”
fileHandle.close()
It is also possible to store the lines of a file into a list:
fileHandle = open ( ‘test.txt’ )
fileList = fileHandle.readlines()
for fileLine in fileList:
print ‘>>’, fileLine
fileHandle.close()
When reading a file, Python’s place in the file will be remembered, illustrated in this example:
fileHandle = open ( ‘test.txt’ )
garbage = fileHandle.readline()
fileHandle.readline() # “Really, it is.”
fileHandle.close()
Only the second line is displayed. We can, however, get past this by telling Python to resume reading from a different position:
fileHandle = open ( ‘test ( ‘test.txt’ )
print fileHandle.readline() # “This is a test.”
print fileHandle.tell() # “17”
print fileHandle.readline() # “Really, it is.”
It is also possible to read the file a few bytes at a time:
fileHandle = open ( ‘test ( ‘testBinary.txt’, ‘wb’ )
fileHandle.write ( ‘There is no spoon.’ )
fileHandle.close()
fileHandle = open ( ‘testBinary.txt’, ‘rb’ )
print fileHandle.read()
fileHandle.close()
{mospagebreak title=Getting Information on Existing Files}
Using several of Python’s modules, it is possible to obtain information on existig files. To get basic information, the “os” module can be used in conjunction with the “stat” module:
import os
import stat
import time
fileStats = os.stat ( ‘test.txt’ )
fileInfo = {
‘Size’ : fileStats [ stat.ST_SIZE ],
‘LastModified’ : time.ctime ( fileStats [ stat.ST_MTIME ] ),
‘LastAccessed’ : time.ctime ( fileStats [ stat.ST_ATIME ] ),
‘CreationTime’ : time.ctime ( fileStats [ stat.ST_CTIME ] ),
‘Mode’ : fileStats [ stat.ST_MODE ]
}
for infoField, infoValue in fileInfo:
print infoField, ‘:’ + infoValue
if stat.S_ISDIR ( fileStats [ stat.ST_MODE ] ):
print ‘Directory. ‘
else:
print ‘Non-directory.’
The above example creates a dictionary containing some basic information about the file. It then displays the data and tells us if it’s a directory or not. We can also check to see if the file is one of several other types:
import os
import stat
fileStats = os.stat ( ‘test.txt’ )
fileMode = fileStats [ stat.ST_MODE ]
if stat.S_ISREG ( fileStats [ stat.ST_MODE ] ):
print ‘Regular file.’
elif stat.S_ISDIR ( fileSTats [ stat.ST_MODe ] ):
print ‘Directory.’
elif stat.S_ISLNK ( fileSTats [ stat.ST_MODe ] ):
print ‘Shortcut.’
elif stat.S_ISSOCK ( fileSTats [ stat.ST_MODe ] ):
print ‘Socket.’
elif stat.S_ISFIFO ( fileSTats [ stat.ST_MODe ] ):
print ‘Named pipe.’
elif stat.S_ISBLK ( fileSTats [ stat.ST_MODe ] ):
print ‘Block special device.’
elif stat.S_ISCHR ( fileSTats [ stat.ST_MODe ] ):
print ‘Character special device.’
Additionally, we can use “os.path” to gather basic information:
import os.path
fileStats = ‘test.txt’
if os.path.isdir ( fileStats ):
print ‘Directory.’
elif os.path.isfile ( fileStats ):
print ‘File.’
elif os.path.islink ( fileStats ):
print ‘Shortcut.’
elif os.path.ismount ( fileStats ):
print ‘Mount point.’
{mospagebreak title=Directories}
Directories, like regular files, are easy to work with. Let’s start by listing the contents of a directory:
import os
for fileName in os.listdir ( ‘/’ ):
print fileName
As you can see, this is extremely simple, and it can be done in three lines.
Creating a directory is also simple:
import os
os.mkdir ( ‘testDirectory’ )
It is equally as easy to delete the directory we just created:
import os
os.rmdir ( ‘testDirectory )
We can also create multiple directories at a time:
import os
os.makedirs ( ‘I/will/show/you/how/deep/the/rabbit/hole/goes’ )
Assuming we add nothing to the directories we just created, we can also delete them all at once:
import os
os.removedirs ( ‘I/will/show/you/how/deep/the/rabbit/hole/goes’ )
Suppose we want to perform a specific action when a specific file type is reached. This can easily be done with the “fnmatch” module. Let’s print the contents of all the “.txt” files we encounter and print the filename of any “.exe” files we encounter:
import fnmatch
import os
for fileName in os.listdir ( ‘/’ ):
if fnmatch.fnmath ( fileName, ‘*.txt’ ):
print open ( fileName ).read()
elif fnmatch.fnmatch ( fileName, ‘*.exe’ ):
print fileName
The asterisk character can represent any amount of characters. If we want to match just one character, we can use the question mark:
import fnmatch
import os
for fileName in os.listdir ( ‘/’ ):
if fnmatch.fnmatch ( fileName, ‘?.txt’ ):
print ‘Text file.’
It is also possible to create a regular expression using the “fnmatch” module, matching filenames with the “re” module:
import fnmatch
import os
import re
filePattern = fnmatch.translate ( ‘*.txt’ )
for fileName in os.listdir ( ‘/’ ):
if re.match ( filePattern, fileName ):
print ‘Text file.’
If we’re just looking for one type of filename, it is a lot easier to use the “glob” module. Its patterns are similar to those used in “fnmatch”:
import glob
for fileName in glob.glob ( ‘*.txt’ ):
print ‘Text file.’
It is also possible to use ranges of characters in the patterns, just as you would in regular expressions. Suppose you want to print the names of text files with one digit before the extension:
import glob
for fileName in glob.glob ( ‘[0-9].txt’ ):
print fileName
The “glob” module makes use of the “fnmatch” module.
{mospagebreak title=Pickling Data}
Using the methods covered in the previous section, it is possible to read strings from files and write strings to files. However, in some situations, you may need to pass other types of data, such as lists, tuples, dictionaries and other objects. In Python, this is possible through a method known as pickling. To pickle data, you would use the “pickle” module included in the standard library.
Let’s start by pickling a short list of strings and integers:
import pickle
fileHandle = open ( ‘pickleFile.txt’, ‘w’ )
testList = [ 'This', 2, 'is', 1, 'a', 0, 'test.' ]
pickle.dump ( testList, fileHandle )
fileHandle.close()
Unpickling the data is just as easy:
import pickle
fileHandle = open ( ‘pickleFile.txt’ )
testList = pickle.load ( fileHandle )
fileHandle.cloes()
We can also store more complex data:
import pickle
fileHandle = open ( ‘pickleFile.txt’, ‘w’ )
testList = [ 123, { ‘Calories’ : 190 }, ‘Mr. Anderson’, [ 1, 2, 7 ] ]
pickle.dump ( testList, fileHandle )
fileHandle.close()
import pickle
fileHandle = open ( ‘pickleFile.txt’ )
testList = pickle.load ( fileHandle )
fileHandle.close()
As you can see, pickling is extremely easy to do with Python’s “pickle” module. Numeous objects may be stored in files with it. You can also use the “cPickle” module if it is availible to you. It’s exactly the same as the “pickle” modue, but it’s faster:
import cPickle
fileHandle = open ( ‘pickleFile.txt’, ‘w’ )
cPickle.dump ( 1776, fileHandle )
fileHandle.close()
{mospagebreak title=Creating In-memory Files}
A number of modules you will encounter contain methods that require a file object as an argument. Sometimes, it is inconvenient to create and use a real file, however. Thankfully, you can create files that store themselves in a computer’s memory using the “StringIO” module:
import StringIO
fileHandle = StringIO.StringIO ( “Let freedom ring.” )
print fileHandle.read() # “Let freedom ring.”
fileHandle.close()
A “cStringIO” module is also availible. It is identical to the “StringIO” module in use, but, just like the “cPickle” module is to the “pickle” module, it is faster:
import cStringIO
fileHandle = cStringIO.cStringIO ( “To Kill a Mockingbird” )
print fileHandle.read() # “To Kill a Mockingbid”
fileHandle.close()
Conclusion
File management is a task that programmers of many languages will often encounter in their applications. Thankfully, Python makes the task incredibly easy compared to other languages. It offers many modules in its standard library that aid programmers, and its object orientation further simplifies things.
You now have a basic understanding of file management in Python, and you will use it in many future applications.
|
http://www.devshed.com/c/a/python/file-management-in-python/4/
|
CC-MAIN-2015-18
|
refinedweb
| 1,287
| 62.85
|
tag:blogger.com,1999:blog-70918315612536948122018-03-06T15:20:07.159+01:00The EgosphereIdeas and opinions about identity, privacy, self-representation and information sharing.razor_nl Brian Martin<blockquote.</blockquote> This is a quote from 1998, people. <a href=""></a>razor_nl, here's a scary thing<div><object width="425" height="344"><param name="movie" value=""><param name="allowFullScreen" value="true"><param name="allowscriptaccess" value="always"><embed src="" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object></div><br /><br />(thanks, <a href="">Paul</a>)razor_nl discussion continuesRegarding <a href="">my previous post</a> on Bruce Schneiers' blog... the discussion there continues and it is great; For the record, I replied again after it evolved, see below (but please <a href="">read the whole thing</a>)<br /><br />Ok, my reply:<br /><br />This is exactly the sort of discussion I was hoping for.<br /><br />Regarding your comments, Bethan; When someone's data or observed behaviour (which is also data) is captured, that person (data subject, thanks for coining), has something to lose. He could for instance be exposed, embarrassed, harassed or whatever, by ill-meaning data-capturers. This is an acknowledged form of harm to individuals, against which laws are instated in many countries.<br /><br />Individuals themselves are also aware of the risks of being 'observed' or 'captured', and commonly display a degree of consciousness and responsibility regarding their (chance of) exposure. Close the curtains, protect privacy. Maintaining a degree of privacy is common, and not only for <a href="">those who have something to hide</a>.<br /><br />Surveillance, spying, or otherwise secretly observing or recording peoples behaviour (physical or otherwise) is usually not allowed as Clive pointed out; (interesting exception: government or police).<br /><br />For me, I'm not concerned with the data capturing activity, legal as it might be, but with the subsequent _uses_ of the data about the data subjects. Here you claim that data subjects can not expect you to limit your use of their representations. This I find disturbing. There is, again as Clive pointed out, a certain expectation of intended use. Unfortunately, there is often no way for the data subjects to prevent deviation from those expectations (which I find even more disturbing). This lack of control for the data subjects is (for me) an area of great interest/concern (which I try to elaborate at )<br /><br /><br />The situation you describe, where a persons data, once captured, could be put to any use that would benefit the capturer, seems to me exactly the thing that most people would like to protect themselves from, if they could.<br /><br />Lacking any control over your representation (its correctness, storage, distribution or exposure), even when it was once willingly conveyed to some organization (such as your energy company) makes you dependent on _their_ willingness and ability to change your relation with them. You might become powerless to influence their behaviour, since their representation of you, once acquired, is the truth for them. Never mind the 'unintended uses' that might occur (see for plenty of examples).>razor_nl are data subjectsIt has been bothering me for some time that I didn't have an accurate, captive term for describing you and me, the people whose identities are represented as data (which is often kept in systems beyond our control). I found it.<br /><br />We are the <a href="">data subjects</a>. <a href="">How would you like to be treated?</a>razor_nl"those entrusted with our privacy often don't have much incentive to respect it"<img border="0" height="127" src="" style="float: left;" width="200" />I love <a href="">this man</a> (no, not McLovin). He accurately describes what I think is the greatest problem with the current practices regarding how information about people is treated today.<br /><br />The title of this post is a quote from <a href="">his article</a>. To recap, Schneier is saying that the organizations who are keeping records about you, do not have an incentive to protect that data from 'other uses'. In fact, I supose their only incentive to safeguard your data is to ensure continuation of their own business. As long as they have the data which describes you, they couldn't care less what happens next with it. Spreading, leaking, selling of your representation is all fine, as far as they are concerned. It doesn't hurt, so why care.<br /><br />However, the article then continues to describe how laws and policies can be created or improved, as to better protect the individual's privacy. Great stuff, but for me, laws and policies are a sign of trouble in itself. Please allow me to explain.<br /><br />The only option available right now for protecting the people being represented in remote systems, is to create artificial incentives in the form of laws (so bad behavior can be punished); Sometimes the fear for bad publicity (eg. a memory stick lost leading to public scandal, see the 'oh dear' section below right) is seen as a reversed incentive. However, it is probably much more efficient to let the PR department handle those cases <i>after they take place</i>. You lose again. <br /><br />As in most cases where laws and 'after the fact' measures are instated, the actual problem is that such mishaps can occur at all. To prevent this, laws try to tell organizations that manage <i>your</i> data, what society finds desirable and undesirable behavior.<br /><br />This is a totally powerless situation for the individual being represented by the data kept by those organizations. The only things you can do once you trust your data to remote system are:<br /><ul><li>hope for the best, and have full confidence that the 'privacy policy' is adequately upheld.</li><li>sue when your identity leaks, through some fault or intentionally via data sales to third parties. I don't think this has much effect in real life, and again, the damage is already done by that time</li></ul><br />The only real option to stay in control is to <i>not entrust anyone with your personal data</i>, but that would mean you would be deprived of most basic services such as telephone, electricity and ahem, twitter. ;)<br /><br />Or, if Santa ever grants my wish, you could have a personally controlled data set which all those organizations need to refer to if they need to know something. A total inversion of data flow. Instead of you handing out your representation to be kept in remote systems, the service providers would be granted (by you) access to some appointed data store (selected by you) to request access to certain bits of your personal profile (created and shaped by you).<br /><br />Empowerment of the individual by means of technological innovation would help people to take ownership and control of their representations, rendering the whole policy discussion moot. The current power imbalance would be fundamentally reshaped.<br /><br />See also my little rant <a href="">'My representation in remote systems, the present'</a>.razor_nl'm still alive... It's just that my attention is being spread out over so many things, sometimes one of my 3 gazillion projects suffers from neglect. I know, I know, but I'm ok with it, so sue me ;)<br /><br />Btw, the book I'm writing on the Egosphere subject is coming along nicely. Stay tuned.razor_nl representation in remote systems, the presentWarning: rant ahead....<br /><br /><br />I, the one represented, allow you, the receiver of information about me, needed to fulfill a service for me, to acquire and store indefinitely, <a href="">some attributes</a> describing me as an individual, in the hope you will record them accurately and use them solely for the purpose as intended in our agreed initial context. <br /><br />From there on, I have no control over the system you use to store these records, describing me. Any subsequent change which I wish to effect (an act of self expression, creating my self representation) can only be realized with your consent. Any error or conscious mis-representation is not noticed by me directly. You can alter data representing me at will, thereby doing dishonor to my intentions, without me even knowing it happened. I am not consulted or notified if such change should occur.<br /><br />I am powerless to express myself unless my intentions are reflected in your records. Once acquired, you value the recorded version, supposed to be representing me, above my subsequent direct communication of my intentions (as in, 'no sir, our computer says here bla bla bla'), even though I should be considered the ultimate authority in describing myself.<br /><br />Even when it were entirely feasible and economical to consult me each and every time you need to acquire some information of me, you prefer to use the version in your system as it was recorded once in the past. That may be out of date, or not reflecting my current intentions in some way, but you don't really care. You don't verify or check at regular intervals with me. I can try and fix your records (which, for you, are the truth about me, but for me, they are not), but you might not let me, or you are incapable because of "call-center issues".<br /><br />To make things worse, I have this issue with 200 different organizations, each treating me the same way as you did above, thus leaving me practically powerless to express my intentions across them all. (even a single one is hard, let alone 200). Such is the way I am reflected in society, through the eyes of the many organizations that deal with me: Disparate views, often not consistent, and not governed by my intentions. I am most incapable of expressing my desired representation in a consistent manner, such that it reflects the way I wish to be known. Where is the justice in that?<br /><br />Oh and by the way, could you <a href="">take more care</a> with my data?razor_nl the OpenID attribute exchange protocol<span class="zemanta-img" style="margin: 1em; display: block; float: right;"><a href="" target="_blank"><img src="" alt="OpenID" style="border: medium none ; display: block;" /></a><span style="margin: 1em 0pt 0pt; display: block;">Image via <a href="" target="_blank">Wikipedia</a></span></span>The <a title="process for new attribute creation" href="" id="v31z">process for new attribute creation</a> (a 5 point list, proposed by D. Hardt) is broken. It assumes central control (or at least some barrier for me) over what can be postulated about <span id="qdew0" style="font-style: italic;">me</span>. My position on this is explained in <a title="The Profile Problem" href="" id="iids">The Profile Problem</a>.<br /><br />I would rather not see the openID initiative which is applauded for its decentralizing effects on Identity, become a centralized point for attribute definitions.<br /><br /).<br /><br />Off course the openID namespace attributes will mostly be <i id="qsod2">identifying</i>.<br /><br />Let's suppose that everyone gets his own namespace (or comparable mechanism) for creating whatever attributes to describe him or her self; This way, no central authority on 'official attributes' stands in the way of full <span id="jqvk0" style="font-style: italic;">self expression of the individuals describing themselves</span>.<br /><br />In order to exchange attributes meaningfully, the two parties must agree on the semantics (they must agree that the attributes, although maybe <i id="g8on0">called</i> differently by both parties, actually are one and the same thing). But if attributes can be dreamed up by anyone, how do we do that?<br /><br /.<br /><br />It would not be unreasonable to expect well defined attribute collections for general use to<br /.<br /><br />The key point here is that all attributes that I create are in my private namespace, and that semantic matching occurs on a different layer, between each of the 2 identities involved.<br /><br /.<br /><br />The result is decentralized attribute collections (they are personal, but allow for consensus via intermediate maps or via plain old human consensus).<br /><br />Let's fast forward from here.<br /><br />I can imagine that certain groups of people (say, project team members) might want to share some pretty interesting attribute sets, which are not 'standard' by any other means. The support of this kind of creativity is essential.<br /><br /).razor_nl (not) to make friends<span class="zemanta-img" style="margin: 1em; display: block; float: right;"><a href="" target="_blank"><img src="" alt="Social Networks world wide" style="border: medium none ; display: block;"></a><span style="margin: 1em 0pt 0pt; display: block;">Image by <a href="" target="_blank">Chewbacka</a> via Flickr</span></span>Regarding the social web and linking of 'friends', the currently available implementations such as <a href="" title="Facebook" rel="homepage" target="_blank" class="zem_slink">Facebook</a> etc. take the following approach: <br /><br />First you identify who is your 'friend' (within the same network or application), this in turn determines which attributes they are allowed to see. Other classes of relationships like 'acquaintance', 'co-worker' 'school-mate' 'best friend' are now being proposed on the Data Portability forums to manage this. <br /><br />This not only smells like bad design, but it appears to me to be an inversion of what happens in reality. <br /><br /><span style="font-style: italic;".</span> In other words, someone might <span style="font-style: italic;">become</span> a friend <span style="font-style: italic;">after</span> you decide he may see some of your attributes. <br /><br />You don't have to decide on the relationship type upfront if you could granularly disclose attributes to various other identities (and maybe have the favor returned to you).<br /><br />Off course people don't want to be bothered continuously with such fine-grained control over their individual attributes. As usual, software programs can ease the burden and help with common tasks. <br /><br /.razor_nl for feed consumersThe rss feed for this site has been changed to <a href=""></a>.<br /><br />Please update your rss clients.razor_nl sink vs information source<a href="">How Sticky Is Membership on Facebook? Just Try Breaking Free - New York Times</a><br /><br />Another example of how most applications act like information sinks. It's easy to enter <span style="font-style: italic;">your</span> information (data about you), but once you do, you lose control. The Facebook application (like almost any other online application) is an <span style="font-style: italic;">information sink</span>.<br /><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href=""><img style="margin: 0pt 0pt 10px 10px; float: right; cursor: pointer; width: 211px; height: 164px;" src="" alt="Image via" border="0" /></a><br />To me it seems the only approach to preserve control over <span style="font-style: italic;">your data</span> is to leave those applications alone. That's why I'm not on <a href="">Myspace</a>, <a href="">Facebook</a> or others (<a href="">Linkedin</a> being the exception, for some reason).<br /><br />Ideally, I would like to have the ability to create an <span style="font-style: italic;">information source</span>, totally under my control, in which I design and edit my profile. A generic protocol for addressing and disclosure would then allow other applications and people to use this <span style="font-style: italic;">information source</span> for many different applications (which would then basically become views on my data, and that of others in the aggregate).<br /><br />What do you think?razor_nl and the Web WorkerOne of my favorite blogs, <a href="">Web Worker Daily</a>, struck a nerve when <a href="">posting</a> about the <a href="">DataPortability</a> initiative. I couldn't resist to <a href="">comment</a>.razor_nl - bad name for a real problem<a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href=""><img style="margin: 0pt 10px 10px 0pt; float: left; cursor: pointer; width: 200px;" src="" alt="Image: (c) corbis" border="0"></a><br /><span style="font-weight: bold;">It's about you</span><br /><br />The recurring theme in social web data is that the data concerned is <span style="font-style: italic;">about an individual</span> (ie. you). Anything that describes (a part of) you or your actions or preferences or you name it, qualifies to be part of your 'profile'. It doesn't matter if you typed it in yourself, or if it is generated by some system. (As long as something pertains to you, represents you, it should be under your control. I'm taking an extremely user- or identity-centric approach here).<br /><br />Currently almost any data describing you is not under your control. See <a href="">The Profile Problem</a> of which the <a href="">Scoble vs Facebook</a> case is an example (not the latest, methinks).<br /><br />Let me be clear: I totally agree with the problems that <a href="" title="DataPortability" rel="wikipedia" target="_blank" class="zem_slink">DataPortability</a> tries to solve. Only the name of the project is misleading to say the least.<br /><br />The name Data Portability (and some of the things I've read on their website and forum) gives me the feeling that they want to be able to extract and import 'user data' from and into various existing <a href="" title="Social web" rel="wikipedia" target="_blank" class="zem_slink">social-web</a> applications, just like Scoble did. That's a nice problem to solve, but it all depends on what level of abstraction the standards are formulated.<br /><br />Let's do a thought experiment, Imagine a less-than-world-wide web where pre-existing publication platforms were hosting content, each in its own proprietary way. At some point the need for inter-operability (linking) and re-usability of this content becomes apparent.<br /><br />Thanks to Tim Berners-Lee, and lucky for us, we don't have this situation on the current world-wide (webpage) web. We're not porting documents from one web-server implementation to the other, and we don't need or want standards to do so. Instead we have the HTML standard for the document format, the HTTP protocol for accessing and creation, and the URL for addressing. <br /><br />These are key components. But on the social web, we <span style="font-style: italic;">do</span> have this situation.<br /><br />The problem isn't then that we can't <span style="font-style: italic;">port</span> or migrate data (we really shouldn't be wanting to go that way), the problem lies deeper in that there aren't any standards for representing, addressing and manipulating this type of content.<br /><br />Similar to the standards that make the world-wide web so successful, I sincerely hope that the DataPorters want to come up with a similar <span style="font-style: italic;">addressing</span> standard for identities and for individual attributes. Already <a href="" title="OpenID" rel="wikipedia" target="_blank" class="zem_slink">OpenID</a> covers the part of the solution.<br /><br />Once identities and specific attributes are uniquely addressable, data at these addresses should be in a standard <span style="font-style: italic;">document format</span> (like HTML documents which resides at url addresses, 'attribute documents' should reside at attribute-url's). I would like to have an addressable document in a standard document format for each of the attributes that are part of my self-representation. (Unlike web-pages, these attribute-documents shouldn't be automatically world-readable, the documents themselves should include disclosure settings, and part of the access protocol should be the decision to disclose or not, depending on the 'requesting party'.)<br /><br />It follows then that we also need a protocol for sending messages to create, retrieve, update, remove and share (disclose) these attribute-documents (defined by their unique addresses); HTTP does this for viewable documents and we should have something similar for identity-centric attribute documents.<br /><br />Once the standards are there at the right level of abstraction (the attribute level imho), the rest is easy. You could implement a Facebook in no time, and it would be inter-operable with any other such system (no need to shovel data to and fro).<br /><br /><span style="font-weight: bold;">Conclusion</span><br /><br />It seems to me that trying to make current proprietary social-web applications inter-operable after the fact, by devising a standard at the application level, is a waste of effort. Too bad we have existing applications without standards, but this still leaves us with the need for low-level standards for the identity-attribute domain. Once we have that, data portability is a non-issue.razor_nl Profile Problem<span class="zemanta-img" style="margin: 1em; display: block; float: right;"><a href="" target="_blank"><img src="" alt="Ama-gi written in Sumerian cuneiform" style="border: medium none ; display: block;"></a><span style="margin: 1em 0pt 0pt; display: block;">Image via <a href="" target="_blank">Wikipedia</a></span></span>Profiles are used extensively on the web and in the enterprise. With the rise of '<a href="" title="Social web" rel="wikipedia" target="_blank" class="zem_slink">the social web</a>', the number of profiles you can use to describe (parts of) yourself is greatly increased.<br /><br />On the web, each site or service needs to know something about you. This is your profile (for that site or service). In an enterprise setting, a company keeps a profile about all their employees or customers (i.e. you) in their identity management system.<br /><br />When seen from a perspective of <a href="" title="Freedom (philosophy)" rel="wikipedia" target="_blank" class="zem_slink">personal freedom</a>, the current practices pose a few problems, which will be discussed next.<br /><br /><span style="font-weight: bold;">Problem 1: You don't have control over the data that describes you.</span><br /><br />This is the most important problem. Apart from the specific elements you are allowed to store (see Problem 2), the data you entered is stored on a system beyond your control. It might be difficult to make changes, or to correct errors. You might be dependent on the service provider or others to have your data changed or deleted. You don't control the security that surrounds your data. You can't choose the systems on which your data is kept. <a href="">You're not allowed to re-use your own self-representation</a>.<br /><br /><span style="font-weight: bold;">Problem 2: Profiles dictate what you can and cannot tell about yourself.</span><br /><br />Most online services and enterprise identity systems come with a prescribed set of properties (like your name, favorite music etc.) that you need to populate with values concerning yourself. The profile dictates what is required and what is optional. There is often no room for extra information.<br /><br /><span style="font-weight: bold;">Problem 3: Lack of sharing control.</span><br /><br />You often don't control who sees the profile, and, in cases where sharing is relevant, you can't control the parts to disclose in enough detail.<br /><br />On the web, you are stuck with the options the site or service offers you for sharing with other users (as is common in many <a href="" title="Virtual community" rel="wikipedia" target="_blank" class="zem_slink">online community</a> services). Can you share all, nothing, or parts of your profile? Which parts?<br /><br /><span style="font-weight: bold;">Problem 4: Duplication of effort.</span><br /><br />This is not really a problem related to individual freedom, but it is worth mentioning anyway.<br /><br />Each service has its own profile page for you to fill out. This is a duplication of effort for you, since you have to maintain the same set of properties over and over again at each site. It also is a duplication of effort on the part of all the service providers, who build and maintain a profile infrastructure, user interfaces and the data it holds.<br /><br />Admitted, the enterprise identity management system solves the duplication of effort problem by using an enterprise-wide profile management system, so the duplication of effort is mainly seen on the web, not inside the enterprise. However, the first two problems remain. Do you have any more influence over your profile (say, as a customer or employee), now that it rests in an enterprise identity system?<br /><br /><br /><span style="font-weight: bold;">What needs to be done?</span><br /><br />Nowadays, with the proliferation on-line services an social media, the need for a solution for these problems is needed more than ever. The challenge lies in identifying what an acceptable solution looks like.<br /><br />We should take a step back from technical issues, and investigate the essence of self-representation, since a profile for an on-line service is just that. Taking the person being represented as the starting point, issues of personal freedom, privacy and control become relevant. <br /><br />In any case, to prevent the problems identified above, the proposed solution should minimally have the following characteristics:<br /><br />It should work with arbitrary attribute collections. It should allow for fine-grained disclosure (sharing) options under the users control. The data should be stored with a provider/technology of choice.<br /><br />Starting from there, one can see the need for <span style="font-style: italic;">standards</span> which allow an individual to manage the the definition, modification, querying, and disclosure of personal attributes.razor_nl Rise of Networked IndividualismIn <a href="">The Social Affordances of the Internet for Networked Individualism</a>, a very interesting analysis is done of the shift from a group-centered towards a person-to-person society. See especially the chapter <a href="">The Rise of Networked Individualism</a>.razor_nl Profiling: APML<a href="">Attention Profiling: APML Beginner's Guide - Robin Good's Latest News</a><br /><br />The APML standard proposes a unified format for capturing a persons interests. The main idea is to keep the user in control of his data (<span style="font-style:italic;">good</span>). It focuses on certain types of data, mainly those that describe a users preferences and interests. One of the goals is to make recommendations and filtering easier and to prevent information overload.<br /><br />I would say the user-in-control approach is very good, but why limit to certain kinds of data? Do we really need a standard format for each domain or application? My point of view would be to create a standard at a more general level. It should be generic enough to let the person describe himself however he/she wants (see <a href="">The Profile Problem</a>) and for describing detailed disclosure policies. I will elaborate in another article.razor_nl portabilityRecently I came across the <a href="">data portability</a> concept. Finally, it seems that the idea is gaining hold that <span style="font-style:italic;">you</span> should be the owner of the data that describes you. Not Facebook or any other organization which tools you use.<br /><br />This article covers some of the issues: <a href="">Are You Paying Attention?: Top 3 Privacy issues for Data Portability on Social Networks</a><br /><br />Now to argue one step further, I think you should not only be the <span style="font-style:italic;">owner</span> of the data describing you, but also the <span style="font-style:italic;"><a href="">designer</a></span>.razor_nl
|
http://feeds.feedburner.com/egosphere
|
CC-MAIN-2018-13
|
refinedweb
| 4,635
| 50.77
|
Java WebService connected to Database
By: Emiley J Emailed: 1645 times Printed: 2110 times
This tutorial takes one step forward in building Java Web Services by connecting your web service to a database and returning a value from a MySQL database.
If you have completed the previous tutorial on creating your first java web service then you will already have met the minimum requirements and created the required folders.
If you already have the javasamples folder then goto that folder or open the command prompt and create a folder named "javasamples" ( md javasamples )
Next cd javasamples to goto that folder. Now create another folder named "two" ( md two )
Next create a file named Users.java ( notepad Users.java )
Copy the below code in that file and save it.
package javasamples.two;
import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
@WebService
@SOAPBinding(style = Style.RPC)
public interface Users {
@WebMethod int getUserCount();
}
Next create a file named UsersImpl.java ( notepad UsersImpl.java )
Copy the below code in that file and save it. Remember to change the dbname in the dbUrl and the username and password based on your db username and password. This file just connects to the database and counts the number of records in a table named Users. You can change the SQL query as you wish.
package javasamples.two;
import java.util.Date;
import javax.jws.WebService;
import java.sql.*;
import javax.sql.*;
@WebService(endpointInterface = "javasamples.two.Users")
public class UsersImpl implements Users {
public int getUserCount() {
int numusers = 0;
String dbUrl = "jdbc:mysql://localhost/yourdbname";
String dbClass = "com.mysql.jdbc.Driver";
String query = "Select count(*) FROM users";
String userName = "root", password = "yourdbpassword";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection (dbUrl, userName, password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
numusers = rs.getInt(1);
} //end while
con.close();
} //end try
catch(ClassNotFoundException e) {
e.printStackTrace();
}
catch(SQLException e) {
e.printStackTrace();
}
finally {
return numusers;
}
}
} returns the system time. Its a time server.
If you get a compile error, then check this solution for package javax.jws does not exist
If you getting java.lang.ClassNotfoundException:com.mysql.jdbc.driver error then check the suggestions in this answer./two folder.
Now create a new java file named UsersPublisher.java ( notepad UsersPublisher.java )
And copy the below code into it.
package javasamples.two;
import javax.xml.ws.Endpoint;
public class UsersPublisher {
public static void main(String[ ] args) {
// 1st argument is the publication URL
// 2nd argument is an SIB instance
Endpoint.publish("", new UsersImpl());
}
} connects to MySQL database server and retrieves a value from it.
Finally, you need to start your UsersPublisher class. You can do this like ( java javamples.two.UsersPublisher ). That't It. You have created your first java web service and publish it. You can double check whether it works by opening your brower and going to
You can now create a java client to connect to your new web service and get the values from this web service.
Go to the javasamples/two folder.
Now create a new java file named UsersClient.java ( notepad UsersClient.java )
And copy the below code into it.
package javasamples.two;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import java.net.URL;
class UsersClient {
public static void main(String args[ ]) throws Exception {
URL url = new URL("");
QName qname = new QName("", "UsersImplService");
// Create, in effect, a factory for the service.
Service service = Service.create(url, qname);
// Extract the endpoint interface, the service "port".
Users eif = service.getPort(Users.class);
System.out.println(eif.getUserCount());
}
}
Now compile and run this UsersClient class in a new command prompt window as follows: (Make sure the UsersPublisher is running in another command prompt)
javac javasamples/two/UsersClient.java
java javasamples.two.UsersClient
|
http://www.java-samples.com/showtutorial.php?tutorialid=1735
|
CC-MAIN-2017-13
|
refinedweb
| 635
| 53.58
|
Updated on Kisan Patel
This tutorial will show you how to declare, initialize and use variables in C#?
When program was executed, data is temporarily stored in memory. A variable is the name given to the memory location holding the particular type of data. Each variable has associated with it a data type and a value.
Syntax
<Data Type> <Name of the variable>;
For example,
int i; float money; char week;
In above example, first line will reserve an area of 4 bytes in memory to store an integer type values and you can access value by the identifier
i;
You can also initialize the variable when you declare it and also declare multiple variables of the same data type in one single statement.
For example,
int i = 5, j = 10, k = 15; float money = 300.23;
constkeyword.
For Example,
const float PI = 3.14;
Lets take one example to understand how to declare variable and initialize in C#?
using System; namespace VariableDemo { class VariableDemo { static void Main(string[] args) { int age = 24; string name; name = "Kisan"; Console.WriteLine(age); Console.WriteLine(name); Console.WriteLine(name + " was " + age + " years old."); } } }
Output of the above C# program…
|
http://csharpcode.org/blog/variables/
|
CC-MAIN-2019-18
|
refinedweb
| 196
| 54.22
|
Hi,
I am not sure if this was there before but I keep pressing Enter instead of + so it must have been :-)
Even if it wasn't it would be useful that the tree expanded on pressing Enter since it would simplify the navigation of the tree when looking for a usage.
R# 5 Beta 2, VS2010rc.
Cheers,
Jose
Hi,
Hello,
I'm sure the tree expands at least with these actions:
• Mouse clicking on
• Mouse double-clicking a non-navigable node
• +
• Right arrow
• *
• ExpandAll button in the toolar
• R# | Options | Env | S&N | Expand...tree by default
• Enter key on non-navigable nodes
I think the expand-by-default thing could prove useful (used to be broken
in a few pre-release v5 builds).
As for the enter key, it only expands the non-navigable nodes (namespaces,
for example, if they're included by the current grouping). On navigable targets,
it navigates to highlight the target without focus leaving the find results
tool window (Ctrl+Enter navigates completely). Having Enter key do double-action
(navigate and expands) confuses because one of the actions is always unexpected.
So I don't think it could be changed right now. Hope the workarounds (right
arrow key, or expand-by-default option, or choosing another grouping) helps
with your scenario.
—
Serge Baltic
JetBrains, Inc —
“Develop with pleasure!”
Hi,
Thanks for the long explanation.
I see now that the difference is that in 5.0 the usages are grouped whereas in 4.5 they weren't. This makes sense when searching for usages of very popular members but for members with a few usages it is adds one more step/keystroke. The Expand by Default should go a long way to solving the problem although it is not working on the build I have at the moment which is a week or two old. I will install Beta 2 later today and try it.
Cheers,
Jose
Hello,
I believe there's no difference in groupings between v4 and v5. You can choose
any grouping like, or no grouping altogether.
Yes, expand-by-default was broken in a few builds. Not quite sure about Beta2,
but in the most recent nightly builds it's definitely working once again.
—
Serge Baltic
JetBrains, Inc —
“Develop with pleasure!”
You are right, I had different Group By options in both installations (doh!)
|
https://resharper-support.jetbrains.com/hc/en-us/community/posts/206068689-Pressing-Enter-in-the-Find-Results-does-not-expand-tree-
|
CC-MAIN-2021-31
|
refinedweb
| 393
| 63.7
|
Implements consistent hashing with Python and the algorithm is the same as libketama.
Project description
consistent-hash
Implements consistent hashing that can be used when the number of server nodes can increase or decrease.The algorithm that is used for consistent hashing is the same as libketama <>
Usage
It’s so easy to use^_^:
from consistent_hash import ConsistentHash # You can construct consistent hash with the below three ways con_hash = ConsistentHash({'192.168.0.101:11212':1, '192.168.0.102:11212':2, '192.168.0.103:11212':1}) # Or con_hash = ConsistentHash(['192.168.0.101:11212', '192.168.0.102:11212', '192.168.0.103:11212'])) # Or con_hash = ConsistentHash('192.168.0.101:11212') # Add servers to hash ring con_hash.add_nodes({'192.168.0.104:11212':1}) # Get a server via the key of object server = con_hash.get_node('my_key') # Delete the server from hash ring, you don't need to indicate weights con_hash.del_nodes(['192.168.0.102:11212', '192.168.0.104:11212'])
Unit test
Firstly, install nose which extends unittest to make testing easier:
pip install nose
Then, run tests:
# Option -s any stdout output will be printed immediately # and -v be more verbose nosetests -s -v
More information about nose <>
Project details
Release history Release notifications
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
|
https://pypi.org/project/consistent_hash/1.0/
|
CC-MAIN-2018-22
|
refinedweb
| 231
| 54.02
|
Starting with nxml
2006-11-29 18:46:18 GMT
Platform: Intel Pentium M,
Ubuntu Dapper,
emacs21 21.4a-3ubuntu2,
nxml-mode 20041004-5
trang 20030619-4
I am a _long_ time psgml user that eventually will try the leap into
nxml. The reason is that I need context sensitive editing for an XML
format for which I have an XSD schema (the Maven2 POM format).
So I'm fumbling about trying to get started.
I started by trying to create a schema locator, from the description
here:
`C-h v rng-schema-locating-files RET' gives me:
rng-schema-locating-files's value is
("schemas.xml" "/usr/share/emacs/site-lisp/nxml-mode/schema/schemas.xml")
So I did `C-x C-f schema.xml RET' in the same directory as the pom.xml
file that is to be edited. nxml gave the minibuffer message "Using
vacuous schema". I pasted in the example in the above URL, ie.
<?xml version="1.0"?>
<locatingRules xmlns="">
<namespace ns="" uri="xhtml.rnc"/>
<documentElement localName="book" uri="docbook.rnc"/>
</locatingRules>
Then I deleted the <namespace> and <documentElement> elements, and
tried creating a new element. I tried `C-c C-e' to see if that would
give me the list of available elements (that's the psgml binding for
the same... who reads manuals...?
).
That didn't work, so I did `C-h b' to see if there was an
nxml-insert-element command or something similar. The only commands
with "insert" in them, are:
C-c C-u nxml-insert-named-char
C-c C-x nxml-insert-xml-declaration
Some more browsing on Dave's Q&A seemed to indicate that `C-RET' was
the correct command (nxml-complete). But this command just reports
"Cannot complete in this context".
So is the problem that it can't find the schema? Or is this the wrong
command? Or am I trying an insert in the wrong place? Or does the
insert command have a problem with empty elements?
I don't think it is a missing schema, because the show schema location
command, reports
"Using schema /usr/share/emacs/site-lisp/nxml-mode/schema/locate.rnc"
Perhaps it's the wrong command? It seems to be a command to complete
_something_, but how do I know what to complete at this stage....?
Ah... if I type a `<' and _then_ `C-RET' I get a list of whatever can
be inserted at point, which is (probably) the allowed tags. And to
insert attributes I type a space and then `C-RET' again. To complete
an attribute value I type " followed by a space. `C-RET' again gives
me the possibility to insert a new attribute. And typing / and >
closes the element (there seemed to be no magic here).
This works after a fashion. But I prefer the psgml way of `C-e',
select the element, and then respond to prompts for required
attributes, followed by `C-c +' commands to insert other attributes.
Perhaps I'll get used to this way in time? Or perhaps there is a more
psgml-like mode of operation that I haven't discovered yet? (12 years
takes a lot of unlearning...)
Ok, so on to the schema. I've now created a schema.xml file that
resides in the same directory as the pom.xml file, that looks like
this:
<?xml version="1.0"?>
<locatingRules xmlns="">
<namespace ns="" uri="maven.rnc" />
</locatingRules>
This based on a pom.xml header looking like this:
<project xmlns="" xmlns:xsi=""
xsi:
Next is to give trang a look. Hm... doesn't look like it supports XSD
schema as an input schema...?
Or has things happened since James dropped it?
Doesn't look that way, when looking at the man page of the Ubuntu
(debian?) deb package. It has XSD as an output format, but not as an
input format.
Hm... unless I can convert the maven2 XSD schema to an RNG schema, I
might as well roll back to good old psgml. Is there something else I
can use? Or is there a maven2 POM XML RNG schema around?
Ok. From the bottom of
I found rngconv. The procedure to use, was:
- download rngconv.zip from
- unzip rngconv.zip. It will create the directory rngconv-20060319/
- go to the rngconv-20060319/ directory, and type the following
commands:
wget
java -jar rngconv.jar maven-v4_0_0.xsd >maven.rng
trang maven.rng maven.rnc
- then move maven.rnc to whereever the schemas.xml file resides
(currently the same directory as the top level pom.xml file of the
project I'm working on)
So now I appearently have a working schema.
I get an error message from the xsi:schemaLocation attribute.
Does nxml support namespaces? Does anyone know what magic is needed
to do so?
Does anyone have a best practice for setting up my own RNG schema
location? I won't do it tonight. Now it's time for actually _using_
that schema on the pom.xml file(s)...
Change settings via the Web (Yahoo! ID required)
Change settings via email: Switch delivery to Daily Digest | Switch format to Traditional
Visit Your Group | Yahoo! Groups Terms of Use | Unsubscribe
List your web site
in Yahoo! Search.
easy 1-click access
to your groups.
in 3 easy steps.
Connect with others.
__,_._,___
|
http://blog.gmane.org/gmane.emacs.nxml.general/month=20061101
|
CC-MAIN-2014-42
|
refinedweb
| 890
| 77.13
|
java.lang.Object
org.netlib.lapack.DLASD3org.netlib.lapack.DLASD3
public class DLASD3
DLASD3 is a simplified interface to the JLAPACK routine dlasdLASD3 finds all the square roots of the roots of the secular * equation, as defined by the values in D and Z. It makes the * appropriate calls to DLASD4 and then updates the singular * vectors by matrix multiplication. * * This code makes very mild assumptions about floating point * arithmetic. It will work on machines with a guard digit in * add/subtract, or on those binary machines without guard digits * which subtract like the Cray XMP, Cray YMP, Cray C 90, or Cray 2. * It could conceivably fail on hexadecimal or decimal machines * without guard digits, but we know of none. * * DLASD3 is called from DLAS (input) INTEGER * The size of the secular equation, 1 =< K = < N. * * D (output) DOUBLE PRECISION array, dimension(K) * On exit the square roots of the roots of the secular equation, * in ascending order. * * Q (workspace) DOUBLE PRECISION array, * dimension at least (LDQ,K). * * LDQ (input) INTEGER * The leading dimension of the array Q. LDQ >= K. * * DSIGMA (input) DOUBLE PRECISION array, dimension(K) * The first K elements of this array contain the old roots * of the deflated updating problem. These are the poles * of the secular equation. * * U (input) DOUBLE PRECISION array, dimension (LDU, N) * The last N - K columns of this matrix contain the deflated * left singular vectors. * * LDU (input) INTEGER * The leading dimension of the array U. LDU >= N. * * U2 (input) DOUBLE PRECISION array, dimension (LDU2, N) * The first K columns of this matrix contain the non-deflated * left singular vectors for the split problem. * * LDU2 (input) INTEGER * The leading dimension of the array U2. LDU2 >= N. * * VT (input) DOUBLE PRECISION array, dimension (LDVT, M) * The last M - K columns of VT' contain the deflated * right singular vectors. * * LDVT (input) INTEGER * The leading dimension of the array VT. LDVT >= N. * * VT2 (input) DOUBLE PRECISION array, dimension (LDVT2, N) * The first K columns of VT2' contain the non-deflated * right singular vectors for the split problem. * * LDVT2 (input) INTEGER * The leading dimension of the array VT2. LDVT2 >= N. * * IDXC (input) INTEGER array, dimension ( N ) * The permutation used to arrange the columns of U (and rows of * VT) into three groups: the first group contains non-zero * entries only at and above (or before) NL +1; the second * contains non-zero entries only at and below (or after) NL+2; * and the third is dense. The first column of U and the row of * VT are treated separately, however. * * The rows of the singular vectors found by DLASD4 * must be likewise permuted before the matrix multiplies can * take place. * * CTOT (input) INTEGER array, dimension ( 4 ) * A count of the total number of the various types of columns * in U (or rows in VT), as described in IDXC. The fourth column * type is any column which has been deflated. * * Z (input) DOUBLE PRECISION array, dimension (K) * The first K elements of this array contain the components * of the deflation-adjusted updating row vector. * *3()
public static void DLASD3(int nl, int nr, int sqre, int k, double[] d, double[][] q, double[] dsigma, double[][] u, double[][] u2, double[][] vt, double[][] vt2, int[] idxc, int[] ctot, double[] z, intW info)
|
http://icl.cs.utk.edu/projectsfiles/f2j/javadoc/org/netlib/lapack/DLASD3.html
|
CC-MAIN-2018-26
|
refinedweb
| 542
| 51.07
|
I have 10 errors whenever I try to build the app. I was trying to troubleshoot an error, and I did a Clear All, then 10 errors appeared after I tried to build the app. There are variations of the same error.
Here is the error:
"The type or namespace name 'XamlFilePathAttributeAttribute' does not exist in the namespace 'Xamarin.Forms.Xaml' (are you missing an assembly reference?) (CS0234) (Relate)"
Answers
@PatrickStephane Try to update your Xamarin.Forms nuget packages to last stable version.
The errors no longer appear when I load the app after I had updated the Xamarin.Forms nuget packages. However, I am still not able to run the emulator.
|
https://forums.xamarin.com/discussion/comment/291420
|
CC-MAIN-2019-13
|
refinedweb
| 112
| 68.97
|
On Fri, 06 Jun 2008 16:28:55 -0400Rik51why oh why? Must we really really do this to ourselves? Cheerfullyunch upeither a) not being told or b) forgetting. I thought that we hada whopping big comment somewhere which describes how all theseflags.Do we do per-zone or global number-of-mlocked-pages accounting for/proc/meminfo or /proc/vmstat, etc? Seems not..> --- linux-2.6.26-rc2-mm1.orig/mm/Kconfig 2008-06-06 16:05:15.000000000 -0400> +++ linux-2.6.26-rc2-mm1/mm/Kconfig 2008-06-06 16:06:28.000000000 -0400> @@ -215,3 +215,17 @@ config NORECLAIM_LRU> may be non-reclaimable because: they are locked into memory, they> are anonymous pages for which no swap space exists, or they are anon> pages that are expensive to unmap [long anon_vma "related vma" list.]> +> +config NORECLAIM_MLOCK> + bool "Exclude mlock'ed pages from reclaim"> + depends on NORECLAIM_LRU> + help> + Treats mlock'ed pages as no-reclaimable. Removing these pages from> + the LRU [in]active lists avoids the overhead of attempting to reclaim> + them. Pages marked non-reclaimable for this reason will become> + reclaimable again when the last mlock is removed.> + when no swap space exists. Removing these pages from the LRU lists> + avoids the overhead of attempting to reclaim them. Pages marked> + non-reclaimable for this reason will become reclaimable again when/if> + sufficient swap space is added to the system.The sentence "when no swap space exists." a) lacks capitalisation andb) makes no sense.The paramedics are caring for Aunt Tillie.> Index: linux-2.6.26-rc2-mm1/mm/internal.h> ===================================================================> --- linux-2.6.26-rc2-mm1.orig/mm/internal.h 2008-06-06 16:05:15.000000000 -0400> +++ linux-2.6.26-rc2-mm1/mm/internal.h 2008-06-06 16:06:28.000000000 -0400> @@ -56,6 +56,17 @@ static inline unsigned long page_order(s> return page_private(page);> }> > +/*> + * mlock all pages in this vma range. For mmap()/mremap()/...> + */> +extern int mlock_vma_pages_range(struct vm_area_struct *vma,> + unsigned long start, unsigned long end);> +> +/*> + * munlock all pages in vma. For munmap() and exit().> + */> +extern void munlock_vma_pages_all(struct vm_area_struct *vma);I don't think it's desirable that interfaces be documented in twoplaces. The documentation which you have at the definition site ismore complete than this, and is at the place where people will expectto find it.> #ifdef CONFIG_NORECLAIM_LRU> /*> * noreclaim_migrate_page() called only from migrate_page_copy() to> @@ -74,6 +85,65 @@ static inline void noreclaim_migrate_pag> }> #endif> > +#ifdef CONFIG_NORECLAIM_MLOCK> +/*> + * Called only in fault path via page_reclaimable() for a new page> + * to determine if it's being mapped into a LOCKED vma.> + * If so, mark page as mlocked.> + */> +static inline int is_mlocked_vma(struct vm_area_struct *vma, struct page *page)> +{> + VM_BUG_ON(PageLRU(page));> +> + if (likely((vma->vm_flags & (VM_LOCKED | VM_SPECIAL)) != VM_LOCKED))> + return 0;> +> + SetPageMlocked(page);> + return 1;> +}bool? If you like that sort of thing. It makes sense here...> +/*> + * must be called with vma's mmap_sem held for read, and page locked.> + */> +extern void mlock_vma_page(struct page *page);> +> +/*> + * Clear the page's PageMlocked(). This can be useful in a situation where> + * we want to unconditionally remove a page from the pagecache -- e.g.,> + * on truncation or freeing.> + *> + * It is legal to call this function for any page, mlocked or not.> + * If called for a page that is still mapped by mlocked vmas, all we do> + * is revert to lazy LRU behaviour -- semantics are not broken.> + */> +extern void __clear_page_mlock(struct page *page);> +static inline void clear_page_mlock(struct page *page)> +{> + if (unlikely(TestClearPageMlocked(page)))> + __clear_page_mlock(page);> +}> +> +/*> + * mlock_migrate_page - called only from migrate_page_copy() to> + * migrate the Mlocked page flag> + */So maybe just nuke it and open-code those two lines in mm/migrate.c?> +static inline void mlock_migrate_page(struct page *newpage, struct page *page)> +{> + if (TestClearPageMlocked(page))> + SetPageMlocked(newpage);> +}> +> +> +#else /* CONFIG_NORECLAIM_MLOCK */> +static inline int is_mlocked_vma(struct vm_area_struct *v, struct page *p)> +{> + return 0;> +}> +static inline void clear_page_mlock(struct page *page) { }> +static inline void mlock_vma_page(struct page *page) { }> +static inline void mlock_migrate_page(struct page *new, struct page *old) { }It would be neater if the arguments to the two versions ofmlock_migrate_page() had the same names.> +#endif /* CONFIG_NORECLAIM_MLOCK */> > /*> * FLATMEM and DISCONTIGMEM configurations use alloc_bootmem_node,> Index: linux-2.6.26-rc2-mm1/mm/mlock.c> ===================================================================> --- linux-2.6.26-rc2-mm1.orig/mm/mlock.c 2008-05-15 11:20:15.000000000 -0400> +++ linux-2.6.26-rc2-mm1/mm/mlock.c 2008-06-06 16:06:28.000000000 -0400> @@ -8,10 +8,18 @@> #include <linux/capability.h>> #include <linux/mman.h>> #include <linux/mm.h>> +#include <linux/swap.h>> +#include <linux/swapops.h>> +#include <linux/pagemap.h>> #include <linux/mempolicy.h>> #include <linux/syscalls.h>> #include <linux/sched.h>> #include <linux/module.h>> +#include <linux/rmap.h>> +#include <linux/mmzone.h>> +#include <linux/hugetlb.h>> +> +#include "internal.h"> > int can_do_mlock(void)> {> @@ -23,17 +31,354 @@ int can_do_mlock(void)> }> EXPORT_SYMBOL(can_do_mlock);> > +#ifdef CONFIG_NORECLAIM_MLOCK> +/*> + * Mlocked pages are marked with PageMlocked() flag for efficient testing> + * in vmscan and, possibly, the fault path; and to support semi-accurate> + * statistics.> + *> + * An mlocked page [PageMlocked(page)] is non-reclaimable. As such, it will> + * be placed on the LRU "noreclaim" list, rather than the [in]active lists.> + * The noreclaim list is an LRU sibling list to the [in]active lists.> + * PageNoreclaim is set to indicate the non-reclaimable state.> + *> + * When lazy mlocking via vmscan, it is important to ensure that the> + * vma's VM_LOCKED status is not concurrently being modified, otherwise we> + * may have mlocked a page that is being munlocked. So lazy mlock must take> + * the mmap_sem for read, and verify that the vma really is locked> + * (see mm/rmap.c).> + */That's a useful comment.Where would the reader (and indeed the reviewer) go to find out about"lazy mlocking"? "grep -i 'lazy mlock' */*.c" doesn't work...> +/*> + * LRU accounting for clear_page_mlock()> + */> +void __clear_page_mlock(struct page *page)> +{> + VM_BUG_ON(!PageLocked(page)); /* for LRU islolate/putback */typo> +> + if (!isolate_lru_page(page)) {> + putback_lru_page(page);> + } else {> + /*> + * Try hard not to leak this page ...> + */> + lru_add_drain_all();> + if (!isolate_lru_page(page))> + putback_lru_page(page);> + }> +}When I review code I often come across stuff which I don't understand(at least, which I don't understand sufficiently easily). So I'll askquestions, and I do think the best way in which those questions shouldbe answered is by adding a code comment to fix the problem for ever.When I look at the isolate_lru_page()-failed cases above I wonder whatjust happened. We now have a page which is still on the LRU (how didit get there in the first place?). Well no. I _think_ what happened isthat this function is using isolate_lru_page() and putback_lru_page()to move a page off a now-inappropriate LRU list and to put it back ontothe proper one. But heck, maybe I just don't know what this functionis doing at all?If I _am_ right, and if the isolate_lru_page() _did_ fail (and underwhat circumstances?) then... what? We now have a page which is on aninappropriate LRU? Why is this OK? Do we handle it elsewhere? How?etc.> +/*> + * Mark page as mlocked if not already.> + * If page on LRU, isolate and putback to move to noreclaim list.> + */> +void mlock_vma_page(struct page *page)> +{> + BUG_ON(!PageLocked(page));> +> + if (!TestSetPageMlocked(page) && !isolate_lru_page(page))> + putback_lru_page(page);> +}extra tab.> +/*> + * called from munlock()/munmap() path with page supposedly on the LRU.> + *> + * Note: unlike mlock_vma_page(), we can't just clear the PageMlocked> + * [in try_to_unlock()] and then attempt to isolate the page. We must> + * isolate the page() to keep others from messing with its noreclaimpage()?> + * and mlocked state while trying to unlock. However, we pre-clear the"unlock"? (See exhasperated comment against try_to_unlock(), below)> + * mlocked state anyway as we might lose the isolation race and we might> + * not get another chance to clear PageMlocked. If we successfully> + * isolate the page and try_to_unlock()_unlock() or try_to_unmap()> + * either of which will restore the PageMlocked state by calling> + * mlock_vma_page() above, if it can grab the vma's mmap sem.> + */OK, you officially lost me here. Two hours are up and I guess I needto have another run at [patch 17/25]I must say that having tried to absorb the above, my confidence in theoverall correctness of this code is not great. Hopefully wrong, butgee.> +static void munlock_vma_page(struct page *page)> +{> + BUG_ON(!PageLocked(page));> +> + if (TestClearPageMlocked(page) && !isolate_lru_page(page)) {> + try_to_unlock(page);> + putback_lru_page(page);> + }> +}> +> +/*> + * mlock a range of pages in the vma.> + *> + * This takes care of making the pages present too.> + *> + * vma->vm_mm->mmap_sem must be held for write.> + */> +static int __mlock_vma_pages_range(struct vm_area_struct *vma,> + unsigned long start, unsigned long end)> +{> + struct mm_struct *mm = vma->vm_mm;> + unsigned long addr = start;> + struct page *pages[16]; /* 16 gives a reasonable batch */> + int write = !!(vma->vm_flags & VM_WRITE);> + int nr_pages = (end - start) / PAGE_SIZE;> + int ret;> +> + VM_BUG_ON(start & ~PAGE_MASK || end & ~PAGE_MASK);> + VM_BUG_ON(start < vma->vm_start || end > vma->vm_end);> + VM_BUG_ON(!rwsem_is_locked(&vma->vm_mm->mmap_sem));> +> + lru_add_drain_all(); /* push cached pages to LRU */> +> + while (nr_pages > 0) {> + int i;> +> + cond_resched();> +> + /*> + * get_user_pages makes pages present if we are> + * setting mlock.> + */> + ret = get_user_pages(current, mm, addr,> + min_t(int, nr_pages, ARRAY_SIZE(pages)),> + write, 0, pages, NULL);Doesn't mlock already do a make_pages_present(), or did that getremoved and moved to here?> + /*> + * This can happen for, e.g., VM_NONLINEAR regions before> + * a page has been allocated and mapped at a given offset,> + * or for addresses that map beyond end of a file.> + * We'll mlock the the pages if/when they get faulted in.> + */> + if (ret < 0)> + break;> + if (ret == 0) {> + /*> + * We know the vma is there, so the only time> + * we cannot get a single page should be an> + * error (ret < 0) case.> + */> + WARN_ON(1);> + break;> + }> +> + lru_add_drain(); /* push cached pages to LRU */> +> + for (i = 0; i < ret; i++) {> + struct page *page = pages[i];> +> + /*> + * page might be truncated or migrated out from under> + * us. Check after acquiring page lock.> + */> + lock_page(page);> + if (page->mapping)> + mlock_vma_page(page);> + unlock_page(page);> + put_page(page); /* ref from get_user_pages() */> +> + /*> + * here we assume that get_user_pages() has given us> + * a list of virtually contiguous pages.> + */Good assumption, that ;)> + addr += PAGE_SIZE; /* for next get_user_pages() */Could be moved outside the loop I guess.> + nr_pages--;Ditto.> + }> + }> +> + lru_add_drain_all(); /* to update stats */> +> + return 0; /* count entire vma as locked_vm */> +}>> ...>> +/*> + * munlock a range of pages in the vma using standard page table walk.> + *> + * vma->vm_mm->mmap_sem must be held for write.> + */> +static void __munlock_vma_pages_range(struct vm_area_struct *vma,> + unsigned long start, unsigned long end)> +{> + struct mm_struct *mm = vma->vm_mm;> + struct munlock_page_walk mpw;> +> + VM_BUG_ON(start & ~PAGE_MASK || end & ~PAGE_MASK);> + VM_BUG_ON(!rwsem_is_locked(&vma->vm_mm->mmap_sem));> + VM_BUG_ON(start < vma->vm_start);> + VM_BUG_ON(end > vma->vm_end);> +> + lru_add_drain_all(); /* push cached pages to LRU */> + mpw.vma = vma;> + (void)walk_page_range(mm, start, end, &munlock_page_walk, &mpw);The (void) is un-kernely.> + lru_add_drain_all(); /* to update stats */> +random newline.> +}> +> +#else /* CONFIG_NORECLAIM_MLOCK */>> ...>> +int mlock_vma_pages_range(struct vm_area_struct *vma,> + unsigned long start, unsigned long end)> +{> + int nr_pages = (end - start) / PAGE_SIZE;> + BUG_ON(!(vma->vm_flags & VM_LOCKED));> +> + /*> + * filter unlockable vmas> + */> + if (vma->vm_flags & (VM_IO | VM_PFNMAP))> + goto no_mlock;> +> + if ((vma->vm_flags & (VM_DONTEXPAND | VM_RESERVED)) ||> + is_vm_hugetlb_page(vma) ||> + vma == get_gate_vma(current))> + goto make_present;> +> + return __mlock_vma_pages_range(vma, start, end);Invert the `if' expression, remove the goto?> +make_present:> + /*> + * User mapped kernel pages or huge pages:> + * make these pages present to populate the ptes, but> + * fall thru' to reset VM_LOCKED--no need to unlock, and> + * return nr_pages so these don't get counted against task's> + * locked limit. huge pages are already counted against> + * locked vm limit.> + */> + make_pages_present(start, end);> +> +no_mlock:> + vma->vm_flags &= ~VM_LOCKED; /* and don't come back! */> + return nr_pages; /* pages NOT mlocked */> +}> +> +>> ...>> +#ifdef CONFIG_NORECLAIM_MLOCK> +/**> + * try_to_unlock - Check page's rmap for other vma's holding page locked.> + * @page: the page to be unlocked. will be returned with PG_mlocked> + * cleared if no vmas are VM_LOCKED.I think kerneldoc will barf over the newline in @page's description.> + * Return values are:> + *> + * SWAP_SUCCESS - no vma's holding page locked.> + * SWAP_AGAIN - page mapped in mlocked vma -- couldn't acquire mmap sem> + * SWAP_MLOCK - page is now mlocked.> + */> +int try_to_unlock(struct page *page)> +{> + VM_BUG_ON(!PageLocked(page) || PageLRU(page));> +> + if (PageAnon(page))> + return try_to_unmap_anon(page, 1, 0);> + else> + return try_to_unmap_file(page, 1, 0);> +}> +#endifOK, this function is clear as mud. My first reaction was "what's wrongwith just doing unlock_page()?". The term "unlock" is waaaaaaaaaaayoverloaded in this context and its use here was an awful decision.Can we please come up with a more specific name and add some commentswhich give the reader some chance of working out what it is that isactually being unlocked?>> ...>> @@ -652,7 +652,6 @@ again: remove_next = 1 + (end > next->> * If the vma has a ->close operation then the driver probably needs to release> * per-vma resources, so we don't attempt to merge those.> */> -#define VM_SPECIAL (VM_IO | VM_DONTEXPAND | VM_RESERVED | VM_PFNMAP)> > static inline int is_mergeable_vma(struct vm_area_struct *vma,> struct file *file, unsigned long vm_flags)hm, so the old definition of VM_SPECIAL managed to wedge itself betweenis_mergeable_vma() and is_mergeable_vma()'s comment. Had me confusedthere.pls remove the blank line between the comment and the start ofis_mergeable_vma() so people don't go sticking more things in there.
|
http://lkml.org/lkml/2008/6/6/521
|
CC-MAIN-2014-42
|
refinedweb
| 2,118
| 58.58
|
In this tip, I demonstrate how you can test if the OutputCache attribute is present on a controller action. I also demonstrate how you can test if the OutputCache attribute is set with a particular duration. you can perform in a web application is database access. The best way to improve database access performance is to not access the database at all. Caching enables you to avoid having to access the database with each and every request.
You can cache the view (or any Action Result) returned by a controller action by adding an OutputCache attribute to the controller action. For example, the controller in Listing 1 is configured to cache the view returned by the Index() action for 10 seconds.
Listing 1 – HomeController.vb (VB.NET)
<HandleError()> _
Public Class HomeController
Inherits System.Web.Mvc.Controller
<OutputCache(Duration:=10)> _
Function Index()
Return View()
End Function
End Class
Listing 1 – HomeController.cs (C#)
using System.Web.Mvc;
namespace Tip27.Controllers
{
[HandleError]
public class HomeController : Controller
{
[OutputCache(Duration=10)]
public ActionResult Index()
{
return View();
}
}
}
The Index() action in Listing 1 returns the view in Listing 2. Notice that this view simply displays the current time (see Figure 1).
Figure 1 – A view cached for 10 seconds
Listing 2 – Index.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="Tip27.Views.Home.Index" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="" >
<head runat="server">
<title></title>
</head>
<body>
<div>
The current time is: <%= DateTime.Now.ToString("T") %>
</div>
</body>
</html>
(By the way, don’t ever set the OutputCache attribute in the view itself. You should only configure caching within a controller).
If you invoke the Index() action, then you get the Index view. If you repeatedly hit refresh in your browser, then the time displayed in the view updates once every 10 seconds.
So, how do you test caching? I don’t mean how do you test whether caching works or not. This is a framework issue that Microsoft has tested for you. I mean how do you test whether or not caching is enabled on a particular controller action in an MVC application that you write?
It turns out that testing whether a particular controller action has an OutputCache attribute is really easy. Take a look at the test in Listing 3.
Listing 3 – HomeControllerTest.vb (VB.NET)
Imports System
Imports System.Collections.Generic
Imports System.Text
Imports System.Web.Mvc
Imports Microsoft.VisualStudio.TestTools.UnitTesting
Imports Tip28
<TestClass()> Public Class HomeControllerTest
<TestMethod()> Public Sub IndexIsCachedFor10Seconds()
' Arrange
Dim indexMethod = GetType(HomeController).GetMethod("Index")
Dim outputCacheAttributes = indexMethod.GetCustomAttributes(GetType(OutputCacheAttribute), True)
' Assert
Assert.IsTrue(outputCacheAttributes.Length > 0)
For Each outputCache As OutputCacheAttribute In outputCacheAttributes
Assert.IsTrue(outputCache.Duration = 10)
End Sub
Listing 3 – HomeControllerTest.cs (C#)
using System.Reflection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Tip27.Controllers;
namespace Tip27Tests.Controllers
/// <summary>
/// Summary description for HomeControllerTest
/// </summary>
[TestClass]
public class HomeControllerTest
[TestMethod]
public void IndexIsCachedFor10Seconds()
// Arrange
MethodInfo indexMethod = typeof(HomeController).GetMethod("Index");
var outputCacheAttributes = indexMethod.GetCustomAttributes(typeof(OutputCacheAttribute), true);
// Assert
Assert.IsTrue(outputCacheAttributes.Length > 0);
foreach (OutputCacheAttribute outputCache in outputCacheAttributes)
{
Assert.IsTrue(outputCache.Duration == 10);
}
The test in Listing 3 grabs all of the OutputCache attributes from the Index method (there might be more than one). If the Index() method does not include at least one OutputCache attribute then the test fails. If each of the OutputCache attributes does not have a Duration property set to the value 10 seconds, then the test fails.
This probably isn't the place to ask this but is there a way in either this release or in a future release so that when the view is cached there is a substitution that replaces dynamic data (such as a user's name?)
Like in this example?
blog.maartenballiauw.be/.../Extending-ASPNET-MVC-OutputCache-ActionFilterAttribute-Adding-substitution.aspx
Yea, about those ... Can we stop'em?
Pingback from this is a test » Dallas Blogging
How can you cache data in MVC? e.g If a cached version of a returned object through say LINQ to SQL is current I want to use that and not have to query the database again. In traditional ASp.NET apps (webforms) we can use the page's cache properties to store data. I can't see where this would be done within MVC, I assume a cache at the controller level is needed?.
|
http://weblogs.asp.net/stephenwalther/archive/2008/08/01/asp-net-mvc-tip-28-test-if-caching-is-enabled.aspx
|
crawl-002
|
refinedweb
| 728
| 51.85
|
What the CSOM does and does not do
The client-side object model (CSOM) is a set of APIs for Project Server 2013 that are designed for both online and on-premises use in apps that can be developed for PCs, mobile devices, and tablets. This article includes some typical scenarios for using the CSOM and also lists limitations of the CSOM.
Last modified: March 09, 2015
Applies to: Project Server 2013
The CSOM enables the development of apps for Project Server 2013 and integration of Project Server with other applications. The apps can be developed to run on PCs, mobile devices such as Windows Phone 7.5, tablets such as Windows 8 devices, and iOS and Android devices. The CSOM provides APIs that cover functionality of the twelve most commonly used PSI services in Project Server. The CSOM APIs are organized differently and are easier to use than the ASMX-based and WCF-based PSI services. The CSOM does not use ADO.NET datasets and is accessible through the OData protocol. You can develop with the CSOM by using .NET Framework 4 libraries, JavaScript, or Representational State Transfer (REST) queries.
For an overview of the CSOM and articles that show how to use JavaScript and .NET Framework 4 with the CSOM, see Client-side object model (CSOM) for Project Server. For more information about the CSOM assemblies, classes, and members, see the Microsoft.ProjectServer.Client namespace reference.
Following are examples of some kinds of apps that the CSOM supports. The CSOM can be used instead of the PSI for many scenarios:
Develop apps that extend Project Server The primary purpose of the CSOM is app development for Project Server 2013, where apps can be created for a wide variety of devices that include PCs, mobile devices, and tablets. Apps can be distributed within a private app catalog or in the public Office Store.
Automate the creation or management of entities in Project Server The CSOM can perform CRUD operations for entities such as projects, tasks, assignments, enterprise resources, custom fields, lookup tables, timesheets, event handlers, and workflow phases and stages. There are often cases where a custom app can save time with bulk or repetitive jobs.
Get data in the published tables of the Project database Because direct database access to the draft, published, and archive tables is not supported, you can use the CSOM to read data that is not available in the reporting tables or views. For example, get information about workflow stages, phases, and activities. To read data in the reporting tables, you can use OData queries.
Validate statusing and timesheet data Use the CSOM in local event handlers or remote event receivers for pre-events to validate assignment status or timesheet data that users enter, before the data is saved in Project Web App.
Create financial projects Create projects for time capture through the timesheet for integration with a financial system. Create a hierarchy of financial codes that reflect the cost breakdown structure of the financial system. Financial projects do not require scheduling or status updates.
Integrate with). remote event receivers A remote event receiver for a ProjectCreating pre-event can use Project Server data from the CSOM to help determine whether to cancel the event. For example, before creating a project, compare the project proposal with existing projects.
Support declarative Project Server workflows The CSOM enables Project Server workflows that are created in SharePoint Designer 2013. The CSOM supports workflow definitions that use Windows Workflow Foundation version 4 (WF4). (The PSI does not support WF4 workflows.)
Create complex Project Server workflows When you develop workflows with Visual Studio 2012, you can use the CSOM for complex actions within workflow stages or create custom workflow actions.
The CSOM is not a complete replacement for the PSI. Because the CSOM internally uses the PSI services, the CSOM has many of the same functional limitations that the PSI has. In addition to limitations of the PSI, such as having no access to data in local projects (.mpp files), the CSOM does not include administrative functionality that Project Web App typically handles. For example, creating custom security groups can be handled in the Site Settings - Permissions page for Project Web App.
For a list of actions that neither the PSI nor the CSOM handle, see the What the PSI does not do section in What the PSI does and does not do.
PSI services that the CSOM does not cover
The CSOM does not include functionality of the following PSI services:
Admin service To manage administrative settings and operations in Project Server and for related project sites, such as creating fiscal periods and making timesheet settings, use PSI methods in the WebSvcAdmin.Admin class. Project Web App itself uses Admin methods in many of the pages that are linked to the Server Settings page ().
Archive service To save and manage entities such as projects, resources, and custom fields in the archive tables, use PSI methods in the Archive class.
CubeAdmin service To create and manage OLAP cubes for on-premises installations, use PSI methods in the WebSvcCubeAdmin.CubeAdmin class, or use the OLAP Database Management page () in Project Web App.
Driver service To create and manage business drivers for project portfolio analyses, use PSI methods in the WebSvcDriver.Driver class.
LoginForms service and LoginWindows service Authentication in the CSOM is done during initialization of the ProjectContext object, with OAuth or Windows authentication. To create applications for multi-authentication, where a local full-trust application can use both Forms authentication and Windows authentication, use PSI methods in the WebSvcLoginForms.LoginForms class and the WebSvcLoginWindows.LoginWindows class.
Notification service To create and manage alerts and reminders, use PSI methods in the WebSvcNotifications.Notifications class.
ObjectLinkProvider service To create and manage web objects and links to documents and SharePoint list items, use PSI methods in the WebSvcObjectLinkProvider.ObjectLinkProvider class.
PortfolioAnalyses service To create and manage project portfolio analyses, including planner solutions and optimizer solutions, use PSI methods in the WebSvcPortfolioAnalyses.PortfolioAnalyses class.
QueueSystem service The CSOM can get basic information about Project Server queue jobs, and includes the ProjectContext.WaitForQueue method. For more extensive management of the Project Server Queuing System, use PSI methods in the WebSvcQueueSystem.QueueSystem class.
Security service To create and manage Project Server security groups, templates, and categories, and to check permissions for the current user, use PSI methods in the WebSvcSecurity.Security class.
WssInterop service To get information about and manage project sites, use PSI methods in the WebSvcWssInterop.WssInterop class.
The CSOM does not enable extensions such as the PSI can have. For example, if you create a PSI extension for local use, the CSOM cannot be modified to use the PSI extension. You can implement extension scenarios in other ways:
Aggregate CSOM calls within a local component or a component that runs on Microsoft Azure.
Use OData queries of the reporting data, instead of directly accessing reporting tables in the Project Server database.
Integrate CSOM calls with third-party applications through OAuth authentication from Project Online or with server-side components for on-premises use.
Applications that use the CSOM can also use custom databases either on-premises or with SQL Azure.
Request limits of the CSOM
The CSOM in Project Server 2013 is built on the CSOM implementation in SharePoint Server 2013 and inherits the limits for the maximum size of a request. SharePoint has a 2 MB limit for an operations request, and a 50 MB limit for the size of a submitted binary object. The request size is limited to protect the server from excessively long queues of operations and from processing delays for large binary objects.
For example, if you use the CSOM to create a project, and then edit the project to add 252 tasks with a minimum amount of information such as a short name, the task GUID, and a duration of 1d, the total amount of data in the DraftProject.Update request is less than 2 MB. But, if you try to add 253 such tasks to an empty project, the 2 MB limit is exceeded, and you get the following exception: Microsoft.SharePoint.Client.ServerException: The request uses too many resources
To capture the data in a CSOM request over HTTP or HTTPS, you can use a web debugging tool such as Fiddler (). For a code example that implements a test for request size and includes a solution that breaks a large request into to smaller groups, see DraftProject.Update.
|
https://msdn.microsoft.com/en-us/library/office/jj163082
|
CC-MAIN-2018-13
|
refinedweb
| 1,414
| 51.18
|
Home -> Community -> Usenet -> comp.databases.theory -> Re: Vocabularies and DBMSs
"x" <x-false_at_yahoo.com> wrote in message news:40c8912e_at_post.usenet.com...
> **** Post for FREE via your newsreader at post.usenet.com ****
>
> "Dawn M. Wolthuis" <dwolt_at_tincat-group.com> wrote in message
> news:ca9obu$91l$1_at_news.netins.net...
> > "mAsterdam" <mAsterdam_at_vrijdag.org> wrote in message
> > news:40c7ac7c$0$559$e4fe514c_at_news.xs4all.nl...
> > > Dawn M. Wolthuis wrote:
>
> > > > It is relational folks who become democratic about this and start
> > thinking
> > > > about understanding the nature of any particular noun outside of its
> use
> > in
> > > > "this" context. Define it based on its use and if a new use comes
up,
> > > > redefine it if necessary, otherwise add qualifiers to it.
> > >
> > > The first department to get a database wins.
> > > The rest has to jiggle their stuff into the imposed hierarchy.
> >
> > Not at all! Dept #2 identifies their major entities, some of which
might
> > align with Dept #1, others of which might be able to see information
that
> > Dept #1 maintains. There actually is no issue whatsoever that crops up
> > here. There could be the usual types of changes that need to be made --
> > adding files, fields, functions, but it works just fine and again I'll
> have
> > to think of how to make that perfectly clear.
>
> Do you think that one departament is the 'owner' of the data its produces
?
> They are the only one that update "their" data ?
> Or that it is a single "view" of data for all application/users that
> maintain that data ?
>
> I'm sure you can provide a more clear description by not mixing levels and
> by mentioning the role of 'vocabulary' (so foreign to "relational
world").
If you look at all of the terms defined in a database -- the metadata, you get a defined vocabulary. But it is typically redundant in that there might be an attribute named Gender in more than one relation. So, the relation is a namespace and defines its own vocabulary. Now, if that relation is a view of the data, then you can see that the data can be anywhere and the vocabulary is all in that relation. So, when I'm talking about the vocabulary for possible queries, it is analogous to a view that gives them just those elements that can be requested through this view. Because it isn't really a SQL view, nor does it operate like a SQL view, I didn't want to call it that. Nor did I want to call it a relation since it is non-1NF and need not be only a base relation. Sorry to have tossed in a not-so-frequently-used term. --dawn Received on Mon Jun 14 2004 - 17:41:08 CDT
Original text of this message
|
http://www.orafaq.com/usenet/comp.databases.theory/2004/06/14/0618.htm
|
CC-MAIN-2015-48
|
refinedweb
| 453
| 73.27
|
Summary: In this blog, the Scripting Wife learns how to use Windows PowerShell to work with an XML file.
Microsoft Scripting Guy, Ed Wilson, is here. It is only eight days until the kickoff of the 2012 Scripting Games. Tomorrow the signup for the 2012 Scripting Games goes live. I have finished all the meetings, and everything is now in readiness state for the big event. I am sitting in the kitchen sipping a cup of English Breakfast tea, and looking over the chapter that I completed last night in my Windows PowerShell 3.0 Step by Step book. I close my eyes to think about one particular sentence when all of a sudden I feel a presence come into the room.
“If you are going to sleep, then you should get up from the table,” the Scripting Wife chided.
“I am not sleeping, I am deep in thought,” I replied.
“Then I am in deep trouble,” the Scripting Wife rejoined.
“What are you doing in here? The sun is still up,” I joked.
“Very funny. In fact, it is so funny I forgot to laugh,” she said. “Actually, since you are not doing anything, I need to you tell me about XML.”
“Say what?”
“XML. I need to know how to read an XML file,” she repeated.
“You are kidding.”
“Nope. I exported my book database, and it saved as an XML file. I need to know how to read it,” the Scripting Wife explained.
“OK. That makes sense. In Windows PowerShell, it is really easy. How do you read a plain text file?” I asked.
“I use the Get-Content cmdlet,” she said.
“It is the same thing, except that you use the letters XML inside square brackets. Open up Windows PowerShell on your computer, and then use Get-Content to read the XML file.”
The Scripting Wife stores her books.xml file in the FSO directory on her C:\ drive. Therefore, her command looks like this:
$books = Get-Content C:\fso\books.xml
“Now look at what is contained in the $books variable,” I suggested.
The Scripting Wife typed the $books variable on its own line in the Windows PowerShell console. The command and its associated output are shown in the image that follows.
“Now look at the XML property,” I suggested.
The Scripting Wife typed the following command.
$books.xml
“OK. Now look at the BookInfo property.”
She typed the command that appears here.
$books.bookinfo.
The command to examine the XML property and the command to look at the BookInfo property are shown in the image that follows, along with the associated output.
“What is that booklist?” the Scripting Wife asked.
“I don’t know. Why don’t you access it and see.”
The Scripting Wife used the Up arrow to retrieve the previous command, and added BookList to the end of the command and pressed ENTER. Here is her command:
$books.bookinfo.booklist
“Well, it looks like a bunch of books,” she replied as she turned her monitor to me so I could see. The image that follows shows her Windows PowerShell console.
“Why don’t you keep going…But this time, pipe the output to More just in case you get all of your books rolling by,” I suggested.
The Scripting Wife once again used the Up arrow to retrieve her previous command, added Book to the end of the command, and piped the output to More. The command is shown here.
$books.bookinfo.booklist.book | more
Sure enough, after a few seconds, the book information began to scroll. The first little bit is shown here.
“Well that looks interesting, but how can I find more information about a book?” she asked.
“Why don’t you index into the collection? Choose the first book,” I suggested.
The Scripting Wife thought for a few seconds, and then she used the Up arrow to retrieve her previous command and then added the index operator. Her command is shown here.
$books.bookinfo.booklist.book[0]
The output from the previous command is shown here.
“You can use the same techniques to find information about the subjects of the book, and to find information about the title, plot, and other information.”
The Scripting Wife typed the commands that follow. As she examined the output from each command she continued to burrow deeper and deeper into the data structure of the first book.
$books.bookinfo.booklist.book[0].subjects
$books.bookinfo.booklist.book[0].subjects.subject
$books.bookinfo.booklist.book[0].mainsection
$books.bookinfo.booklist.book[0].mainsection.authors
$books.bookinfo.booklist.book[0].mainsection.authors.author
$books.bookinfo.booklist.book[0].mainsection.authors.author.person
Finally, she sat back and examined her handiwork. The output from these commands are shown in the image that follows.
I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.
Ed Wilson, Microsoft Scripting Guy
@Bartek
I was playing edvils advocate. I see the issue of namespace come up everywhere but it is seldom described in any blog that refernces PowerShell.
There are videos and books on this. It is a bit tricky for most users and most XML is hidden in a namespace or should be.
I have numerous examples of XML with a dozen or more namespaces.
I thought it might be a hint for Ed to blog on with. I had not seen the Brundage videos. Others here will be glad to have the link. Thanks.
With [xml] we do it a bit differently by adding a namespace manager and using that to query. The technique is pretty much the same in VBScript, jscript, java and others. Select-Xml makes this easier for some things by hiding the complexity of doing this although you still need to know how to reference these in an XPath.
@Klaus – yes Altova is great. I have become very adept at XPath with PosH XML. ONce you learn the namespace manager it is very useful and quick. Just extract. I tend to use it for testing of queries before stuffing them into XSLT. XSLT is better at format conversions than PowerShell.
It is also useful when we are on systems with no VisualStudio/Altova/PrimalXML.
Good info:
—books.xml —
msdn.microsoft.com/…/ms762271(v=vs.85).aspx
$books=[xml](cat books.xml)
$books.SelectNodes(‘//book[*]/title’)
This works like a charm. I can look up any attribute quickly – BUT …
If the root looks like this: <catalog xmlns="…/">
nothing is returned.
Since most modern documents have one or more schemas and namespaces; how can we query nodes embedded in a namespace?
OK, you got me. 🙂 I should probably expect it.
And I agree: easy <root><branch></branch></root> examples are usually not really practical in the world full of namespaces and other elements, that those basics do not cover. But since this is Scripting Wife article its target is probably beginners, that may need only basic XMLs.
Re: video – found it by accident today. Also glad I've found it, very handy IMO. 🙂
@jvr Why not use Select-Xml instead?
Here is very nice movie that shows how to handle namespaces with it:
So in your example: Select-Xml -Xml $books -XPath //Catalog:book[*]/Catalog:title -Namespace @{
Catalog = ‘…/’ } | Select -Expand Node
… or something along those lines should do. 😉
Hi Ed, Hi Teresa
a very good intro into the world of XML!
XML is a great standard for information exchange but we all should appreciate every tool that helps us to cope with it.
Powershell has some support for XML and that's fine!
We have to learn XPATH and we have to deal with namespaces anyway … no way out, if you are diving deeper into business XML!
@jrv and @Bartek: you know enough XML to be right and sure, there is never enough support for documents with many namespaces.
This blog presents enough basic material for most average XML users, I suppose.
I won't use Powershell in more complicated cases, I have specialized tools like the Altova Missionkit for that!
It's good to have basic XML support in Powershell.
Klaus
How would you iterate through every book in the booklist?
Great post
I am a PS beginner. What if I want to use the info in the books.xml to create a directory hierachy on my (or any) disk?
[xml]$books = Get-Content C:fsobooks.xml
$DirectoryName = $books.bookinfo.booklist.book[0].mainsection.authors.author.person
I guess I have the author stored in a variable with above and now I want to create a file directory with the name of the author:
New-Item -Path C:fsoBooks -Name @DirectoryName
Now I just want to run through the list of authors and create a directory for each.
And later maybe create sub directories with names by subject. And finally I would grab the book files from the location referenced in books.xml
How would that look like with PS and would it be better to script in a programming language?
/Martin
Is there a way to get the contents of an xml file from an list of computers, like say from a csv?
Great Article Ed. 🙂 Now, if you want to change the value of one of the parameters for example coverprice. Then how would you do it?
|
https://blogs.technet.microsoft.com/heyscriptingguy/2012/03/25/the-scripting-wife-learns-to-use-powershell-to-work-with-xml/
|
CC-MAIN-2017-09
|
refinedweb
| 1,574
| 75.71
|
GPy seems very unstable
- helltoupee last edited by
I have been struggling since purchasing my GPy to work reliably with it, and was hoping someone had some suggestions for what I may be doing wrong.
I updated my firmware to the latest stable using the firmware updater tool (appears to be 1.18.2) and wrote some simple scripts for interacting with a TCP server via LTE through a Hologram SIM.
When attempting to run PyMakr/Atom, I get a lot of strange behavior, so I've taken mostly to uploading my files via PyMakr and importing my scripts from the REPL. They seem to start but frequently suffer random pauses, failures, and other breakage.
For example, sometimes it will hang on the construction of the LTE object. If I press enter a few times, the REPL will come back to life but no error message or other indication of success is apparent.
I used some sample code to configure and attach the modem, but it never seems to work from my script (it hangs while waiting for isattached()), but if I enter them one by one in the REPL, the modem attaches without a problem. I tried to mimic exactly what I had done with sleeps between every AT command, along with any crazy thing I could think of - varying sleeps, resetting modem, calling detach or dettach or disconnect (or all 3) prior to trying to configure anything, changing order of commands, sending various queries to the MT, etc.
I had started with time.sleep(10) between each command, but often the sleep would never seem to return (no print out ever occurred). If I pressed enter several times, the REPL prompt would show back up, again, without any sort of Python error or other indication.
Below is my current code after a morning spent trying random things to make it work. I would appreciate any ideas, because so far it seems like I can't make this thing do anything I would expect. Thanks!
from network import LTE print('starting') lte = LTE() # instantiate the LTE object lte.reset() print('lte created') for i in range(0,10): print (i) time.sleep(1) print (lte.send_at_cmd('AT+CGDCONT=1,"IP","hologram"')) print('cmd1') for i in range(0,10): print (i) time.sleep(1) print (lte.send_at_cmd('AT+CFUN=1')) print('cmd2') time.sleep(1) print (lte.send_at_cmd('AT+CEREG=2')) while not lte.isattached(): time.sleep(1) print('connecting') time.sleep(1) lte.isconnected() time.sleep(1) lte.connect() # start a data session and obtain an IP address while not lte.isconnected(): time.sleep(1) print('connected')
@helltoupee Oops, should have read P2 not P23. Check the flash instructions to be sure.
Also have a look at safe boot options. You might be able to boot your previous firmware.
@helltoupee I have not had problems trying to reflash. Make sure you have a good connection between P23 and GND when you boot to force the device into flash mode.
Did the reflash appear to go all the way to completion?
I would try again.
Peter.
- helltoupee last edited by helltoupee
@tuftec Thanks for the response. I am using a 5V 2A supply and connections seem nice and solid. The sim card is a Hologram, LTE Cat-M1, I believe.
I tried rewriting my code using the built in attach vs AT commands and had no better luck (still worked from the REPL when entered manually but not from a script).
I tried to flash the latest firmware and now the device is acting even stranger than before. I can't actually get it to re-enter flash mode so I can't even try to roll back. Any suggestion on how to recover it? Is this level of instability or change between firmware updates expected? I'm new to the PyCom world but so far there seem to be so many basic connectivity and configuration issues.
Hi.
How are you using your Gpy? NB-IoT, Cat-M1?
I am using a FiPy for NB-IoT.
Here are few pointers that I have fond useful:
- Make sure you have a good clean 5V (@1A or so) powering your device
- Use the latest version of Pycom h/w (upgraded with the latest Sequans modem features)
- Use the latest Pycom f/w (1.20.0.rc7 or later)
- Be careful with interconnection of other devices for monitoring repl output etc. I had an issue with a TTL connected USB dongle that would feed current into my module when it went to sleep. This caused strange behaviour on wake up. Sometimes I would get random watchdog resets (not actually using the watchdog feature).
- Make sure you keep all input pins within the 0 - 3.3V range. May cause issues as per 4).
- I use the LTE specific commands to set up the device rather than dropping down to the AT command level. This seems to work for me. So use lte.init, lte.attach, lte.isattached, lte.connect, lte.isconnected, lte.deinit. Then use sockets for sending data (UDP works well for NB-IoT). I still have an issue where I occasionally get an OS error when trying to use lte.deinit (OSError: the requested operation failed). I have not tracked the cause down yet.
I always use pymkr (within Atom) over the wifi repl to load new application code changes now. It is relatively fast and easy. You might need to add a button to your harware to force it back to the repl (safe boot) if your code has no obvious exit to the repl (like mine).
I hope this helps.
Please share your experience.
Peter.
|
https://forum.pycom.io/topic/4471/gpy-seems-very-unstable
|
CC-MAIN-2020-40
|
refinedweb
| 946
| 74.08
|
I am relatively new to programming and I am having trouble with my JApplet program. I am looking for a way to get the value for a variable in a different class. I want to use the value of a textField that is created in one class as a cap for a 'for loop' in another class. When the user presses a button, the program should draw a number of pictures equal to the number in the text field.
The program layout is somewhat like this:
public class sampleProgram extends JApplet implements ActionListener{
... JTextField sampleField;
... JButton sampleButton;
... int numPictures;
... public void init{
...... PaintSurface sampleSurface = new PaintSurface();
...... this.add(sampleSurface);
...... JPanel samplePanel = new JPanel();
...... JButton sampleButton = new JButton("Draw");
...... JButton.addActionListener(this)
...... JTextField sampleField = new JTextField(5);
...... samplePanel.add(sampleButton);
...... samplePanel.add(sampleField);
...... this.add(samplePanel);
...... //Scheduled pool thread executor
... }
... public void actionPerformed(actionEvent e){
...... if(e.getSource == sampleButton){
......... numPictures = Integer.parseInt(sampleField.getText());
...... }
... }
}
class AnimationThread(){
... //Animation thread stuff(with repaint())
}
class PaintSurface extends JComponent{
... //import image
... int numberOfPictures = ??????
... public void paint(Graphics g);
...... for(int i = 0; i < numberOfPictures; i++){
......... g.drawImage(image,0,0,this);
...... }
... }
}
So, I need a way for numberOfPictures in the PaintSurface class to access numPictures in the sampleProgram class. I don't know if this is a simple command or if I will need to rewrite everything I have. I have tried using interfaces and objects to get the information but I am not very familiar with either, so I haven't had much luck. Any help would be much appreciated!
There are three main ways to access values in another class object. You can access the variable directly in the other object, or call a method on the object that returns a value, or have the other object pass the value to the target class as a method parameter. Providing access to the raw data is typically undesirable; providing a getXxxx() method to return a suitable value, or passing the value as a parameter is preferred.
If the PaintSurface class is a stand-alone class (i.e. it could be used elsewhere) and needs the number of images to work with, its constructor can take the number of images as a parameter. The SampleProgram class can then pass the number of images to the PaintSurface class when it constructs it.
But where does PaintSurface get its image from?
In theory, there is no difference between theory and practice, but not in practice...
Anon.
Please use [CODE]...your code here...[/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.
Thank you for the reply. I used a toolkit object and assigned it a bitmap image from my computer (not a url). I have not tried your solution yet, but you are saying that I should include the sampleProgram variable as a parameter when I create the new PaintSurface?
Just tried it and it works perfectly! Thanks so much!
Originally Posted by shindig
Just tried it and it works perfectly! Thanks so much!
You're welcome.
That is what a constructor is for - to initialise a class object to a valid state. Any essential information it can't get for itself must be passed in to it.
If you're not failing every now and again, it's a sign you're not doing anything very innovative...
Woody Allen
View Tag Cloud
Forum Rules
|
http://forums.codeguru.com/showthread.php?511362-Help-with-accessing-variables-in-other-classes&p=2009908
|
CC-MAIN-2013-20
|
refinedweb
| 570
| 67.04
|
So given that a class that is nothing more than a data bag. After all, each object is just a bag of dict’s which are pointers to some byte array some place. What can we introspect about the byte array in each language?
The following is my attempt to document my metadata experiments.
Let’s start with .Net, its what I know the best and what I am ultimately comparing everything too.
.Net
public class Loan { public decimal Amount { get; set; } } var aLoan = new Loan {Amount=5}; aLoan.GetType(); //an instance of Type filled with data about Loan for(var prop in aLoan.GetType().GetProperties()) { Console.WriteLine(prop.Name); } aLoan.GetType().GetProperty("Amount"); //returns an instance of PropertyInfo
Links:
Type:
PropertyInfo:
Ruby
class Loan attr_accessor :amount def initialize(initialAmount) @amount = initialAmount end end aLoan = Loan.new 5 aLoan.class #Loan aLoan.method(:amount) #a method object
After playing around, I couldn’t find anyway to get the type returned by the ‘amount’ function. This is exactly what I expected, but wanted to confirm. I could get the number of arguments via the ‘arity’ method. That said, I was able to extract a lot more information than I had expected. Special thanks to @jflanagan for the much need schooling in ruby.
Links:
Python
class Loan(object): def __init__(self, initialAmount): self._amount = initialAmount @property def amount(self): return self._amount aLoan = Loan(5) aLoan.__class__ #Loan aLoan.amount #nope, this returns 5 dir(aLoan) #return 'all the things'
Links
JavaScript
function Loan(initialAmount) { //as recommended by Ryan Rauh this.amount = initialAmount; return this; } var aLoan = new Loan(5); typeof(aLoan); //object Object.getPrototypeOf(aLoan).constructor.name; //Loan for(prop in aLoan) {console.log(prop)}; //prop is a string typeof(aLoan['amount']); //number //this is actual a typeof(5)
I was again surprised at how much I could extract. Special thanks to @rauhryan for the JavaScript schooling.
Beyond my reach (for now)
So I wanted to do some other languages outside my comfort zone like lisp, haskell, and erlang. But my brain was exploded by the very different nature of the languages. What I do have is how I would set the structure up roughly in the various languages. I hope to come back overtime and update this as I learn or people share with me.
Lisp
('Loan, ('Amount, 20))
Haskell
data Loan = Loan { Amount :: Int }
Erlang
-record(Loan, { Amount })
Links:
Any feedback on how to do these kinds of things in other languages will be most appreciated.
-d
|
http://codebetter.com/drusellers/2012/01/11/a-brief-overview-of-type-system-metadata-in-various-languages/
|
CC-MAIN-2013-48
|
refinedweb
| 418
| 67.25
|
Remove the duplicate name_compare() function and use the one provided by read-cache.c.
Advertising
Signed-off-by: Jeremiah Mahler <jmmah...@gmail.com> --- Notes: There is one small difference between the old function and the new one. The old one returned -N and +N whereas the new one returns -1 and +1. However, there is no place where the magnitude was needed, so this change will not alter its behavior. unpack-trees.c | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/unpack-trees.c b/unpack-trees.c index 4a9cdf2..c4a97ca 100644 --- a/unpack-trees.c +++ b/unpack-trees.c @@ -629,17 +629,6 @@ static int unpack_failed(struct unpack_trees_options *o, const char *message) return -1; } -/* NEEDSWORK: give this a better name and share with tree-walk.c */ -static int name_compare(const char *a, int a_len, - const char *b, int b_len) -{ - int len = (a_len < b_len) ? a_len : b_len; - int cmp = memcmp(a, b, len); - if (cmp) - return cmp; - return (a_len - b_len); -} - /* * The tree traversal is looking at name p. If we have a matching entry, * return it. If name p is a directory in the index, do not return -- 2.0.0 -- To unsubscribe from this list: send the line "unsubscribe git" in the body of a message to majord...@vger.kernel.org More majordomo info at
|
https://www.mail-archive.com/git@vger.kernel.org/msg53585.html
|
CC-MAIN-2016-50
|
refinedweb
| 216
| 67.55
|
#include <sys/types.h> #include <login_cap.h> login_cap_t * login_getclass(char *class); char * login_getstyle(login_cap_t *lc, char *style, char *type); int login_getcapbool(login_cap_t *lc, char *cap, unsigned int def); quad_t login_getcapnum(login_cap_t *lc, char *cap, quad_t def, quad_t err); quad_t login_getcapsize(login_cap_t *lc, char *cap, quad_t def, quad_t err); char * login_getcapstr(login_cap_t *lc, char *cap, char *def, char *err); quad_t login_getcaptime(login_cap_t *lc, char *cap, quad_t def, quad_t err); void login_close(login_cap_t *lc); int secure_path(char *path); int setclasscontext(char *class, unsigned flags); int setusercontext(login_cap_t *lc, struct passwd *pwd, uid_t uid, unsigned flags);style() function is used to obtain the style of authentication that should be used for this user class. The style argument may either be NULL is not available, or if no style is available. class was used and the /etc/login.conf file is missing). It returns a non-zero value if cap, with no value, was found, zero otherwise. The secure_path() function takes a path name and returns 0 if the path name is secure, -1 if not. To be secure a path must exist, be a regular file (and not a directory), owned by root, and only writable by the owner (root). setusercontext() function returns 0 on success and -1 on failure. The various bits available to be or-ed together to make up flags are: LOGIN_SETENV.
|
http://www.mirbsd.org/htman/sparc/man3/login_getcapstr.htm
|
CC-MAIN-2014-10
|
refinedweb
| 222
| 59.33
|
The Apache Mahout™ project's goal is to build an environment for quickly creating scalable performant machine learning applications.
For additional information about Mahout, visit the Mahout Home Page
Whether you are using Mahout‘s
You will need
$JAVA_HOME, and if you are running on Spark, you will also need
$SPARK_HOME.
Running any application that uses Mahout will require installing a binary or source version and setting the environment. To compile from source:
mvn -DskipTests clean install
mvn test
mvn eclipse:eclipseor
mvn idea:idea
To use maven, add the appropriate setting to your pom.xml or build.sbt following the template below.
To use the Samsara environment you'll need to include both the engine neutral math-scala dependency:
<dependency> <groupId>org.apache.mahout</groupId> <artifactId>mahout-math-scala_2.11</artifactId> <version>${mahout.version}</version> </dependency>
and a dependency for back end engine translation, e.g:
<dependency> <groupId>org.apache.mahout</groupId> <artifactId>mahout-spark_2.11</artifactId> <version>${mahout.version}</version> </dependency>
Linux Environment (preferably Ubuntu 16.04.x) Note: Currently only the JVM-only build will work on a Mac. gcc > 4.x NVIDIA Card (installed with OpenCL drivers alongside usual GPU drivers)
Install java 1.7+ in an easily accessible directory (for this example, ~/java/)
Create a directory ~/apache/ .
Download apache Maven 3.3.9 and un-tar/gunzip to ~/apache/apache-maven-3.3.9/ .
Download and un-tar/gunzip Hadoop 2.4.1 to ~/apache/hadoop-2.4.1/ .
Download and un-tar/gunzip spark-1.6.3-bin-hadoop2.4 to ~/apache/ . Choose release: Spark-1.6.3 (Nov 07 2016) Choose package type: Pre-Built for Hadoop 2.4
Install ViennaCL 1.7.0+ If running Ubuntu 16.04+
sudo apt-get install libviennacl-dev
Otherwise if your distribution’s package manager does not have a viennniacl-dev package >1.7.0, clone it directly into the directory which will be included in when being compiled by Mahout:
mkdir ~/tmp cd ~/tmp && git clone cp -r viennacl/ /usr/local/ cp -r CL/ /usr/local/
Ensure that the OpenCL 1.2+ drivers are installed (packed with most consumer grade NVIDIA drivers). Not sure about higher end cards.
Clone mahout repository into
~/apache.
git clone
When building mahout for a spark backend, we need four System Environment variables set:
export MAHOUT_HOME=/home/<user>/apache/mahout export HADOOP_HOME=/home/<user>/apache/hadoop-2.4.1 export SPARK_HOME=/home/<user>/apache/spark-1.6.3-bin-hadoop2.4 export JAVA_HOME=/home/<user>/java/jdk-1.8.121
Mahout on Spark regularly uses one more env variable, the IP of the Spark cluster’s master node (usually the node which one would be logged into).
To use 4 local cores (Spark master need not be running)
export MASTER=local[4]
To use all available local cores (again, Spark master need not be running)
export MASTER=local[*]
To point to a cluster with spark running:
export MASTER=spark://master.ip.address:7077
We then add these to the path:
PATH=$PATH$:MAHOUT_HOME/bin:$HADOOP_HOME/bin:$SPARK_HOME/bin:$JAVA_HOME/bin
These should be added to the your ~/.bashrc file.
Currently Mahout has 3 builds. From the $MAHOUT_HOME directory we may issue the commands to build each using mvn profiles.
JVM only:
mvn clean install -DskipTests
JVM with native OpenMP level 2 and level 3 matrix/vector Multiplication
mvn clean install -Pviennacl-omp -Phadoop2 -DskipTests
JVM with native OpenMP and OpenCL for Level 2 and level 3 matrix/vector Multiplication. (GPU errors fall back to OpenMP, currently only a single GPU/node is supported).
mvn clean install -Pviennacl -Phadoop2 -DskipTests
Mahout provides an extension to the spark-shell, which is good for getting to know the language, testing partition loads, prototyping algorithms, etc..
To launch the shell in local mode with 2 threads: simply do the following:
$ MASTER=local[2] mahout spark-shell
After a very verbose startup, a Mahout welcome screen will appear:
Loading /home/andy/sandbox/apache-mahout-distribution-0.13.0/bin/load-shell.scala...._ sdc: org.apache.mahout.sparkbindings.SparkDistributedContext = org.apache.mahout.sparkbindings.SparkDistributedContext@3ca1f0a4 _ _ _ __ ___ __ _| |__ ___ _ _| |_ '_ ` _ \ / _` | '_ \ / _ \| | | | __| | | | | (_| | | | | (_) | |_| | |_ _| |_| |_|\__,_|_| |_|\___/ \__,_|\__| version 0.13.0 That file does not exist scala>
At the scala> prompt, enter:
scala> :load /home/<andy>/apache/mahout/examples /bin/SparseSparseDrmTimer.mscala
Which will load a matrix multiplication timer function definition. To run the matrix timer:
scala> timeSparseDRMMMul(1000,1000,1000,1,.02,1234L) {...} res3: Long = 16321
Note the 14.1 release is missing a class required for this; will be fixed in 14.2. We can see that the JVM only version is rather slow, thus our motive for GPU and Native Multithreading support.
To get an idea of what’s going on under the hood of the timer, we may examine the .mscala (mahout scala) code which is both fully functional scala and the Mahout R-Like DSL for tensor algebra:
def timeSparseDRMMMul(m: Int, n: Int, s: Int, para: Int, pctDense: Double = .20, seed: Long = 1234L): Long = { val drmA = drmParallelizeEmpty(m , s, para).mapBlock(){ case (keys,block:Matrix) => val R = scala.util.Random R.setSeed(seed) val blockB = new SparseRowMatrix(block.nrow, block.ncol) blockB := {x => if (R.nextDouble < pctDense) R.nextDouble else x } (keys -> blockB) } val drmB = drmParallelizeEmpty(s , n, para).mapBlock(){ case (keys,block:Matrix) => val R = scala.util.Random R.setSeed(seed + 1) val blockB = new SparseRowMatrix(block.nrow, block.ncol) blockB := {x => if (R.nextDouble < pctDense) R.nextDouble else x } (keys -> blockB) } var time = System.currentTimeMillis() val drmC = drmA %*% drmB // trigger computation drmC.numRows() time = System.currentTimeMillis() - time time }
For more information please see the following references:
Note that due to an intermittent out-of-memory bug in a Flink test we have disabled it from the binary releases. To use Flink please uncomment the line in the root pom.xml in the
<modules> block so it reads
<module>flink</module>.
For examples of how to use Mahout, see the examples directory located in
examples/bin
For information on how to contribute, visit the How to Contribute Page
Please see the
NOTICE.txt included in this directory for more information.
|
https://apache.googlesource.com/mahout/
|
CC-MAIN-2020-24
|
refinedweb
| 1,043
| 50.63
|
"The primary use of a chat room is to share information via text with a group of other users." - Wikipedia. During this Premium tutorial, I'll show you how to create a chatroom using Flash, AIR, PHP, MySQL and XML.
The User Interface
We'll start by creating the user interface. You can copy my UI to the pixel, or you can create your own design.
Step 1: Setting up the Document
Open Flash and create a new 'Flash File (Adobe AIR)' document. Save the file into a new folder as 'chatroom.fla'. Next, create a new 'ActionScript' file and save that as 'chatroom.as' and save it in the new folder.
Step 2: Linking the Files
In Flash, navigate to the 'Properties' panel. In the text field type in 'chatroom' and hit enter. This will link the actionscript file (which we will soon create) and Flash document together. You can find a complete tutorial on how to set up the Document class here.
Step 3: Setting up the Stage and Background
In the properties panel, set the size of the stage to 230x400 pixels. Next, select the rectangle tool. Set the rounded corners property to 5 pixels. Give it a fill color of white and give it any alpha number you like -- I set mine to 10%. Also, give it a black stroke that is 1 pixel wide. Draw out a rectangle on the stage that is 245 pixels wide and 400 pixels in height. Press F8 to convert it to a movieclip. Give it a name of 'background' and an instance name of 'background'. In the filters panel, add a glow filter that has a blur of 24, strength of 66%, and set the quality to high. Next add a drop shadow filter. Give it a blur of 4, strength of 50%, high quality, 90 angle and set the distance to 2.
Step 4: Creating the Login/Sign up Panel
In the components panel, drag out a copy of the List component onto the stage. This will contain the list of users that are currently online. Give it an instance name of 'uList'. Set the width property to 200 and the height to 189. Next, grab the text tool. With the static text setting, draw out a text field above the new List component. In the text field, enter 'Users online'.
With the text tool still selected, draw out another text field below the List component and enter 'Username'. Below that text field, draw out another text field. The new text field should say 'Password'. Underneath the 'Username' text field, create a new input text field. Give it an instance name of 'user'. Set the width to 200 and the height to 17. Set the text color to black and font size to 12. Create another input text field with the same settings underneath the 'Password' text field. Give the new input text field an instance name of 'pass', and set the Line type to 'Password'. This will make the characters entered appear as asterisks.
Step 5: Finishing the Login/Sign up Panel
Next select the rectangle tool. Give it a rounded corner of 5, a color of #00CC00 and no stroke. Draw out a rectangle that has a width of 122 and height of 43. Convert the rectangle to a new movieclip and give it a name and instance name of 'button'. Double click on the button to enter edit mode.
Inside the button movieclip, create a new layer. Create a new dynamic text field. Give it an instance name of 'dyText', width of 110, height of 36, font size of 26 and white color, and set it to bold. Exit the edit mode and get back to the stage.
Select the button, and navigate to the filters panel. Give the button a drop shadow with a blur of 2, strength of 66%, high quality, an angle of 90 and distance of 1. Lastly, drag out a copy of the Checkbox component. Place it underneath the button movieclip. Give it an instance name of 'remember'. In the parameters panel, set the label to 'Remember'. Next, copy the Checkbox, and paste a new instance right next to the previous one. Give the new Checkbox an instance name of 'signUp'. Set its label property to 'Sign up'. Select all the elements and convert them to one big movieclip. Give it an instance name of 'screen1.'
Step 6: Creating the Rooms Panel
To the right of the 'screen1' movieclip, draw out a static text box, and give it a value of 'Rooms online'. Below the text field, drag a new List component onto the stage to contain the rooms. Give it an instance name of 'rList'. Set the width to 200 and the height to 189. Next create another static text field below the List component. Set it to say 'Room'. Underneath that text field, create a new input text field. Give it an instance name of 'table', a width of 200 and height of 17. Set the font size to 12 and color to black.
Step 7: Finishing the Rooms Panel
Drag another copy of the button movieclip onto the stage. Give it an instance name of 'button2' and place it under the 'rList' component. In the filters panel, apply the same drop shadow settings that were applied to the 'button1' movieclip. This will be used to enter the selected room.
Now, drag a copy of the Checkbox component onto the stage. Give it an instance name of 'createRoom'. The user will check this box to indicate that they wish to create a new room instead of entering an existing one.
Next, select the rectangle tool again. Give it a fill color of #BA0101 and no stroke. With the rounded corners still set at 5, draw out a rectangle that is 71 pixels wide and 25 pixels high. Convert the rectangle into a movieclip and give it an instance name of 'out'. Double click to enter the edit mode of the new 'out' movieclip. Create a second layer on top. Select the text tool and draw a dynamic text field. The next text field should be 63 in width and 18 in height. Give it an instance name of 'dyText'. Exit the edit mode and give the button a new drop shadow filter with the same properties as the other two green buttons. This red button will be used to go back to the login screen.
Select all the new elements and convert them to a movieclip. Give the movieclip an instance name of 'screen2'.
Step 8: Creating the Chatroom Panel
To the right of the 'screen2' movieclip, create a new static text field that says 'Current chat'. Underneath the text field, drag out a copy of the TextArea component. Give it a width of 200, a height of 123 and an instance name of 'cList'.
Next, drag out another copy of the List component and place it under the new TextArea. Give the new List component an instance name of 'uList'. This will hold the list of users currently in the chatroom.
Create another static text field under the 'uList' component that reads 'Comment'. Now, create an input text field underneath the 'Comment' text field. Give it an instance name of 'comm', a width of 200, height of 17, font size of 12 and color of black. Drag another copy of the green button onto the stage. Give it an instance name of 'button3'. Finally, drag a copy of the red button onto the stage and give it an instance name of 'back'. Select all of the new elements and convert them, as a group, to a movieclip with an instance name of 'screen3'.
Step 9: Creating the Error Panel
This will slide in whenever there's a problem (for example, if the user enters an incorrect password).
On the stage, create a new layer. Double click on the 'background' movieclip to enter its edit mode. Select the background shape and copy it. Navigate back up to the stage, and, on the new layer, paste the new shape to the left of the 'screen1' movieclip. Give the shape a color of black and alpha of 50%. Convert the shape into a movieclip and give it an instance name of 'errorPage'. Double click on the 'errorPage' movieclip to edit.
Inside the movieclip, create a new layer. Select the text tool and drag out a new dynamic text field. Give it a width of 120, a height of 26, font size of 20, white color and bold font. Align the text field to the vertical and horizontal center of the background shape.
Step 10: Finishing up the UI
Create a new layer on the stage for the exit button. Since we always want that button on top of everything else, move the new layer to the top of the stack. Select the text tool, and make an 'X'. Convert that to a movieclip with an instance name of 'closer'. Double click on it.
Create a new layer inside the 'closer' movieclip. Place the new layer underneath the layer with the 'X' text field. Draw out a square that is 16 pixels wide and 16 pixels in height. Give the square a fill of any color and an alpha of 0. Give the 'closer' movieclip a new drop shadow filter with a blur of 2, strength of 66%, high quality, angle of 90 and a distance of 1. Move it closer to the top right corner of the background movieclip.
Basic Application Code
The next seven steps deal with setting up the client application, before we get to the server-side PHP.
Step 11: Starting to Code
Open up the blank actionscript file that we created. Here is the skeleton for the document class we'll be using.
package { import flash.display.Sprite; public class chatroom extends Sprite { public function chatroom() { } } }
Step 12: The Imports
Here are all the imports we'll be using for this project. I will be using the Tweener class which can be found here
import caurina.transitions.*; //this is Tweener;
Step 13: Global Variables
Here we are defining our global variables. We'll need to keep track of the user, the room the user is in, and their newest post in the chatroom. We also put the location of the most used PHP files into some constants.() { } }
Step 14: The INVOKE Event
The first thing we do is listen for the INVOKE event. Whenever the app starts, it will fire the INVOKE event. When it does fire, we will check the EncryptedLocalStore for login credentials (in the next step).() { NativeApplication.nativeApplication.addEventListener(InvokeEvent.INVOKE, onInvoke); } }
Step 15: Checking the EncryptedLocalStore
When the INVOKE event is fired, the EncryptedLocalStore will check for an object called 'creds' (short for 'credentials'). If it finds that object, it will pass the login credentials to the appropriate text fields. After that, we call the init function.
private function onInvoke(event:InvokeEvent):void { var value:ByteArray = EncryptedLocalStore.getItem("creds"); if(value != null) { var object:Object = value.readObject(); screen1.user.text = object.user; screen1.pass.text = object.password; screen1.remember.selected = object.remember; } init(); }
Step 16: The init Function
Here we are setting some properties and adding some event listeners. We also create masks dynamically for our screen movieclips. We also create a new Timer so that we can check the database every three seconds for new comments, new users or new rooms. We're also listening for when the user goes idle and when the user returns, using NativeApplication.
private function init():void { screen1.mask = createMask(); //we'll create this function in the next step screen2.mask = createMask(); screen3.mask = createMask(); errorPage.mask = createMask(); var timer:Timer = new Timer(3000); //check for new activity every three seconds timer.addEventListener(TimerEvent.TIMER, onTimer); timer.start(); tracker = 0; //keeps track of where the user is in the app. see Step 36 screen1.button.addEventListener(MouseEvent.CLICK, logOn); NativeApplication.nativeApplication.idleThreshold = 120; //after 120 seconds, a USER_IDLE event will be dispatched NativeApplication.nativeApplication.addEventListener(Event.EXITING, onExiting); closer.addEventListener(MouseEvent.CLICK, closerClick); NativeApplication.nativeApplication.addEventListener(Event.USER_IDLE, onUser); NativeApplication.nativeApplication.addEventListener(Event.USER_PRESENT, onUser); //if the user has been idle, but then starts using the mouse/keyboard again, a USER_PRESENT event will be dispatched background.addEventListener(MouseEvent.MOUSE_DOWN, backgroundDown); exiting = 0; loadSomething(USERS, userLoaded); //loads users, rooms, or chat //the rest of this function just sets up the UI screen1.button.dyText.text = "Start"; screen2.button2.dyText.text = "Go"; screen3.button3.dyText.text = "Say"; screen2.out.dyText.text = "Log out"; screen3.back.dyText.text = "Leave"; screen2.out.dyText.mouseEnabled = false; screen3.back.dyText.mouseEnabled = false; screen1.button.dyText.mouseEnabled = false; screen2.button2.dyText.mouseEnabled = false; screen3.button3.dyText.mouseEnabled = false; screen1.button.buttonMode = screen2.button2.buttonMode = screen3.button3.buttonMode = screen2.out.buttonMode = screen3.back.buttonMode = true; }
Step 17: Creating the Dynamic Masks
Since we're using components and different type of text fields, we have to dynamically create the masks for the screen movieclips. We create a rounded rectangle that is the same size as the 'background' movieclip. We move the rectangle to the top of the display list and return the Sprite object.
private function createMask():Sprite { var rect:Sprite = new Sprite(); rect.graphics.beginFill(0x000000, 1); rect.graphics.drawRoundRect(0, 0, 219, 392.6, 5, 5); rect.graphics.endFill(); rect.x = 5.5; rect.y = 3.8; this.addChildAt(rect, this.numChildren-1); return rect; }
The Server-Side Code
Next we will switch over to the back end: PHP and MySQL on your server.
Step 18: Setting up MySQL
The first step is to create a database. I use 'phpmyadmin' to do all my database and table setup. Log in to your account. In the 'Create new database' area, enter in 'chatroom' for the database name and click 'Create'.
When the database is successfully created, we will need to add a table that keeps track of all our users. In the 'Create new table on database chatroom', name the table 'chat_room_users', and in the 'Number of fields' section, give it a value of 4 and click 'Go'.
After you've clicked the 'Go' button, you will have to fill out the column detail. We'll need to store an ID, a username and a password for each user, as well as a flag to say whether they are currently online.
Set the first column name to 'id', set its type to 'INT', set it to auto-increment, and set it as the primary key. The name column should be named 'user'. The type should be 'VARCHAR' with a 'Length/Value' of 40. The third column should be named 'pass'. The type should be 'VARCHAR' with a 'Length/Value' of 40. The final column should be called 'on' with a type of 'VARCHAR', and a 'Length/Value' of 2.
If you are using something other than 'phpmyadmin', here is the MySQL code to set up the database.
#Create database CREATE DATABASE `chatroom`; #Create table CREATE TABLE `chatroom`.`chat_room_users` ( `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY , `user` VARCHAR( 40 ) NOT NULL , `pass` VARCHAR( 40 ) NOT NULL , `on` VARCHAR( 2 ) NOT NULL ) ENGINE = MYISAM;
Step 19: Switching to PHP
First we will need to set up our database access. Create a new PHP document, paste in the following code, replace the login credentials with your own, and save it to your webserver as 'chat_require.php'.
<?php $username = "USERNAME"; $password = "PASSWORD"; $hostname = "HOSTNAME"; $dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL"); $selected = mysql_select_db("chatroom",$dbhandle) or die("Could not select examples"); ?>
Step 20: Showing Users That are Online
This is where we will show a visitor who is currently online. We will need to use our database login information. Next, create a new PHP file and save it to your web server as 'user.php'. Then we will select all the users from the 'chat_room_users' table on our database. The PHP will echo out XML for Flash to read.
<?php require_once 'chat_require.php'; $query = "SELECT user FROM `chat_room_users` WHERE `on` = 1"; $result = mysql_query($query); header ("Content-Type: text/xml"); header("Cache-Control: no-cache, must-revalidate"); header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"; echo "<users>\n"; if (mysql_num_rows($result)) { while ($row = mysql_fetch_row($result)) { echo "<user>" . $row[0] . "</user>\n"; } } else { echo "<user>There are no users online.</user>\n"; } echo "</users>"; ?>
The XML will look like this:
<?xml version="1.0" encoding="utf-8"?> <users> <user>Jack</user> <user>Ben</user> <user>Jacob</user> </users>
Or, if no-one is online, like this:
<?xml version="1.0" encoding="utf-8"?> <users> <user>There are no users online.</user> </users>
Step 21: Logging in the User
Next we'll create the login logic. Create a new PHP file, and save it to your server as 'logon.php'. We'll need to require our database credentials. Next we check to see if the user, pass, and log variables are set. If they've been received from Flash, we sanitize the variables, and check the database for the user. We check to see if the username is already in the database. Also, we're looking to see if the user is trying to create a new username. When the logic is complete, we send back a numeric value for Flash to parse.
<?php require_once 'chat_require.php'; if(isset($_POST['user']) && isset($_POST['pass']) && isset($_POST['log'])) { $user = sanitize($_POST['user']); $pass = sanitize($_POST['pass']); $log = sanitize($_POST['log']); $sign = sanitize($_POST['sign']); $query = "SELECT user FROM `chat_room_users` WHERE `user` = '$user'"; $result = mysql_query($query) or die(mysql_error()); if(mysql_num_rows($result)) { if($sign === 'true') { //User exists echo 6; } else { $query = "SELECT user, pass FROM `chat_room_users` WHERE `user` = '$user' AND `pass` = '$pass'"; $re = mysql_query($query) or die(mysql_error()); if(mysql_num_rows($re)) { $query = "UPDATE `chat_room_users` SET `on` = '$log' WHERE `user` = '$user' AND `pass` = '$pass'"; $r = mysql_query($query) or die(mysql_error()); if($r) { if($log === "1") { //Logged in echo 1; } else { //Logged out echo 5; } } else { echo 0; } } else { //Wrong Password echo 4; } } } elseif($sign === 'true') { $query = "INSERT INTO `chat_room_users` VALUES ('', '$user', '$pass', '1')"; $result = mysql_query($query) or die(mysql_error()); if($result) { //Account created echo 2; } else { echo 0; } } else { //User doesn't exist echo 3; } } function sanitize($string) { $string = mysql_real_escape_string($string); $string = strip_tags($string); $string = filter_var($string, FILTER_SANITIZE_STRING); $string = trim($string); return $string; } ?>
Step 22: Picking a Room
Now that the user has logged in, we'll give them access to the chatrooms. Create a new PHP file, save it to your web server as 'rooms.php'. We require our database credentials of course. Then we show all the tables that have been created on the database. The only table that we hide is our users table. We take the result and echo out some XML for Flash.
The first time the app is used there will be no tables in the database apart from the users table, as no rooms will have been created. We'll resolve this in the next step.
<?php require_once 'chat_require.php'; $query = "SHOW TABLES FROM chatroom"; $result = mysql_query($query); if (mysql_num_rows($result)) { header ("Content-Type: text/xml"); header("Cache-Control: no-cache, must-revalidate"); header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"; echo "<rooms>\n"; while ($row = mysql_fetch_row($result)) { if($row[0] === "chat_room_users") { // } else { echo "<room>" . $row[0] . "</room>\n"; } } echo "</rooms>"; } ?>
Step 23: Creating a Room
The user also has the option to create a room. First, create a new PHP file, and save it to your server as 'create.php'. We will need to sanitize our variables. Next, we query the database to see if the user is trying to create a room that already exists. If it doesn't we create a new table (not a new row in an existing table). Again, we send integers back to Flash.
<?php require_once 'chat_require.php'; if(isset($_POST['table']) && isset($_POST['create'])) { $table = sanitize($_POST['table']); $create = sanitize($_POST['create']); $user = sanitize($_POST['user']); $query = "SELECT * FROM $table"; $result = mysql_query($query); if($create === 'true') { if(!$result) { $query = "CREATE TABLE `$table` (id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), user VARCHAR(40) NOT NULL, comment VARCHAR(120) NOT NULL, logged VARCHAR(2) NOT NULL)"; $result = mysql_query($query) or die(mysql_error()); if($result) { echo 1; } else { echo 0; } } else { echo 2; } } else { if(!$result) { echo 3; } else { echo 1; } } } function sanitize($string) { $string = mysql_real_escape_string($string); $string = strip_tags($string); $string = filter_var($string, FILTER_SANITIZE_STRING); $string = trim($string); return $string; } ?>
Step 24: Getting the User's Newest Comment
When the user logs in, we don't want to show them the entire chat history. Since every time a user enters a room they automatically announce their presence, that results as a new entry into the database table. We will need to find the user's latest entry as a starting point for them to start receiving the chat. We will use the 'MAX' MySQL function to find it and send it back to Flash. Copy the code below and save it to your web server as 'enter.php.'
<?php require_once 'chat_require.php'; if(isset($_POST['comment']) && isset($_POST['table']) && isset($_POST['user'])) { $user = sanitize($_POST['user']); $comment = sanitize($_POST['comment']); $logged = sanitize($_POST['logged']); $table = sanitize($_POST['table']); $query = "INSERT INTO `$table` VALUES ('', '$user', '$comment', '$logged')"; $result = mysql_query($query) or die(mysql_error()); if($result) { $query = "SELECT MAX(id) FROM `$table` WHERE `user` = '$user'"; $r = mysql_query($query) or die(mysql_error()); if($r) { while($row = mysql_fetch_row($r)) { echo $row[0]; } } } } function sanitize($string) { $string = mysql_real_escape_string($string); $string = strip_tags($string); $string = filter_var($string, FILTER_SANITIZE_STRING); $string = trim($string); return $string; } ?>
Step 25: Posting a Comment
Finally, we are at the point where the user can start to chat. We use this page to check if the user has submitted a comment. If they have said something, we put it into our table. We also use this file to echo out the chat since the user entered the room. This page also shows which user is currently in the room.
<?php require_once 'chat_require.php'; $table = sanitize($_POST['table']); $id = sanitize($_POST['id']); if(isset($_POST['comment']) && isset($_POST['table']) && isset($_POST['user'])) { $user = sanitize($_POST['user']); $comment = sanitize($_POST['comment']); $logged = sanitize($_POST['logged']); $query = "INSERT INTO `$table` VALUES ('', '$user', '$comment', '$logged')"; $result = mysql_query($query) or die(mysql_error()); } $query = "SELECT user, comment FROM `$table` WHERE `id` > $id"; $r = mysql_query($query) or die(mysql_error()); if($r) { header("Content-Type: text/xml"); header("Cache-Control: no-cache, must-revalidate"); header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"; echo "<comments>\n"; while ($row = mysql_fetch_row($r)) { echo "<comment>\n"; echo "<user>" . $row[0] . "</user>\n"; echo "<text>" . $row[1] . "</text>\n"; echo "</comment>\n"; } mysql_free_result($r); $query = "SELECT DISTINCT user FROM $table"; $r = mysql_query($query) or die(mysql_error()); if($r) { while ($row = mysql_fetch_row($r)) { $user = $row[0]; $query = "SELECT user, logged FROM $table WHERE user = '$user' ORDER BY id DESC LIMIT 1"; $result = mysql_query($query); if($result) { while($tr = mysql_fetch_row($result)) { if($tr[1] === '1') { echo "<users>" . $tr[0] . "</users>/n"; break; } else { // } } } else { // } } } else { // } echo "</comments>"; } else { // } function sanitize($string) { $string = mysql_real_escape_string($string); $string = strip_tags($string); $string = filter_var($string, FILTER_SANITIZE_STRING); $string = trim($string); return $string; } ?>
Connecting the Client to the Back End
Now it's time to make the chatroom connect to the server so that it can be truly interactive.
Step 26: Back to Flash
When the user first goes to log in to the chat area, they will click the 'button1' movieclip. When that button is clicked, it will call the 'logOn' function. All that function does is call the 'logger' function. The 'logger' function will do some simple checking to see if the required fields are filled in. Also, it will load the 'logon.php' file.
private function logOn(event:MouseEvent):void { logger(); } private function logger(log:int = 1):void { if(log === 1) { if(screen1.user.text.search(/[a-zA-Z0-9]/g) === -1) //make sure the user entered a valid name { errorPage.dyText.text = "Enter a user name"; tweenerTimer(); return; } if(screen1.pass.text.search(/[a-zA-Z0-9]/g) === -1) //make sure the user entered a valid password { errorPage.dyText.text = "Enter a password"; tweenerTimer(); return; } } //this section loads the logon.php page we created earlier: var url:URLLoader = new URLLoader(); var req:URLRequest = new URLRequest(URL + "logon.php"); var vars:URLVariables = new URLVariables(); req.method = URLRequestMethod.POST; vars.user = screen1.user.text; vars.pass = screen1.pass.text; vars.log = log; vars.sign = screen1.signUp.selected; req.data = vars; url.addEventListener(Event.COMPLETE, loggingOn); //when logon.php has loaded, call loggingOn() url.load(req); _user = screen1.user.text; }
Step 27: The User is Logging in
When the user tries to log in, we send the credentials to the database to check whether they have access. We use the numbers that PHP returns to do some checking. If the number returned is a 1 or 2, the user is logged in. If a different number is returned, we use the 'errorPage' movieclip to handle it. This function is also the last function that we call when the user is closing the application. After we've told the database that the user is leaving the chat area, the application will close. This function also populates the room list on 'screen2'.
private function loggingOn(event:Event):void { screen1.signUp.selected = false; switch(event.target.data) { case "0" : //Error -- shouldn't ever receive this number break; case "1" : case "2" : tracker = 1; //keeps track of where the user is in the app. see Step 36 Tweener.addTween(screen1, {x: -screen1.width - 50, time:1}); //slide the current screen out... Tweener.addTween(screen2, {x: (stage.stageWidth>>1) - (screen2.width>>1), time:1}); //...and slide the new screen in. //load the list of rooms using rooms.php var url:URLLoader = new URLLoader(); url.addEventListener(Event.COMPLETE, popRList); url.load(new URLRequest(ROOMS)); screen2.button2.addEventListener(MouseEvent.CLICK, room); break case "5" : //Log out break; case "3" : case "4" : case "6" : var string:String = event.target.data; switch(string) { case "3" : errorPage.dyText.text = "User doesn't exist"; break; case "4" : errorPage.dyText.text = "Wrong Password"; break; case "6" : errorPage.dyText.text = "User already exists"; break; } tweenerTimer(); //slide the error screen in break; } loadSomething(USERS, userLoaded); if(exiting === 1) { if(screen1.remember.selected) { //if the user checked the "remember" box on the login screen, this saves their name and password to the EncryptedLocalStore var value:ByteArray = new ByteArray(); value.writeObject({user:screen1.user.text, password:screen1.pass.text, remember:screen1.remember.selected}); EncryptedLocalStore.setItem("creds", value); } else { EncryptedLocalStore.reset(); } NativeApplication.nativeApplication.exit(); } }
Step 28: Loading the Available Rooms
The 'popRList' function handles the xml that is returned from the PHP file. If the user sees a room that is already created, they can simply click on the list and the 'room' text field gets populated with their selection. The user is also able to log out here if they would like to sign in as a different user.
private function popRList(event:Event):void { screen2.out.addEventListener(MouseEvent.CLICK, outClick); var xml:XML = new XML(event.target.data); var list:XMLList = xml..room; //creates an XMLList from all the <room> nodes in the XML returned by rooms.php var len:int = list.length(); screen2.rList.removeAll(); for(var i:int = 0; i<len; i++) //loops through all the <room> nodes in the XMLList { screen2.rList.addItem({label:list[i], data:list[i]}); } screen2.rList.addEventListener(Event.CHANGE, onChange); }
Step 29: Logging Out
If the user decides that they would like to log in under a different username, they can click on the 'out' button on 'screen2'. This will call the 'logger' function again except it will pass a zero to the database. When a zero is passed, the user is logged out, and we return to 'screen1.'
private function outClick(event:MouseEvent):void { logger(0); Tweener.addTween(screen2, {x: stage.stageWidth + 50, time:1}); Tweener.addTween(screen1, {x: (stage.stageWidth>>1) - (screen1.width>>1), time:1}); tracker = 0; //keeps track of where the user is in the app. see Step 36 loadSomething(USERS, userLoaded); }
Step 30: Entering Room
When the user decides on a room they want to enter, the 'room' function is called. If the user is trying to create a new room, we do some simple checking to ensure the text field is filled in. We also replace any spaces with underscores.
private function room(event:MouseEvent):void { if(screen2.table.text.search(/[a-zA-Z0-9]/g) === -1) { errorPage.dyText.text = "Select a room"; tweenerTimer(); return; } screen3.cList.text = ""; screen3.comm.text = ""; var url:URLLoader = new URLLoader(); var req:URLRequest = new URLRequest(URL + "create.php"); var vars:URLVariables = new URLVariables(); req.method = URLRequestMethod.POST; vars.table = screen2.table.text.replace(/[\s]/gi, "_"); vars.create = screen2.createRoom.selected; vars.user = _user; req.data = vars; url.addEventListener(Event.COMPLETE, roomed); url.load(req); _room = screen2.table.text; }
Step 31: Handling the Room Response
When Flash gets the response from PHP, we use a switch statement to determine the logic. If the user successfully enters the room, we add some event listeners, and we load the 'enter.php' file.
private function roomed(event:Event):void { screen2.createRoom.selected = false; switch(event.target.data) { case "0" : //Error break; case "1" : tracker = 2; //keeps track of where the user is in the app. see Step 36 Tweener.addTween(screen2, {x: -screen2.width - 50, time:1}); Tweener.addTween(screen3, {x: (stage.stageWidth>>1) - (screen3.width>>1), time:1}); screen3.button3.addEventListener(MouseEvent.CLICK, commentClick); this.addEventListener(KeyboardEvent.KEY_UP, onKeyUp); screen3.back.addEventListener(MouseEvent.CLICK, commentClick); screen3.uList.addEventListener(Event.CHANGE, userClick); var url:URLLoader = new URLLoader(); var req:URLRequest = new URLRequest(URL + "enter.php"); var vars:URLVariables = new URLVariables(); url.addEventListener(Event.COMPLETE, enteredRoom); //see next step for this function req.method = URLRequestMethod.POST; vars.user = _user; vars.comment = "has just entered the room"; vars.logged = 1; vars.table = _room; req.data = vars; url.load(req); break; case "2" : errorPage.dyText.text = "Room already exists"; tweenerTimer(); break; case "3" : errorPage.dyText.text = "Room doesn't exist"; tweenerTimer(); break; } }
Step 32: Entering the Room
When the user has entered the room, we have to get their newest post to determine how much of the conversation to display. We use the '_id' variable to track it. When the variable is set, we call the 'callComments' function.
private function enteredRoom(event:Event):void { _id = parseInt(event.target.data); callComments(); }
Step 33: Getting the Comments From the Database
With this function, we will load the PHP file that will contain the XML of the chat. When we call this function, we say whether the user is logged in or logging out. Also, we pass it the user's comment. If the user hasn't said anything, we load just the XML and don't put anything in the database.
private function callComments(string:String = null, logged:int = 1):void { var url:URLLoader = new URLLoader(); var req:URLRequest = new URLRequest(COMMENTS); url.addEventListener(Event.COMPLETE, loadComments); var vars:URLVariables = new URLVariables(); req.method = URLRequestMethod.POST; if(string != null) //if the user said anything { vars.user = _user; vars.comment = string; vars.logged = logged; } vars.table = _room; vars.id = _id - 1; req.data = vars; url.load(req); }
Step 34: Displaying the Comments
In the comments XML, we have a list of all the comments by all the users since the current user has entered the room. We also populate the user list with the users currently in that room.
private function loadComments(event:Event):void { if(exiting) { logger(0); } else { var xml:XML = new XML(event.target.data); var list:XMLList = xml..comment; var llist:XMLList = xml..users; var len:int = list.length(); var i:int; screen3.cList.text = ""; for(i = 0; i<len; i++) { screen3.cList.text += list[i].user + ": " + list[i].text + "\n"; //chat box } len = llist.length(); screen3.uList.removeAll(); for(i = 0; i<len; i++) { screen3.uList.addItem({label:llist[i]}); //list of users } } }
Step 35: Sending a Comment to the Database
When the user has filled out their comment, they can click the 'button3' movieclip. When that happens, we call the 'callComments' function and pass it the user's message. However, we also use the 'commentClick' function for when the user wants to leave the room. We call the 'callComments' function but pass it a string saying that the user has left as well as a zero.
private function commentClick(event:Event):void { if(event != null) { if(event.target.name === "back") { Tweener.addTween(screen3, {x: stage.stageWidth + 50, time:1}); Tweener.addTween(screen2, {x: (stage.stageWidth>>1) - (screen2.width>>1), time:1}); callComments("has just left the room", 0); screen3.cList.text = ""; tracker = 1; //keeps track of where the user is in the application. See next step. } else { callComments(screen3.comm.text); screen3.comm.text = ""; } } else { callComments(screen3.comm.text); screen3.comm.text = ""; } }
Step 36: Tracking the User
With these two functions we can track which PHP file we should be loading. The 'tracker' variable will keep track of where the user is in the application. Every three seconds, the timer will fire and call the 'loadSomething' function depending on the 'tracker' value.
private function loadSomething(string:String, func:Function):void { var url:URLLoader = new URLLoader(); url.addEventListener(Event.COMPLETE, func); url.load(new URLRequest(string)); } private function onTimer(event:TimerEvent):void { switch(tracker) { case 0 : loadSomething(USERS, userLoaded); break; case 1 : loadSomething(ROOMS, popRList); break; case 2 : callComments(); break; } }
Step 37: Leaving the Application
When the user has decided to leave the app, we call the 'onExiting' function. When the 'closer' movieclip is clicked, we dispatch a new 'EXITING' event. When the 'onExiting' function is called, we tell the event to 'preventDefault'. What this means is that the event will not actually cause the default action of closing the app. We want to do some database stuff before the user can actually leave the application.
private function closerClick(event:MouseEvent):void { NativeApplication.nativeApplication.dispatchEvent(new Event(Event.EXITING)); } private function onExiting(event:Event):void { event.preventDefault(); exiting = 1; callComments("has just left the room", 0); }
Step 38: Other Functions
Here are some functions that are used throughout the application. We handle the 'errorPage' tweening, as well as moving the 'nativeWindow' around. Also, if the user wants to hit 'return' instead of clicking the 'button3' movieclip, the 'onKeyUp' function handles that.
private function onKeyUp(event:KeyboardEvent):void { if(event.keyCode === 13) { if(event.shiftKey) { screen3.comm.multiline = true; screen3.comm.appendText("\n"); } else { commentClick(null); } } else { // } } private function onChange(event:Event):void { screen2.table.text = event.target.selectedItem.label; } private function onUser(event:Event):void { if(event.type === Event.USER_IDLE) { callComments("is idle"); } else { callComments("has returned"); } } private function backgroundDown(event:MouseEvent):void { stage.nativeWindow.startMove(); //lets the user drag the app } private function userClick(event:Event):void { screen3.comm.appendText("@" + event.target.selectedItem.label); //lets the user direct a comment at another user } private function tweenerTimer():void //used to slide the Error screen { Tweener.addTween(errorPage, {x:background.x, time:1, onComplete:function(){ var timer:Timer = new Timer(1000); timer.addEventListener(TimerEvent.TIMER, function(){ Tweener.addTween(errorPage, {x:-220, time:1}); timer.stop(); }); timer.start(); }}); }
Finishing off
We're almost done!
Step 39: Packaging the Application
We are finally ready to package our application to be distributed. Go to File > Commands > AIR - Application and Installer Settings.
Under 'Window style', select 'Custom Chrome (transparent).'
Click the 'Publish AIR File' button.
Step 40: Packaging the Application
When the 'Publish AIR File' button is clicked, a prompt to add a Digital Signature will pop up. You can select a file that you have already created. If you haven't, click on the 'Create' button.
Fill out the information and click 'OK'. After the file is created, you enter in the password and click 'OK'.
Once the file is created, you will get a prompt that says 'AIR file has been created'. Your chatroom application is now ready to be distributed.
Conclusion
I hope you enjoyed reading this tutorial. Don't forget to subscribe to the tuts+ feed to learn all kinds of the cool things PHP, MySQL and Flash can do.
Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post
Envato Market has a range of items for sale to help get you started.
|
http://code.tutsplus.com/tutorials/build-a-chatroom-with-flash-adobe-air-and-php-active-premium--active-4393
|
CC-MAIN-2016-22
|
refinedweb
| 6,075
| 67.96
|
BBC micro:bit
LEDs With MicroPython
Introduction
You can use the external pins to connect more LEDs and have colours other than red. Using some LEDs gives us a chance to use the 3 main large pins as digital and analogue outputs. - Digital
We can turn the LEDs off by using the write_digital() method and supplying either a 1 (HIGH) or 0 (LOW) in the brackets to specify what we want to do.
This program blinks each of the LEDs in turn.
from microbit import * pin0.write_digital(0) pin1.write_digital(0) pin2.write_digital(0) sleep(1000) while True: pin0.write_digital(1) sleep(500) pin0.write_digital(0) pin1.write_digital(1) sleep(500) pin1.write_digital(0) pin2.write_digital(1) sleep(500) pin2.write_digital(0)
Programming - Analog
We use the write_analog() with a value from 0 to 1023. This creates a PWM signal (pulse width modulation) on the pin that makes the LEDs fade in and out very slowly.
from microbit import * pin0.write_digital(0) pin1.write_digital(0) pin2.write_digital(0) sleep(1000) while True: for i in range(0,1024): pin0.write_analog(i) pin1.write_analog(i) pin2.write_analog(i) sleep(10) for i in range(1023,-1,-1): pin0.write_analog(i) pin1.write_analog(i) pin2.write_analog(i) sleep(10)
Challenge
Using 3 LEDs, you can count up to 7 in binary. The following table shows you how we can represent these using 3 bits (3 binary place values).
The following pseudocode will give you a one or zero in the variables fours, twos and units. Your leftmost LED is the fours LED, then twos, then units.
denary ← any integer from 0 to 7 included
fours ← denary // 4
remainder ← denary % 4
twos ← remainder // 2
units ← remainder % 2
|
http://www.multiwingspan.co.uk/micro.php?page=pymoreled
|
CC-MAIN-2019-09
|
refinedweb
| 284
| 67.35
|
Environment: Visual Basic .NET
Introduction
In many Windows applications, it could be useful to add some kind of print functionality. The DataGrid included in Windows Forms does not include any support for this. In this article I will show how to use a custom DataGrid I wrote in Visual Basic .NET inheriting from the class System.Windows.Forms.DataGrid to implement an application with a print preview and obviously print support. If you already have a window with a DataGrid, you can go directly to the section Using the Custom DataGrid..
The custom DataGrid also has other useful features such as the possibility to print column headers using more then one row (enabled by default), export data in XML and HTML formats, and send data by e-mail. Basic Application
The first thing you have to do is to create a new Windows application project with a form hosting a standard DataGrid and a MainMenu object. Then you can add (using the designer or with code if you like) some menus to this form. Normally, the main form can have a Sizable FormBorderStyle. The DataGrid will have the Dock property set to Fill.
Now you can add a Database connection, a DataAdapter, and a DataSet (typed or untyped) that you will use to fill the DataGrid (for the sake of simplicity, this code is omitted here).
In the demo project you will find a test file called Demo.xml used to fill the DataSet with its data. In the sample application in the form constructor, I simply use the method ReadXml to read a table named orders in a DataSet named dsOrders.
If you compile and run your project now, you will obtain a basic Windows application showing some data in a DataGrid.
Using the Custom DataGrid
The first thing to do is to add to your project a reference to the library hosting the custom DataGrid (customcontrols.dll) or to add to your solution the existing project with the DataGrid (customcontrols.vbproj). If you choose this second way, you must add a reference in your main project to the second project you just added.
To transform the normal DataGrid in my custom DataGrid, the simplest way is by using the Search and Replace feature in Visual Studio. Open your form in Code View and then use the Replace function (CTRL+H). As source text, insert System.Windows.Forms.DataGrid and as replace text, insert CustomControls.DataGridEx.
There is another way to use my custom DataGrid if you start by scratch with a new form. You can customize the Visual Studio toolbox, adding my custom DataGrid (the class name is DataGridEx and is hosted in customcontrols.dll). Then, instead of dragging in the designer the standard DataGrid, you will drag the DataGridEx control. The result will be the same as in the previous approach.
If you try to compile and run the application now, you will obtain a runtime exception. This is because to obtain print preview support and to support column headers using more then one row you have to create a TableStyle with information about every column (especially the column width). Looking in MSDN, you can find this kind of information but this can be a long and extremely tedious process. To skip this in the form constructor, you can call the method AdjustColumnWidths of the DataGrid (this method evaluates an optimum column width for each column based on the table data). Alternatively, you can invoke the method AdjustColumnWidthToTitles (that evaluates column widths based on column header text). This code can also be placed in the form Load event handler. If you call either of the two methods, you also have some interesting features like the possibility to display boolean columns in colored cells or to use custom cell controls.
To use custom column header text, you can use the method SetColumnName as in the following example.
To add the Page Setup code, you simply invoke the PageSetup method (a static/shared method) of the PageSetup class contained in the CustomControls namespace.
To add Print and Print Preview support, you can simply call the methods Print and PrintPreview of the DataGrid. The following code is more complex because it works also if the DataSource used is a DataTable and not only if it is a DataView.
Adding Custom Columns
To add custom columns in a DataGrid, you have to create your own ColumnStyle class inheriting from the class System.Windows.Forms.DataGridColumnStyle (or other classes inheriting from it).
In the CustomControls library, you can find two sample classes usable in your applications. The first one is DataGridBoolColumnEx (a normal boolean column with a background painted in a custom color if the value in its cell is true) and the second is DataGridPushPinColumn (a boolean column with custom painting). In the sample application, after calling AdjustColumnWidths, I added a call to a private function called AddOtherColumns. This function in the first 11 rows simply obtains a reference to the table loaded from the XML file and add two new boolean columns initializing their values. Then two new ColumnStyles are created and initialized supplying the column header, the column name in the DataTable, and the column width in the DataGrid. Finally, these column styles are added to the table style used by the DataGrid.
The following two images show the form when the application is started and when the print preview is invoked.
Low-Level Details
As mentioned earlier, the class DataGridEx inherits from the standard .NET DataGrid. It offers some more functionality and these new features are spread among classes contained in a DLL called CustomControls.
The DataGridEx class offers many new methods. Mainly there are methods used for Print support, to extend basic functionality, and to work with table styles.
I will not explain every method and its functionality but I will cite only the most important and useful ones. If you look at the code, I think you will find many other features.
There is a method called HitCellTest usable to raise an event called CellHitTest. This event is fired based on mouse position and tells the user what the cell under the mouse pointer is. A property called MouseOverNotificationEnabled is usable to enable or disable the notification of the current cell based on mouse pointer position. If the notification is enabled, every second the mouse position is checked and an event called MouseOverNotification is eventually fired (this can be useful to display custom tooltips based on mouse position).
When you call the method AdjustColumnWidthToTitles, a new TableStyle is created and for each column in the table passed as parameter a ColumnStyle is created. The column width is evaluated based on the header font. The method AdjustColumnWidths simply calls AdjustColumnWidthToTitles and then makes a cycle on the table for each row and each column, eventually enlarging the column width. These methods create column styles based on the datatype hosted in the columns. They try to create extended column styles (the ones I wrote), so if there is, for example, a boolean column, a DataGridBoolColumnEx is created.
The class PrintPreviewDialogEx inherits from the standard Print Preview dialog. The code in this class is quite interesting because the standard PrintPreviewDialog has a private Toolbar. If I simply inherit from this class, I cannot obtain a standard reference to this toolbar, so I couldn't add any more toolbar buttons. The solution to this problem was to use the features of .NET Reflection to obtain a reference to the private variable. The true print preview dialog usable by users is TablePrintPreviewDialog. It inherits from PrintPreviewDialogEx and adds some functionality as the export of data in XML or HTML and the possibility to send the data by e-mail.
Please e-mail me for upgrades, questions, bugs found, and so forth. Thanks.
Downloads
Download zipped demo project files - 46 Kb.
Download zipped library source files - 34 Kb.
|
https://mobile.codeguru.com/vb/controls/vbnet_controls/datagridcontrol/article.php/c3981/Print-Support-in-a-Custom-DataGrid-Control.htm
|
CC-MAIN-2018-34
|
refinedweb
| 1,316
| 61.97
|
Microsoft Visual Studio 2010 provides a project type that enables you to build event receivers that perform actions before or after selected events on a Microsoft SharePoint 2010 site. We can create Event Receivers (Event Handlers) to take care of things for us when specific things happen. For example, we can subscribe to the "ItemAdded" event for a specific list, and have our custom code execute when the event fires.
In this article I am going to explain how to create a simple Item added event receiver for a custom list in SharePoint 2010. The event receiver will change the Title of the item to current year Time once it’s added to the list. We will create and deploy the solution as a farm and will run in debug mode.
· Open Visual Studio 2010 and create a new Project.
· In project types select Event Receiver and give it a name.
· Select .net framework 3.5.
Next in the SharePoint Customization Wizard, choose deploy as a farm solution and specify the site URL where you want the event handler to be deployed as shown in the below figure:
Next, in Event Receiver Settings dialog select the “List Item Events” as a type of event receiver and “Custom List” in the Item source dropdown. Select “An Item was Added” from Handle the following events as shown below:
Next, we will write some code to change the Title of an item to the current year when it is added to a custom list.
using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
namespace EventHandlinginSP.EventReceiver1
{
public class EventReceiver1 : SPItemEventReceiver
{
public override void ItemAdded(SPItemEventProperties properties)
{
base.ItemAdded(properties);
SPListItem _currentItem = properties.ListItem;
_currentItem["Title"] = DateTime.Now.Year;
_currentItem.Update();
}
}
}
To build and deploy an application press “F5″.
Once press F5 the solution gets deployed to your site and your Visual studio project goes into a debug mode. Now we will create a new custom List “My List” and add a new item to test our handler.
Create List:
Create a New Item -
Once you add the Item you will see the results.
Thanks for reading this article. I think after reading this article you can easily implement event handler for SharePoint sites.
|
https://www.mindstick.com/Articles/845/event-receiver-in-sharepoint-2010
|
CC-MAIN-2018-09
|
refinedweb
| 382
| 65.83
|
9, 2001 Copyright Date: 2001 Subjects Spatial Coverage: United States -- Florida -- Franklin -- Apalachicola Coordinates: 29.725278 x -84.9925 ( Place of Publication ) Record Information Bibliographic ID: UF00089928 Volume ID: VID00153 Source Institution: Florida State University Holding Location: Florida State University Rights Management: All rights reserved by the source institution and holding location. Full Text ~~'~~1 ?!jrjf]f~ ff111 47A4 BULK RATE ? r nli C U.S. POSTAGE PAID T h e APALACHICOLA, FL .rankhi Chromicle, 50 Volume 10, Number 3 A LOCALLY OWNED NEWSPAPER February 9 22, 2001 St. George Water Management Obtains Initial Approval for Low Cost State Revolving Fund Loan Loan Expected to Keep Water Costs Down During Construction of Line to St. George Water Management Services, Inc, serving about 1400 water custom- ers on St. George Island, has announced that the company has ob- tained preliminary approvals for a low cost loan to assist the water utility to construct a new pipeline for the new bridge to the island. The company has been advised by Don W. Berryhill, Engineer and Chief, Bureau of Water Facilities Funding, at the Department of Envi- ronmental Protection, that they may "...incur costs, effective January 5, 2001, until such time as a loan agreement can be signed." The authorization covers the following listed project components: 1. Installation of new 10-inch water line from well 4 to well 2 and new 12-inch water main from well 2 to well 3 and to the water treatment plant. The water main to the treatment plant is to be secured to the new bridge being constructed by the Department of Transportation from East Point to St. George Island. 2. A new aerator to be constructed atop the existing ground storage tank. 3. A third high service pump installed at the water treat- ment plant. About a week later, Berryhill also advised Gene Brown, president of the company, that the proposed water improvements were in con- formance with the requirements of state law and that the plans and specifications have been accepted by the Dept. of Environmental Pro- tection. He wrote on January 16th, "Our review of your plans and specifications was per- - ....formed only to verify conformance with the administra- tive requirements of the Drinking Water State Revolving Fund loan program. We did not review the technical as- pects of your plans and specifications in order to avoid duplicating the review performed, or that may be per- formed by the permitting agency or agencies. Accordingly, our review does not substitute for any required permit- ting reviewss. An authorization to incur construction costs prior to ex- ecuting a loan agreement has been issued for your project. Our acceptance of your plans and specifications repre- sents one of the requirements that you have satisfied with respect to this Contract. You will be advised as to the appropriate time to submit the completed loan appli- cation to the Bureau. When you proceed with procurement and after bid open- ing and evaluation, please submit the bidding informa- tion to the Bureau for review. Do not award any contract until the Bureau concurs with your award recommenda- tions. Note that improper or unauthorized procurement may result in the disqualification of contract costs for funding." The State Revolving Fund (SRF) Program provides grants and low interest loans to eligible entities for administration, design and con- struction of public water facilities costing not less than $75,000. Dis- bursements are made after costs are incurred. Disbursements dur- ing construction are generally on a monthly basis. The money for the SRF comes from Federal and State appropriations. This is a revolving fund because loan repayments are used to make additional loans.. The Florida Legislature authorized this program on July 1, 1997. The Department of Environmental Protection (DEP) developed rules in April 1998' that implement the program. Cities, counties, authorities, spe- cial districts and other entities representing privately owned, investor-owned or cooperatively held public water systems legally re- sponsible for community water systems are eligible for loans. Projects eligible for loans include new construction of and improvements to public water systems inclusive of storage, transmission, treatment, disinfection and distribution facilities. Loans are to be repaid over a period of 20 years (30 years for "disadvantaged communities"). The interest rate is 60% of the market rate as established using the "Bond Buyer" 20-Bond Go Index, and the rate does not change over the life of the loan. Currently, the rate is about 3.7 per cent. other loans might go as high as 12 per cent, so the low rate is likely to help reduce monthly water costs to St. George Island customers over the long run, as the loan funds are applied to the bridge pipeline. Under the Public Service Commission rate increases, with a conventional loan at 12 percent, the cost of water service might go as high as $85 per month for a very long period.,A low cost loan applied to the esti- mated $5 million costs of putting a new pipeline on the new bridge is expected to keep water costs down for island consumers, so that the average bill will be approximately $50 per month. Carrabelle City Commissioners Approve Kecd Plan To Seek To Negotiate With Contractor: "One Last Attempt" By Tom Campbell At the regular meeting of the Car- rabelle City Commissioners Feb- ruary 1, 2001, all commissioners were present and heard Daniel W. Keck, Project Engineer for Baskerville-Donovan who is ad- vising the city, offer the plan of "one last attempt to negotiate with the contractor (KMT)." Keck's plan would have the City Attorney Douglas Gaidry, one commissioner, and Keck meet with the contractor, to attempt to negotiate with the contractor in order to successfully complete the project. Apparently, the contrac- tor has been making claims by letter that there have been 757 days of "delay" because of the city. Attempts will be made to set up a meeting with the contractor some time during the week of February 8, 2001. Work on the city's water replacement project has been stalled for some time because of disputes with contractor KMT. After that proposed meeting, the committee will come back to re- port to the City Commissioners and have them recommend action at that time. There were nine items of "Unfin- ished Business," which Mayor Wilburn C. Messer guided the commissioners through with skill and in record time. There was only one bid for the "Yamaha Tournament Reef' arti- Continued on Page 10 I, The First Permanent Facility Of The Franklin County Library SGroundbreaking Held For FWC Evaluates Carrabelle Species And Branch of the Adjusts Regulations Franklin County SOyster Harvest Rules Remain Public Library The Same Skimmer Trawls In Apalachicola Bay To Remain In Use Cobia, a popular marine game fish, is going to be the subject of tighter management. The Florida Fish and Wildlife Conservation Commission (FWC) has voted to classify cobia as a "restricted spe- cies" and to impose a new one- fish-per-day bag limit per person and a six-fish-per-day vessel limit (whichever is less) for recreational fishermen. For commercial fish- ermen the new bag limits are two per person and six per vessel (whichever is less). Commercial fishermen must meet certain in- come requirements to sell re- stricted species. These new cobia rules take effect March 22. During its three-day meeting in Miami, which ended Friday, the Commissioners directed staff to develop a draft rule regarding the spiny lobster trap reduction pro- gram to eliminate the mandatory 10-percent reduction schedule this year. Instead, the FWC will take a "passive/active" approach, intended to reduce the number of traps in Florida waters by 4 per- cent each year. The Commission emphasized that "passive reduc- tion," including a 25-percent re- duction during the transfer of trap certificates, should be employed to achieve the management goal. The Commission will review the draft rule in March and hold a fi- nal public hearing in May. Commissioners also directed staff to study other spiny lobster fish- ery issues, including the effects of commercial diving, recreational harvest and the two-day sport season, as well as trap theft, in- dividual catch effort, trap con- struction and other factors. In addition, Commissioners di- rected staff to conduct a final pub- lic hearing in March on a rule that would prohibit all fishing, spearfishing and collection of marine life in state waters in the proposed Tortugas Ecological Reserve. The FWC also voted to remove snook from the list of species of special concern. Under new cri- teria, snook no longer qualify for the listing. However, current pro- tective management measures for snook will not be affected by this action. The four and one-half- month closed season, 26- 34-inch slot limit, two-fish bag limit and other restrictions will remain in force. Commercial snook fishing will continue to be prohibited. In other marine business, the FWC received a stock assessment of the mullet fishery and reports on various federal fisheries man- agement projects, and declined to amend oyster harvest rules at this time. Thus, the size limits will re- main at 3 inches and a tolerance of 5%. Also, Commissioners di- rected staff to further study the sponge fishery and evaluate vari- ous management recommenda- tions. Commissioners also directed staff to remove the sunset provision that would have prohibited the use of skimmer trawls to harvest shrimp in Apalachicola Bay. The Commission intends to continue a bycatch reduction evaluation of skimmer trawls. Thus, skimmer trawls may continue to be used. The two year trial period was pre- viously scheduled to end on June 30, 2001, but this sunset provi- sion has been removed. The FWC also wants further study of the bycatch reduction devices. Continued on Page 10 On January 29, under a bright morning sun, Denise Butler and Eileen Annie opened brief public ceremonies to break ground for the new Carrabelle branch of the Franklin County Public Library System. The Apalachicola High School band played the National Anthem, and provided appropriate drum rolls as representatives from nu- Imerous community organizations shared shovel honors in scooping the first rounds at the building site just adjacent to highway 98 in Carrabelle. These organizations included: (1) the Franklin County Board of County Commissioners; (2) Franklin County state and congressional representatives; (3) State Library representatives; (4) -Franklin County School Board; (5) Carrabelle and (6) Apalachicola High School representatives; (7) grade and middle school repre- sentatives; (8) Carrabelle City Commission; (9) Franklin County Public Library representatives; ('10) the Franklin County Advisory Board; (11) Wilderness Coast Public Library; (12) the Library Building Committee chaired by Mary Ann Shields and (13) Car- rabelle children, one beneficiary group of the Library. Special rec- ognition was also given to many individuals and organizations, and as Denise Butler stated, when the building is officially dedicated, more honors would be announced in behalf of many whose "time, treasure and talents" were given to the project. Jackie Gay'and the Paul Newman Foundation pro- vided the stimulant to begin con- templating a facility when Ms. Gay donated her prize-winnings for gumbo from the Newman Foun- dation to the building project. Mary Ann Shields and others worked to generate matching funds for the $500,000 project. Denise Butler is President of the Library Advisory Board. Eileen Annie is the Director of the Franklin Library System. Mcllroy Concert At Trinity Church The Ilse Newell Fund for the Per- forming Arts is proud to present The McIlroys-John, Patti, and daughter Katie, in a concert at Historic Trinity Church on Sun- day, February 18th at 4.00 P. M. The Mcllroy family roots were firmly established in their home town of Edinburgh, Scotland, and they .have performed at Scottish and Celtic gatherings in the United Kingdom, Africa. and the Middle East, as well as at festi- vals all over the U.S.A. Patti is an accomplished vocalist, Katie plays flute and dances the Highland Fling and John plays guitar, fiddle, penny whistle, bhodran and the Scottish High- land Bagpipes. This will be a pro- gram of great versatility and vari- ety to please audiences of every age and taste. Following the concert, the recep- tion for annual contributors in all categories, "Friend" through "Benefactor" will be held in the Trinity Church Rectory at the cor- ner of Highway 98 and 6th Street. Inside This Issue 10 Pages Franklin Briefs.................................. ................. 2 Monarch Butterflies ............................................... 2 School Board .......................................................... 2 Editorial & Commentary ..................................... 3, 4 Franklin Bulletin Board ......................................... 4 Hazardous Weather ..................................... ... 5 Dr. Michael Wilder ............................................... 5 Children Of The Street ....................................... 7, 9 FCAN .................................................................... 8 Bookshop........................................................... 10 S. " Carrabelle City Commissioners begin the shoveling ceremony. iJ. . Clarence Williams '. \ .1 iL -- Apalachicola High School Band furnished music and drum rolls. Celeste Elliott Selected As Coca-Cola Semi-Finalist Alexis Celeste Elliott, a senior at Apalachicola High School, has recently been selected as a semi- finalist in the 2001 Coca-Cola Scholars Program. Approximately 2,000 students from the United States were chosen from over 106,000 applicants. Then semi- finalists will be notified in March if they have been chosen as final- ists. There will be 251 finalists chosen; 51 will be named National Scholars and will receive $20,000 each, the remaining 200 will be named Regional Scholars and will receive $4,000 each. During the first half of the school term Celeste was selected as the Wendy's Heisman High School Scholarship nominee and the Toyota Community Scholars nominee from Apalachicola High. She has also been selected as a Buffalo Rock Pepsi/WJHG-TV Student of the Week. She is scheduled to be featured during the week o7t ebruary 18 24 on Channel 7 during their newscasts at 6, 7 and 11 p.m. Coincidentally that will be her birthday week, she turns 18 on February 23. Celeste has been accepted at Florida State University, where she has qualified to enter their Honors Program. She has also earned the honor of being Vale- dictorian of her graduating class. She is active at school in volley- ball, tennis, softball, Student Gov- ernment, Beta Club, National Honor Society, senior class sec- retary and Beta Club vice-presi- dent. Additionally, Celeste is a dual enrolled student at Gulf Coast Community College and should have approximately 30 hours of college credit when she begins fall classes at FSU. She has been se- lected for "Who's Who Among American High School Students" for the previous two years. Celeslc is the daughter of James and Debra Elliott of Apalachicola. Florida. ,A^ VAW ^4 ^^^S 4 ft 'p h 40 po., 7 9 Fehruarv 2001 A LOCALLY OWNED NEWSPAPER The Franklin Chronicle Franklin Briefs February 6, 2001 Commissioners Present: Chair- person Eddie Creamer, Bevin Putnal, Cheryl Sanders, Jimmy Mosconis, Clarence Williams. The Board approved the use of Vrooman Park for the Cancer Re- lay for Life fund-raiser April 20 - 21st. The Board authorized letters to be sent to the county Legislative del- egation objecting to the Governor's proposed cuts in mos- quito control. Kendall Wade reported that, on January 16, Governor Bush rec- ommended shifting the costs for the predisposition detention of juveniles to the counties. The. state would require counties to pay a fee based on the number of juveniles arrested in a county awaiting disposition. This shift of costs to all Florida counties will result in an $85.6 million fiscal impact annually. Counties will not be provided any resources to help absorb this impact. The cost to Franklin County would be about $89,471.91. A letter of com- plaint would be prepared to ad- dress this issue. A letter to Ms. Eva Armstrong about the county's position on land acquisition is to be sent from the Board to her and the Legisla- tive Delegation. The draft contains this language: "Franklin County does not have a local land acquisition program. Further, on Sept. 19, 2000, the Franklin County Board of County Commissioners voted to send a letter to the Governor re- questing that the state not purchase any more land in the county. The argument being threefold: erosion of the county's tax base; state ac- quisition of land interferes with hunting activities that residents have become accus- tomed to; and state acquisi- tion of one particular parcel in 1995 cost Franklin County a prison which was highly anticipated and much needed. .But your request has re- kindled the issue, so I am go- ing to take this opportunity to inform you of the reasons why the county does not have a local land acquisition pro- gram. Every acre the county or the state buys removes land from the tax roll, and the state's payment-in-lieu ofjtax program only lasts for ten, years by current state law. After that, the county suffers a loss of revenue (The county commission currently re- ceives approximately $160,000 in payments, and we are in our 7th year, so in four more years the county tax payers will have to cover what the state fails to pay). On several occasions, the state has bought land and then changed or prevented traditional hunting uses, which caused great anger in the local population. The state and federal government already own 63% of the county, so there'are limited places where the county would want to buy additional land, especially for the pro- tection of natural resources. Finally, the county commis- sion is extremely suspicious of the unforeseen impacts of land acquisition since it was an acquisition program which blocked our prison. Now, in 2001, Franklin County has seen almost 200,000 acres of land purchased by the state, and yet we still do not have a prison." A Resolution of Appreciation was read, signed and approved. It read, in part: RESOLUTION OF APPRECIATION FRANKLIN COUNTY BOARD OF COUNTY COMMISSIONERS WHEREAS, the Franklin County Board of County Commissioners recognizes the need for public li- brary service for the residents of the county, and WHEREAS, the Governor of the State of Florida has recognized the month of February, 2001, as Li- brary Appreciation Month, and WHEREAS, this designation by the Governor is based upon the important role libraries play for The floor plan for the proposed Annex to the Court House was presented by Engineer Consult- ant David Kennedy with Judge Steinmeyer and Judge Russell in attendance. The court room. will also be used for the Board of County Commissioners with 116 seat capacity, with offices around the outside perimeter. The brick structure is about 10,000 square feet, costing about $1 million, or about $100 per square foot. Bill Mahan, County Extension Director The Florida Fish and Wildlife Con- servation Commission, the Florida Marine Institute and the Florida Sea Grant program have joined forces to monitor the spread of an unwanted invader in Florida waters -- the Asian Green Mussel. This mussel was found in Tampa Bay two years ago, and since then it has spread north and south of Tampa. The turnout for the Vibrio vulnificus risk reduction work- shops was light; about 20 persons contributed their comments to four workshops. The plan will be finalized and put into effect. Rezoning A public hearing was held for re- zoning 23.31 .acres on the Apalachicola River, from R-4 Single family home industry to R- 1Single family residential. Ap- proved by the Board. Van Johnson, Solid Waste Director The Florida Department of Envi- ronmental Protection is closing non-permitted dump sites throughout Franklin County. Last Wednesday, Van Johnson re- ceived a request from Carrabelle City Commissioner Rita Preston, asking that the County help Car- rabelle by providing twice per month yard trash pickup with the knuckle boom truck. The work- shop with DEP to discuss this matter has been set for February 16th .at 11 a.m., in the Board meeting room, county court- house. The Board approved Car- rabelle pickup. A 5-minute video was shown dem- onstrating an air curtain incinera- tor. Funds are available from landfill tipping fees to purchase a S-21 unit, a 21-foot self-contained box for about $93,000 plus freight. The Board approved the purchase of the device contingent upon some additional research. Food Bank Franklin County Food Bank Don Banta requested use of a build- ing on Bluff Road for the Food Bank. He said, "The Franklin County Food Bank is a non profit volun- teer organization, which pro- vides food to the elderly and disabled income families In Franklin County. The Food Bank is adminis- tered by a board of non-paid volunteers from our local community. It is at presently working out of the American Legion build- ing,' but as of March 1, will be charged $1,500.00 per month rent to continue oper- ating from this location. Since this organization works from donated funds this' is more than we can afford. It is our hope that there might be a county building which is not being used that our orga- nization could lease at a rate which Is within our budget We have noticed there is a building located on the county yard on Bluff Road. In Apalachicola that is vacant which we would like to in- quire about. This organization provides a needed service within our community and any assis- tance you could provide would be appreciated." The Board approved the request. Alan Pierce, County' Planner At the last Board meeting, the Board agreed to schedule a pub- lic hearing to consider rezoning property on Alligator Point from R-1 to R-4, Home Industry, to al- low a new resident to raise seed clams for the proposed clam aquaculture project in Alligator APALACHICOLA'S residents seeking information and knowledge on every subject known to man, NOW, THEREFORE, BE IT RE- SOLVED BY THE FRANKLIN COUNTY BOARD OF COUNTY COMMISSIONERS that the month of February, 2001, is hereby designated as Library Ap- preciation Month: This Resolution adopted by the Franklin County Board of County Commissioners this 5th day of February, 2001. BY EDDIE CREAMER, Chairman Cuts were also referred to in re- gard to the Literacy Project housed near the Franklin County Library in Eastpoint. Harbor. Mr. Larry Joyner was the applicant, and he encountered some opposition from residents on the Point. Thus, Mr. Pierce asked the Board to reverse them- selves and vote not to schedule a hearing until the Alligator Point residents have a chance to dis- cuss this matter amongst them- selves. Joyner agrees that he would have to resubmit his ap- plication through county P and Z again. The Board approved a request from Ms. Shirley Walker, SHIP Administrator, to have the Board authorize the use of $22,000 worth of interest money accrued by the SHIP program to be used in combination with $17,000 worth of private insurance money to rebuild the house of Ms. Marie Rochelle. Ms. Rochelle was a SHIP recipient who had work done on her home, but then her house caught fire and burned. The Board approved moving $2,619 out of reserves into Emer- gency Managementto take advan- tage of a slight and recent in- crease in funding f or emergency Management. The Board approved a budget amendment involving projects that were not accomplished in the prior fiscal year, and are now con- tinued into 2001. Alligator Point Erosion Control Study Representatives from Preble-Rish, Coastal Technologies, DEP, and the county, met with some 35 Point residents to be briefed on the what the study has learned. The Board will be presented with a more refined study in about 60 days, but here are the highlights. The consultants are looking at three options for stabilizing the shore in an area stretching for about 5000 feet along the shore in front of the campground, which is the area that is eroding the fast- est, and of course threatening the road. The options are: A) beach enhancement-pump up beach sand to build the beach and protect existing shoreline. Initial cost $2.5 million, with a refur- bishing cost of $900,000 every 7- 10 years. The high refurbishment cost is because there will be noth- ing to hold the sand in place, and it is expected to wash away that fast. B) build offshore breakwater ap- proximately 200 feet offshore. Ini- tial cost $6.0 million, with refur- bishment cost of $500,000 every 7-10 years. The refurbishment cost is because of the large wave action from the open Gulf will eventually move rocks into sand. C) build T-head groins & beach fill. These groins win stick out about 125 feet. Initial cost of $3.5 million and refurbishment cost of $500,000 every 7-10 years. The US Army Corps of Engineers is trying to figure out where the funds will come from, so that is unknown, but I believe someone said at the meeting that no mat- Monarch Research Project Draws Standing Room Only Crowd At Research Reserve Dozens of local folk crowded into the Apalachicola Research Re- serve last Thursday, January 26th, for a talk and slide show on the Monarch Butterfly Research Project by retired FSU Professor Dr. Richard Rubino. Dr. Rubino's informative presen- tation centered on the Monarch migration research project being conducted at St. Marks in the panhandle, but he also described in details the life stages of the butterfly and identified their mi- gration patterns from the U. S. to Mexico. His talk was received by over 75 guests with standing room only in the Research Reserve's lec- ture hall. Richard Rubino is Professor Emeritus in Urban and Regional Planning at FSU, and has also taught at the Uniers'ity "6of Wisconsin-Madison and Mel- S. bourne University in Australia. .H now spends his retirement time Directing the monarch monitoring Program at the St. Marks National Wildlife Refuge in Wakulla SCounty, and assisting in the set Sup of other monitoring programs Sin Apalachicola and Cedar Key. Mike's ?aint 1Located at the intersection of 3 19 & 98, Medart BOtdl .I-CAR CERTIFIED TECHNICIANS *ASE CERTIFIED 3140 Coastal Highway MV #12153 Crawfordville, FL 32327 K, (850) 926-6181 WREC EC GARLIC ENVIRONMENTAL ASSOCIATES, Inc. -:-' SERVING;FLORIDA'S COASTAL AREA ,- Offices rn r--c- Kendrick Visits Schools; Board ter what there will be a local match, which might be as high as 50%. All three choices are set to with- stand a 25 year storm event, which is essentially a 7 foot storm surge, which is what Hurricane Opal did on the Point. All three leftp the road in the same place. These three options, protect the shore, but do not provide the resi- dence with a secure evacuation route for storms above a Category 2 hurricane. Inquiry Into Blaske Death Continues The investigation into the gunshot death of Louis Blaske, Jr. 18, Car- rabelle is continuing. The Franklin County Sheriffs Office and the Florida Department of Law Enforcement began their in- quiries following a telephone call about the shooting that occurred on River Road in Carrabelle about 6:15 p.m. Wednesday, January *24th. The gun belonged to William E. Larimore, 19. There was another person present, a juvenile, when the shooting occurred. The gun was reportedly a .22 caliber pistol. By Sue Riddle Cronkite State Representative Will Kendrick visited schools in his home county Thursday, February 1st. At the Franklin County school board meeting that evening, Su- perintendent Jo Ann Gander, Board Chairperson Jimmy Gan- der, members Katie McKnight, Teresa Ann Martin, David Hinton, and George Thompson, lauded Kendrick or his caring attitude toward students. Gander, present Chair, presided in the position Kendrick held for many years, and suggested a resolution thanking Kendrick, and former Chair Willie Speed for their long service to the schools of Franklin County. The board also approved hiring former Superintendent Brenda Galloway as Exceptional Student Education Parent Services Spe- cialist. In this position Galloway will develop alternative education program to address students with behavioral or other difficulties in- terfering with their schooling. Charlotte Smith was approved as Secretary for. Superintendent Gander. She presented minutes for the October 5, October 24, November 9, and November 21 meetings which were approved except for a couple of items of clarification. The board gave the go-ahead to Assistant School Superintendent Mikel Clark and David Meyer, technology specialist, to pursue a $425,000 district-wide grant for training, hardware, software, and personnel for distance learning programs and Florida High School On-Line, enabling the district to offer those services to more stu- dents. In school board member reports Martin said she had talked with Denise Butler, Apalachicola High Principal, about getting driver education back and asked about ROTC. Butler said she had re- searched ROTC and the problem was geographic: "They can only have a certain number of pro- grams within a certain area. Chairman Gander suggested get- ting Jimmy McCloud to speak tc the Board about it. Bob McDaris, Carrabelle Princi- Sea Oits lrtf allerw Your Destination for Art on this IUfiorettable Coast FIArURING( OVI:R THIRTY FINEi ARlA ARl~t'rs AND CRAIITSPI'(I'I.I: . Original Oils Watercolors Hand Built Pottery v: Jo(ci: Esi:s Turned Wooden Bowls Carved Waterfow'l \" Consuliani & Organizer Painted Silks Collectible Prints Serving Franklin Couny Joyce Estes Original Art . V ...... : ..r. r * SSt 8 Just Aolrrived fi. - Ttanzrnia Afriica. k t Tinga Tiiao urtc,'V Wedding & Event Planznir, NNand a-ik Catering Ttuxed. S*'FTD af Flo wers ftnr il a s Occasion, . 260 HIGHWAY 98 EASTPOINT, FL 32328 (850) 670-893 1 (800) 929-8931 ONLY FULL-SERVICE BOAT DEALERSHIP all for"si 'a Q egg. L U~j~ Y / r uu- -----~ -- -- I pal, said his school had a great Science Fair this year and is send- ing a "good group to the regional Science Fair in Quincy." The school's stock market group came in second in competition with other schools, he said. Ina Meyer, Chapman Principal, reported that Eleanor Mount- Simmons was named Teacher of the Year at Chapman, and that in addition to Science Fair activities the school is getting in FCAT prac- tice and tutoring 4th. 5th, and 6th grades. Butler reported that Nina Marks was selected Teacher of the Year at Apalachicola High, and said the Science Fair had 87 entries. Claudette Hamilton was chosen to represent her school for the District Governor's All-Star Award. The National Junior Honor Society is to induct 28 new members. She said when seniors receive acceptance to a college or university or sign up for the mili- tary it is announced at school with a recent announcement that Dakaya Floyd has been accepted by Bethune Cookman College.' Deborah Huckaba, Principal of Brown Elementary, reported a successful PTO fund-raiser, with $630 raised, and she shot'a bas- ket. Nan Collins said the Workforce Development Board's one-time Carl Perkins culinary grant has been a great success. Hinson said he had "heard many good things about the culinary arts program." Assistant Superintendent Clark had warned against getting one- time grants and then having the burden of continuing the expense. "In this instance it really worked," said Collins. Finance Director Terry St. Cyr is setting up a system of number- ing employment positions. "I'm still informed there are no new positions, that we are re-filling funded positions." said Chairman Gander. "That is correct," said St. Cyr. Among personnel recommenda- tions approved were Karen Ward and Misty Hitt, teaching, and SGeorge F. Peddie, custodial, for i Brown Elementary. It was also .approved to advertise a bookkeep- ing position at CarrabelleHigh. The Franklin Chronicle A LOCALLY OWNED NEWSPAPER 9 February 2001 Page 3 EDITORIAL AND COMME Mid-America Band In Apalachicola February 24th In The February 2001 National Geographic RinR m Tide nf Crncrn: rn a LeTPvels Are The Mid-America Band, from Scott Air Force Base in Ohio, will per- form for the veterans and the public at no charge from 1:00 to 2:30 p.m. on February 24h and is sponsored by Gulf State Community Bank. The concert will be in Battery Park. This is a nationally recog- nized orchestra of 45 active duty Airforce men and women who are professional musicians. The public is invited to bring their lawn chairs or blankets. Should the weather be too cold or wet, two shorter performances with limited (250) seating will be held in the Dixie Theatre at 1:30 and 3:00. Priority of issue for these tickets will be youth musicians and veterans. Everyone should request tickets and will be given tickets to the Concert in the Park. Those who are veterans or musicians will also be issued Dixie Theatre Seating tickets on a first request-first issue basis (see ticket request form). In conjunction with this event, the Veterans' organizations of Gulf, Franklin and Wakulla Counties (see below) are sponsoring a veter- ans' appreciation event in Battery Park (Apalachicola, Florida) on February 24th from 11 a.m. to 4 p.m. This event will include a BBQ meal for veterans at no charge, who are members of any veterans' organization, and $5/plate for the public. Veterans' organizations will be on site to join members as needed. Each meal purchased by the public should feed two veterans as the veterans' organizations of Gulf, Franklin and Wakulla County and their generous community and corporate sponsors have donated much of the supplies needed to honor these veterans. Meal availability can only be assured with pre-purchased tickets. To obtain meal tickets, complete the Honor-A-Veteran form either including your veterans' information or sending a check made out to 'Honor-A-Veteran' for $5 per person and return these items with a self-addressed, stamped envelope to Honor-A-Veteran, % Gulf State Community Bank, P 0 Box 488, Apalachicola, Florida 32329. (Drive-Thru, pickup of meals will also be available if you are not able to remain for the concert. If you are able and willing to assist this veterans' recognition event and free concert in the park, please contact any veterans' organiza- tion listed below or myself at 653-9593 at Gulf State Community Bank. LTC (ret) David K. Butler Concert in the Park Coordinator Veterans Organizations Gulf County VFW Post 10069 American Legion Post 116 Franklin County American Legion Post 82 American Legion Post 106 American Legion Post 169 AMVETS Post 107 Camp Gordon Johnston Association Vietnam Veterans Association Wakulla County VFW Post 4538 Regulars Veterans Association 363 VFW Post 8285 \ r---------------------- FOR FREE CONCERT TICKETS To Request FREE Tickets, deliver or mail this form and a self addressed, stamped envelope to: HONOR-A-VETERAN, % Gulf State Community Bank, P.O. Box 488, Apalachicola, FL 32329. Please send me tickets (Limit of 4). Name Ph# Address email City State Zip OPTIONAL INFORMATION for inclement weather seating in Dixie Theatre. Name of veteran's org. you are a member of Are you a musician in a school band? YES/NO If Yes, what in- strument? Other reasons to receive limited seating @ Dixie Theatre (If weather requires indoor performance) L J L----------------------JU F --------------------- 1 FOR VETERAN MEAL TICKETS To Request HONOR-A-VETERAN meal tickets for a BBQ dinner, deliver or mail this completed form and a self addressed, stamped envelope to: HONOR-A-VETERAN, % Gulf State Community Bank, P 0 Box 488, Apalachicola, FL 32329 Name Ph# Address email City State Zip Name of a veteran's organization. You are a member of S___(#) of meals at $5/meal Total amount enclosed $__ Make checks payable to 'HONOR-A-VETERAN' ------ ---------------- U RI &o POST OFFICE BOX 590 EASTPOINT, FLORIDA 32328 Phone: 850-927-2186 850-385-4003 (TALLAHASSEE) Facsimile 850-385-0830 THE FRANKLIN COUNTY CHRONICLE, INC. Vol. 10, No. 3 February 9, at. Rising-and People Are In Harm's Way This brief report is about coastal and island dwellers risk of los- ing their homes, or even their lives, as a consequence of rising oceans. Sea levels have already risen six inches by 2000. By 2100, the prediction is a rise by another 18.5 inches. For more information: Climate Institute, Washington, D. C.. Intergovernmental Panel on Climate Change. Geneva, Switzerland. Resources and a forum at: nationalgeographic.com/ngm/0102/earthpulse. 0NTARY i An Apology Time was that shame caused delay, as did lack of courage and a search for words. But now I shall do my best to give to you (the youth) this delayed apology. I am sorry your world is so barren, and it was so rich when I was you. I am sorry that your nightmares come to you in the stark light on the -daily news, and mine came with the night and were imaginary, that the monsters aren't under your bed or just outside your window: but in the air you are breathing and the food you are eating. Our rivers are foul and deformed, our wetlands have been drained. and all the life they held is no more. I apologize. When I was you, there was no talk of thousands of unborn babies who had perished at their mother's command. There was a time when government and government agencies seemed to have the' people's welfare as their goal, and life, liberty and the pursuit of happiness had meaning. Kindness, loyalty, integrity and courage are colors of mankind; but the colors of power and excessive wealth cannot blend, and yet they are now our executioners and jailers. It was not always so. Love and liberty are dying in our hearts, and our hearts will soon become barren like the life in the once-rich wetlands. Some of us did the draining, and others of us watched and were silent. The great spirit nestled us in a land of bounty and beauty. The beauty has been desecrated and the bounty we once killed for food we now kill for fun. Our smiles are false and our laughter hysterical. The hearth that warmed and comforted me is now cold for you. Strang- ers guide your steps, wash your face and make laws to defeat you; and wonder still at the look of aloneness in your eyes. I apologize to you for this day and for as many days as will come. Marilyn Blackwell Resignation Dawn Evans Radford Panhandle Writer On Oysterman Tragedy Dawn Evans Radford, a member of the Panhandle Poets and Writers Group in Carrabelle, read a poem she had written recently. She said she felt compelled to write the following, after the tragedy of the two Franklin County oystermen. She read the piece at the January 31 meeting of the writers group and consensus was that it was a deeply moving tribute. White Sock If town talk could raise the drowned, the oysterman would have surfaced before the next sunrise. The details: Two tourists shelling the beach found the oysterman in knee-deep water twenty days later and ten miles down current, after the northeaster's' kicked-up bay water iced him down with a boatload stacked with burlap bags of fresh oysters. The buyer at the oysterhouse and his oyster brothers over black thirty-nine-cent coffee at the baytown cafe had said it won't worth it, and anyhow he needed time to shake off last week's flu. He hacked a cough and claimed that was the reason forcing him to go- no money in the house ten days running' and they won't nobody lining up to do it in place of him. He adjusted the bill of his cap. and scanned the coldest bay water in ten years' records, looked west at the low gray clouds. He could tong and cull a couple of hours and be at the dock before the wind blew in. He nearly did. He was figuring dollars per bag, not the speed of clouds, when he lay down his tongs and switched his outboard into a drone, and the first northwest growl rocked the boat. They found it four feet deep, said it sank like a rock and he'd froze in five minutes flat. They sold the bags to help pay for the funeral, when and if they found him. Other details: at the cape, twenty days and miles down current, for early morning sellers to find: one white woven oyster-culling glove, washed clean of oyster muck, bleaching in the polished sand; a blue billed cap, sand-blasted at the high tide line, here yesterday and gone tomorrow; two scrub-holed thermal socks a mile apart, riding tidal pool ripples, seaweed sprouting from the holes in one. Dawn Evans Radford January 2001 Permission granted for Franklin Chronicle to publish. First publication rights. Dawn Evans Radford, January 31, 2001, Panhandle Poets and Writers Meeting. Th rakinCroil No itibtdi FakiSaul Publisher's Note: Barbara Revell recently resigned from the Franklin County Planning and Zoning Commission. Her views may be at variance from others but the concern over develop- ment has certainly been the subject of many discussions at local meetings such as the St. George Civic Club or the Franklih County Commission. Indeed, the lamentation on the same subject by Pam Vest in a recent issue of The Apalachicola Times is very similar to Barbara Revell's viewpoint. Ms. Vest wrote about the impact of island changes on the physical landscape and the com- munity of St. George. While easy solutions are NOT in sight, the fact that more individuals are expressing their views on growth and "development" indicates any plan of action must involve the community at the outset. Are these the "first shots" in a war of words on "growth and development?" Franklin County Commissioners Franklin County Courthouse Apalachicola, FL Dear Commissioners: Regretfully, I hereby tender my resignation as a member of the Franklin County Planning and Zoning Commission effective March 1, 2001, or sooner if a replacement is found. When I was appointed two years ago I was pleased to be doing something for my County. I thought it was an honor, privilege and my civic duty to serve. Since then I have be- come quite disillusioned in the process. It appears to me to be a sham and a waste of time, at least mine. There are other ways I can serve my County. Even if the P&Z recommends against a particular project, the person making the request can go to the Board of Adjustments or appeal to the Franklin County Commissioners. For awhile the County Com- missioners paid very little attention to the P&Z Commission until they almost had a revolt on their hands. Now, at least, they appear to be paying more attention to P&Z. I have come to the conclusion that the developers will get what they want regardless of the possible deleterious effect on the County and/ or the environment. Nothing in this statement is intended to be a reflection on the staff of the Planning and Zoning Office or any mem- bers of the P&Z commission. I have become fond of all of them. I think that, perhaps, the P&Z should be restructured. I think that terms should be limited. One should not be allowed to serve indefi- nitely on the Commission. Also, I think the County should be very careful to ensure there is no conflict of interest on the Commission Sand an effort made to reduce the number of realtors on the Commis- sion. Jimmy Mosconis frequently speaks about expanding the County's tax base. It is my firm belief that growth DOES NOT pay for itself. The more development and increase in population greatly impacts the infrastructure'and the demands on the County increase. The County should not encourage growth. It will happen anyway. No one can slow down the rapid growth occurring in the County, however it can and should be better controlled. Growth should not be subsidized or encouraged. For the above reasons I can no longer enthusiastically or in good conscience continue to serve on the Franklin County Planning and Zoning Commission. Thank you, however, for the opportunity to serve. Sincerely, Barbara Revell ANNOUNCING OnLine Internet Banking GulfLink sign-up at Gulf State BA ember BANKFDIC Providing Modern Banking With Personal Service ! Apalachicola Carrabelle Eastpoint e-mail us at bank@gscb St. George Island - - Thie Frainklin Chronicle F -1 4- f t F ,1 IAI NA7 V A rz IjA iW 1) iL'7 Page 4 9 February 2001 A LULALLY uWvvNE Nir vvrr'" -r EDrIORIAL & COMMENTARY Letter To The Editor February 6, 2001 Dear Editor: Ifyou measured the time frame of Jessie Jackson's self-imposed exile and compared it with the time frame that it took Florida's new Jr. Senator, Bill Nelson, to join the political correct and liberal bigots that have inundated Washington, D.C,, you will find that Jessie and Bill ran a neck and neck race. It was with some distaste and surprise that I learned that our freshman Senator had joined hands with the likes of Ted Kennedy and other Democratic liberals in an unsuccess- ful attempt to defeat the nomination of John Ashcroft as Attorney General. According to news sources, Nelson and his new found friends op- posed the Ashcroft nomination to be our Attorney General because of Ashcroft's strong religious convictions and his opposition to gun con- trol. Unless my sixth grade class teacher was wrong, this country was founded by men and women seeking to practice their strong re- ligious beliefs and have fought and died Tor the right to hold to these beliefs ever since. As to gun control, has Mr. Nelson not read the Second Amendment to our Constitution? Does Mr. Nelson want our government to take away your right to own a firearm? It would behoove us all to look beyond the pretty faces in the next election and search the souls of those that wish to represent us. If we are not careful whom we elect, a Federal Marshall will be at our door in the not too distant future to confiscate our firearms. What is a person to do? I suggest you join and support a conservative organiza- tion. I joined the Republican Party. Sincerely, Willie Norred St. George Island FranklIin Bulletin Board February 9 March 24, 2001 By Tom Campbell February 9-Seminole Classic Soft- ball with FSU, Florida International University, University of Tennessee- Chattanooga, and Florida A and M University, all day. Lady Seminole Soccer/Softball Complex, Chieftain Way. For more information phone 644-1403. (February 9 to 11): February 9-Concert at Ruby Dia- mond Auditorium..Concert Band and Symphonic Band, 8 p.m. Ruby Dia- mond Auditorium, Westcott Building. For more info, phone 644-3424. February 12-5:00 p.m. Refuge House Task Force Meeting. For loca- tion or information, call 653-3313. February 12-Tallahassee: Seven Days of Opening Nights-Tallahassee Symphony Youth Orchestra; 3 p.m.; Ruby Diamond Auditorium, Westcott Building. Phone 644-6500. February 12-Wilderness Coast Pub- lic Libraries-Serving Franklin, Jefferson and Wakiilla Counties- Governing Board Will meet on Monr- day, February 12, 2001, at 2 p.m. at the Wilderness Coast Public Librar- ies Office in Crawfordville. For more information phone 850-926-4571. February 14-VALENTINE'S Day. Mark your calendar! February 15-Art Exhibit: "Pleasures of Sight and States of Being". Open- ing Reception, 6 9 p.m., Museum of Fine Arts, Fine Arts Building, corner of Copeland and Call Streets, 644-6836. Exhibit runs to April 1. February 15-Tallahassee Seven Days of Opening nights: The Suzanne Farrell Ballet, 8 p.m., Ruby Diamond Auditorium, Westcott Building. Phone 644-1000. February 17-Bow Wow Ball (Benefit for Humane Society). Harry A's on St. George Island. For more information, phone 850-927-3259. February 18-Concert: Handel's "Saul," an oratorio in three acts, part of Tallahassee's Seven Day of Open- ing Nights. 4 p.m., Opperman Music Hall, Kuersteiner Music Building. Phone 644-3424. February 19-Concert: Harmonie wind ensemble, 8 p.m., Opperman Music Hall, Kuersteiner Music Build- ing. Phone 644-3424. February 20-Tallahassee's Seven Days of Opening Nights: "Mark Twain Tonight". Actor Hal Holbrook, 8 p.m., Ruby Diamond Auditorium, Westcott Building, 644- 1000. February 22-Crooked River Light- house-Carrabelle Lighthouse Asso- ciation-new meeting time and place: 4th Tuesday of the month, February 22, 6:30 p.m. at Yaupon Garden Club, 302 Avenue F, Carrabelle. February 22-"The Diary of Anne Frank," FSU; Mainstage production of Frances Goodrich's and Albert Hackett's play, newly adapted by Wendy Kesselman, 8 p.m., Richard G. Fallon Theatre, Fine Arts Building, comer of Copeland and Call Streets. Guest starring George Hosmer, a member of the Dixie Theatre Summer Repertory Acting Group, Summer 2000. Mr. Hosmer is currently teach- ing acting at FSU. March 3-St. George Island Charity Chili Cookoff and Auction (Benefit for SGI Volunteer Fire Department) St. George Island. Phone 927-2753. March 10-Camp Gordon Johnston Parade and 10th Annual Reunion- Carrabelle and Lanark Village. Phone Sid Winchester at 697-3395 for more details. March 24-U.S. Air Force Aerial Dem- onstration Team, the Thunderbirds, bring their high-flying aerobatics to Tyndall Air Force Base for the annual Gulf Coast Salute. Air shows March 24 and 25, free and open to the pub- lic. Free parking and free shuttle bus transportation provided to the 'flightline show area. Demonstrations include: Air Force Demonstration Teams for the A-10 Thunderbolt II and the F-15 Eagle, Navy F/A-18 Hornet. Several civilian demonstrations are scheduled-the Red Bull MIG-17 fighter, a vintage F-86 demonstration by retired Air Force Colonel and Apollo 8 commander Frank Borman, and an acrobatic demonstration by Susan Dacy in her 450 horsepower Super Stearman. "We are doing all we can to treat our community to a great event," said Maj. Dave Green. Gulf Coast Salute Chairman. An F- 16 simulator ride and traveling display are also available to young people. Back by popular demand is "the world's fastest 1957 Chevy pickup- the 25,000 horsepower jet truck which is guaranteed toelectrify audiences as it rockets down Tynall's runway at more than 300 miles per hour. Check out the Gulf Coast Salute web site at. homestead.com/index.html for fur- ther information. FWC Schedules Artificial Reef Public Workshops The Fish and Wildlife Conserva- tion Commission has scheduled two public workshops concerning grant applications for artificial reef construction and monitoring. These grants are available to lo- cal coastal governments and pri- vate non-profit corporations that include artificial reef construction and monitoring in their bylaws. The Commission is interested in receiving public comment regard- ing grant application forms, the criteria to be used for evaluating .grant applications, and the future direction of the grant program. The public is encouraged to par- ticipate at these workshops, which will take plac'e'from 3-5 p.m. as follows: Tuesday, Feb. 13 Destin Community Center 101 Stahlman Ave. Destin Thursday, Feb. 15 Fort Myers Beach Town Hall 2523 Estero Blvd. Fort Myers Beach Funding applications for artificial reef projects must be received by the Commission no later than 5 p.m. on March 2. Requests for application forms can be made by calling (850) 922-4340. From The Southeastern Fisheries Association, Inc. Eating Fish Is Good For You AMA Study validates ish as reducing risks of mini-strokes in women The Journal of the American Medical Association released a report of a study of 80,000 women on a diet high in fish and con- cluded fish was linked to reduc- tions in the ischemic, or clot-related strokes. which ac- count for 83% of all strokes. Women who ate about 4 ounces of fish two to four times weekly cut their risk of ischemic strokes by 48%. Slightly higher reduc- tions were found in women who ate fish 5 times a week but there, were relatively few women in that" group." And if that wasn't reason enough to eat more fish, the American Heart Association's position on fish is that because of increased; evidence 'of cardiovascular ben'i;: efits of fish (particularly fatty fish) consumption of at least 2 fish servings per week is now recom- mended. The bottom line is fish is good for humans. There are fish that can cause ill- riesses if not handled properly, particularly, mahi mahi, tuna, Spanish mackerel, king mackerel and a few more species that can develop histamine unless kept cold "from the boat to the throat". This is why it is so very impor- tant to purchase your fish from a licensed fish business that has been certified under the federal Hazards Analysis and Critical Control Point (HACCP) program. if you purchase fish from a road side vendor with no sanitation facilities just ask yourself, how does the sales person wash his hands? If he relieves himself be- hind a tree and then handles your fish without washing his hands, that's ugly. Who checks the -.tal.e? Where were the fish cauglit' Wh 'l'll? Have they been doctored and brought back to-having a fresh smell with Clorox or som, other voodoo chemical? Wildlife Recreaion Creates Economic Boon For Florida Outdoor enthusiasts spent twice as much money last year in Florida on hunting, fishing and wildlife viewing as Florida lottery players did on buying tickets. According to a recent study conducted by the Florida Fish and Wild- life Conservation Commission (FWC) hunting, wildlife viewing and saltwater and freshwater fishing annually generate approximately $5.5 billion in retail sales resulting in an economic impact to Florida of $7.8 billion. In addition, the study revealed sales tax benefits to the state are esti- mated at $336 million, and 138,210 jobs are directly associated with Florida's fish and wildlife-related recreation. "The sheer scale of the economic benefits provided by fish and wild- life to Florida's economy is one reason for maintaining wildlife popu- lations and habitats in a healthy state," said Dr. Allan L. Egbert. ex- ecutive director of the FWC. The economic benefits by type of activity are: Participants Retail Sales Sales Tax Economic Impact Jobs Hunting 233.992 8356.812.910 $21.408.775 8383.994.869 12.492 Freshwater Fishing1.375.875 8958.117.52!1 $57.487,050 $1.029.352.539 18.759 Wildlife Viewing 3.938.918 81.887.887.300 $113.273.243 81.993.645.537 52.140 Saltwater Fishing 2.493;858 8$2.3951869r789 8143.752.189 $4.474.842.714 54.819 By, wayr o,cornparison:, ,, Florida sales tax revenue from hunting, fishing and wildlife viewing is more than the annual tuition paid by 34,000 in-state university students. More than one out of every five state residents are wildlife viewers and, spend an average of $696 annually on trip-related and equip- ment expenditures. "Our strategy for maintaining abundant wildlife populations is to re- mind decision makers that Florida's wildlife resources should be con- sidered economic assets as well as natural assets to be conserved and managed for the benefit of all Floridians," Egbert said.. The FWC recently completed the economic study of Florida's fish and wildlife-related recreation in 2000. The study was based on the U.S. Fish and Wildlife Service's National Survey of Fishing, Hunting and Wildlife Associated Recreation, conducted by the U. S. Bureau of Cen- sus. Postal Jobs $48,323.00/Yr. Now Hiring-No Experience-Paid Training Great benefits for app, and exam info: 1-800-429-3660 ext. J-815 7 days a week CLAIM OF LIEN NOTICE Per Florida Statutes 713.78 (3) (b) File No. Date of this Notice 01/31/01 Invoice No. b172 Description of Vehicle: Make Ford Model Va' color Blue/Tan Tag No Year 1983 stateFlorida in No. IFTDE14YXDHA35628 To Owner: Stephen and Teresa Jones To Lien Holder: Charles H. Scott 191 Ave. L 234Ave.F Apalachicola, FL 32320 Apalachicola, FL 32329 You and each of you are hereby notified that the above vehicle was towed on 01/26/01 at the request ofJonathon Ro NO STETM TO0UCIB O0H FRAKLI CONTYCHRNACLE Complaints About Fuel for EMS Trucks Compound Reactions Centennial Healthcare Proposal to Transfer Lease Creates Stir At County Commission Meeting At the end of the Tueday., Feb~lj ry. meeting of the Board of County Commissioners, the, anOumeiit f a proposed change in the lease agreement of Weeims I' ~ ..-z.'o' raised e'. -I: ..:Fi.'.; 'C. Commis- sion, particularly Eddie Creaffr .- wo ,-. ..'. h... rs, jusi. Centennial Healthcare sent a ~nwi~ 6 wm to heC Commission ad- vising them that -1 -.' a .u, ,** .;- I-*' ..1r, lf :e-;- ,:'a wanted to assign its t ig l v titlm e anlt ilter~Sd1 te w Ci r-p1waL,,: h- DasSee Community H,:-lAh Systeffas LLC, oC,. bef13 e i.. 2001 Subsequent discussion revealed that Centennial was sLhtiton tthie focus of its cor- porate goals to include nro -..'.7-1 ho'".' .'-- '.' ...' .i:-r.: ,i elf of some hospitals. The DasSee Community I i~ .., ~.. ;.'-. .- ir. was created to assume control over the former Centenniial l~tspital, as explained by Michael C. Lake, Senior Vice President of6r Cen nial, and soon to become President of DasSee Co.r:i rrt, 'i r.' t Health Systems LLC. The entire matter was tabled until the next meeting of the Board of County Commissioners, when representatives of Centennial and DasSee will present their credentials, and a review of the rationale for seeking to transfer the lease. Compounding the rising concern were two complaints about Emer- gency Medical Services (EMS). A memorandum from hospital admin- istrator Susan B. Ficklen described the situation r, iardir.: fuel prob- lems for the trucks used to pickup and transport patients. She said. "First, the E.M.S. crews have been reminded that there is a process in place when they need fuel in the trucks. The fuel became an issue because this process was not followed. The fuel provider has been paid in full, and the ambulance crews have money for fuel in their trucks." "Second, the base rate of pay for paramedics has been raised to be competitive with neighboring counties. There are two Advanced Life Support trucks running 24 hours per day, 7 days per week. We are currently seeking appli- cants for E.M.S. staffing." Incarceration Scheduled To Begin For Nita Molsbee And Maxie Carroll February 15th According to the Judgment Order handed down by Federal Judge Robert Hinkle in December 2000, Maxie Carroll (Eastpoint) and Nita Molsbee (Carrabelle) were to report under their own recognizance to federal prison authorities on February 15, 2001. The third convicted and sentenced defendant in the Medicare fraud case, Thomas Novak, self-reported to prison authorities, and has been transferred to a minimum security prison camp near Montgomery, Alabama on February 5th. All three defendants had received varying incarceration times, and have filed notices of appeal as early as October 2000, but as of last week, the Clerk's office at the U. S. Court of Appeals (Atlanta), they have not.received any appeal briefs for any of the defendants. March 6, 2001 is the deadline for filing the appeal briefs in Atlanta. If Molsbee or Carroll sought to remain free on bond, a hearing would have to be scheduled with the Federal Court in Tallahassee but the public file does not reveal any such request, nor has any been scheduled with Judge Hinkle as of press time. Brenda M. Molsbee was convicted of conspiracy to commit mail fraud, wire fraud, making false statements, making and using false documents and impeding the Internal Revenue Service (Count 1). She was also convicted of making false statements on a tax return (Counts 2,3,4 and 8) and making false statements dur- ing a bankruptcy proceeding (Count 9). She is to be committed to the custody of the U. S. Bu- reau of Prisons to be imprisoned for a term of 62 months. The Court recommended that Ms. Molsbee be designated to a facil- ity as near to Carrabelle, Florida, as possible. Her attorney has in- dicated this would be the Federal Correctional Institute, Tallahas- see. Maxie G. Carroll was convicted of conspiracy to commit mail fraud, wire fraud, making false state- ments, making and using false documents and impending the Internal Revenue Service (Count 1). She was also convicted of mak- ing false statements on tax re- turns (Counts 5, 6 and 7). She is to be committed to the custody of the U. S. Bureau of Prisons to be imprisoned for a term of 51 months. The Court recommended that Ms. Carroll be designated to a facility as near to Eastpoint, Florida, as possible -This is likely to also be the Federal Correctional Institute, Tallahassee, although the U. S. Marshall indicated to the Chronicle that the exact location may be changed. St. George Island Plantation Beach Access "Summer Place" 1808 Denise Drive Lovely 3 bedroom, 3 bath 2100 +/- sq. ft. home of stucco construction with con- crete pilings and a standing seam metal roof. Amenities include: tile and hardwood floors, two screened porches, paved parking under the house, a landscaped yard and private heated swimming pool. "Summer Dreams" is an immaculate, well ap- pointed home. Offered fully furnished at $469,000. MLS#8018. Select Bavfront Homesites Eastpoint, Magnolia Bay, Lot 30, 1 acre: cleared, driveway, pier. $215,000. MLS#6731. St. George Island Plantation, Lot 61 Sea Palm Village, 1 acre. $179,000. MLS#6963. Eastpoint, So. Bayshore Drive, 2.50 acre, 225' bay frontage. $239,500. MLS#6616. SPrudential Toll-Free: 800-974-2666 O Phone: 850-927-2666 Resort Realty e-mail: info@stgeorgeisland.com 123 Gulf Beach Drive West St. George Island, Florida 32328 An Independently Owned and Operated Member of The Prudential Real Estate Affiliates, Inc. a COOKOFFI AUCTION ITEMS Theo franklin Chronicle A LOCALLY OWNED NEWSPAPER 9 February 2001 Page 5 Hazardous Weather Awareness Week Is b~.m-a.. I y f 0 ,,0 A rueruary IV-Zarl The Dept. of Community Affairs, State of Florida, has proclaimed February 19-23rd as Hazardous Weather Awareness Week in or- der to sensitize Floridians to pre- paring for severe weather in the coming months. A guide has been prepared for distribution to pub- ic and private schools statewide, and is now available on the internet at. The guide systematically identi- fies five hazard areas with recom- mendations to deal with (1) light- ning, (2) hurricanes and flooding, (3) tornadoes and thunderstorms (4) marine hazards and (5) tem- perature extremes and wildfires. The appendix also contains in- valuable data on the Florida Warning and Information Net- work, the warning process, use- ful web sites and, of course, a hurricane tracking map. Steven M. Seibert, Secretary of the Department of Community Af- fairs, reminds Floridians that, "...Keeping the public informed and helping them make the right decisions before, during and af- ter a disaster is our primary fo- cus. But this is only the first step. Families must take some personal responsibility in preparing for a disaster. Every family should have a disaster plan." The guide was developed by state and local emergency managers and the national weather service to help individuals, schools and communities gain a more thor- ough understanding of severe weather and steps they can take to help keep them safe during a disaster. Purchasing a weather radio that can alert persons in times of se- vere weather events is strongly recommended as a first step in such preparation. ~. j ~~~g~ y~i-a-i'C -L .-r 'I :t.' Dr. Michael Wilder Returns From Bangladesh Success .-1 ...'1I ri II Tornado in the city. Dr. Wilder visited a computer school while in Bangladesh. He said the building looked like a "shack," but had all the latest computer equipment.. Dr. Michael Wilder rides an '' elephant with a native driver oil visit to India in 1974. Coast Guard Cutter SEAHAWK Assists With Shrimp Boat Fire Quick action by the Coast Guard Cutter SEAHAWK materially aided in the putting down of a fire aboard the fishing vessel ROLLIN STONE in Carrabelle Harbor on Friday, January 26th. The SEAHAWK was departing Carrabelle for a patrol about 11:10 a.m. when they contacted the fishing vessel ROLLIN STONE. The STONE, an 86 foot shrimper, reported that they had a bunk fire and were occupied with fighting that but the fire soon spread out of control. The SEAHAWK pulled alongside with charged fire hoses as their crewmen donned fire fighting equipment, The cutter's crew passed the hoses to the ROLLIN STONE's crew who were able to put out the fire through a port window of the bunkroom. The SEAHAWK escorted the ROLLIN STONE back'f6_her moibi-- e--" aeTfer fit was' dtermiiied that there were no injuries nor burin- ing. The SEAHAWK is an 87-foot coastal patrol boat homeported in Carrabelle, Fl. She is designed for week long coastal patrols and is ;equipped for search and rescue, environmental protection, and maritime law enforcement. The SEAHAWK is commanded by *Master Chief Boatsweain's Mate George Wilson. By Tom Campbell Dr. Michael Wilder of Eastpoint returned to Franklin County from Bangladesh in December of 2000. He is now living on St. George Is- land and continues his work with the Franklin County Health De- partment. He recently completed a three-month volunteer assign- ment to participate in the Stop Transmission of Polio (STOP) ef- fort. The Centers for Disease Control. WHO, the United Nations Children's Fund, and Rotary In- ternational are partner organiza- tions in the global mission to eradicate polio. "Every Child Counts" is the slogan that STOP has adopted to stress that all chil- dren need to be reached and vac- cinated against this disease of polio. Polio is an infectious disease .caused by the poliovirus. It can strike any age, but typically af- fects children under three years of age. While not all polio results in paralysis, polio paralysis is al- most always irreversible. In the most severe cases, poliovirus at- tacks the motor neurons of the brain stem, resulting in difficulty breathing and sometimes death. The poliovirus was last prevalent in America in the 1950's. The iron lung was much feared then and mothers were reluctant to send their children to public swimming pools. The Americas have been certified polio-free since 1994, and the number of polio infected countries is now down to 3Q. The' uperr ,ofg, polio infeqteld countries are now concentrated in parts of sub-Saharan Africa and the Indian sub-continent. Dr. Wilder has a Masters Degree in Preventive Medicine, in addi- tion to,the M.D. He spent three months in India in 1974 with the successful Smallpox eradication ...no matter where you are- ours is a service you can trust. SKEJLLEY FUNERAL HOME KELLEY-RILEY FUNERAL HOME .i serving all of Franklin County 653-2208 697-3366 Bayside A Reaync. ikcenard Real Esate Broker 850-697-9500 Residential, Waterfront & Dog Island Properties NEW LISTING! "BAY WATCH ACRES" Completely renovated home with over 1,900 sq.ft. in immaculate condition. On 4 acres over looking Apalachee Bay with bay frontage. A must see! $495,000. "DOG ISLAND PROPERTIES" Lots on the Gulf, Bay, Canal and Interior Homes on the Gulf, Bay and Interior. Ask for Jan, "The Island Lady". Bayside Realty, Inc. 101 Marine Street P.O. Box S Carrabelle Office: 850-697-9500 Fax: 850-697-9541 Mobile: 850-545-7714 E-mail: Janatbayside@msn.com Jan Stoutamire Realtor Multiple Listing Service Freda White Lic. R.E. Broker Raymond Williams Licensed Real Estate Broker program. Bangladesh is considered one of the polio virus "reservoirs," areas where transmission is particularly intense due to large dense popu- lations, low routine immunization coverage, and poor sanitation. The target date for global polio eradication is 2005. By then, it is hoped, no child will lose life or functionality again due to the po- liovirus. Purpose of Mission The Duty Station of Dr. Wilder were five districts: Faridur, Rajbari, Gopalganj, Madaripur, and Shariatpur. These five dis- tricts have a total population of more than 6 million people. The five districts include approxi- mately 4.5 percent of the nation's 150,000,000 people.; His tour of duty was 10 Septem- ber to 5 December, 2000. The purpose of the mission was to assist in the effort to interrupt the transmission of wild polio vi- rus, and leave behind an even more organized network of highly trained and motivated Public Health Professionals and Volun- teers who can rapidly detect and respond to any subsequent rein- troduction of wild polio virus into Bangladesh's five Districts of the Dhaka Division, south of the Padma River. This regional mission is part of the larger national and international Polio Eradication Programs. This is a highly successful program involving three key elements: .1. Routine polio immunization (EPI), 2. National jmrmunization Days (NIb);, and 3. Acute Flaccid Paraly- sis'(AFP) surveillance. Each of these elements must be demon- strably in place and functioning at a high level for three continu- ous years without polio transmis- sion in order for certification of the nation and region as Polio Free. Much progress has been made on all of these elements over the past few months and years. During this past year (2000), the amount of polio virus is estimated to have been reduced by 97 per- cent. In 1999, wild polio virus was isolated from 29 cases, with an additional 293 clinically con- firmed polio cases. That compares most favorably with only one (1) virus confirmed and an additional 116 clinically confirmed cases of polio this past year, 2000. These improved data are bolstered further by the concomitant im- provement in polio surveillance sensitivity as represented in na- tional statistics. As Bangladesh enters the new millennium, the country is poised on the brink of interrupting the transmission of wild polio virus and, if this momentum can be sustained for the next three years, polio free certification will follow, on schedule, in 2004. This is Dr. Wilder's hope. He points out that there is a great need not to "take public health and preventive medicine for granted. It takes a lot of dedicated souls and very little money to keep us all well." He pointed out that "there was a great deal of other totally prevent- able diseases occurring with great frequency such as tetanus. That horrible disease is seldom seen here in the U.S.,... due to rou- tine immunizations. Not so in Bangladesh. I noted more cases there, in areas the size of two U.S. counties, than seen in the entire U.S. per year. They have Tetanus Wards in their hospitals!" There, he said, only one percent of the infants with neonatal teta- nus survive. There is much in the U.S. for which to be grateful, not the least of which is the tremendous pro- gram of public health and preven- tive medicine. Dr. Wilder and his co-workers are to be congratu- lated. They should never be taken for granted. F r a nn kk I i nn: Chronicle ulf Cou ti Ii ] ie I Now distributed inn FFrranklinn,, Wakulla, and Gulf Counties lic V I 4allimi-l wen i Chronicle A LOCALLY OWNED -rc Bridge pilings begin to take the traditional form. r F ,. I >-- .4 Cc, tb. f~ -. ~ .1 .., In early February 2001, a progress shot of the new bridge connecting Eastpoint with St. George Island. The contractor reported that all permits have been issued, and the concrete pilings for the super structure are being put into place. Some of the beneficiaries of the new branch library in Carrabelle. p / \'0 II" PI I -[. . Boyd Meets With Cheney In the first, of what he says will be regular trips to Capitol Hill', Vice President Dick Cheney met with Congressman Allen Boyd (D- North Florida) and the fiscally conservative Blue Dog Coalition. Vice President Cheney called the meeting on February 6th to pitch the Administration's tax package to the Blue Dogs. Rep. Boyd, a leader of the Coali- tion, felt the meeting was "produc- tive and positive." "The Blue Dogs have taken a unified position that the national debt reduction is the. best financial service the Con- gress can give to the American people." The Blue Dogs have a reputation for being fiscal watch- dogs and tout the mantra of re- sponsible budgeting. "Fiscal dis- cipline drove our nation to where it is today. We can not throw away a decade of hard work and re- sponsibility," added Boyd. The Blue Dogs, who will unveil their own budget proposals within the coming weeks, have endorsed a "50-25-25" equation for respon- sible budgeting. The formula would put the Social Security and Medicare Trust Funds off limits, use half of the surplus to pay down the national debt and divide,, the remaining surplus between tax cuts and spending priorities such as Agriculture, Education and National Defense. "We have a budget surplus that is large Franklin County Commissioners wield their gold-tipped shovels. The context for the historic ground-breaking. Insulated Concrete Forms of North Florida Inc. An Independent Authorized SReward Wall Dealer (850) 670-5600 Fax: (850) 670-1076 P.O. Box 281 9 Island Drive SEastpoint, Florida 32328 -Gift Certificates Party Trays Fruit & Gift Baskets Choice Beef Fresh Poultry Fresh Seafood (in season) We specialize in choice Custom Cut Meats with a Mon. Sat.: Cold Cut Department. 9 a.m. 6:30 p.m. Fresh Produce Groceries noon 6:3p.m. Beer and Wine Pine Street Mini Complex 2nd and Pine East St. George Island, Florida 850-927-2808 The Supply Dock Bayside Floorcovering Carpet Tile Blinds 139B West Gorrie Drive St. George Island, FL Telephone: (850) 927-2674 Ray & Marlene Walding, new owners ! Denise Butler with Eileen Annie in the background. enough to provide solvency for Social Security and Medicare, hammer away at the national debt * and increase funding for American's priority programs, but we must do this in the confines of a fiscally responsible and com- mon-sense budget framework." Friends Of Florida State Forests New program enables public to help enhance state's natural resource. Florida residents now have a di- rect role in helping enhance their state forests through a public-private partnership that allows them to contribute funds directly to projects of their choice. Friends of Florida State Forests is a not-for-profit corporation founded by concerned citizens and approved by the Florida Leg- islature to help the state's Divi- sion of Forestry with its forest management needs. It was cre- ated to enable individuals, orga- nizations and businesses to con- tribute toward general forestry operations or toward specific for- estry projects. The Division of Forestry, part of the Florida Department of Agri- culture and Consumer Services. has been the state's lead agency for managing state forests for more than 60 years. Currently, the division manages 29 state for- ests encompassing more than 834,000 acres. More than a half-million people visit Florida's state forests each year. "Friends of Florida State Forests helps fill an important need by augmenting government funding with private contributions for for- est enhancement projects," Divi- sion of Forestry Director Earl Peterson said. "It is an excellent opportunity for the outdoor rec- reational business community and individuals to promote rec- reation as a part of their interest." For more information, contact: Program Coordinator Friends of Florida State Forests, Inc. 3125 Conner Boulevard, C-21 Tallahassee, FL 32399-1650 Telephone: (850) 414-0869 E-mail: FFSF@doacs.state.fl.u6 Web site: MARKS INSURANCE AGENCY, WRITING: Home, Auto, Life, Business, Marine, Bonds and Other Lines of Insurance See us for your insurance needs at: 61 Avenue E Apalachicola, Florida 32320 850-653-2161 800-586-1415 GENERAL CONTRACTORS RG0055056 Tractor Work * Aerobic Sewage Treatment Systems Marine Construction Septics Coastal Hauling Foundation Pilings SCommercial Construction Utility Work-Public & Private INC. UNITED STATES AIR FORCE Band of Mid-America February 24th See Page 3 for information about obtaining tickets and the rain plan. THE EPISCOPAL CHURCH WELCOMES YOU Srinitp S850 I Y OU CABLEGOODBLY! SPFRO\T OMLY \SRP S49'15sF *FREE 1st Month Programming *35.99/mo. for Top 100 Channels *FREE Professional Installation *30-DAY Satisfaction Guarantee *HBO. Showtime. Cinemax and PPV *TWO Receiver System "Digital Pictu'e, CD Quality Sound" "America's Top 50 Channels only S21.99 mo." is available - I DIRECT SALES Seclae Fe 1-888-292-4836 Offer ends 3131101 All prices, packages and programming subject to change. Local and state sales laxes may apply. Restlctions apply to DISH Network hardware and programming availability and for all offers All service marks and Iade. marks belong to their respective owners. OCHLOCKONEE BAY REALTY Tiht. * Bald Point! See the sunrise on the beach from large screened porch, block 2BR/ 1BA at Bald Point. Large kitchen/great room, lots of twisted oaks adorn this beauti- ful property. Won't last! Just $125,000. 68FAH. *Alligator Point! 2BR/1.5BA home on pilings with great view of Gulf. Large sundeck, large screen porch, open kitchen, great room, storage area below with screened fish cleaning room. Just $156,900. 70FAH. WAKULLA COUNTY WATERFRONT HOMES * Oyster Bay! Two houses, two docks! Main house has 1,430 sq. ft., 3BR/2BA, fireplace, mezzanine deck, with workshop, CHA, and majestic view of the bay. Guest house has 2BR/1BA, 1000 sq. ft. comes fully furnished, deck with canal for large boat. Just $229,000. 143WWH. * Mashes Sands Rd!, dock, CHA, vaulted ceiling, carport, workshop/guest house is 2BR/1BA, screened. All this for $225,000. 158WWH. / I 2001 "'"-""" UI - ^ IL- I ]BE~a~P ~ ,, ~ar iin" rl a :,t i P A LOCALLY OWNEvi N IWSPAPER IThe v UI nu 12 %i, i 9 February 2001 Pane 7 Harare, Capitol Of Zimbabwe Children Of The Street By Brian Goercke By the gates of their palaces. I have uttered my lamentations, And all have paid a deal ear to me. They hear me cry... But they seem not to hear what they hear. -From the poem. "Lamentations q/'a Street Child." David Jimmy Bricks (standing) concludes lesson as his students enjoy a snack. sfJRATES JUST LOWERED! 'TYIP 0BO,RROBqOW, ANY LOAI , SS70,000 S'100,000 "" . PAYONL PAY ONLY AMOUNT SS465 S665 AVAILABLE BO (R0 B01"dNY LO N '" *Debl (onsolidllon Loans Home Improvement Loans .Morigage Rel;inancng -Seiond Morigges "Antiques and old toys cheerfully bought and sold." 3 te e5nm Ctree DISTINCTIVE ANTIQUES & ACCESSORIES 79 MARKET STREET APALACHICOLA, FL 32320 STORE (850) 653-2084 WESLEY & ANN CHESNUT STORE (850) 653-2084 HOME (850) 653-8564 Residential Commercial Property Management Vacation Rentals Smm New Listing! 106 Whispering Pine rive, Eastpoint. .,New starter home in quiet m.j division. Features include: Open floor Ot'ral light, 3 bed- rooms, 2 full a .g C' ow maintenance vinyl siding, encldQ 1 ,apiance package with self clean- ing range, re or/ice maker, dishwasher, washer/dryer hook-up, and much more. $89,500. It is estimated that 10,000 childel-l H10W spend a considerable por- lion of their lives on the streets of iihianiam r' Some live permanently on the streets, while others are tellpoa. nU r-esidents. Many more come to the streets and spend a large part of their days working or begging. Even though a child may spend ilw i .ijrui i\ of his or her time on tifw street, that person may not be rc-rigi, i'rd by social workers and relief or.irs:i..I(in-s as a street child. UNICEF regards those children who live permanently on the streets as "children of the streets." These are the country's most '1,- i-t r.i- children. Food, lothing and shelter are their primary '-crj I II-, are at tremendous risk of contracting illnesses and are more likely t6 be abused by members of society. They are by definition street liii dren. Children who have homes, but still spend their days working or beg- ging oti the streets are classified by UNICEF as, "children on the streets." They are still quite needy. Although they do have shelter, it does not mean that their homes contain food. 1M.Iu-, must go to the streets in order to obtain what their homes do not provide. About Street Life: Gangs Most children who find themselves living on the streets for prolonged periods of time eventually join these small gangs. These gangs con- sist of approximately 10i20 members, per group. They are somewhat territorial and there are cases of violence between the city's gang mem- bers. However, violence is by no means as severe as that which is experienced in the states. Of course, if guns were as readily available, the country's gang violence could be as horrific. Street children join these gangs more out of necessity than for pur- poses of status among peers. Gangs offer the younger and more vul- nerable children protection from older boys who may otherwise at- tempt to harass and exploit them. Gang membership also provides companionship for street kids and may even lead to job opportuni- ties. To live alone on the streets of the city is to live with almost no human contact. Gangs provide identity to those who have almost nothing to call their own. Mainstream society does everything in their power, to ignore street children. Its people avoid eye contact and limit dialogue to just a few words or phrases; such as, "Aiwal (No!)". "Handina Mari (I don't have money)" and "Handidi (I don't want anything)." There are some work opportunities for those living on the street. Of- ten, being a part of a trusted group of children may lead to temporary employment opportunities. If a person or business gains respect and confidence in a certain gang, affiliation with such a group can be Students at Streets Ahead enjoy bread and tea. financially profitable. Even on the city's streets, networking is essen- tial. Making Money and Surviving There are a variety of ways in which street children generate funds or food to survive from day to day. Some of the more popular jobs in- clude washing cars and guarding property during the evenings. Some children look after local shops in the city and are rewarded with left- over food or spare change, . Some of the children attempt to vend sweets, popcorn and cigarettes throughout the city. Often, they do so without vending licenses and are therefore targeted by police officers in the area looking for a bribe. Sometimes the officers just confiscate the young vendor's goods. These homeless children often work at bus terminals by directing prospective passengers to the vehicles of their temporary employers. Those with artistic talents and adequate funds for supplies sell their crafts mostly to tourists on the streets. Others perform music or drama in the city square on Second Street. Unfortunately, young girls who come to the streets frequently go di- rectly into prostitution. The girls are usually so desperate that they do not consider the consequences of their choice of lifestyle. Society, which refers to them as commercial sex workers, seems to tolerate their heavy presence throughout the business sections of the city. In the more prominent, residential areas, they are usually discouraged from soliciting customers. Begging is one the more common ways for needy boys and girls to raise money. Some of these children begin begging as young as two and three years of age; their parent bring them to the streets with the hopes that passers-by will take pity on such young, unfortunate chil- dren and give generously. The older the child becomes, the less likely people will be to toss coins in their direction. Those who beg for their bread often frequent the busiest intersec- tions of the city to solicit from motorists and pedestrians. It's usually an all day affair. Many of these children know very little English, which makes it difficult for them to beg from those most likely to give such as tourists. Their common refrain is, "hungry baas*, hungry." The children who are unable to raise enough money through begging are often forced to pick through garbage bins located behind restau- rants and convenience stores. One of the main concerns, though, is that some of the stores spray their bins with pesticides. (*The word baas is an Afrikaner word, which was used during apart- heid and essentially means sir. Native Africans at that time were ex- pected to greet their white counterparts with this word.) Sleeping Conditions Of all things relating to street life, the conditions in which these chil- dren are compelled to sleep upsets me the most. It's hard for me to accept that children as young as.eight and nine years old are sleeping on the city's streets. And I don't know what to do to change their circumstances. They sleep on the sidewalks with their friends huddled nearby. They sleep in drainage ditches and tunnels, which become dangerous dur- S. , Reduced! Las Brisas Way, Las Brisas, Magnolia Bluff. Beautiful custom built executive home on oversized lot in new community. Features include: 6 bedrooms (2 mas- ter suites), 4 baths, fireplace, large sundeck overlooking private back yard, 2 car garage, beautifully landscaped and much more. This one of a kind home is an absolute must see. $185,000. Coldwell Banker Suncoast Realty s. 224 Franklin Boulevard e-mail: sales@uncommonflorida.com St. George Island, FL 32328 850/927-2282 -800/341-2021 SUNCOAST REALTY SUNCOAST REALTY ing the rainy season, hey sleep in parks while the weather is ilt';r. and in bus terminals when it is overcast. These ,' !'irr, l ofi~ ~ the front steps of shops and in the back .;;*,-',': ti xy the .,.," bins.. They sleep on the green located lust out- side of' freed area by :'- ~P Station on Samara Machef Avenue. And on winter evning they huddle around small fires to chase the ehilU from their boes.. leepeing night after a;i t the streets of city takes its toll on these rhildreli. Their skin beeoeo cracked and illness latches onto them. 'l*l-, hair becomes liee filed and W heir teeth rotten. Their clothing beomesl dirty and iwoorn.- A nd : .'.,: r', their whole systems break down, The streets ilnfect l ofi-:, wi fis t lcWhure of'hJm-, and promiscuity. Some have 'il:, '. iln, r .::k......' ;-, from the freedom that the streets supposedly offer, In al! i,,, t,:.- 't eedom is an illusion. Living on these urban streets makes them svanI ard enemies to mainstream society. They are the twst easy to exploit and most difficult to repre- sent. Drug Use I never give money to children of the streets% I know all too well that this money may be used to purchase glue, which is their drug of choice. Street children say that ,r;;ill:;: glue helps them to forget their miserable lives. It eases their hunger and makes them oblivious to the cold. These children sniff glue from plastic milk bags. They make few at- tempts to hide their consumption of the drug. At many of the inter- sections, they hold these bags to their face with one hand while put- ting another outstretched hand through a bus or car window. "Hun- gry, baas, hungry." Marijuana and alcohol are also abused on the streets, though not to the extent of glue, Alcohol is just as accessible to them; most minors can purchase alcohol with very little difficulty. However, alcohol is not as potent as glue. It does not seem to masque reality quite as effectively as glue. Marijuana is also fairly accessible on the streets, though some children are reluctant to use it because they say that it causes insanity. So they sniff glue ... hourly, daily and weekly. They inhale this venom at eight, nine, ten years of age and continue as long as they remain children of the streets. It is an integral part of street culture. Getting Involved During my first few months in Harare, I worked solely with former street children at Lovemore Home. I listened to their testimonial of surviving street life. These children now seem to be well adjusted and living very healthy lives. They just needed a chance, and Lovemore Home was there to help them. On my daily walks to and from Lovemore Home, I came into contact with many of the children "of' and "on" the street. I became more familiar with them, and even began to know to some by name. And I wondered whether their lives could be transformed as dramatically as those living at Lovemore Home. Did they just need a chance? It didn't take long for me to realize that I wanted to work with the city's street children in some capacity. I wasn't sure exactly what 1 could do for them. I just knew that I wanted to get involved. Streets Ahead In mid-September, I began visiting some of the various shelters in the city of Harare. I wanted to see what services these shelters provided and whether they needed volunteer assistance. One particular shel- ter located on Samora Machel Avenue grabbed my attention almost immediately. Many of the children that I had met regularly on the streets visited this shelter frequently. It had a caring staff and offered many programs to the youth. This shelter was Streets Ahead. Streets Ahead is a day shelter. Unlike Lovemore Home, it does not provide overnight accommodations to the homeless. Streets Ahead offer a variety of recreational and educational activities to the chil- dren; it provides one daily meal and has bathroom facilities for the children to wash themselves and their clothes. ( 1 ,k' ,. -- Youth leaders prepare bread and tea for Reading and Feeding program at Streets Ahead. Mr. Markim Wakatama, Director of Streets Ahead, informed me that approximately 1,000 children were living permanently on the streets of Harare. Between 50-100 of these children he said, visited his shel- ter on a daily basis. And, yes, he could use some volunteer assistance at Streets Ahead. Lovemore Home's program director gave his blessings for me to work each Friday at the day shelter. Now, I just needed to figure out how I could best help a group of children with a mountain of needs. Continued on Page 9 FISHERMAN'S CHOICE H ..v.,. i' ,.E .-tc:,,t:- ,rit FL -.232 . *T~.li. .1.1I.I * ~~ri~ r t first saptistt I" Specializing in Live Shrimp 'H-1t f- h'- Et i -,'F--. t r ,- H,-.ujr: .1.;.r, '. .: .: '.un.1, r I_.-1 r I r r ,-r r, rnr QUALITY WORK JOHN'S REASONABLE RATES CONSTRUCTION of Franklin County, Inc. SRemodeling & Custom Homes Roofing & Repairs Vinyl Siding SJohn Hewitt CONTA 850-697-2376 OWNER GEN. CONTRACTOR LIC. NO: RG0050763FR 106 St. James Avenue CARRABELLE ROOFINGOC6 Drawer Carrabelle 32322 NO: RC0051706 P.O. Drawer JJ Carrabelle 32322 1 - -- -- - qru- ChronicleIIYllill I I Ji ... Page 8- 9RFebhrllurv. FCO Adoption ADOPTION IS LOVE Your baby will lovingly bethecenter otourlives Expensespaid Helen & Kelin(800)990-7667 Andy Nichols Fla Bar .024704 Auctions LPL's LOG HOME AUCTION Saturday. February 24th 'Tampa. Florida 28 new log home packages to be offered I absolute to the highest bidder. May takedelivery withinone year Packages include logs. roofing rafters. windows. doors. trusses. ect Manufacturer OLD-TIMER LOG HOMIES Call (800)766-9474 AUCTION- Feb3. lOam Brooks Co. GA Two imgated farms & laio modek elt ma.inrined farm qupment. Rowell Realty & Auction Co. Inc. i800)323-8388. 'vw.rowellauctions corn G.-L 701. THREE-DAY GIGANTIC AUCTION! Farm and construcaton equipment' Five mils north of Dothan. Alabama on Highway 431 North Thursday Februar Ist. 10a.m CST: Dozers. Crawler Loaders. Excavators. lMotorgradcrs. Loader Backhos Rollers. Rubber Tire Loaders. Scrapers. Trenchers. Ditchwitches, Fork- lfts. Manlifts. .r Comprssors. inpas. Dump Truc. Com- mercial Vehicles. Specialty Trucks. Autos, Trucks. Trailers. Golf Carts and more FridayFebruary 2nd and Saturday, Febru- ary 3rd. 9a.m. CST: Farm Tracto Combines. Harvester Spray- ers. ATVs. Peanui. Cotton. Grain. Hay and Irrigation Equip- ment plus miscellaneous tools and much more! Download FREE color brochure at or call (888)702- 9770. Deanco Auction and Real Estate Co.. Inc.. Donnie W. Dean. AL Lic #907 GOVERNMENT SURPLUS auctions. Visit wm-w.govdealscom or call (800)613-0156. Unbelievable bar- gains and huge selection of conflicted properties, office and construction equipment, vehicles and unclaimed items. SIEZEDIREPO CARS S200+. Cars to be auctioned by IRS. DEA, FBI & Banks. Trucks, boats, computers & more. For listings call (800)240-1573 Dept. C-Ill Business Opportunities Share in profits locat ditressed properties. Free training and supplies. Call (800)695-3572. Hardboard siding settlement, you may be entitled to thousands Free infomatiao Homew e For Justice. ALL CASH CANDY ROUTE. Do you earn SS800 in a day' Your own local candy route 30 Machines and Candy all for 59.995 Call (800)998-.END AIN92000-033 THE HOTTEST NEW PRODUCT in America' We need distributors. S9.300 Investment required. 100% financing if qualified. Call (800)840-2499 AIN 2000-079 Financial OVER YOUR HEAD IN DEBT? Do You Need More Breathing Room?' Debt Consolidation. No Qualifing'!! *FREEConsultation (800)556-1548 w6ww.anewhorizon.org Licensed. Bonded. NonProfitNational Co. CONSOLIDATE BILLS. Low rates. No up front fees, Bad credit OK. Bankruptcies accepted. Same day approval. (866)227-8889 ATTENTION Home Owners/ Home Buyers. Mortgage loans for all? Commercial & Residential losw rates. Fast closings Good very bad credit. All approved. (388)831- 5521 24 hrs. v'I; "I ^TFr C' PD "C .J. .. ...*...t C. :r-,:,i ;. ; :,' .d 9282 x 14 A BAD DAY IS BEING IN DEBT! Loer your paymacmrs and interest immediately & confidentially. Call ACCC now at (88)BILL-FREE Non-Profit For Sale HAIR CLOGGED DRAINS. Buy 10 minute hair clog removerl Dissolves clogs fast. Safe for all pipes & septic system Guar- anteed. Available at The Home Depot Zep help line (888)805- 4357 or E THE MARKET STREET MPORfIUM For Sale FACTORY DIRECT POOL HEATERS: Heatpump. Solar. or Gas. lMajorbrands New and.or Used. Do it yourself or installed Free Phone Quotes. (800)333-WARM (9276) cor Lic. #CWC029795. POOL HEATERS. World's most efficient!! By Eco-Energy, Inc Heat pumpsisolar;free household hot water Cut electric 50%" Archie Gay Certified. EMC056963 24hrs. days (800)474-7120 CHURCH FURNITURE. Does your church need pews. pulpit t. baptistery, steeple, windows, carpet, lighting? Big sale on new cushioned pews/ upholstery for hard pews. (800)231, 8360 FREE SATELLTE Free install! DirectTVt Call for details! (800)677-2202. Some restrictions may apply! While Health & Mlisc. For Sale VIAGRA www vial000.com (877)835-9042 x3. FREEfed ex in the US 56 00 per 50 mg dose. ELECTRIC W1iEEL.CIIAIRS. New at no cost to you if eligible. Medicare Accepted Merits. Pride, Tuffcare. Best quality-fast delivery. Call Today (800)411.7406 Help Wantedl OPPORTUNITIES AVAILABLE-Earn while you train for an exciting career in health occupations, landscaping, diesel mechanics, clerical, electronicsand others No tuition GED High school diploma program available at some centers Ilousing. meals, medical care and pa check pro'.ided Help vwithjob placement atcompletion Ages 16-24 JobCorps- U.S Ddpartlment of Labor program Call (.00)733-JOBS OPPORTUNITIES AVAILABLE FOR FEMALES-Earn while you train for an exciting career in health occupations. clerical, culinary arts, child care attendant, hotel clerk and others No tuition GED High school diploma program available at some centers Housing, meals, medical care and paycheck provided Help sith job placement at completion Ages 16-24 Job Corps-U.S. Department of Labor program Call (800)733-JQBS. A DRIVING CAREER is waiting for you with Swift Transportation No experience necessary. Earn S500-S700 weekly as a-professional truck driver with excellent benefits. No CDL? Training is available. Call Today (800)435-5593. AVON. Looking for higher income' More flexible hours'" Independence? AVON has w hatyou're looking Cor. Let's talk (888)561-2866. No up-front fee ATTENTION BE YOUR OWN BOSS! Mail order business. Need help immediately. S522 plus per week PT SI.000-S4.000 per week FT. Full training Free booklet. vs (800)582-2757, COMMUNITY REPRESENTATIVE. Part time work, full timefun! Work with international exchange studentsand host families. Strong community spirit and warm hearts forteens. (888)552-9872 ATTN. COMPUTER. INTERNET PERSONS WORK online' S25 00 toSI 75 00,hour from your oSn PC! FULL Training! Vacations, Bonuses, Incentives' Mult-Linguals also needed! Free e-book. vww.cash4eser.net (863)993- 9S13 POSTAL JOBS S48.323.00 yr. Now hiring-No Experience- Paid Training-Great Benefits. Call for lists 7 days. (800)429- 3660 ext. J-800. DRIVERS: NORTH American Van Lines has openings in Logistics, Relocation, Blankelwrap and Flatbed heels. Mini- mum of 3 monthsoi'trexperience required. Tractorpurchase available. Call (800)348-2147. Dept. FLS. WEEMS MEMORIAL HOSPITAL POSITIONS AVAILABLE: R.N.'s Lab Supervisor Lab Techs R.T.'s E.M.S. Personnel Admissions Clerks For information, to obtain an application, to set up an interview contact: Mickey Majerus, Human Resources (850) 653-8853, ext. 107 Guaraneed BET Pric VIAGRX XenicalTM Propecia7M SRMS MA.RINEM I $RMS3SUPPLY, INC 811E4 ELECTRONICS ICOM RADIO ICOM RADIOS Children's & Adults Boots Anchor Retrieval Systems Rope Frozen Bait Triple Fish Line Deep Sea & Flat Rods 4/0 & 6/0 Penn Reels * Daiwa 350H & 450H Reels Help Wanted MUSIC FOR YOUNG CHILDREN(TM)- wants people who: love teaching young children, have good piano skills. Innovative teaching techniques. Maximum opportunity. Seminar information available (800)631.1948. x 9159 DRIVER-COVENANT TRANSPORT 'Coast to coast runs "Teams start up to .46c *S1,000 sign-on bonus for esp co drivers. For experienced drivers (800)441-4394. For owner operators(877)848-6615. Graduate students (800)338-6428 DRIVER- IT PAYS to start with us Call SRT today (877)244-7293 or (877)BIG-PAYDAY *Great Pay *Paid Weekly *Excellent Benefits 'SI.250sign-onbonus 'Student graduates welcome. Southern Refrigerated transport DRIVERS- Home Every Weekend! Family owned Ileet leased to Landstar Ligon needs OTR Ilathed dris ers Con en- tional Equipment. Regional & OTR. Benefits! Call Today (800)362-7690 A 535.000 PER YEAR CAREER' C.R England needs driver trainees'! I15 day CDL training"' Housing' Meals included!! NoUiplrontSSS!!Tracrtrirtraieraining-(83)731- 8556. HOME WEEKENDS TIT Driers for S E. 1F., 01R M. n age 23. Class A CDL required. E.p drivers or school grads CYPRESS TRUCK LINES (877)467-5663 (800)545-1351 CAREER OPPORTUNITY' Earn Excellenl income pro- cessing medical claims for local doctors, Full training pro- sided Computer required P'lsicianm& He. lth Care I)tel- opincen (800)772-5933 c\ .2062 S1500 WEEKLY' Be your own boss Processing Visa Miastercard invitations! S2 Per invitation' No experience needed! Materials supplied' Frlday Paychecks' (800)230- 6609 EASY WOtK!Great pay' EarnS500 plus a week assembling products No experience necessary Call toll free (800)267. 3944 ext 104 AIR FORCE. GREAT arer opportmniti available for high school gd. ages 17-27. Plus up to S17.000 enlidiunnt bonus if you qualify! To request additional inionration call(800)423. USAF or visit EXTRAORDINARY INCOME OPPORTUNITY! Muti-til. lion dollar prefab housing manufacturer since 1979 seeks local are representative. Applicant hosen for this prestigious po- sition must sart inmmediatcly. Details (888)235-0769. 343 DRIVERS NEEDED!!! No experience needed! 14 day CDL program available with no cost training Earnm.30.000+ st year. CDL Drivers (888)253-8901 Experienced drivers w/ Clas A call (800)958-2353 Legal Services SERIOUSLY INJURED? Need a lawyer? Personal injury. auto accidents. rape. assault. HMO negligence, medical mal- practice. work injuries, wrongful death, nursing home. AAA Anorny Referral Service (800)733-5342 24hn DIVORCE 5175.00 *COVERS children, proper division. name change, militar. missing spouse. etc Only one signature required 'Excludes govi. fees. uncontested Paperwork done for you (800)522-6000 B. Divorced Real Estate NORTH CAROLINA Whre Blue Ridge meets the Smoki.e Homes. cabins, acreage, lots. ms. creclakefromt. Carolina Mountain Homes RE 5530 West US 64 Murphy, NC 28906 (800)747-7322 ext 40 cmheamcon GRAND OPENING SALE! Lake lot -S24900. Free boat slip! Beautifully wooded lake view acreage with accss to spenau- lar 35,000 acre recreaional lake in Tenessee. Near 18 bole golf course. Paved roads. muiliies, more, Excllent financing. Call now (800)704-3154 ea 75 FORECLOSED GOV'T HOMES' 50 or Low down' Tax repos and bankruptcies HUD. VA. FHA Low or no down' O.K. Credit For listmgs. (800)501-1777 ext 1699 TENNESSEE LAKE BARGAIN 3 Acres with boat slip S24,900. Beautifully wooded, spectacular iews, deeded access to 35,000 acre recreational min lake -next to 18 hole golf course' Pated roads, utlities, soil tested Low. low financing Call now (300)704-3154. ext 94 So Colorado Ranch 35 AC -5S9.900 Driveway In'! This outstanding property is located just I hr Colo Springs Enjo) 360 mmn views & lots of trees. Deer, elk. & turkey abound Near 1000's of acres of rec land & world class rafting & fly fishing County rd .' tel & lec. Great financing Call nos toll-free(877)676-6367 S42.000 With Deeded Boat Slip, Waterfront community on South Carolina Lake with clubhouse, marina, pool. tennis Great Financing Harbour Watch (800)805-9997 lakernurrahyliing.com FORECLOSED HOMES- MUST SELL. Save 20-50%' o morn! Minimum or no down payment! For listings in your area call (800)337-9730 Dept. H-222 Steel Buildings BUILDING SALE...AIt seel. peaked roof. straight ides 20 x 24 S2.800.00. 25 x 30 53,866.00. 30 x 40 $5,362.00. 35 x 50 S7,568.00. 40 x 60 38.648.00. Other styles. Pion-er (800)668- 5422. pioneerstil.com. Since 1980. STEEL BUILDINGS MUST SELL Immediately. Contractor's packages 2430\9=5S3799. 30\40x10=S4895, 30x60xI0=S5990. 50xI00 12=SI2,940 United Struc- ltures (800)332-6430. ext. 100 w w.usmb.com TanningBeds/.lisc for Sale WOLFF TANNING BEDS Tan at home! Buy DIRECT and SAVE' Commcrcial ome Units from S199.00 Low Monthly Pamnents FREE Color Catalog Call TODAY' (800)842-1310 ~saw ip elstan com Wanted to Buy WE I'AY S 100 Cash for old DISS UiracTV s.ieltllereceie rs Call Greg toll-frce (8SS)663-2466 or visit our vebsitc vs; dsspav n coin Ifor more information. Notices AFFORDABLE TERM LIFE INSURANCE S100,000. Male 40-S10.l5/mo. Male 50-S17.00/mo. Male 60-S33.73'mo. Su- per-preferred non-tobacco. 10 year level term guaranteed l0yrs. Policy Tbrm =92-TRl,00 E-I. Jeff Beck FL Uc. OA017248 (800)381-0997 wa.thebeekagency.com Flex term issued by Ohio National Lifa Assurance Corp. PAYING TOO MUCH for your term life insurance? To see if you are. visit our website at hslinsurance corn ;call HSL Insurance at (88S)440-4915 for lowest rates nationstde Spelling Bee Winners From Donna Barber, Coordinator Carrabelle Elementary Winner: Cody DiOrio Alternate: Erica McKnight Carrabelle Middle School Winner: Chris Totten Alternate: Daren Hoffman All four will participate in the County Spelling Bee on February 15th at 1:00 p.m. at the County Office. At left, Carolyn Hatcher, York, received an award from Secretary-Treasurer of Carrabelle School for Panhandle Poets and Writers "increasing children's and published poet Jean awareness of the arts" Paige of Carrabelle/New presented by Marian Morris. NO S T E T M TOSUCIETTH FRNLI ONT HONCE Advertisement Hate Diets? Try Vinega to Lose Pou'ds, Inches .. No v. oi der Ms. Galend is smiling. She found an easy way to l.s-,e pounds without pills, diets or calorie counting. < Her secrel' The healthy vinegar plan. "I dropped 30 S-l pol.; so fst it scared me, she writes. Just a few table- i poo'ns of rieg,/ dJil', '..;li ha. e you feeling and looking 4 -bellr a3 r.i:ui melt sa i uiheAilthy pounds. For FREE mnlimnti.onr packet without obligation, write to: The ar. I' eg.v Pln, Dept. FD5097, 718 12th St. N.W., Box =. .-* 5I iJ. Canlon, Ohio 44701. To help us cover printing Snd p-sloige. $1 would be appreciated, but not necessary. /... Jeanne lend hp i ., t 0)2001 TCO FD0213S12 ^h'BSI o L iue;-T inir? The Emergency Beacon Bulb Instantly becomes a flashing signal for help simply by flicking your light switch twice $9.95 Pinpoints your location Fits any standard socket include S Reduces emergency response time Major Cr S Recommended by the national crime Acce prevention council, police and emergency services nationwide each es S&H edit cards spted I alTllFre-80 STEVEa -EUE Liene &Isue THE~ WOODSHE TRES FREOO). Shed Spedcializing kin Naudtial Antiques A unvtqe bl end of antlqules, nautical Items, Jfuri.tre, co Lecti Les, art, books and mVantL more distinctive accent pieces. Photos cLrca 1900, of area li.gktlkoises at St. M arks, St. George Island, Dog Island, Cape San Bias. PostcarRs, circa 1900, ofold Apalachicola. ExtrevmebLy u.nque nautical items, archRtect~ral stars, turtle lamps and match more! A tnques es v r Collectibles Loolkfor the Lbg tin shedon 170 Water Street along the historic Apalachicola River. 170 Water Street P.O. Box 9 Apalacktcola, FL 32329 (850) 653-3635 Linda & Harry Arnol., Owners HAVE GRINDER WILL TRAVEL: Stump and root grind- ing, reduced to chips. No job too small or large. Call Clarence DeWade in Lanark Village at 697- 2562. FREE ESTIMATES. 9. 2001. The next issue will be February 23. 2001. Thus, ad copy, your check and your telephone number must be received by Tuesday, February 20, 2001. Please indicate the category in which you want your ad listed. Thanks. I :1-800930877 3026 CoastalHighway awfoieFlorida32327 1U6~ V / LV-Ul L -CiK. COOKOFFI AUCTION Th, Frarnklin Chronicle A LOCALLY OWNED NEWSPAPER 9 February 2001 Pape 9 Children of the Street from Page 7 The Reading and Feeding Program A group of students from a nearby Catholic school had already begun a tutoring program at Streets Ahead. They were mostly working with the shelter's more advanced children on secondary school level les- sons. I did not want to duplicate their efforts. I also felt that the shelter's more basic learners would benefit from a program with les- sons appropriate to their abilities. I decided to focus on basic reading, writing and mathematics. Special lessons to develop life skills would also be taught. And, to ensure that both their minds and bodies would he nourished, food would be in- cluded. This was to be the foundation of The Reading and Feeding Program. For the first two sessions, I briefly interviewed each child in atten- dance to determine their education level and educational interests. I brought along some old math workbooks and primary school readers from Lovemore Home's library to help me through these sessions. As I became more familiar with my students, I. tried to make the les- sons more personal. I began writing fictional short stories about young Zimbabweans involved in real life situations. This seemed to generate more interest in the reading and comprehension exercises, and some even asked me to write about their lives. After my first month at Streets Ahead, I felt that the program had generally been successful. Between 10-15 children visited my class weekly. However, a lingering problem remained; some of the children understood very little English, and were not grasping the entire les- sons. I know a fair amount of Shona vocabulary but am far from fluent in the language. Help arrived in the person of David.Jimmy Bricks, a youth leader affiliated with Streets Ahead. We were able to collaborate on each session. While I plan all of the lessons, Mr. Bricks agreed to help conduct some of the lessons in both English and Shona. His pres- ence in the classroom has made a big difference. Providing Food To get the feeding program started at the shelter, I've had to use my own funds. This has not been too expensive ... approximately $300 weekly in Zimbabwe currency (U.S. $6) to purchase such food items as fruit, bread, margarine, tea and sugar. I've 'begun writing to US corporations based in the country such as Coca-Cola and Colgate, to see if they may be willing to contribute to the feeding program. I've also requested that a food drop box be placed in the Peace Corps office. Bringing food to the shelter has its positive and negative aspects. On the positive side, providing food makes it easier for children to attend lessons; they might otherwise be reluctant to leave the streets be- cause working/begging often yields food money. Providing food has also been a great way of recruiting potential stu- dents. I usually walk a considerable distance down Samora Machel Avenue with the food. When I arrive at places, where the kids congre- gate, usually one or two of them offer to carry the food to the shelter. - nd 'they often stay for lessons when they reach Streets Ahead. For sale at the Cookoff (or before) one fire station, 2-story, less fire engines. Call 927-2753. N year, an ,'w'' SCOLA. ~ --a-. --.-"- New this year, an afghan wall hanging comprised of Cookoff scenes-to be available for sale at the Cookoff. New this year, a Cookoff Chili cookbook. Some recipes from professional cookers, many more from Chili Cooker fans! For sale at the Cookoff. On the negative side, there's always the lingering thought that I'm bribing the children with food to learn. And learning, of course, should he its own reward. Also, there are some children who attend sessions just for tile food. Some sleep during lessons and expect food during break and lunch time. I find it hard to refuse any of these children food when it's available. Those who participate during lessons are not happy that less interested parties receive food. This sometimes cre- ates morale problems but it is hopefully something that can he rem- edied as the program matures. Departing Thoughts Working with street children requires a tremendous amount of laith in the human potential. The emotional and financial challenges that these young individuals must confront are monumental. And still. they return daily to the city's shelters with the hope of improving their lives. Some come to these shelters looking only for the basic necessities they provide. For their own reasons these children are not ready to leave the streets. Others participate faithfully in the educational ac- tivities that are offered. They want a different life, but they don't know how to obtain it. I understand that many of these children of the street have limited futures. Many will lose their lives to the streets. I can have only a limited impact on their lives. I can only tend to the symptoms of this social disease that plagues them. It will take more than one person to get to the root of this illness. If I have helped to validate the existence of some of these individuals ... if I have caused hope to surface even briefly ... if I have helped them to imagine a world better than street life, then I have not wasted my time. "It is better to light one candle than to curse the darkness." -Special thanks to David Jimmy Bricksfor providing large amounts of information about street life to make this article possible. Brian Goercke may be contacted through this address: Post Office Box A773; Avondale, Harare; Zimbabwe, Africa or e-mail: brian_goercke@yahoo.com. Attendance At Panhandle Poets And Writers -Meeting Sets Record By Tom Campbell In their first meeting of the new year 2001, the Panhandle Poets and Writers Group set a record for attendance. There were eigh- teen writers at the meeting held in the Episcopal Church in Car- rabelle, one from Canada, one from the Philippines, two from New York, two from Michigan, one from Illinois, one from Ohio, and others from St. George Island, Apalachicola, Carrabelle and La- nark Village. Jean Paige, a published author from New York, read some works from her book, "Whispers From a Silver Bracelet." Dawn Evans Radford, a poet from Apalachicola, read her piece called "White Sock,",which.iwas , inspired by the recent tragedy in- volving the drowning of the 'Franklin County oystermen. The writers group was impressed by the moving quality of the work and Ms. Radford was requested to allow her poem to be printed in The Franklin Chronicle, to which she agreed. The poem can be found elsewhere in this edition. An Award was presented from the Carrabelle School by Marian Mor- ris to Carolyn Hatcher, Secre- tary-Treasurer of Panhandle Po- ets and Writers. The award read: tmillargtCm ,-1F % TAHIC'PE Famrra 40 AS -r (C ) Ar d')"' 2 St Ari~d RotIsHLstuor FQo. Yror~r r'oral Rr'rrlrr,r STATEBANK*1 897 Service. Commilmeni And The Reol Is Hiorory ~ a9Cta "With appreciation from the Car- rabelle School to the,Panhandle Poets and Writers Association for increasing our children's appre- ciation of the arts, 1999-2000." Ms. Hatcher had joined Jean Paige in reading selections from their works before some of the children in the Carrabelle School. The children were "spellbound" by the writers as they read their works, according to Marian Mor- ris. The Panhandle Poets and Writers Association will meet regularly the last Wednesday of the month through February, March and April. Anyone interested in writ- ing, or just listening to writers read their works, may attend the meetings, which begin at 7 p.m. at the Episcopal Church in Carrabelle. 19th ANNUAL "'" ":" 19 h A NA IStucco, Stune. & Simulated BrIck CHARITY CHILI COOKOFF t AND AUCTION GULF COAST REGIONAL -.- Barbara Yonclas ST. GEORGE ISLAND, FLORIDA Interior design SNick Yonclas 2001 CORPORATE SPONSORS 49,Attorneyat Law Miss Chili Pepper DON KIRKSEY AUTOMOTIVE Kay Ford, Inc. 800-876-2890 su 'S nshine yjPainting A Complete Painling Sei ice Chet & Mark (850) 653-3261 M C'.-IM T, IL111 IrPeINTED SPOeTSWEA* SCREENPRINTING EMBROIDERY | 912-872-320 CITIZENS FEDERAL SAVINGS BAK ILI COOKOFFAUCTION OF PORT ST JOE CH Member International Chili Society c .O,,ccsn ( .. [. SATURDAY, MARCH 3rd, 2001 10:00 A.M. UNTIL Auction Starts at 11 a.m. M AHR SUNCOAST REALTY .UIRi ,Red Pepper 5K HRun DEVELOPMENT CORPORATION MA Re Red Pepper 5K Run oFooat 8:00 -M Starts at 8:00 a.m. Executive Office Furniture LAZ BOY GALLERY First American For Auction Donations or for further information, contact any local business GOLD KEY TERMINIX CONSTRUCTION TRM'T PEST HOFFMA CONTROL S DESIGN, INC. THENATIONWIDEPEST (850) 567-2791 CONTROL EXPERTS" M,,,t.,l.d ,.,. 850-927-2949 AS-27.1424 Title Insurance Florida Non Profl ( '' Florida Coatal Cardiology Corporation FL N-20424 f' t-.M.. Shezad Sana ullah, MD, FACC Company FID#59-2915451 1,4.,.,, yi (850) 653-8600 Org. Ex. Under 501 (C) (3) , Gulf State , 'tt "' MEMORIAL HOSPITAL BANK AT V I FL'or W y... y 850/878-2000 Apalachicola, FL We have your best Interest in nd 850878-2000 SCONSTRUCTIONTHE ORMSAN OF ST. ,0G14 ISLAND BUILDING-- .... S & C stoOffice (800) 367-1680 Y.ae"el, c.a: .. h-hm.rn (850) 927-2596 oDs.5,0i -k,.8e^lm .- .27-Z ;as-e,2-Aa a ,nu 1 ,, 1 (850) 570-1864 TI-P=-- St. Georgelsland.FL P Prudential Bso fl Realty of St. George Island 100.5 FM ) Your local source for: News Wealher S Music Paint Mall .4 Eastpoint. FL G.J. Grace Fine Building Products Begonia St., Easlpolnt 850-942-4441 Obituaries Jack Terry Ward Jack Terry Ward. 84. died on Thurs- day. January 25. 2001 at Joan Clancy Memorial Hospital in Duluth. GA. A native of Malvern. AL. Jack had been a longtime resident of Apalachicola before recently moving to Georgia. He was a retired U.S.A.F. Colonel and was retired from the U.S. Army Property Disposal Agency. He attended Trinity Episcopal Church in Apalachicola. He is survived by his great-nieces: Terry Luke & husband. Steve and Nancy Stallings: his great-nephews Michael Stallings & wife. Susan. Ward Stallings & wife. Donna. Bill Stallings & wife. Leah, and Russ Stallings & wife. Cathy: his great nieces and neph- ews: Claire Parker. Mark Stallings. Emily Boimare. Arianne & Sam Stallings. Sara. Jessica & Parker Stallings. and Cameron. Caroline & Lansdell Stallings: and many dear friends in Apalachicola. Funeral ser- vices were held on Tuesday. January 30. 2001 at Trinity Episcopal Church in Apalachicola. Interment followed in the Malvern Cemetery in Malvern. AL. All arrangements were under the di- rection of Kelley Funeral Home. Apalachicola. FL. Jaime Arin Stefanko Jaime ArinStefanko. 21. of Apalachi- cola. died on Saturday. January 27. 2001 due to injuries sustained In an automobile accident. Born in Talla- hassee. Jaime had lived in Apalachi- cola for 15 years. She was a server at Tamara's Cafe Floridita and a sales associate at Chez Funk. both in Apalachicola and she was Catholic by faith. Jaime was loved by everyone. She is survived by her mother. Mary Lou & husband Michael Athorn of Apalachicola: her father. Jim & wife Sharon Stefanko. Jr. of Eastpoint: her grandparents: Jim & Vern Stefanko of Eastpoint and Clifford & Sheila Athorn of Binghampton. NY: two step-brothers: Richard Brown and J.R. Serrato, both of Eastpoint. Memorialization by cremation. A me- morial service was held on January 30. 2001 at Lafayette Park in Apalachicola. Those desiring may make a contribution' to a charity of your choice in memory of Jaime. Kelley Funeral Home. Apalachicola. FL, in charge of arrangements. Bruce Emmerson Keith, Jr. Bruce Emmerson Keith, Jr.. 44. of Carrabelle. died on December 28. 2000 while working on the Apalachi- cola Bay. A native and life-long resi- dent of Carrabelle, Bruce was an oysterman and attended Living Wa- ters Assembly of God Church in Apalachicola. He is survived by his daughter. Heather Keith of Kinard: his parents. Bruce & Anna Keith of Car- rabelle: two brothers: Alga Keith and. David Keith. both of Carrabelle: three sisters: Vicky Keith & Helen Keith Haulotte, both of Carrabelle and Ruthann Stine of Sharps Chapel. TN: his grandmother. Mrs. Louise Keith of Wewahitchka: and one granddaugh- ter. Thelma Haven Keith. Funeral ser- vices were held on January 29. 2001 at the First Assembly of God Church in Carrabelle. Interment followed in the Evergreen Cemetery in Carrabelle. All arrangements were under the di- rection ofKelley-Riley Funeral Home. Carrabelle. FL. Louis Edward Blaske, Jr. Louis Edward Blaske. Jr.. 18. of Car- rabelle. died on Wednesday. January S24. 2001 in Carrabelle. Born in Talla- hassee. Louis had lived his life in Car- rabelle. He was a landscaper and had attended Carrabelle High School where he played football and baseball for the "Carrabelle Panthers". He was Baptist by faith. He is survived by his mother. Belinda Blaske of Monticello: his father. Louie E. Blaske of Carra- belle; his brother. James Robert Blaske of Monticello: his maternal grandmother. Velma O'Neal of Carra- belle: his maternal great-grand- mother. Dora Parramore of Mt. Pleas- ant. FL: his paternal grandparents. Jerry & Rita Blaske of Carrabelle: and his paternal great-grandmother. Beulah Carroll of Carrabelle. Funeral Services were held on Saturday. Janu- ary 27. 2001 at the Carrabelle United Methodist Church in Carrabelle. In- terment followed in the Evergreen Cemetery in Carrabelle. All arrange- ments were under the direction of SKelley-Riley Funeral Home. Carra- belle. FL. Birdwatchers Needed For Research Project If you have a bird feeder, the Florida Fish and Wildlife Conser- vation Commission (FWC) is en- couraging you to sign up for Project FeederWatch. The Cornell Lab of Ornithology and National Audubon Society conduct Project FeederWatch No- ivember through early April each year to gather information about winter bird populations across SNorth America. Of the 15,000 par- ticipants, only 300 live in Florida. For a $15 participant's fee, birdwatchers receive instructions, :submission forms, a bird identi- fication poster, a wall calendar and a one-year subscription to the Birdscope newsletter. For more information, interested persons can contact the Cornell Lab at 159 Sapsucker Woods Rd., Ithaca, N.Y. 14850 or call (800) 843-BIRD. The lab's Web site is at. The Cookoff supports the VOLUNTEER St. George Island Fire Department and First Responders. 3, 2001 8:00 AM Red Pepper 5K Run 8:30 AM Booth Set-up (Booth construction & area setup will be allowed from 12 noon Friday 10 AM Saturday) 9:30. alift Iill %-,AAA .1 Nero' BottY-air A LOCALLY OWNED NEWSPAPER FWC from Page 1 Earlier, the Commission voted to re-establish the Amelia Island Critical Wildlife Area to include three additional miles of shoreline that may be posted if used by, nesting or wintering shorebirds or seabirds. Corridors for pedestrian and vehicle traffic will be main- tained as long as beach driving remains legal. Commissioners also established Hardee Lakes Park in Hardee County as a Fish Management Area (FMA). However, the area will be closed to public access while the agency works out an appro- priate set of regulations and al- lows the fish population to im- prove. In addition, the FWC es- tablished public access, ft har- vesting and boating regulations for the Lake Piney Z FMA in Leon County. The fisheries staff delivered re- ports concerning freshwater and saltwater hatcheries and stock enhancement programs and ex- otic freshwater fish programs. We'd like your opinions about a new product to remove uncomfortable corns. We'll send you a free product to use for several days. Then we'll call and ask your opinions in a 5 minute interview. Participants will receive a choice of gifts. Call toll-free 1-800-220-7878. Ask for Mrs. Carson. Bruno & Ridgway Research Assoc. 3131 Princeton Pike, Lawrenceville, NJ Cook Insurance Agency, Inc. AUTO HOME COMMERCIAL + LIFE + Specializing in Coastal Properties from Alligator Point to Mexico Beach 23 Avenue D, Apalachicola, FI 32329 850-653-9310 800-822-7530 "fl 8 8t Estabiished1913 AUni-. ( (Goastal Sntenail IY medicinee i/ I| 74 Sixteenth Stre I Telephone: (850) ,I Helen Nitsios, MD Diplomate American Board of Internal Medicine et Apalachicola, Florida 32320 653-8600 Fax: (850) 653-4135 1-800-767-4462 ) Renewal- Basic Subscription, 26 issues. 1 Out of County 0 In County Date: 'If renewal, please include mailing label Please send this form to: Franklin Chronicle Post Office Box 590 Eastpoint, Florida 32328 850-927-2186 or 850-385-4003 The Commission also recognized retired biological administrator James L. Schortemeyer and re- tired maintenance mechanic Larry Janek for their 30 years of service and retired chemist Homer E. Royals for his 28 years. In ad- dition, the American Fisheries Society (AFS) recognized the Florida Marine Research Institute's Florida Boater's Guide as the.AFS Outstanding Project of the Year in the aquatic educa- tion category. The next Commission meeting is tentatively scheduled for March 29-30 in Tallahassee. Carrabelle City from Page 1 ficial reef. It was from Coastal Reef Builders from Pensacola and was for $23, 100,just under the Grant amount of $25,000. It was recom- mended the Board approve, which they did as the motion carried. Dave Hemphill, Landscape Archi- tect with Baskerville-Donovan, reported on the remaining work to be done on the city's Riverwalk. Completion of the Riverwalk Park. Plans were approved. It was pointed out that the "retaining wall on the river" would be the largest portion of the remaining work. Payment of Invoice #64352 was tabled until the March meeting. Approval to pay Invoice #64786 - $2,267, Regulatory Coordination, motion carried. a Engineer Grady Lee Marchman, Chief, Bureau of Surface Water, Northwest Florida Water Manage- ment District, reported on Storm Water in Franklin County and said that Carrabelle has a "good record. Carrabelle has good con- trol generally of storm water." He said it was "no threat to Apalachicola Bay, in 1996 and 1997." But he did point out that Carrabelle needs a Storm Water Plan for the future. Mr. W. J. Oaks addressed the Commissioners concerning the Water Users Agreement and asked for credit to his daughter on a bill that had been paid. The commis- sioners agreed that the wording of the agreement was confusing and moved to give Mr. Oaks' daughter the requested credit. The motion carried. Approval was moved for increase of the city's liability insurance from $300,000 to $1 million. Mo- tion carried. Consideration was given to the annexation of the city's new wa- ter plant into the city's corporate limits. It was pointed out this would include "just the road and the plant," but not Freda White's property, 54 acres. The motion carried. Under "New Business," there were 12 items, and some of them were: Approval was given to the Ameri- can Red Cross for Hazardous Weather Awareness Week, the third week of February, 2001. Also, support of Disaster Resis- tant Neighborhoods. Sheila Cozier is Coordinator of the program, which deals with flash flooding, hurricanes, forest fires and tor- nadoes. A Proclamation was read by City Clerk Rebecca L. Jackson, approving the American Red Cross for Hazardous Weather Awareness Week, the third week of February. Approval was given for Mr. Joe Ham volunteering eight (8) hours a month to the Carrabelle Police Department, to keep up stan- dards, "contingent on the insur- ance coverage" being all right for this volunteer service. The motion carried. Approval was recommended by the mayor to hire Carl Renfro as a full-time police officer. The mayor pointed out that FDLE grants will be granted in 30 days, and Mr. Renfro will be hired back at the budgeted salary. The mo- tion carried. Approval was given for installa- tion of restroom in the Carrabelle Police Department at an esti- mated cost of $700, to come from the Capital Funds Project. Motion carried. Freda White of Bayside Realty came before the commissioners, representing the Citizens Federal of Port St. Joe. She requested pro- cedures to close the alley between 8th Street and 9th Street, which would affect the property next to IGA in Carrabelle. Motion carried. The meeting was adjourned at 8:40 p.m. the Chronicle Bookshop Mail Order Service * 2309 Old Bainbridge Road Tallahassee, FL 32303 Pauep n 9 Februarv 2001 . have kept gossip colum- nists buzzing for years. Like his movies, the book deliv- ers one-helluva good time. Sold nationally for $22.95. Bookshop price = $15.95. . .FLORIDA LIGHTHOUSES Kev 7----------------- Order Form I Mail Order Dept., Chronicle B( (273) The Vitamin E Fac- tor by Dr. Andreas Papas, Ph.D. "I can only most heartily recommend finding the time to read it ... Prac- ticing physicians who have to deal with nutritional problems related to dis- eases such as diabetes and athrosclerosis should find this book particularly use- ful as a quick reference source..." signed Marvin L. Bierenbaum, M. D. Direc- tor, Kenneth L. Jordan Heart Foundation and Re- search Center. A Harper Perennial, Division of Harper Collins, Publisher, 395 pp, 1999, Paperback. Including the latest re- search findings of the 8-family vitamin discovery of the last century, the "Mi- raculous Antioxidant for the Prevention and Treat- ment of Heart Disease, Can- cer and Aging." This is the book you can give to your doctor. Why is Natural Vi- tamin E better? Did you know the difference? The book says, in part "There is no argument that the natu- ral d-alpha-tocopherol, gram for gram is more po- tent than the synthetic dl-alpha-tocopherol.." This book could save your life" Sold nationally for $12.95. Bookshop price = $10.95. bookshop I (Please Print) Your Name Address Town State ZIP ITelephone ( ) Book Number Brief Title Cost Total book cost Shipping & handling 1 book....... $2.50 Sales tax (6% in Fla.) + 2-3 books .... $3.50 4-5 books.... S400 Shippin and S6-10books... S5.00 handling + Bookshop List of 9 February 2001 Total ------------------------_- The Franklin Chronicle -, e : it "L ; .. :n .,, I .-, '!, ,, .r, the-^:'. qi afi-''i~L-i iub~ -v ---------J COOKOFF AUCTION ITEMS NEEDED 850-927-2753 i* I Contact Us | Permissions | Preferences | Technical Aspects | Statistics | Internal | Privacy Policy © 2004 - 2010 University of Florida George A. Smathers Libraries.All rights reserved. Acceptable Use, Copyright, and Disclaimer Statement Last updated October 10, 2010 - - mvs
|
http://ufdc.ufl.edu/UF00089928/00153
|
CC-MAIN-2015-11
|
refinedweb
| 21,408
| 65.22
|
On Mar 20, 2012, at 5:26 AM, Richard Sandiford wrote: > So what I was trying to say was that if we remove the assert > altogether, and allow CONST_DOUBLEs to be wider than 2 HWIs, > we need to define what the "implicit" high-order HWIs of a > CONST_DOUBLE are, just like we already do for CONST_INT.
Advertising
The problem with your position is you are wrong. Let me give you an concrete example: typedef __attribute__((mode(OI))) signed int256_t; int256_t foo() { return (int256_t)0x7000000000000000 << 10; } This fails your assert you want to move down. This is _wrong_, wrong, wrong wrong. This is getting tiring. This is perfectly well defined, with no change in any definition. Would you like to try again? > If we remove the assert altogether, it very much matters what is done by that > last "*vp" line. > If Mike or anyone is up to doing that, then great. I categorically object to moving it down, it is wrong, for all the same reasons the original is wrong. > But if instead it's just a case of handling zero correctly, moving rather than > removing the assert seems safer. Sure, that fixes 1 testcase, and is monotonically better. The problem, it fixes less than 1% of the values for which we assert currently which are wrong. What is the point of bug pushing? Bug pushing is wrong. > I'm obviously not explaining this well :-) No, you are explaining your position well, it is just that your position is wrong. Your position is you want to bug push, that position is wrong. You can't win with me by having that position. The only solution is to change your position. You've done it once now, and you are moving in the right direction. You are now willing to remove the assert for 0, which you didn't want to do before. Your next stop, will be to remove the assert for (int256_t)0x7000000000000000 << 10. I will keep pushing until you relent on that point. Once you do, your position will have changed twice, mine, unchanged. I will not relent after that step, merely, I will select the next value and make you agree to it, then the next, and the next and the next, until I succeed in moving you to my original position. Now, you might be thinking that this check will protect wrong code generation in the rest of the compiler, and that may be somewhat true. A counter point would be: (int256_t)1 << 254 which would have been my next interesting value to get you to agree with me on, but, the assert you point at, doesn't prevent great badness from happening with this case. Other parts of the compiler just suck, because people didn't care enough. This I can change, but will take time. In my first patch, it will not be complete nor perfect. If you want to reject all the patches until every single last test case works, well, that isn't usually what we do. We usually approve each one as long as it is monotonically better, that's the standard by which to judge patches. Is your position, the rest of the compiler isn't perfect, so, no progress can be made in fixing it until the rest of it is perfect? If so, this is a very bad position to take. I have time now to fix and submit work to make things better. After I have things working perfectly, I may have 0 time with which to do this. I'll give you a concrete example which exactly parallels this work. There was a time when gcc didn't work on 64-bit targets. I did the first 64-bit port. It was done as a series of patches, one at a time, that pushed the compiler kicking and screaming in the right direction. That work is the basis for all the 64-bit ports today; they are now less rare than they were when I first started. gcc is reasonably good at supporting 64-bit ports. What is different today, absolutely nothing, just N. Instead of 64, it is 256, life goes on. All I can say, if you have this mistaken notion that work to make OI work should be blocked because OI doesn't work, is you are wrong. So, my question is, do you have this position?
|
https://www.mail-archive.com/gcc-patches@gcc.gnu.org/msg28559.html
|
CC-MAIN-2017-22
|
refinedweb
| 733
| 81.22
|
Gallery: Histograms
Examples
- Displaying (x,y) data points as a histogram
- Displaying (xlow,xhigh,y) data points as a histogram
- A histogram which shows the bin edges
- A histogram showing the full range of options
- Filling a histogram with a pattern
- Comparing two histograms
1) Displaying (x,y) data points as a histogram
Histograms are used to plot binned one-dimensional data - of the form (xmid, y) or (xlow, xhigh, y) - with optional error bars on the Y values. A later example shows how to display error bars on the points.
add_histogram("spectrum.fits[fit][cols x,y]")
In this example the data is stored as a set of (x, y) points, where the x values give the center of each bin. Unlike curves, histograms default to only being drawn by a solid line; the symbol.style attribute is set to none.
The preferences for curves can be found by using the get_preference call:
chips>
The settings for the current histogram can be found by using the get_histogram routine:
chips>
2) Displaying (xlow,xhigh,y) data points as a histogram
In the first example, the binned data was given using the mid-point of each bin. In this example we show how histograms can be plotted by giving the low and high edges of each bin.
tbl = read_file("spectrum.fits[fit]") xlo = copy_colvals(tbl,"xlo") xhi = copy_colvals(tbl,"xhi") y = copy_colvals(tbl,"y") add_histogram(xlo,xhi,y,["line.color","red"]) log_scale(X_AXIS)
The bin edges can not be specified by passing in a file name to add_histogram, so we have to read in the arrays using crates routines and then plot them. We use the read_file to read in the file, copy_colvals to get the column values, and then add_histogram to plot them.
3) A histogram which shows the bin edges
When using xmid values, the bins are assumed to be contiguous. This is not the case when the bin edges - namely xlow and xhigh - are given. Here we plot data from a histogram with non-contiguous bins, setting the dropline attribute so that all the bin edges are drawn (this attribute can also be used with histograms like that used in the first example).
tbl = read_file("histogram.fits") xlo = copy_colvals(tbl,"xlo") xhi = copy_colvals(tbl,"xhi") y = copy_colvals(tbl,"y") add_histogram(xlo,xhi,y,["line.style","longdash","dropline",True])
4) A histogram showing the full range of options
In this example we change most of the attributes of a histogram. The Filling a histogram with a pattern example shows how you can change the fill style of a histogram from solid to a pattern.
tbl = read_file("histogram.fits") xlo = copy_colvals(tbl,"xlo") xhi = copy_colvals(tbl,"xhi") y = copy_colvals(tbl,"y") dylo = copy_colvals(tbl,"dylo") dyhi = copy_colvals(tbl,"dyhi") hist = ChipsHistogram() hist.dropline = True hist.line.color = "red" hist.symbol.style = "diamond" hist.symbol.size = 4 hist.symbol.fill = True hist.symbol.color = "orange" hist.err.color = "green" hist.fill.style = "solid" hist.fill.opacity = 0.2 hist.fill.color = "blue" add_histogram(xlo,xhi,y,dylo,dyhi,hist) # Move the histogram behind the axes so that the tick marks are not hidden shuffle_back(chips_histogram).
5) Filling a histogram with a pattern
In this example we fill the histogram using a pattern, rather than a solid fill as used in the A histogram showing the full range of options example.
add_histogram("spectrum.fits[fit][cols x,y]") set_histogram(["fill.style","crisscross"]) set_histogram(["fill.color","green","line.color","red"])
The fill.style attribute of histograms is used to determine how the region is filled. Here we use the value "crisscross", rather than "solid", to fill the histogram with crossed lines. These lines can be colored independently of the histogram boundary.
6) Comparing two histograms
Multiple histograms can be added to a plot. Here we use a combination of the opacity setting and careful bin placement to allow the data to be compared.
The idea of this figure is to compare the Normal and Poisson distribution, calculated using the routines from the np.random module.
def compare(mu, npts=10000): """Compare the Poisson and Normal distributions for an expected value of mu, using npts points. Draws histograms displaying the probability density function.""" ns = np.random.normal(mu, np.sqrt(mu), npts) ps = np.random.poisson(mu, npts) # Calculate the range of the histogram (using # a bin width of 1). Since np.histogram needs # the upper edge of the last bin we need edges # to start at xmin and end at xmax+1. xmin = np.floor(min(ns.min(), ps.min())) xmax = np.ceil(min(ns.max(), ps.max())) edges = np.arange(xmin, xmax+2) xlo = edges[:-1] xhi = edges[1:] # Calculate the histograms (np.histogram returns # the y values and then the edges) h1 = np.histogram(ns, bins=edges, normed=True) h2 = np.histogram(ps, bins=edges, normed=True) # Set up preferences for the histograms hprop = ChipsHistogram() hprop.dropline = True hprop.fill.style = "solid" hprop.fill.opacity = 0.6 add_window(8, 6, 'inches') split(2, 1, 0.01) # In the top plot we overlay the two histograms, # relying on the opacity to show the overlaps hprop.fill.color = "blue" hprop.line.color = "steelblue" add_histogram(xlo, xhi, h1[0], hprop) hprop.fill.color = "seagreen" hprop.line.color = "lime" add_histogram(xlo, xhi, h2[0], hprop) # Start the Y axis at 0, autoscale the maximum value limits(Y_AXIS, 0, AUTO) # Annotate the plot set_plot_title(r"\mu = {}".format(mu)) hide_axis('ax1') set_yaxis(['majorgrid.visible', True]) # Add regions to the title indicating the histogram type xr = np.asarray([0, 0.05, 0.05, 0]) yr = [1.02, 1.02, 1.1, 1.1] ropts = {'coordsys': PLOT_NORM, 'fill.color': 'blue', 'edge.color': 'steelblue'} lopts = {'coordsys': PLOT_NORM, 'size': 16, 'valign': 0.5, 'color': 'blue'} add_region(xr, yr, ropts) add_label(0.07, 1.06, 'Normal', lopts) ropts['fill.color'] = 'seagreen' ropts['edge.color'] = 'lime' lopts['color'] = 'seagreen' lopts['halign'] = 1 add_region(xr+0.95, yr, ropts) add_label(0.93, 1.06, 'Poisson', lopts) current_plot('plot2') # In the bottom plot we separate the two histograms, # so that they each cover half the bin width hprop.fill.color = "blue" hprop.line.color = "steelblue" add_histogram(xlo, xlo+0.5, h1[0], hprop) hprop.fill.color = "seagreen" hprop.line.color = "lime" add_histogram(xlo+0.5, xhi, h2[0], hprop) set_yaxis(['majorgrid.visible', True]) set_xaxis(['majortick.style', 'outside', 'minortick.style', 'outside']) limits(Y_AXIS, 0, AUTO) bind_axes('plot1', 'ax1', 'plot2', 'ax1') limits(X_AXIS, xmin, xmax) compare(7)
The code is written as a routine, which takes a single argument, mu, the expected value for the two distributions. An optional argument (npts) allows the number of points used to create each distribution to be changed, but is not actually used when we call the routine with mu=7 at the end of the script.
The calls to np.random.normal and np.random.poisson create 10000 random numbers each, drawn from the given distribution (we set the sigma of the normal distribution to be the square root of the expected value). These arrays are used to determine the minimum and maximum ranges for the histograms (converted to the nearest integer) using the np.min, np.max, np.floor and np.ceil routines from numpy. From these values we can calculate the edges array used to create the histogram; see the np.histogram documentation for an explanation of the bins and normed arguments.
The visualization consists of two plots; the first with the two histograms overlain and the second has the bins split evenly within each bin.
Annotation is added to label the visualization; in particular regions and labels are added to the left and right of the title area (by using the plot-normalized coordinate system and taking advantage of the halign attribute to right-align the "Poisson" label).
Most of the examples set attributes using the "list" approach but here we either use a dictionary, where the key is the attribute name, or use the ChipsXXX object. The following would all produce a curve with no symbols and a green line:
lopts1 = ['line.color', 'green', 'symbol.style', 'none'] lopts2 = {'line.color': 'green', 'symbol.style': 'none'} lopts3 = ChipsCurve() lopts3.line.color = 'green' lopts3.lsymbol.syle = 'none' add_curve(x, y, lopts1) add_curve(x, y, lopts2) add_curve(x, y, lopts3).
|
https://cxc.cfa.harvard.edu/chips/gallery/histograms.html
|
CC-MAIN-2020-16
|
refinedweb
| 1,370
| 59.3
|
Types of Loops in C
Depending upon the position of a control statement in a program, looping in C a post-checking loop.
:
1. No termination condition is specified.
2. The specified conditions never meet.
The specified condition determines whether to execute the loop body or not.
‘C’ programming language provides us with three types of loop constructs:
1. The for loop
2. The while loop
3. The do-while loop
(1). for loop.
Loops are used to repeat a block of code.
Syntax of for Loop :
for (init; condition; increment) { // block of statement. }
Example :
#include <stdio.h> int main() { int i; for(i = 0; i < 10 ; i++) { printf("%d ",i); } return 0; }
Output :
1 2 3 4 5 6 7 8 9 10
Explanation :.
(2).While loop.
while loop statement in C programming language repeatedly executes a target statement as long as a given condition is true.
Syntax :
while( condition ) { statement(s); }
Example :
#include <stdio.h> int main () { // local variable definition int a = 1; // while loop execution while( a < 5 ) { //loops comes inside this body, until condition is true printf("Value of a: %d\n", a); a++; } return 0; }
Output :
Value of a: 1 Value of a: 2 Value of a: 3 Value of a: 4
(3) :
do { statement(s); } while( condition );
Example :
#include <stdio.h> int main () { // declared local operand (variable) int a = 1; // do-while loop do { printf("value of a: %d\n", a); a = a + 1; } while( a < 5 ); return 0; }
Output :
value of a: 1 value of a: 2 value of a: 3 value of a: 4
One more Example where condition is false :
#include <stdio.h> int main () { // declared local operand (variable) int a = 1; //here, Condition is false. a is not equals to zero do { printf("value of a: %d\n", a); a = a + 1; } while( a == 0 ); return 0; }
Output :
value of a: 1
I Hope It will helpful for you.
|
https://blog.codehunger.in/loop-structure-in-programming-in-c/
|
CC-MAIN-2021-43
|
refinedweb
| 319
| 71.44
|
Hi,
I would like to share my simple rule for Presence items.
items:
Group:Switch:OR(ON, OFF) Presence "Presence" (All) Switch Person1 "Person1" (Presence) \\phone1 Switch Person2 "Person2" (Presence) \\phone2 Switch Presence_Timer "Presence_Timer" (Presence) \\dummy item for anti-flaping of Presence
rules:
import org.openhab.model.script.actions.Timer var Timer myTimer = null rule "Presence Timer" when Item Person1 changed or Item Person2 changed then if(Person1.state == ON || Person2.state == ON) Presence_Timer.sendCommand(ON) else if(myTimer!==null) { myTimer.cancel myTimer=null } myTimer=createTimer(now.plusMinutes(5), [| Presence_Timer.sendCommand(if(Person1.state == OFF && Person2.state == OFF) OFF) ]) end
So, very simple, Presence_Timer is a dummy switch which is a member of Presence group switch, and it will not allow for Presence group to go down for 5 minutes after all members went OFF. for coming ON (coming back home) there is no delay.
|
https://community.openhab.org/t/example-of-simple-anti-flaping-mechanism-for-presence/82487
|
CC-MAIN-2022-21
|
refinedweb
| 145
| 51.04
|
W.
Asynchronicity through the HTTP adapter is provided by the use of a standard Dart futures based interface or by using client supplied completion callbacks.
Authentication is provided using the Basic HTML method, cookie authentication is not supported, see the CouchDB_and CORS.txt document in the doc directory for more details here..
Please read the STARTHERE.txt document in the docs directory for more detailed information.
Numerous examples of Wilt usage in both browser and server environments are coded as tests in the unit test suite under the test directory. Please read the Testing.txt document in doc/testing for further details.
Wilt is hosted here. Please use github to raise issues, any other queries you can direct to me at steve.hamblett@linux.com
Strong mode updates, switch to json_object_lite. Major test refactor Wilt now compiles under the dev compiler, tests factored into common and platform specific.
Update to latest packages/Dart environment. Retire the completion tests.
Issues 15, 21, 22 and 23.
Update to latest HTTP package
Issue 17, CouchDb 1.6.1 updates
Updates for Issues 13, 11 and 14
Updates for Dart V1.5.3, all tests running.
Issues 8 and 9, this makes Wilt both Browser and Server capable
Issue 7 fixed
Issue 6 fixed
Issue 5 fixed
Issues 3 and 4 fixed.
Standalone attachments added Change notification interface added
Updated for Dart 1.0 release Unit tests now use expectAsync0(() Native adapter success/error response hardening Various bugs NOTE - No API changes.
API docs generated
Updated to use dart:convert
Add this to your package's pubspec.yaml file:
dependencies: wilt: ^3.4.1
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:wilt/wilt.
|
https://pub.dev/packages/wilt/versions/3.4.1
|
CC-MAIN-2019-22
|
refinedweb
| 310
| 60.21
|
Writing Your First Test & The Core TDD Cycle
After setting up the project, you’ll now write your first unit test and learn about the core TDD cycle.
Thanks @Dan, is the material covered in the video available on Github?
BTW, I like the revamped real-python platform a lot!
Not right now but that’s a great idea, we can definitely put the sample code up on GitHub and then link it from here :)
Could you please share information on your Visual Studio theme and setup? Looks wonderful!
@Vikram: Here they are—
The theme is Monokai Pro.
I use either Dank Mono or Operator Mono. dank.sh
I copied this from one of Chyld’s comments on another video in this series.
That import line gives me an error with this file structure, but everything works if I move test_stack.py directly under the DS folder. Is there a better way to make it work?
Nice tutorial, terminal that is used is it ZSH?
Had issues with running pytest with this setup. Got it working with:
test_stack.py from ds import Stack ...
(venv)$ python -m pytest tests/
Quick question - I am getting this message trying to run Pytest
AVal-iMac% python -m pytest -v /usr/bin/python: No module named pytest AVal-iMac% python3 -m pytest -v /usr/local/bin/python3: No module named pytest
I have the package installed according to my list.
AVal-iMac% pip3 list Package Version ------------------ ---------- pytest 5.1.2 pytest-cache 1.0 pytest-pep8 1.0.6
Any subjection why it is not working for me? I already un-installed and re-installed but is not working.
Thanking you in advances for your help
@AugustoVal, try running the
pytest command directly like so:
pytest -v
I’m getting the following error when running pytest:
ImportError while importing test module '/test-driven-dev/tests/test_stack.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: tests/test_stack.py:1: in <module> from ds.stack import Stack E ModuleNotFoundError: No module named 'ds'
My directory schema:
test-driven-dev ]$ tree . ├── ds__.py │ └── stack.py └── tests ├── __pycache__ │ ├── test-stack.cpython-37-pytest-5.2.0.pyc │ └── test_stack.cpython-37-pytest-5.2.0.pyc └── test_stack.py │ ├── __init
Any one gone through this?
I believe that saying that a single underscore makes variable private and protects from accessing the value directly does not make any sense. Would rather say that __var makes the variable somewhat private i.e: not accessible by just a . notation on the object (__var is called _ClassName__var instead and . accessible anyway).
Never in the history of forever has anyone ever picked such a terrible font to due a coding tutorial, it’s like a horrible Walt Disney style of text that I cannot read…
@Dri Yes, me too if I try just
pytest -v
(Though your problem may be that
__init.py__ should be in
ds/ not
tests/ – as ds is meant to be the package from which one can import the module stack with the Stack class. However, supposedly in Python 3.3+
__init.py__ is no longer required…but, maybe you’re running an earlier version and this causes ds to not show up as a package for you?)
@Dan Bader First off, I don’t understand why we’re not running pytest directly as you suggest (i.e. why he’s using
python -m pytest -v to start with, instead of just
pytest -v as you suggest)…?
Indirectly, maybe this is why: When I attempt to run pytest directly, I get the same error @Dri reported:
12:08 ~/src/python/examples/tdd} pytest -v ============================= test session starts ============================= platform darwin -- Python 3.8.2, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /Library/Frameworks/Python.framework/Versions/3.8/bin/python cachedir: .pytest_cache rootdir: /Users/rich/src/python/examples/tdd plugins: cov-2.10.0 collected 0 items / 1 error =================================== ERRORS ==================================== ____________________ ERROR collecting tests/test_stack.py _____________________ ImportError while importing test module '/Users/rich/src/python/examples/tdd/tests/test_stack.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: tests/test_stack.py:1: in <module> from ds.stack import Stack E ModuleNotFoundError: No module named 'ds'
My import is same as in the course:
from ds.stack import Stack
My file structure is also the same:
12:08 ~/src/python/examples/tdd} tree . ├── README.txt ├── README.txt~ ├── ds │ ├── __init.py__ │ ├── __pycache__ │ │ ├── stack.cpython-38.pyc │ │ └── test_stack.cpython-38-pytest-5.4.3.pyc │ ├── stack.py │ └── stack.py~ └── tests ├── __pycache__ │ └── test_stack.cpython-38-pytest-5.4.3.pyc ├── test_stack.py └── test_stack.py~
I’m glad about this error, actually, as it points out something I don’t understand, but feel is important: I’d like to understand how the import is searching for the ds module in general, and why it’s not finding it with “pytest”, but does find it with
python -m pytest…?
From web sleuthing, I’ve read that the latter adds CWD to
sys.path. But, I still don’t see how it all fits and why one works and the other doesn’t? Why would it need to add CWD to a path when I’m running from that same dir? Is it searching from
tests/ since it finds
test_stack.py there, but no
ds/ subdir in
tests/?
To test that, I tried adding CWD to
--rootdir, but got the same error:
01:15 ~/src/python/examples/tdd} pytest -v --rootdir=$HOME/src/python/examples/tdd/ ============================= test session starts ============================= platform darwin -- Python 3.8.2, pytest-5.4.3, py-1.8.1, pluggy-0.13.1 -- /Library/Frameworks/Python.framework/Versions/3.8/bin/python cachedir: .pytest_cache rootdir: /Users/rich/src/python/examples/tdd ... tests/test_stack.py:2: in <module> from ds.stack import Stack E ModuleNotFoundError: No module named 'ds'
…so, I added an assert to
test_stack.py to check
sys.path and found that, sure enough, the difference is that
CWD = /Users/rich/src/python/examples/tdd on the
sys.path (and that
--rootdir=$HOME/src/python/examples/tdd/ does NOT add it to
sys.path!!)
via
python -m pytest -v:
sys.path = ['/Users/rich/src/python/examples/tdd/tests', '/Users/rich/src/python/examples/tdd', '']
via
pytest -v:
and
pytest -v --rootdir=$HOME/src/python/examples/tdd/:
sys.path = ['/Users/rich/src/python/examples/tdd/tests', '/Library/Frameworks/Python.framework/Versions/3.8/bin', '']
So, I’m at a loss to figure out just what’s going on here (unless there’s a bug in
pytest --rootdir), nor how to get pytest to work directly as suggested…
[ other than this symlink hack in tests/: 01:29 ~/src/python/examples/tdd/tests} ls -l ds lrwxr-xr-x 1 rich staff 5 Jul 29 01:28 ds@ -> ../ds ]
I’d really appreciate some help with this!!
PS. After reading docs.python.org/2/tutorial/modules.html#the-module-search-path, I found that this also allowed
pytest -v to work (ie, find the ds.stack module):
01:35 ~/src/python/examples/tdd} export PYTHONPATH="$HOME/src/python/examples/tdd/"
But, that also seems like a hack: In order for this to work automatically, we’d need to be setting
PYTHONPATH every time we change directories!
Why doesn’t pytest just include CWD by default? Why doesn’t
--rootdir=CWD work either?
(Maybe the author’s already been down this path!? All the sudden
python -m pytest isn’t looking so bad! :)
Become a Member to join the conversation.
Dan Bader RP Team on March 13, 2019
@Elie: Thanks for your question. Our video lessons are only available for streaming at the moment.
|
https://realpython.com/lessons/writing-your-first-test-core-tdd-cycle/
|
CC-MAIN-2020-34
|
refinedweb
| 1,280
| 66.23
|
Generating PHP Documentation with Sami
Documenting your methods, classes, and functions is becoming second nature for everyone, so it makes sense to have a way to generate a separate documentation instead of navigating through the source code. In this article, I’m going to introduce you to Sami, the new API documentation generator.
What Is a DocBlock?
A DocBlock is a multi-line comment inserted at the top of an implementation (Class, Interface, Method, Attribute…etc). To clarify this, let’s use some code snippets from Laravel.
abstract class Manager { /** * The application instance. * * @var \Illuminate\Foundation\Application */ protected $app; /** * Create a new manager instance. * * @param \Illuminate\Foundation\Application $app * @return void */ public function __construct($app) { $this->app = $app; } }
The DocBlock must start with a
/**, end with a
*/, and every line in between should start with a
*.
When defining a class attribute or a method, we write a description, and one or more annotations to define more information about the implementation. In these examples, the @param and @var annotation tags were used. You can visit the documentation for each of these annotations to view a list of annotations phpDocumentor supports.
API Documentation Generators
There are many API documentation generators out there, but one of the best is phpDocumentor. One of the main reasons I like Sami, however, is the ability to use your versioned documentation on Github, and you can also use Twig for generating the templates.
Installing Sami
There are two ways to install Sami. The first one is to download the PHAR archive and run it using php.
php sami.phar
The other way is through Composer. You can run the
composer require sami/sami:3.0.* command to add the package to your project.
php vendor/sami/sami/sami.php
Cloning Laravel’s Documentation
For our example I will generate documentation for the Laravel Illuminate package.
git clone git@github.com:laravel/framework.git docs
Now our folder structure looks like the following.
docs/ vendor/ composer.json
The
update command is responsible for refreshing the documentation and it’s used like the following.
php vendor/sami/sami/sami.php update config/config.php
Where
config.php is the file that describes your documentation structure and how the output is rendered.
Configuration
The configuration file must return an instance of
Sami\Sami. It accepts a
Symfony\Component\Finder\Finder instance and an array of options.
// config/config.php $dir = __DIR__ . '/../docs'; $iterator = Symfony\Component\Finder\Finder::create() ->files() ->name('*.php') ->exclude('build') ->exclude('tests') ->in($dir); $options = [ 'theme' => 'default', 'title' => 'Laravel API Documentation', 'build_dir' => __DIR__ . '/../build/laravel', 'cache_dir' => __DIR__ . '/../cache/laravel', ]; $sami = new Sami\Sami($iterator, $options); return $sami;
The
$dir variable holds our source file location. The
$iterator will get all files and select
*.php and exclude the
build and
test directories inside our source path.
The
$options variable is self explanatory. The
theme is set to default, but we will talk about making your own theme later on. The
build_dir holds our output files, and the
cache_dir is used for Twig cache, while
title is the title of the generated documentation.
Now, open your command line and run the previous update command.
php vendor/sami/sami/sami.php update config/config.php
After the command has executed, you can run the built-in PHP server to see how your documentation works. Run
php -S localhost:8000 -t build/, and visit to see the result.
Using Git Versioning
I mentioned before that one of the main reasons I like Sami is because of its Git versioning integration. The
options['versions'] parameter accepts a
Sami\Version\GitVersionCollection which holds your Git repository configuration. As an example, let’s create the documentation for the
5.0 and
4.2 branches.
$dir = __DIR__ . '/../docs/src'; $iterator = Symfony\Component\Finder\Finder::create() ->files() ->name('*.php') ->in($dir); $versions = Sami\Version\GitVersionCollection::create($dir) ->add('5.0', 'Master') ->add('4.2', '4.2'); $options = [ 'theme' => 'default', 'versions' => $versions, 'title' => 'Laravel API Documentation', 'build_dir' => __DIR__ . '/../build/laravel/%version%', 'cache_dir' => __DIR__ . '/../cache/laravel/%version%', ]; $sami = new Sami\Sami($iterator, $options); return $sami;
When using versions, your
build_dir and
cache_dir must contain the
%version% tag. The second parameter for the
add method is the label displayed inside a select option. You can also use the
addFromTags,
setFilter methods to filter versions.
php vendor/sami/sami/sami.php update config/config.php
Now your build directory will contain a folder for each version, and the user will have the ability to choose which one he wants to read.
Creating Themes
Until now, we’ve only used the
default theme, but Sami is flexible enough to give us the ability to create our own themes.
The
vendor/sami/sami/Sami/Resources/themes folder is where the default theme is. However, you must not place your own themes there. Sami provides a way to add your own themes path to the lookup path.
// config/config.php $templates = $sami['template_dirs']; $templates[] = __DIR__ . '/../themes/'; $sami['template_dirs'] = $templates;
Now we can have our
themes folder in the root of our application. To create a new theme, you need to create a folder and put a
manifest.yml file inside it.
// themes/laravel/manifest.yml name: laravel parent: default
Our new theme is called
laravel and it will extend the
default theme properties. As an example, we will try to add some assets to the page and override the behavior of the template.
Adding Assets
Let’s create a
css folder inside our theme folder and create a
laravel.css file inside it.
// themes/laravel/css/laravel.css #api-tree a { color: #F4645F; }
// themes/laravel/manifest.yml … static: 'css/laravel.css': 'css/laravel.css'
The static configuration section tells Sami to copy the files as they are inside the specified destination. The build folder will contain the new file inside
build/laravel/%version%/css/laravel.css.
// themes/laravel/manifest.yml … global: 'layout/base.twig': 'layout/base.twig'
// themes/laravel/layout/base.twig {% extends 'default/layout/base.twig' %} {% block head %} {{ parent() }} <link rel="stylesheet" href="css/laravel.css" /> {% endblock %}
Every time Sami wants to load the
base layout, it will use the defined file inside your theme. We extend the default base layout to keep the default look and feel, and we inject our stylesheet link to the
head block. Calling The
parent() function will cause Twig to keep any existing content in the
head block, and output it before our
link tag.
// config/config.php $options = [ 'theme' => 'laravel', //... ];
php vendor/sami/sami/sami.php render config/config.php --force
By default Sami will not reload the documentation if nothing has changed. However, using the
--force flag will force it to refresh the files. Visit the documentation page in your browser to see that the color of the left navigation links has changed.
Changing Markup
// themes/laravel/manifest.yml global: 'namespaces.twig': 'namespaces.twig'
As the name suggests, the
namespaces file defines how our namespace content is rendered.
// themes/laravel/namespaces.twig {% extends 'default/namespaces.twig' %} {% from "macros.twig" %}
If you open the
default/namespaces.twig page, you’ll see that Sami is using macros to simplify the process of extending templates. We will create our own
macros.twig file to override the default markup.
Because Twig doesn’t support inheriting and overriding a function inside a macro, I’m going to copy and paste the default theme macros and start editing them.
// themes/laravel/macros.twig {% macro render_classes(classes) -%} <div class="container-fluid underlined"> {% for class in classes %} <div class="row"> <div class="col-md-6"> {% if class.isInterface %} <span class="label label-primary">I</span> {% else %} <span class="label label-info">C</span> {% endif %} {{ _self.class_link(class, true) }} </div> <div class="col-md-6"> {{ class.shortdesc|desc(class) }} </div> </div> {% endfor %} </div> {%- endmacro %}
The only thing we’ve changed in this macro is the way we distinguish a class from an interface. Sami used to emphasize the interface, but we are going to insert a colored label before every item depending on its type instead.
We didn’t change much on the page, but you may want to try and use bootstrap styles on your pages, make the menu more responsive, and so on.
Now, after regenerating the documentation you can see that when you list a namespace, the classes and interfaces are preceded by labels.
Conclusion
In this article we introduced a new Symfony tool that can help you manage the documentation of your package. You can also create a unique theme for your package docs. You can find the final result of our example on Github. If you have any questions or comments you can post them below.
No Reader comments
|
https://www.sitepoint.com/generating-php-documentation-sami/
|
CC-MAIN-2018-30
|
refinedweb
| 1,441
| 51.04
|
JavaScript is one of those languages that can be easy to pick up, it can be infinitely more difficult to master. However, a lot of articles seem to assume that you are already a master.
I've been using JavaScript since its introduction as LiveScript in 1995, but slowly moved away from client-side development to retreat into the safe confines of the server. For the past five years, I've refocused on the client-side. I'm happy to find that browsers are far more competent, powerful, and easier to debug than they were in the early days. But JavaScript has grown in complexity and is not any easier to master. Recently I came to a conclusion. I don't necessarily need to master JavaScript - but I can get better. I am happy being a "good" JavaScript developer.
What follows are the tips and techniques that I have found to be useful and - most of all - practical in terms of writing JavaScript: organizing code; linting; testing; and using browser developer tools. While some of these may seem obvious to experienced JavaScript developers, it's very easy to fall into bad habits when you are new to a language. These guidelines have helped me level up my skills and produce better experiences for my users. And that's our number one goal, right?
You can download the source code for the examples in this article here.
As a new JavaScript developer begins learning their craft, they will inevitably begin with a large block of code on top of their HTML page. It always starts simple. A simple bit of jQuery to autofocus a form field. Then maybe form validation. Then a little dialog widget that marketing just loves - you know, the ones that stop people from reading content so that they can Facebook Like the site itself. After a few iterations of this you've got a few hundred lines of JavaScript within an HTML file that probably has a few hundred lines of tags.
It's a mess. Stop doing it. It sounds simple, and I'm almost embarrassed to even write it down as a tip, but it is very tempting to just whip up a quick script block on top of your page. Avoid that temptation like the plague please. Make it a habit when you create a new web site to go ahead and create an empty JavaScript file. Include it via the script tag and it will be ready for you when you begin adding interactivity and other client-side features.
Once you've gotten off the HTML page (doesn't that feel cleaner?), the next problem you'll run into is organization of the code itself. Those few hundred lines of JavaScript may work just fine, but the first time you have to debug or modify the code after a few months away you may find yourself wondering just where in the heck a particular function exists.
So if simply moving a bunch of code off HTML into another file isn't enough, what's the next solution?
Obviously a framework is the solution. Move everything to AngularJS. Or Ember. Or React. Or one of the hundred or so other options. Rebuild the entire site into a Single Page Application and MVC and just go crazy.
Or maybe not. Don't get me wrong, I love Angular when I'm building apps, but there's a difference between an "app" and a web page with interactivity. There's a difference between a fancy Ajax-enhanced product catalog and Gmail - at least a few hundred thousand lines of code different. But if you aren't going to go the framework route, what's the other choice?
Design patterns are a fancy way of saying, "here is an approach to handle a problem that people have had in the past." They can definitely be useful. Addy Osmani wrote an excellent book on the topic, Learning JavaScript Design Patterns, that you can download and read for free. I recommend it. But an issue I had with the book (and similar discussions on the topic), was that you end up looking at code like this.
var c = new Car(); c.startEngine(); c.drive(); c.soNotRealistic();
Abstractly, design patterns made sense to me, but practically, they did not. It was difficult to take the patterns and apply them in context to a real web page with real code.
Among all the patterns I read about, I felt like the Module pattern was both the simplest and easiest to apply to existing code.
At a high level, the Module Pattern simply creates a package around a set of code. You can take a related collection of functions, drop them into a module, and then explicitly decide what you want to expose. This creates a "black box" of code that can more easily be shared amongst other projects. You can also move code in modules into separate files.
Let's look at a simple example of the Module Pattern. It has a syntax that may seem weird at first. It certainly did to me. Let's begin with the "wrapper" and I'll explain the various bits.
Wrapper for the module pattern.
So, am I the only one who sees that and gets confused by all the parentheses? Mentally it was difficult to wrap my head around what this was doing - and I know JavaScript. It helped me to look at it from the inside out.
The inside of the module pattern is just a regular function.
You begin with a simple function. This is where you will define the methods you can call on your module.
The parenthesis will automatically run the function.
The parenthesis at the end there will then automatically run the function. Whatever we return is the module, which, for now, we're keeping empty. What you see highlighted now is not valid JavaScript however. So what makes it valid?
The outer parenthesis makes this crazy stuff work.
The parenthesis around the
function() { }() block is what makes this whole thing valid JavaScript. If you don't believe me, you can open up your developer tools console and try entering that yourself.
Which brings up back to the beginning...
The result is assigned to a variable.
The very last thing that happens is the result is assigned to a variable. Even with me personally understanding of all this, every time I see this in code I have to mentally pause for a second and remind myself of just what in the heck is going on here. I'm not ashamed to say it - I keep this code handy in my editor so I can copy and paste the 'empty' Module for quick reuse.
Now that we've gotten over the hump of that slightly weird syntax, what does an actual Module pattern look like?
var counterModule = (function() { var counter = 0; return { incrementCounter: function () { return counter++; }, resetCounter: function () { console.log("counter value prior to reset: " + counter ); counter = 0; } }; }());
The previous code creates a module called
counterModule. It has two functions:
incrementCounter and
resetCounter. Using them could look something like this:
console.log(counterModule.getCounter()); //0 counterModule.incrementCounter(); console.log(counterModule.getCounter()); //1 counterModule.resetCounter(); console.log(counterModule.getCounter()); //0
The idea is that all of the code behind my
counterModule is packaged away nicely. Packaging is computer science 101, and the future of JavaScript will provide even simpler ways of doing this, but for now, I find the Module pattern to an incredibly simple, practical way of handling the issue of organization.
I began this discussion by complaining about the appropriateness of some of the examples I see online (see the Car example). Let's build a simple example of this that actually matches a real world scenario. I'm going to keep it simple for the sake of this article, but applicable to something you may actually encounter in a real web application.
Your online game company, Lyntendo (don't sue me), has a user sign up portal where users must create a game identity. You need to build a form where the user can select a name. The rules for identifiers are a bit weird:
Let's mock this up in an incredibly simple form.
<html> <head> </head> <body> <p>Text would be here to describe the rules...</p> <form> <input type="text" id="identifer" name="identifier" placeholder="Identifer"> <input type="submit" id="submitButton" value="Register Identifer."> </form> <script src="app.js"></script> </body> </html>
You can see the form I mentioned as well as a submit button. I'd also include text describing the rules I mentioned above, but I'm keeping it simple for now. Let's look at the code.; } document.getElementById("submitButton").addEventListener("click", function(e) { var identifier = document.getElementById("identifer").value; if(validIdentifier(identifier)) { return true; } else { console.log('false'); e.preventDefault(); return false; } });
Starting at the bottom, you can see I've got some basic code to get the elements from the page (yes, folks, in this case I didn't use jQuery) and then listen for click events on the button. I get the value the user used for their proposed identifier and then pass it to my validation. The validation is nothing more than what I described above. The code isn't too messy, but as my validation rules increase and as I add other interactivity points to my page, it will get harder to work with. Let's rewrite this as a module.
First, I created a new file called game.js and included it via a script tag in my index.html file. I then moved the contents of my validation logic inside a module.
var gameModule = (function() {; } return { valid:validIdentifier } }());
This isn't terribly different from before, but now it's packaged into a variable called
gameModule that has one API,
valid. Now let's look at app.js.
document.getElementById("submitButton").addEventListener("click", function(e) { var identifier = document.getElementById("identifer").value; if(gameModule.valid(identifier)) { return true; } else { console.log('false'); e.preventDefault(); return false; } });
Notice how much less code we have mixed in with our DOM listeners. All the functionality of validation (two functions and a list of bad words) are all now safely put away in the module making the code I have here easier to work with. Depending on your editor, you'll also get code completion for the methods of your module.
Working with modules isn't necessarily rocket science, but it is cleaner and simpler and that's a real good thing!
If you aren't aware of the term, linting refers to checking your code for best practices and other problems. A noble cause, right? As nice as it is, I was always left with the impression that linting was something only fussy developers worried about. Obviously I want my code to be great. I also want time to play video games too. Having my code be less than some Perfect High Ideal(tm) while it still actually worked was perfectly fine by me.
But then...
You know those times when you rename a function and remind yourself that you're going to fix it later?
You know those times when you define a function to accept two arguments and end up only ever using one?
You know how sometimes you write really stupid code? I mean code that won't even come close to working. My favorite is
fuction and
functon.
Yeah, linting actually helps with that! As I keep saying, while it is probably obvious to everyone but me, the fact that linting was more than just best practices but also syntax and basic logic checking as well was news to me. Another factor also put it over the edge from "Will do when I have more time than I know what to do with" to "I will use this religiously" was the fact that most modern editors have it built in. My current editors (Sublime, Brackets, and Visual Studio Code), all support providing real time feedback on your code.
As an example, here is a report from Visual Studio Code on some code I intentionally wrote poorly. Honestly. I did it on purpose.
Visual Studio Code linting.
In the figure above, you can Visual Studio Code
complainingpointing out a few mistakes in my code. Visual Studio Code's linter, and most linters, have options for what you care about and what is considered an error ("must fix") versus a warning ("should fix, stop being lazy").
If you don't want to install anything or try configuring your editor, a great way to test linting online is at JSHint.com. JSHint is probably the most popular linter and is based on another linter, JSLint (Not confusing at all, honest). JSHint was created partially in response to how strict JSLint could be. While you can use JSHint directly in editors or via the command line, one of the easiest ways to to try it out is on the site itself.
JSHint site.
While it may not be immediately obvious, the code on the left hand side is a live editor. On the right hand side is a live report based on that code. The easiest way to see this is to just introduce a simple error in the code. I began by changing the
main function to
main2:
function main2() { return 'Hello, World!'; } main();
Immediately, the site reported two errors from this. Now keep in mind, these aren't syntax errors. Everything may look valid in the code above, but JSHint notices the problems that you may not (Of course, this is a 5 line block of code, but imagine a larger file with the function and call separated by many lines).
JSHint errors.
How about a real example? In the code below (yep, now I am using jQuery), I've written a simple bit of JavaScript to handle form validation. It's trivial stuff, but probably half the JavaScript written today is doing something like this (Oh, and creating pop up modals asking you to "Like" the site. I love those). You can find this code in the demo_jshint folder as app_orig } }); });
The code begins with two functions written to help with validation (for age and email). Then we have a
document.ready block where we listen for the form submission. Values from three fields are fetched, checked if blank (or invalid), and then either an alert is fired that the form is invalid or things carry on (or in our example case, the form just sits there).
Let's throw this into JSHint and see what we get:
JSHint errors for our demo.
Woah, that's a lot! However, it looks like it's actually similar problems that occured multiple times. This was common for me as I began using linters. I typically wasn't making a lot of unique errors, just a lot of the same error again and again. The first one is easy enough - using triple equals for checking versus double equals. The short story on that it is stricter test for checking that the values are empty strings. Let's fix that first (demo_jshint/app_mod1 here is the updated report from JSHint:
JSHint errors for our demo.
Ok, we're getting there. The next block is about "undefined variables." That may seem odd. If you're using jQuery, you know
$ exists. The issue with
badForm is simpler - I forgot to
var scope it. But how do we fix
$? JSHint provides a way to configure how code is checked for issues. By adding a comment to our code, we can let JSHint know that the
$ variable exists as a global and is safe to use. Let's add that and fix the missing
var statement (demo_jshint/app_mod2 the updated report from JSHint:
JSHint errors for our demo.
Woot! Almost done. This final issue is a perfect example of where JSHint can provide useful information that isn't an error or best practice. In this case, I simply forgot that I wrote a function to handle age verification. You can see I've created
validAge, but in the form checking area, I don't use it. Maybe I should kill the function - it's only one line - but it feels more proper to keep the function - just in case the validation gets more intense later on. Here is the final version of the code (demo_jshint/app(!validAge(age)) badForm = true; if(email === "") badForm = true; if(invalidEmail(email)) badForm = true; console.log(badForm); if(badForm) alert('Bad Form!'); else { //do something on good } }); });
This version finally "passes" the JSHint test. To be clear, this code isn't perfect. Notice how I have a validation function called
validAge and one called
invalidEmail. One is positive while the other is negative. It would be better if I were consistent. Also notice how every time validation is run, jQuery is asked to fetch three items from the DOM. They really only needed to be loaded once. I should create those variables outside of the submission block and reuse them every time. As I said, JSHint isn't perfect, but the final version of the code is definitely better than the first and it didn't take long to update.
You can find linters for JavaScript (JSLint and JSHint), HTML (HTMLHint and the W3C Validator) and CSS (CSSLint). Along with editor support, if you're really fancy, you can also automate it with tools like Grunt and Gulp.
I don't write tests.
There. I said it. The world didn't end. To be fair, I do write tests (ok, I try to write tests) when working on client projects, but for my main job I tend to do blog posts and demos of various features. I don't write tests for these as they're just proof of concepts and not production work. That being said, I can say that even before I became an evangelist and stopped doing "real" work, I often used the same excuses for not linting as for not writing tests. And it turns out that many of the same things that made linting easier are also helping out on the testing side.
First - many editors will actually generate tests for you. For example, in Brackets, you can use the xunit extension. It lets you right click on a JavaScript file and generate a test (in multiple popular testing framework formats).
Test being created with xunit.
The extension will do its best to attempt to write a test based on existing code. This test will be a 'stub' and you'll need to flesh out some actual data in it, but the important thing is that it gets the grunt work out of your way.
Test created with xunit.
Once you begin actually fleshing out those details, the extension will automatically run your tests for you. Honestly, at this point, not writing tests begins to plain look lazy.
Test report.
You'll probably have heard of TDD (Test Driven Development). This is the concept of writing unit tests before any actual functionality. Essentially, the idea is that your tests help drive your development. As you write your code and see your tests begin to pass, you have some assurance that your on the right path.
I think that's a noble idea, but it may be difficult to achieve for everyone. How about starting simpler? Imagine you've got a set of existing code that - as far as you know - works just fine. Then you discover a bug. Before fixing the bug, you can create a test to verify the bug, fix it, then use the test to ensure it stays fixed as you work on it in the future. As I said, this isn't the ideal path, but can be a way to gently ramp up into including testing in all stages of your development.
For our sample code with a bug we'll use a little function that I wrote that tries to shorten numbers. So for example, 109203 could be simplified as 109K. An even bigger number like 2190290 could be turned into 2M. Let's look at the code and then I'll demonstrate the bug.
var formatterModule = (function() { function fnum(x) { if(isNaN(x)) return x; if(x < 9999) { return x; } if(x < 1000000) { return Math.round(x/1000) + "K"; } if(x < 10000000) { return (x/1000000).toFixed(2) + "M"; } if(x < 1000000000) { return Math.round((x/1000000)) + "M"; } if(x < 1000000000000) { return Math.round((x/1000000000)) + "B"; } return "1T+"; } return { fnum:fnum } }());
Maybe you see the issue right away? Give up? When given 9999 as an input, it returns 10K. Now, that might be a useful shortening, but the code is supposed to treat all numbers below 10K as their original value. It is an easy enough correction, but let's use this as an opportunity to add a test. For our testing framework we'll use Jasmine. Jasmine has a great, easy to understand language for writing tests and a simple way to run them. The quickest way to get started is to download the library. Once you've done that and extracted it, you'll find a file called SpecRunner.html. This file handles loading your code, loading a test, and then running the tests and creating a pretty report. It requires the lib folder from the zip but you can begin by copying both SpecRunner and the lib to someplace on your web server.
Open up SpecRunner.html and on top you'll see:
<!-- include source files here... --> script tags here... <!-- include spec files here... --> more script tags here...
Under the first comment you'll want to remove the existing line and simply add a script tag pointing to the code containing your code. If you've got the zip file for this article you can see my code in demo4 in a file called formatter.js. Next you'll want to add a script tag pointing to the spec, or test. Maybe you haven't seen Jasmine before, but take a look at the spec. It is very readable, even to the untrained eye.
describe("It can format numbers nicely", function() { it("takes 9999 and returns 9999", function() { expect(9999).toBe(formatterModule.fnum(9999)); }); });
Basically my test is saying that when 9999 is passed to the library it should get 9999 out again. If you open the SpecRunner.html in your browser you can see it reporting the failure.
Report of the failing test.
The fix, is rather simple. Change that conditional using 9999 to 10000:
if(x < 10000) { return x; }
Now when you run the tests you'll see a much happier picture:
Report of the passing test.
Looking at the module, you can probably think of a number of related tests that would really flesh out the suite. In general, there's nothing wrong with going overboard on your testing and trying to cover every possible use of your code possible. Consider the awesome date/time library Moment.js. It has - I kid you not - over fifty-seven thousand tests. That's thousand. You read it right.
Other options for testing JavaScript code include QUnit and Mocha. As with linting you can automate testing with tasks runners like Grunt, and you can even go full stack and test the browser itself with Selenium.
The final tool I'll mention are those within the browser itself - the dev tools. You can find multiple articles, presentations, and videos on this topic so I won't say much more about it, outside of my belief that, amongst everything I've discussed today, this is probably the one thing I'd call required knowledge for web developers. It is perfectly fine to write broken code. And it is perfectly fine to not know everything. But browser dev tools at least help you find the broken bits. At that point a solution is typically one Google search away.
If I can add one final piece of advice here, it is that you should not focus on only one browser's dev tools. I was playing with App Cache a few years ago (yes, I'm a glutton for punishment) and ran into issues with my code working in Chrome. Of course, I had my dev tools open, but it wasn't helping. On a whim, I opened up the code in Firefox and used their dev tools, and immediately I discovered the issue. Firefox simply reported more information about the request compared to Chrome. Running it one time was all I needed to correct the issue. (Ok, that's a lie. Firefox showed me the problem but it took a bit longer to fix.) If you find yourself stuck, just open another browser and see if the error reporting offers a different perspective.
On the off chance you've never actually seen your browser tools in action, here are instructions on how to view them in all the major browsers, as well as the best link to get started for reading more.
To open dev tools, click the hamburger menu icon on the upper right of your browser, select "More Tools", and then "Developer Tools". You can also open up dev tools using your keyboard. For example, on OSX the combination is
CMD+SHIFT+C. You can find documentation for Chrome's dev tools at "Chrome DevTools Overview".
To open dev tools, click "Tools" in the main menu, then "Web Developer" and "Toggle Tools". Note that Firefox has a cool toolbar that can be used to issue commands and make opening up dev tools even easier. This can be enabled from the same menu. You can learn more at Firefox Developer Tools.
Before you can work with dev tools, you have to enable the "Develop" menu. Go to Safari preferences, then "Advanced", and click "Show Develop menu in menu bar." Then you can select the "Develop" menu and use "Show Web Inspector" (or the three items below it) to open dev tools. You can read more about this at "About Safari Web Inspector".
You can open Internet Explorer's Dev Tools by clicking the gear icon in the upper right hand of the browser (or by presing F12). You can read more here, "Using the F12 developer tools".
Sometimes it seems as if our job as developers is never complete. While writing this article, did you know that thirteen more JavaScript frameworks were released? True story! So here is some final advice on how to learn and how to keep up - as best as possible.
For learning, I focus my attention on the Mozilla Developer Network (when you google, try preprending your term with "mdn"), CodeSchool (a commercial video training company with great content), and Khan Academy. I want to specifically call out Mozilla Developer Network (MDN) as I avoided it for years thinking it was a Netscape/Firefox only site. That was pretty dumb.
Another suggestion is to just read code! Many of us have used jQuery, but have you ever actually opened up the file to take a look at how it is built? Reading other people's code can be a great way to get exposed to other techniques and methods. While it may be scary, I also strongly encourage you to share your own code. Not only will you get the benefit of having an extra pair of eyes (or many thousands of them) look at your code, you may actually help others as well. A few years back I was watching a junior programmer share some code and while he made some fairly typical "noob" mistakes, he also used some techniques that were outright brilliant.
For keeping up on the latest news, I subscribe to the various "weekly" newsletters run by Cooper Press. They have an HTML weekly, a JavaScript one, a Node one, a Mobile one, and so forth. It can get overwhelming, but do what you can do. When I see that some new tool has been released that does Foo and I don't particularly need Foo at the moment, I don't even try to learn this tool. I just remember, "Hey, there's a tool that does Foo." so that when I need it in the future, I can dedicate the time then.
Related Resources:
Header image courtesy of Lemsipmatt.
|
https://www.telerik.com/blogs/leveling-up-your-javascript
|
CC-MAIN-2021-39
|
refinedweb
| 4,733
| 73.47
|
The Play cache API
The default implementation of the Cache API uses EHCache. You can also provide your own implementation via a plug-in.
Accessing the Cache API
The cache API is provided by the
play.api.cache.Cache object. It requires a registered cache plug-in.
Note: The API is intentionally minimal to allow several implementation to be plugged. If you need a more specific API, use the one provided by your Cache plugin.
Using this simple API you can either store data in cache:
Cache.set("item.key", connectedUser)
And then retrieve it later:
val maybeUser: Option[User] = Cache.getAs[User]("item.key")
There is also a convenient helper to retrieve from cache or set the value in cache if it was missing:
val user: User = Cache.getOrElseAs[User]("item.key") { User.findById(connectedUser) }
Caching HTTP responses
You can easily create smart cached actions using standard Action composition.
Note: Play HTTP
Resultinstances are safe to cache and reuse later.
Play provides a default built-in helper for standard cases:
def index = Cached("homePage") { Action { Ok("Hello world") } }
Or even:
def userProfile = Authenticated { user => Cached(req => "profile." + user) { Action { Ok(views.html.profile(User.find(user))) } } }
Next: Calling web services
|
https://www.playframework.com/documentation/2.0.2/ScalaCache
|
CC-MAIN-2015-22
|
refinedweb
| 201
| 50.53
|
Implementing sound in C and C Plus Plus
Introduction
Sound, in the meaning of one shot sound effects, background ambiance and background music, is an essential element of modern games. A good sound can build up the atmosphere far better than a thousand words.
The implementation of sound, however, is considered a difficult task, especially for inexperienced programmers. Fortunately, there exist libraries that allow developers to introduce sound to any C and C++ program. One is called FMOD Ex, by Firelight Technologies Pty, Ltd. and another is called Audiere.
Audiere
Audiere is an open-source and free interface for C and C++. Installing it is as easy as including the appropriate DLL file and include file in your Makefile or IDE of choice -- no compilation necessary to get a binary, since they are included in the download from the site.
The purpose of Audiere is to provide developers with a braindead easy API, support for all the major file formats (WAVs, FLAC, MP3, and more!), and to provide other basic functionality and capabilities that a programmer may find useful in their sound programming endeavors.
FMOD
The first thing you need to do is to download the library from FMOD site. The library is available free of charge for anyone, provided you use it only for noncommercial productions. The installation file includes an extensive programmer's API reference, so you can browse it to learn to use FMOD. After that, you just link your project with the appropriate library and you're ready to go.
There is one thing you should be aware of: if you use the C++ interface of FMOD, it won't compile with MinGW. It is a known problem and it can be avoided by either using the C interface or writing your own C++ code that uses FMOD's C interface internally.
Below you can find example code that should make FMOD reproduce looped background music in any C++ project.
Code: sound.hpp
#include "fmod.h" //FMOD Ex /******** CLASS DEFINITION ********/ class Sound { private: static bool on; //is sound on? static bool possible; //is it possible to play sound? static char * currentSound; //currently played sound //FMOD-specific stuff static FMOD_RESULT result; static FMOD_SYSTEM * fmodsystem; static FMOD_SOUND * sound; static FMOD_CHANNEL * channel; public: static void initialise (void); //initialises sound //sound control static void setVolume (float v); //sets the actual playing sound's volume static void load (const char * filename); //loads a soundfile static void unload (void); //frees the sound object static void play (bool pause = false); //plays a sound (may be started paused; no argument for unpaused) //getters static bool getSound (void); //checks whether the sound is on //setters static void setPause (bool pause); //pause or unpause the sound static void setSound (bool sound); //set the sound on or off //toggles static void toggleSound (void); //toggles sound on and off static void togglePause (void); //toggle pause on/off };
Code: sound.cpp
#include "sound.hpp" /******** CLASS VARIABLE DECLARATIONS ********/ bool Sound::on = true; //is sound on? bool Sound::possible = true; //is it possible to play sound? char * Sound::currentSound; //currently played sound //FMOD-specific stuff FMOD_RESULT Sound::result; FMOD_SYSTEM * Sound::fmodsystem; FMOD_SOUND * Sound::sound; FMOD_CHANNEL * Sound::channel; /********,2,; } } //frees the sound object void Sound::unload (void) { if (possible) { result = FMOD_Sound_Release(sound); } } //plays a sound (no argument to leave pause as dafault) void Sound::play (bool pause) { if (possible && on) { result = FMOD_System_PlaySound(fmodsystem,FMOD_CHANNEL_FREE, sound, pause, &channel); FMOD_Channel_SetMode(channel,FMOD_LOOP_NORMAL); } } //toggles sound on and off void Sound::toggleSound (void) { on = !on; if (on == true) { load(currentSound); play(); } if (on == false) { unload(); } } //pause or unpause the sound void Sound::setPause (bool pause) { FMOD_Channel_SetPaused (channel, pause); } //turn sound on or off void Sound::setSound (bool s) { on = s; } //toggle pause on and off void Sound::togglePause (void) { FMOD_BOOL p; FMOD_Channel_GetPaused(channel,&p); FMOD_Channel_SetPaused (channel,!p); } //tells whether the sound is on or off bool Sound::getSound (void) { return on; }
Code: Conclusion
With this code, adding a looped background track is as easy as adding these lines to your main.cpp file:
Sound::initialise(); Sound::load("yoursound.mp3"); Sound::play();
There! You have sound playing in the background while the rest of the program continues!
For details about the used FMOD functions, as well as others, please refer to FMOD API documentation.
by Dominik "Mingos" Marczuk
|
http://roguebasin.com/index.php/Implementing_sound_in_C_and_C_Plus_Plus
|
CC-MAIN-2021-43
|
refinedweb
| 711
| 58.72
|
The below code is given. You need to determine what the output will be, or if there is an error.
#include<stdio.h> int main() { int *j; int *fun(); j = fun(); printf("%d\n",*j); printf("%d",*j); return 0; } int *fun() { int k = 35; return(&k); }
What is given in a well known book
This was the explanation given in a well known book Let Us C by Yashavant Kanetkar (5th Edition)
Here we are returning an address of k from fun() and collecting it in j. Thus j becomes pointer to k. Then using this pointer we are printing the value of k. This correctly prints out 35. Now try calling any function (even printf()) immediately after the call to fun (). This time printf () prints a garbage value. Why does this happen? In this case, when the control returned from fun () though k went dead it was still left on the stack. We then accessed this value using its address that was collected in j. But when we precede the call to printf () by a call to any other function, the stack is now changed, hence we get the garbage value.
please ignore this answer, as it is not correct.
Actual answer
This is a perfect example of undefined behavior. Which means that the behaviour of such code is not defined in the C Language, and the output can be anything, the program can print the old value of k it can print garbage, the program can crash, or an earthquake or alien invasion could occur. Note, because the behaviour is not defined, we cannot rule out earthquake or alien (also the 2012 deadline of Earth is approaching).
Undefined Behavior is defined in C99 standard Section 3.4.3 Paragraph 1 and 2. I am quoting Paragraph 1 below:
undefined behavior
behavior, upon use of a non-portable or erroneous program construct or of erroneous data, for which this International Standard imposes no requirements
If you compile this code with a good compiler it will also throw you a warning, like gcc does in my case:
t.c: In function ‘fun’: t.c:18:5: warning: function returns address of local variable [enabled by default]
Explanation
First we need to understand lifetime or storage duration of a variable in C. Lifetime of a variable or an object is defined as the portion of the program during which storage is guaranteed to be reserved for the object. The storage duration related to an object/variable determines its lifetime. The Section 6.4.2 Paragraph 2 defines lifetime of a variable, which is quoted below. (or just past) reaches the end of its lifetime.
I think this paragraph explains it all.
k is automatic (local), therefore its lifetime will end whenever the block in which it is defined ends, which is actually the end of function fun (). The local variables k is allocated in the stack frame created for the function fun (). Whenever the function returns, the current active stack frame becomes the stack frame of the function main (), in this case, and the stack frame area of fun () is no more allocated, therefore the system can do whatever with it. Just because you are not doing anything, you can never assume that the stack frame of the last function call is unmodified. It can change in whatever manner, and therefore accessing any address location from that location can result in retrieval of the correct value, garbage value, pagefault or anything, which you can never tell definitely.
Therefore when the function fun () returns the address of the local variable k and it is assigned to the pointer variable j, also whenever the fun () returns, the lifetime of k is finished, and therefore its address location is not any more “guaranteed” to hold the “last-stored” value. The case of accessing the address location of k with *j falls exactly under the line “The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime.” . This clearly indicates that the behaviour will be undefined.
One thing should be noted, it is immaterial if the automatic/local variables/objects are stored on the stack frame, and they may or may not be erased. If someone implements the function call in some other way and chooses some other place to allocate the local variables, then also the behaviour has to be the same as defined in the language definition.
You can run this code with a local k declaration in other compilers and will get different answer in different platforms and compilers.
Lifetime of automatic variables are defined in Section 6.2.4 Paragraph 5 and 6.
You can have a look at the entire Section 6.2.4 which contains the definitions about Storage Durations in C language.
This is the same cause for which you cannot return a local array.
If “k” was static
In the case k was defined as static the story would be something else. The code would have been perfectly all right, and a well defined behaviour, which is you will get the value last stored in the location. Why? This is to do with the lifetime of static variables. Static storage duration is defined in Section 6.2.4 Paragraph 3, which tells that the lifetime of a static variable/object is the entire execution of the program. Therefore the storage location of a static variable is guaranteed to be allocated throughout the execution of the program, therefore making it possible returning an address of a local static variable and use it without any problem. Similarly it will be same as the case of global variables, as they also have lifetime of the entire program.
Using address of local variable in a function call
Note that passing address of a local variable in a function call is perfectly all right. For example:
#include <stdio.h> void fun (int *k); int main (void) { int j = 5; printf ("j = %d\n", j); fun (&j); printf ("j = %d\n", j); return 0; } void fun (int *k) { *k = 10; }
This will first print 5 and next 10. This is because when the function fun () is called the lifetime of j is not finished as the execution has not passed through the block in which j declared. From the other point of view the stackframe is preserved, and a new stackframe is created for fun ().
5 thoughts on “C Q&A #0: Returning address of local variable”
But the scope of a static variable is also local? How can we say that its memory location not destroyed when the function hands over the control to main?
The *scope* of static local variable is inside the function, but its *lifetime* is throughout the entire runtime of the program execution. To support this statement I have included in the above text that this behaviour is mentioned in C99 Standard Section 6.2.4 Paragraph 3. I am quoting the paragraph below.
This paragraph unambiguously states the behaviour, note the line “Its lifetime is the entire execution of the program … ” .
Thanks for stopping by and asking the question!
Thanks for the reply :)
When we do the same thing without pointers… den wat?
Like…
And in the main..we have
When you perform a return s;, this copies the value stored inside s into a temporary location (generally in a register), which will be accessed and copied to the variable C after the function call fun returns. Therefore this is safe, as the copied variable in C is just a value, and is not linked to something else.
In case the value of s was an address local to fun, then it would have been a problem. This is because, upon return C will contain the address of something local to fun and upon the return the lifetime of the object related to that address has ended, so dereferencing C will lead to trouble.
Bottom line: The code you have shown is perfect, and is an example of a normal function call.
|
https://phoxis.org/2012/06/11/c-code-question-1-return-local-var-addr/?shared=email&msg=fail
|
CC-MAIN-2019-51
|
refinedweb
| 1,347
| 69.41
|
PAPER DB1, INCORPORATING SUBJECT AREAS – FINANCIAL STRATEGY – RISK MANAGEMENT
TUESDAY
Present Value Rates are on page 2.
Module B
The net present value of £1 receivable at the end of n years at 10 per cent n 0 1 2 3 4 5 10% 1·00 0·91 0·83 0·75 0·68 0·62
2
Section A – All 20 questions are compulsory and MUST be attempted. Each question within this section is worth 2 marks. Please use the Candidate Registration Sheet provided to indicate your chosen answer to each multiple choice question. 1 Calcite Ltd used the NPV and IRR methods of investment appraisal to evaluate a project that has an initial cash outlay followed by annual net cash inflows over its life. After the evaluation had been undertaken, it was discovered that the cost of capital had been incorrectly calculated and that the correct cost of capital figure was in fact higher than that used. What will be the effect on the NPV and IRR figures of correcting for this error? Effect on NPV IRR Decrease Decrease Decrease No change Increase Increase Increase No Change
A B C D
2
A business evaluates an investment project that has an initial outlay followed by annual net cash inflows of £10 million throughout its infinite life. The evaluation of the inflows produced a present value of £50 million and a profitability (present value) index of 2·0. What is the internal rate of return and initial outlay of this project? IRR % 20 20 40 10 Initial outlay £m 25 100 25 100
A B C D
3
Quartz plc pays an annual dividend of 30 pence per share to shareholders, which is expected to continue in perpetuity. The average rate of return for the market is 9% and the company has a beta coefficient of 1·5. The risk-free rate of return is 4%. What is the expected rate of return for the shareholders of the company and the predicted value of the shares in the company? Expected rate of return (%) 23·5 17·5 16·5 11·5 Predicted value (pence) 705 171 182 261
A B C D
3
[P.T.O.
4
Agate plc is a company that is listed on the London Stock Exchange. It intends to announce immediately a one-for-four rights issue at an issue price of £5·00. The current share price of the company is £8·00. What will be the theoretical value of the rights attached to each original share? A B C D £2·40 £1·85 £0·75 £0·60
5
Chrysotile plc has ordinary shares with a par value of £0·50 in issue. The company generated earnings per share of 45p for the financial year that has just ended. The dividend cover ratio is 2·5 times and the gross dividend yield is 2% (Ignore taxation). What is the price/earnings ratio of the company? A B C D 2·8 times 5·0 times 20·0 times 40·0 times
6
Different types of efficiency can be identified in the operation of capital markets. To which particular type of efficiency does the terms ‘weak form’, ‘semi-strong form’ and ‘strong form’ apply? A B C D Allocative efficiency Operational efficiency Information processing efficiency Economic efficiency
7
The validity of using the existing weighted average cost of capital as the appropriate discount rate for deducing the net present value of a project rests on a number of key assumptions. These include the following: 1. 2. The investment project has the same level of risk as those projects normally undertaken by the business. The investment project is small in relation to the size of the business.
Which one of the following combinations (true/false) concerning the above statements is correct? Statement A B C D 1 True True False False 2 True False True False
4
8
Tourmaline Ltd pays its major credit supplier 40 days after receiving the goods and receives no settlement discount. The supplier has recently offered the company revised credit terms of 3/10, net 40. (i.e. 3% discount allowed if payment is made within 10 days, otherwise payment in full within 40 days). If Tourmaline Ltd refuses the settlement discount and pays in full after 40 days, what is the approximate, implied, interest cost that is incurred by the company per year? A B C D 10·3% 27·4% 28·2% 37·6%
9
Gypsum plc has 20 million £0·25 ordinary shares in issue. The company has a market capitalisation of £60 million and has reported post-tax profits of £15 million for the year that has just ended. The company expects profits to rise by 20% and the dividend payout ratio is expected to be 30% in the forthcoming year. The company is committed to increasing the dividend by 4% per annum for the foreseeable future. Which one of the following is the expected rate of return from the ordinary shares? A B C D 4·1% 11·5% 13·0% 15·1%
10 Opal Ltd has 2 million £0·50 ordinary shares in issue. The company achieved the following results for the year that has just ended: Operating profit Interest payable Corporation tax Dividend payable £000 440 120 –––– 320 80 –––– 240 100 –––– 140 ––––
Kyanite plc, which operates within the same industry as Opal Ltd, has £1·00 ordinary shares in issue that have a current market price of £9·00. It has recently announced a dividend per share of £0·30. Kyanite plc maintains a constant dividend payout ratio of 40%. What is the value of each ordinary share of Opal Ltd on the basis of Kyanite plc’s price/earnings ratio? A B C D £0·84 £1·44 £1·92 £9·00
5
[P.T.O.
11 Consider the following graph: Profit
Breakeven price Premium
Exercise price Share value
Loss
Which one of the following positions is represented by the graph? A B C D Long call position Short call position Long put position Short put position
12 Galanthus plc is a recently listed company that is financed entirely by equity shares. The directors of the company wish to establish the likely beta value of the equity shares and wish to use data from Hesperis plc, a similar listed company within the same industry, to do this. Hesperis plc has an equity beta of 1·2 and is financed by 60% equity shares and 40% loan capital. The loan capital of the company can be regarded as risk-free and the rate of corporation tax is 20%. What is the estimated equity beta for Galanthus plc, based on the information above? A B C D 0·52 0·78 0·82 0·90
13 Mentha plc is financed entirely by equity and has a cost of capital of 10%. Picea plc has the same operating and risk characteristics as Mentha plc but is financed by 30% loan capital and 70% equity. The cost of the loan capital, which is risk free, is 4%. The rate of corporation tax is 20%. Using MM theory (including taxation), what is the cost of equity capital of Picea plc? A B C D 10·57% 11·44% 12·06% 21·20%
6
14 Consider the following statements concerning currency risk: 1. 2. Leading and lagging is a method of hedging transaction exposure. Matching receipts and payments is a method of hedging translation exposure.
Which of the above statements is/are true? Statement A B C D 1 True True False False 2 True False True False
15 Typha plc, a UK business, has recently sold goods to a US customer and expects to be paid $300,000 in three months’ time. Typha plc enters into a forward exchange contract to sell $300,000 in three months’ time to protect against foreign exchange risk. Exchange rates are: £/$ spot 3-months forward 1·4505–1·4545 $0·0025–0·0020 pm
What is the sterling amount that will be received by the company in three months’ time (to the nearest £)? A B C D £205,973 £206,540 £206,612 £207,182
16 The Combined Code states that each listed company should provide, within its annual report and accounts, a corporate governance report that includes: 1. 2. A brief report of the remuneration committee and its composition. A statement on relations and dialogue with investors.
Which of the following combinations is correct with regard to the above statements? Statement A B C D 1 True True False False 2 True False True False
17 Taxus plc takes out a borrower’s option on a loan for £10 million that has a notional interest period of 92 days. The business can borrow over this period at LIBOR plus 0·2%. The option has a strike rate of 5·5% and a premium of £10,000. What is the total borrowing cost for the business if LIBOR is 5·0% at the expiry date of the option? A B C D 5·3% 5·6% 5·8% 6·1%
7
[P.T.O.
18 Nicandra plc, a company that is committed to increasing shareholder wealth, holds the following European-style options at their expiry date: 1. 2. 3. A call option on a notional loan that gives the right to borrow £5 million for one year at a strike rate of 5·0%. LIBOR is 4·5% at the expiry date of the option. A put option on £500,000 in exchange for euros at an exchange rate of £1 = €1·5342. The exchange rate is £1 = €1·5154 at the expiry date of the option. A call option on 10,000 shares in Potentilla plc at an exercise price of 840p. The current share price is 820p at the expiry date of the option.
Which of the above options should be exercised and which should be allowed to lapse at their expiry date? Option 2 Exercise Lapse Exercise Exercise
A B C D
1 Lapse Lapse Exercise Lapse
3 Exercise Exercise Lapse Lapse
19 Mazus plc has an outstanding loan for £15 million with a floating rate of interest of LIBOR + 1·0%, which is payable annually. The company wishes to protect itself against possible fluctuations in interest rates and so, for the next interest period, the company has taken a LIBOR cap at 6% per year for a premium of 0·5% per year. In addition, it has arranged to sell a LIBOR floor at 4·5% interest per year for a premium of 0·2% per year. If the LIBOR rate is 7·6% for the next interest period, what will be the effective interest rate paid by Mazus plc? A B C D 5·8% 7·3% 7·5% 8·9%
20 Consider the following statements concerning forward rate agreements (FRAs): 1. 2. 3. 4. FRAs FRAs FRAs FRAs cannot be tailored to the specific requirements of a customer. are binding agreements that must be settled at the settlement date. do not require any payments or receipts until the settlement date. can be resold in the secondary market.
Which of the above statements are correct? A B C D 1 and 2 1, 2 and 4 2 and 3 2, 3 and 4 (40 marks)
8
Section B – Candidates MUST attempt ONE question from Section B, ONE question from Section C and ONE further question from either Section B or Section C. 1 Galena plc owns an open-cast coal mine in Wales that was purchased from the UK government in 1992. In recent years, the performance of the mine has been badly affected by a decline in demand for coal and also by cheap imports. Mining engineers employed by the company believe that the mine could be operated for another four years before coal supplies finally run out. If the mine is operated during this period, the following financial results are expected: Year Operating profit (loss) Interest payable Net profit (loss) for the year 1 £m 54 (11) ––– 43 ––– ––– 2 £m (46) (11) ––– (57) ––– ––– 3 £m (15) (11) ––– (26) ––– ––– 4 £m 22 (11) ––– 11 ––– –––
The following additional information is available: (i) (ii) (iii) (iv) (v) The machinery and equipment at the mine cost £18·0 million and have a written down value of £8·0 million. The machinery and equipment will be sold at the end of the four-year period for an estimated £2·0 million. A depreciation charge for the machinery and equipment of £1·5 million per year and an amortisation charge for depletion of the mine of £4·0 million per year are included in the above calculations. The working capital tied up in the mine is £3·6 million and this can be liquidated immediately the company discontinues its operations. Redundancy payments to employees will amount to £2·2 million if the company operates the mine for a further four years and employees are released at the end of this period. The company has agreed with the UK government to fill in the mine and build a community centre in the area in five years’ time. This is estimated to cost £2·5 million and this commitment will not be affected by any decisions concerning the future of the mine.
The company has been approached by a miners’ co-operative, consisting of employees of the mine. The co-operative has offered to lease the mine for the remaining four years of its life at a lease rental of £6·0 million per year, payable at the end of each year. The co-operative has also offered to buy the existing machinery and equipment from the company for £5·0 million immediately if a lease agreement can be reached. It has also offered to make a contribution of £1·5 million towards the cost of building the community centre in five years’ time. No other parties have declared an interest in taking over the mining operations. If the company agrees to lease the mine, and thereby discontinue operations, it will have to make redundancy payments of £3·4 million immediately. Galena plc has a cost of capital of 10%. Ignore taxation. Required: (a) Calculate the incremental cash flows arising from a decision to continue operations for a further four years rather than to lease the mine to the miners’ co-operative. (12 marks) (b) Calculate the net present value of continuing operations for a further four years rather than leasing the mine to the miners’ co-operative. (3 marks) (c) State whether or not the company should continue to operate the mine. You should clearly state your reasons and any key assumptions that you have made in arriving at your decision. (5 marks) (20 marks)
9
[P.T.O.
2
Olivine plc is a holiday tour operator that is committed to a policy of expansion. The company has enjoyed record growth in recent years and is now seeking to acquire other companies in order to maintain its growth momentum. It has recently taken an interest in Halite plc, a charter airline business, as the Board of Directors of Olivine plc believes that there is a good strategic fit between the two companies. Both companies have the same level of risk. Abbreviated financial statements relating to each company are set out below. Abbreviated profit and loss account for the year ended 30 November 2003 Olivine plc Halite plc £m £m Sales 182·6 75·2 ––––– –––– ––––– –––– Operating profit 43·6 21·4 Interest charges 12·3 10·2 ––––– –––– Net profit before taxation 31·3 11·2 Corporation tax 6·3 1·6 ––––– –––– Net profit after taxation 25·0 9·6 Dividends 6·0 4·0 ––––– –––– Retained profits for the year 19·0 5·6 ––––– –––– ––––– –––– Balance sheets as at 30 November 2003 Olivine plc Halite plc £m £m Fixed assets 135·4 127·2 Net current assets 65·2 3·2 ––––– ––––– 200·6 130·4 Creditors due after more than one year 120·5 104·8 ––––– ––––– 80·1 25·6 ––––– ––––– ––––– ––––– Capital and reserves £0·50 ordinary shares 20·0 8·0 Retained profit 60·1 17·6 ––––– –––– 80·1 25·6 ––––– –––– Price/earnings ratio before the bid 20 15 The Board of Directors of Olivine plc is considering making an offer to the shareholders of Halite plc of five shares in Olivine plc for every four shares held. It is believed that a rationalisation of administrative functions arising from the merger would reap after tax benefits of £2·4m. Required: (a) Calculate: (i) the total value of the proposed offer; (ii) the earnings per share of Olivine plc following the successful acquisition of Halite plc; (iii) the share price of Olivine plc following acquisition, assuming that the benefits of the acquisition are achieved and that the price/earnings ratio declines by 5%. (10 marks) (b) Calculate the effect of the proposed takeover on the wealth of the shareholders of each company. (5 marks) (c) Comment on your results in (a) and (b) above and state what recommendations, if any, you would make to the directors of Olivine plc. (5 marks) (20 marks)
10
3
Fluorspar plc manufactures motor parts for a range of leading motor-car companies. It has recently appointed a new Finance Director who has concluded that the business does not exert sufficient control over its stocks. Within the first few weeks of taking up the new job, she found evidence of both overstocking and understocking of many items. She has decided to bring the matter to the attention of the Board of Directors as she believes that they are not fully aware of the cost of these stock control problems. She believes that the longer term solution to these problems is to adopt a just-in-time approach for many items. However, in the short term she has started to implement stock management models to help minimise costs. As a starting point, the company has implemented the Economic Order Quantity model to the management of its stock of exhaust pipes. Although this has already proved beneficial, the business has now received an offer from a supplier of one particular type of exhaust pipe. The supplier has offered Fluorspar plc a discount of 2·5% on the cost of each exhaust pipe for order sizes of 200 or more and a discount of 4% for order sizes of 400 or more. Each exhaust pipe costs £60 to purchase and the cost of holding one exhaust pipe in stock is estimated at £80 per year. The ordering cost is £50 and the annual sales demand is 8,000 exhaust pipes, which accrues evenly over the year. Required: (a) Identify and discuss the types of cost that may be incurred by the business when holding: (i) too much stock; and (ii) too little stock; and state whether these costs are likely to be captured by traditional financial reporting systems. (6 marks) (b) Discuss the arguments for and against the implementation of a just-in-time approach to stock management as a solution to the problems of the business. (6 marks) (c) Calculate the appropriate order size for the exhaust pipes that will minimise the total annual costs associated with the purchase of this item. (8 marks) (20 marks)
11
[P.T.O.
Section C – Candidates MUST attempt ONE question from Section B, ONE question from Section C and ONE further question from either Section B or Section C. 4 Malva plc is a large manufacturer of motor vehicle components. In recent years, the business has embarked on a policy of expansion and now requires additional loan capital of £100 million, over a ten-year period, in order to build and equip a new factory. The financing policy of the company is to borrow at both fixed and floating rates of interest and to use interest rate swaps to obtain the required interest rate profile. The company enjoys a good credit rating and can raise fixed rate loan capital at 6·0% and floating rate loan capital at LIBOR plus 0·5% from its bank. Malva plc wishes to raise long-term, floating rate finance and is considering a ten-year swap arrangement to help achieve this. A swap bank has been approached and the bank has identified another company, Genista plc, as a potential counterparty to the agreement. Genista plc is a large chemical company that has a reasonable credit rating. It can raise fixed interest loan capital at 7·8% and floating rate loan capital at LIBOR plus 1·2% from its bank. The swap bank is prepared to arrange the swap agreement and to act as guarantor for both parties for a total fee of 0·2%. The two parties to the agreement will pay to, or receive from, the swap bank a fixed amount and will receive, or pay, LIBOR in return. The Finance Director of Malva plc is prepared to undertake the swap arrangement providing that it will lead to annual savings of at least 0·4% and the Finance Director of Genista plc is prepared to undertake the swap agreement providing it will lead to savings of at least 0·5%. LIBOR is 6·2%. Required: (a) Show, with calculations, how a swap arrangement can be devised that will meet the requirements of both companies. (4 marks) (b) Provide an analysis of the interest cost payments and receipts of Malva plc and Genista plc in the first year assuming the swap arrangement goes ahead. (6 marks) (c) Evaluate the swap arrangement from the perspective of each company if LIBOR increased by 1·4% at the beginning of the second year of the agreement and stayed at this higher rate for the remainder of the swap period. (4 marks) (d) Briefly discuss the advantages and disadvantages of interest rate swaps. (6 marks) (20 marks)
12
5
Dryas plc operates in a mature, low-risk industry and has had a stable level of profits for many years. Profits after tax for the current year were £120 million and this level of profit is expected to continue in the future providing the current dividend/retention policy is maintained. The company adopts a dividend policy based on a dividend payout ratio of 80% and it has just paid a dividend for the year that has recently ended. However, a newly-appointed Chief Executive is considering three new investment strategies. Whilst these strategies will have the same initial investment, they will require different levels of future investment but will lead to different future growth rates. The Board of Directors has agreed that if any one of the three new strategies is decided upon the future investment required will be financed entirely from retained earnings rather than any new issue of equity. This will entail a reduction in future dividends. Alternatively, the business can continue its current strategy of high dividend and no growth. The Board has arranged to meet again in the near future to decide whether to support one of the proposed strategies or whether to continue with the existing strategy of high dividend payments and no growth. The following figures, which relate to the proposed strategies, will be presented to the Board at this meeting: Strategy Dividend payout ratio % 10 30 60 Growth rate in profits % 8 5 3 Required return by shareholders % 12 10 9
1 2 3
The cost of ordinary share capital for the company is currently 8·0%. Required: (a) State, with supporting calculations, what recommendation you would make concerning the proposed strategies. (9 marks) (b) Explain why the proposed change in dividend policy is likely to be regarded as important by shareholders. (7 marks) (c) Briefly explain why a company may prefer to fund investment projects by the use of retained profits rather than by the issue of new equity shares. (4 marks) (20 marks)
6
Nerium Engineering plc is a recently-listed company that has just appointed a new, non-executive director to its main board of directors. At the first board meeting that the non-executive director attended, he was asked to become a member of the audit committee. This committee has only just been established and its terms of reference have yet to be finally agreed. The non-executive director is unsure what such a role might involve and, as a qualified engineer without a detailed understanding of finance, he is also unsure as to whether he is the right person for such a committee. He has, therefore, written to you for advice. Required: Write a report to the non-executive director setting out the possible role and responsibilities of the audit committee and the main qualities that a member of such a committee should possess. (20 marks)
End of Question Paper
13
|
https://www.scribd.com/document/15725477/Dec-2003-Qns-Mod-B
|
CC-MAIN-2018-47
|
refinedweb
| 4,128
| 57.1
|
i tried to create a dll using c# and now i have something like this
I have 5 files Extension.cs, Encryption.cs, MySQLQuery.cs, etc.
and in my MySQLQuery file i have somthing like this
using System; using System.Data; using System.Text; using MySql.Data.MySqlClient; namespace gLibrary { public class MySQLQuery { protected internal static string connectionString; public class ConnectionString { public string temp { get; set; } public static void Default(string ConnectionString) { connectionString = ConnectionString; } public static void dispose() { connectionString = null; } } public class ExequteQuery { //Some code here... } //and so on... } }
now i import it then i try to access like this
using gLibrary.MySQLQuery;
but i got an error
but when i tried something like this
using gLibrary;
and accessing like this
MySQLQuery.somefuntion();
it works perfectly but what i want to accomplish is to have something like this
Using gLibrary.MySQLQuery; namespace something { class something { //then i want to access it like this somefunction(); } }
i hope someone can help me with this, actually i already done it with vb.net but i cant implement to c#
i will appreciate for any help
|
https://www.daniweb.com/programming/software-development/threads/435035/creating-dll-using-c
|
CC-MAIN-2017-09
|
refinedweb
| 182
| 55.74
|
TeseoLiv3F Module¶
This module implements the Zerynth driver for the STM Teseo Liv3F
Teseo(ifc, mode=SERIAL, baud=9600, clock=400000, addr=0x00)¶
Creates an intance of TeseoLiv3F.
Example:
from teseoliv3f import TeseoLiv3F ... gnss = TeseoLiv3F.TeseoLiv3F(SERIAL1) gnss.start() mpl.init() alt = mpl.get_alt() pres = mpl.get_pres()
stop()¶
Stop the TeseoLiv3F by putting it into backup mode. It can be restarted only by setting the FORCE_ON pin to high. Refer to the Teseo Liv3F documentation for details here
pause()¶
Stop the Teseo Liv3F by putting it into standby mode. It can be restarted by calling resume. Refer to the Teseo Liv3F documentation for details here
resume()¶
Wake up the Teseo Liv3F from standby mode. Refer to the Teseo Liv3F documentation for details here
set_rate(rate=1000)¶
Set the frequency for location fix (100-10000 milliseconds is the available range).
fix()¶
Return the current fix or None if no fix no UTC time is available. A UTC time is a tuple of (yyyy,MM,dd,hh,mm,ss,microseconds).
UTC time can be wrong if no fix has ever been obtained.
|
https://docs.zerynth.com/latest/official/lib.stm.teseoliv3f/docs/official_lib.stm.teseoliv3f_teseoliv3f.html
|
CC-MAIN-2020-24
|
refinedweb
| 180
| 67.45
|
As with so many things these days, it starts with clickbait.
“17 tricks to running a digital agency” was, for the most part, the same kind of unremarkable listicle that surfaces on Twitter from time to time. You know the sort – it keeps things light, you chuckle at a few zingers about office-dogs, exposed piping and wall-mounted fixies. You hit retweet and carry on with the day. This time though, there was one section that stood out to me. On naming your agency, it read:
Just pick a random word or two, and go with that
Could it really be that simple? Let’s find out.
Striking the right tone. permalink
Random is a pretty strong word.
Think about the web agencies that you admire. The best names might seem random but usually carry some extra weight or depth behind them. This is all perhaps quite obvious, but it pokes an immediate flaw in our meme-ified advice. How can our choice be random, but still retain some deeper meaning?
Fortunately for our soon-to-be-industry-leading web agency, there’s a whole branch of machine learning that can help us automate exactly this kind of problem: Natural Language Processing.
An introduction to NLP. permalink
Natural Language Processing, or NLP, is all about training computers to process and understand human languages. At this point you might be thinking that teaching language to humans is already pretty difficult and, honestly, you wouldn’t be wrong. NLP is a really dense topic, but building even the smallest NLP applications can feel hugely empowering.
That said, NLP tutorials have a tendency to get very technical, very quickly and they often assume that anyone entering the field is coming armed with a dual-PhD in linguistics and computer science. On top of that, NLP and machine learning are often cushioned by a thick layer of marketing BS that makes it hard to separate reality from building SkyNet. It’s clear that NLP is an exciting topic but, for newcomers, all of the above means that it isn’t always clear what you might actually want to do with it.
In this tutorial, we’re going to start slow and ease into a few core NLP concepts. We’ll write a short script to ‘borrow’ the tone of voice from other agencies that we like. We’ll do this by scraping their websites and plucking a list of nouns and adjectives from the text content. Finally, as the original meme suggested, we’ll randomly mash some of those words together to generate a few names for our awesome new web agency.
Pre-requisites and setup. permalink
Python is considered to be the de facto place to start for natural language processing and to generate our agency name, we’re going to need Python 3.7. We’ll also need to manage our dependencies with a Pipfile (for the JavaScript fluent amongst you: think package.json). For that, we’re also going to need pipenv.
If you’re new to Python, then you can install everything you need with the brilliant Hitchhiker’s guide. Once you have installed Python itself, the guide has a handy page explaining how to install pipenv. This tutorial will assume some knowledge of Python syntax, but I’ll keep the code as simple as possible.
With everything installed, create a project directory and we’re ready to get going.
Before we can process any text content, we first need to find a suitable a body of text. In NLP terminology this input text is known as our ‘corpus‘.
In our case, we want to grab our text content from other web agencies that we admire, so we can kick things off by writing a function to grab text content from a remote url. Fortunately the Beautiful Soup package helps us to do this.
Let’s install Beautiful Soup, and the HTML5 library to our project dependencies. Open the project directory in your terminal and run:
pipenv install bs4 html5lib
Next, create a file called
main.py with the following contents:
import requests
from bs4 import BeautifulSoup, Comment
def read_urls(urls):
content_string = ''
for page in urls:
print(f'Scraping URL: {page}')
scrape = requests.get(page).content
soup = BeautifulSoup(scrape, "html5lib")
for script_tag in soup.find_all('script'):
script_tag.extract()
for style_tag in soup.find_all('style'):
style_tag.extract()
for comment in soup(text=lambda text: isinstance(text, Comment)):
comment.extract()
text = ''.join(soup.findAll(text=True))
content_string += text
return content_string
You don’t need to worry too much about the specific code of the function above, but it goes as follows: It read a list of URLs, making a request to each before parsing the content with BeautifulSoup. The scraped markup needs to be tidied up a bit though, so next it removes any comments, script or style tags before pulling out the remaining text content and appending it to a string. When every URL in the list has been scraped, the string is returned as our corpus.
Now we have our corpus, we can start to process it.
SpaCy bills itself as ‘Industrial-strength Natural Language Processing in Python’. Whereas packages like NLTK offer immense amounts of flexibility and configuration, the flipside is a steep learning curve. SpaCy on the other hand, can be set up and ready to go in minutes.
We need to add SpaCy to our project as a dependency. Open your project directory in your terminal and run:
pipenv install spacy
SpaCy doesn’t do much by itself though – it needs a pre-trained language model to work with. Fortunately several are available out of the box. We’ll also install the standard english model and save it to our Pipfile:
pipenv install
With our dependencies installed, let’s get back into the code. Open up
main.py and add SpaCy to our imports at the top:
import requests
from bs4 import BeautifulSoup, Comment
import en_core_web_sm
Next, underneath our
read_urls function, we can define a new function to allow SpaCy to parse the corpus.
def get_tokens(corpus):
nlp = en_core_web_sm.load()
return nlp(corpus)
Notice the name of our function,
get_tokens. What’s that all about?
Parts of Speech and Tokenization. permalink
Most languages divide their words up into different categories. These usually comprise nouns, verbs, adjectives, adverbs and more. In linguistic terms, these categories are known as ‘parts of speech’, or POS. This is important to us as, to generate our agency name, we want to single out nouns and adjectives. But how can we get at them?
One place to start would be to break each sentence up into its individual parts but this isn’t a straightforward as using
String split(). We need a way to intelligently divide our text, whilst retaining the individual purpose of each word. Doing this manually would be too time consuming, so this is where machine learning becomes necessary. Most NLP libraries use trained language data to intelligently scan, compare and identify the characteristics of each word. Once identified, these words are separated out into ‘tokens’. This process is known as tokenization and is one of the most important core principles of NLP.
Our
get_tokens function tokenizes our corpus. Or, in simpler terms, SpaCy reads over the corpus, splits out individual words and returns a list of tokens. In creating that list, SpaCy also adds a lot of extra information to each extracted word, such as its relationship to other words in the sentence or which part of speech it is. We can use those attributes to filter the list down to find a specific part of speech.
Let’s create another function:
def get_word_list(tokens, part_of_speech):
list_of_words = [
word.text.capitalize()
for word in tokens
if word.pos_ == part_of_speech
]
unique_list = set(list_of_words)
return list(unique_list)
This function receives the list of tokens, a part of speech code, and then filters the results using a list comprehension (again, for JS developers, a list comprehension is a bit like a cross between
Array.map and
Array.filter). To break this list comprehension down, it’s best to work from the inside out – For every word in our tokens list, we grab
word.text and capitalise it, but only if the part of speech (
word.pos_) matches our POS code parameter. You can find a full list of these POS codes in the SpaCy POS documentation. If you’re curious about what other attributes might be available on each token, you can read the Token reference.
Lastly, we can filter out any duplicated words by casting the results to a
set(). We’ll need to perform some list actions later though, so it is cast back to a list before being returned.
This is all looking great and we can now use this function to create a list of nouns, adjectives, verbs or adverbs. There’s a slight problem though – if you were to use this function as-is, you might find that the list of words you get back is a bit of a mess.
Most languages have a set of core words that occur frequently. In English, this might be words like “the”, “at”, “from”, “in”, “for” and so on. Whilst these words are useful for humans, they can quite quickly get in the way extracting meaning with NLP. As a result, it’s common to filter them out and these kinds of words are known as stop words.
Our script is no different and the stop words need to go. Whilst we’re here, we can also get rid of any rogue punctuation. Fortunately SpaCy tokens have two handy attributes that allow us to do this – the aptly named
is_stop and
is_punct. Let’s update the list comprehension in our
get_word_data function:
list_of_words = [
word.text.capitalize()
for word in tokens
if word.pos_ == part_of_speech
and not word.is_stop
and not word.is_punct
]
Now we can extract a nice sanitised list of words, but there’s a tiny bit more optimisation that we can do.
Let’s say you’ve scraped your website content and in amongst your list of tokens are the words “goes”, “going”, “went” and “gone”. That’s quite a few words to express the same base idea. We can make this simpler.
These words could all be lumped together under the core concept: “go”. In linguistic terms, we call this a word’s ‘lemma‘ or the uninflected root form of a word.
The simplest way to think of a lemma is to see it as what you might look for in a dictionary:
Out of the box, SpaCy provides a convenient means to convert any matched term back to its lemma. This is called lemmatization. Let’s hone our list of tokens down into a much tighter list of core ideas by updating our list comprehension. We’ll change the first line to call
.lemma_ instead of
.text.
Your final
get_word_list function should look like this:
def get_word_list(tokens, part_of_speech):
list_of_words = [
word.lemma_.capitalize()
for word in tokens
if word.pos_ == part_of_speech
and not word.is_stop
and not word.is_punct
]
unique_list = set(list_of_words)
return list(unique_list)
Bringing it all together. permalink
Now we’ve set up a few functions and we’ve covered the core concepts, let’s pull everything together. To generate the final name, we’re going to need to be able to make random selections from our word lists. At the top of
main.py, add
random to your imports.
import requests
from bs4 import BeautifulSoup, Comment
import en_core_web_sm
import random
At the end of the file, underneath your
get_word_list function, paste the following:
CORPUS = read_urls([
'',
'',
''
])
TOKENS = get_tokens(CORPUS)
nouns = get_word_list(TOKENS, "NOUN")
adjectives = get_word_list(TOKENS, "ADJ")
list_of_combos = set(
[
f'{random.choice(adjectives)} {random.choice(nouns)}'
if random.choice([True, False]) is True
else random.choice(nouns)
for x in range(500)
]
)
output_file = open("./output.txt", 'w')
for item in list_of_combos:
output_file.write(f'{item}rn')
Let’s break that code down.
First of all, we pass a list of URLs into our
read_urls function and store the result in a constant for later. Be sure to change the example URLs to your own choices here, and remember: the more text on your chosen pages, the better your results will be.
Next, we pass the corpus into our
get_tokens function. This is where SpaCy does its magic, tokenizing the corpus and returning a list of data-rich tokens.
To generate our agency name, we want some random nouns. Nouns by themselves aren’t much fun, so we’ll grab some adjectives too. This uses the
get_word_list function we created earlier. The first argument is the list of tokens, and the second filters by a ‘part of speech code‘.
Now we have our nouns and adjectives lists we can prep our final list of names. We want to generate a list of names – let’s say 500 of them. We can use another list comprehension to do this.
Remember the random library we imported above? It gives us access to the
random.choice function. As the name implies, it allows us to randomly choose a single item from a list.
random.choice also gives us a handy way to embed a 50/50 chance into our comprehension. Here, an if-else means each iteration of our loop will return either an adjective-noun combo or a single noun. Finally, with the comprehension complete, we wrap the list in
set() to ensure that we only have unique results.
Ok, everything is ready. At the very end we create a file called
output.txt, loop through our list of names and write each to a new line.
And…we’re done! If you need to, you can double check your code against the final source on github.
Generate the name. permalink
It’s time to fire up the final script and generate some names. At your terminal, run the following command:
pipenv run python main.py
If all goes well, you should have now a file named
output.txt chock full of multi-award-winning agency names.
And the winner is…. permalink
“Just pick a random word or two and go with that”. So, after all this, what name did I go with?
Well, I had some real gems: Loaf, Strategic Bear, Rise, Chaotic Rest, Bold Tomorrow. After a few minutes crawling through the output list though, I spotted the one.
Exciting, yet confident. Like a life-raft in a sea of comedic nonsense:
Ok, I get it. Like most clickbait, this might not have been a completely satisfying ending. Hopefully though, you’ve learned a little about the potential application of even the most superficial Natural Language Processing scripts.
To recap, in this introduction, we’ve used and learned about:
- Corpus: The body of text to be processed
- Parts of speech: The name given to the categories of words comprising nouns, verbs, adjectives etc.
- Tokenization: The act of splitting sentences into individual words, or tokens
- Stop words: Small, frequently occurring words that we do not wish to include in our results i.e. “the”, “for”, “it” etc.
- Lemmatization: Changing a word back to its root concept, or dictionary form i.e. the lemma of “best” or “better” is “good”
From these core concepts, the possibilities are vast. Imagine going into a pitch having scanned the client’s website in advance to profile exactly how they talk about themselves. Or perhaps you could take the jump into sentiment analysis to scan how well received a particular topic is on Twitter. There’s still a lot to learn but, with these core building blocks, you’re on your way.
If you enjoyed this article and have any ideas on how to extend this example, or if you generated a particularly badass name, then please let me know on Twitter.
If you’re looking to learn more about NLP, I strongly recommend the Advanced NLP with SpaCy course by Ines Montani – it’s free, and really rather good.
|
https://hackerworld.co/how-to-name-your-agency-with-nlp
|
CC-MAIN-2021-04
|
refinedweb
| 2,660
| 73.47
|
While reviewing the source code for CoffeeScript on Github, I noticed that most, if not all, of the modules are defined as follows:
(function() { ... }).call(this);
This pattern looks like it wraps the entire module in an anonymous function and calls itself.
What are the pros (and cons) of this approach? Are there other ways to accomplish the same goals?
Harmen's answer is quite good, but let me elaborate a bit on where this is done by the CoffeeScript compiler and why.
When you compile something with
coffee -c foo.coffee, you will always get a
foo.js that looks like this:
(function() { ... }).call(this);
Why is that? Well, suppose you put an assignment like
x = 'stringy string'
in
foo.coffee. When it sees that, the compiler asks: Does
x already exist in this scope, or an outer scope? If not, it puts a
var x declaration at the top of that scope in the JavaScript output.
Now suppose you write
x = 42
in
bar.coffee, compile both, and concatenate
foo.js with
bar.js for deployment. You'll get
(function() { var x; x = 'stringy string'; ... }).call(this); (function() { var x; x = 42; ... }).call(this);
So the
x in
foo.coffee and the
x in
bar.coffee are totally isolated from one another. This is an important part of CoffeeScript: Variables never leak from one .coffee file to another unless explicitly exported (by being attached to a shared global, or to
exports in Node.js).
You can override this by using the
-b ("bare") flag to
coffee, but this should only be used in very special cases. If you used it with the above example, the output you'd get would be
var x; x = 'stringy string'; ... var x; x = 42; ...
This could have dire consequences. To test this yourself, try adding
setTimeout (-> alert x), 1 in
foo.coffee. And note that you don't have to concatenate the two JS files yourself—if you use two separate
<script> tags to include them on a page, they still effectively run as one file.
By isolating the scopes of different modules, the CoffeeScript compiler saves you from the headache of worrying whether different files in your project might use the same local variable names. This is common practice in the JavaScript world (see, for instance, the jQuery source, or just about any jQuery plugin)—CoffeeScript just takes care of it for you.
The good thing about this approach is that it creates private variables, so there won't be any conflict with variable names:
(function() { var privateVar = 'test'; alert(privateVar); // test })(); alert(typeof privateVar); // undefined
The addition of
.call(this) makes the
this keyword refer to the same value as it referred to outside the function. If it is not added, the
this keyword will automatically refer to the global object.
A small example to show the difference follows:
function coffee(){ this.val = 'test'; this.module = (function(){ return this.val; }).call(this); } var instance = new coffee(); alert(instance.module); // test function coffee(){ this.val = 'test'; this.module = (function(){ return this.val; })(); } var instance = new coffee(); alert(typeof instance.module); // undefined
This is similar syntax to this:
(function() { }());
which is called an immediate function. the function is defined and executed immediately. the pros to this is that you can place all of your code inside this block, and assign the function to a single global variable, thus reducing global namespace pollution. it provides a nice contained scope within the function.
This is the typical pattern i use when writing a module:
var MY_MODULE = (function() { //local variables var variable1, variable2, _self = {}, etc // public API _self = { someMethod: function () { } } return _self; }());
not sure what the cons might be exactly, if someone else knows of any i would be happy to learn about them.
|
https://javascriptinfo.com/view/63426/pattern-for-coffeescript-modules-duplicate
|
CC-MAIN-2020-45
|
refinedweb
| 629
| 75.61
|
Clarification needed for simple_calendar sort_by method
Hi Chris,
I've seen
simple_calendar ruby gem and i stuck at sort_by method (calendar.rb)
def events_for_date(current_date) if events.any? && events.first.respond_to?(:simple_calendar_start_time) events.select do |e| current_date == e.send(:simple_calendar_start_time).in_time_zone(@timezone).to_date end.sort_by(&:simple_calendar_start_time) else events end end
May be its stupid question or i dont know and i also tried tracing using pry for this method but i cannot understand how here sort_by works ..! Do you mind give me some idea on this how
events are sorting here.
The
&:symbol syntax basically just turns a method name into a block to call. What it is doing is sorting the array of events by the
simple_calendar_start_time column. First we select out the ones for the day in the select block and then we sort by the start time so that all the events are filtered and in order.
That make more sense?
|
https://gorails.com/forum/clarification-needed-for-simple_calendar-sort_by-method
|
CC-MAIN-2021-17
|
refinedweb
| 154
| 55.84
|
Hi,
I am trying to pass CAMUsename and CAMPassword in the URL and getting the prompt page (default.html) instead and the values are unable to pass into the input fields. Here is the url I have:∾tion=run&ui_navbar=false&ui_appbar=false&ui_CAMUsername=_CAMPassword=
Works perfectly good in Cognos 10.x versions, but not working in Cognos 11.0.10. Need Help on fixing this issue.
Thank you
Answer by 10EJ_Andreas_Weber (56) | Aug 12 at 05:18 AM
please use the following guide to allow the CAM Parameters to be used in Cognos Analytics:
This should resolve it.
Thank you very much.
Kind regards Andreas Weber
Answer by Ted123 (18) | Aug 14 at 11:23 AM
Thank you for sharing the link. I tried to set namespace, CAMUsername and CAMPassword to true it has been set and now I am able to run the report without prompting for authentication.
Thank you,
Regards, Ted123
136 people are following this question.
Cognos Analytics and Metric Server configuration on single machine 2 Answers
My Parameters 1 Answer
Is there any web page to find a Cognos version shipped with a specific TCR version? 1 Answer
Has this issue been resolved? 1 Answer
Cognos Analytics report link (default action URL in C10.x) after upgrade 0 Answers
|
https://developer.ibm.com/answers/questions/464156/cognos-11010-unable-to-pass-camusername-and-campas.html
|
CC-MAIN-2018-43
|
refinedweb
| 214
| 65.52
|
plotting from a string
I have a string from a textfield that I want to input as the math function. How do I take this string and allow the plot function to recognize it as a math expression?
t = arange(0.0, 2.0, 0.01) s = self.tf.text #text coming in from textfield is: 'sin(2*pi*t)' plt.plot(t, s)
Just to verify, the program works by setting s = to the function:
t = arange(0.0, 2.0, 0.01) s = sin(2*pi*t) plt.plot(t, s)
Try:
s = eval(self.tf.text)however, be warned that
Eval really is dangerous.
I'll keep the UI part out of this to make the code simpler, but here's a start:
from numpy import arange import matplotlib.pyplot as plt from math import * x_values = arange(0.0, 2.0, 0.01) s = 'sin(2*pi*t)' y_values = [eval(s, globals(), {'t': t}) for t in x_values] plt.plot(x_values, y_values) plt.show()
The basic idea is to create a list (
y_values) by evaluating your string as a Python expression once for each element in
x_values.
Thank you. I like dangerous.
|
https://forum.omz-software.com/topic/1923/plotting-from-a-string
|
CC-MAIN-2021-49
|
refinedweb
| 195
| 77.03
|
Since the advent of the modern web, performance has been a key consideration when designing a website or a web app. When a website requires no server interaction whatsoever, what is hosted on the web is served to a user as is, this is referred to as a static site.
In this post, we will simply be explaining the basics of Gatsby.js and build out a simple static blog in the process. The Blog will be deployed to the web using Netlify. Blog posts will be written in Markdown and GraphQL will be used to query markdown data into the blog. The final product will look like this:
Table of Contents
What is a Static Site?
A static site is a site which contains fixed content. In several use cases including event listings, portfolio pages and blogs, static sites are preferred to dynamic websites (requiring client-server interaction) because of challenges including slow load-time, security flaws, and hosting costs amongst others. The absence of a server mitigates these risks. Static Site Generators are tools used develop static sites, effectively and efficiently. Recently the use of static sites is on the rise and various tools and technologies such as Metalsmith, Jekyll, and Gatsby are taking center stage.
Introducing Gatsby.js
Gatsby is simply a robust and fast static site generator which uses React.js to render static content on the web. Content is written as React components and is rendered at build time to the DOM as static HTML, CSS and JavaScript files. By default, Gatsby builds a PWA. Like most static site generators, Gatsby requires plugins to either extend its functionality or modify existing functionality.
Gatsby is said to be robust in a way that the static content rendered can be sourced from a large number of sources and formats including markdown, CSV and from CMS like Wordpress and Drupal. All that is required are plugins to handle the data transformation. Plugins in Gatsby are of three categories.
- Functional Plugins: These plugins simply extend the ability of Gatsby. An example is the gatsby-plugin-react-helmet which allows the manipulation of the Head of our document.
- Source Plugins: This plugin ‘finds’ files in a Gatsby project and creates File Nodes for each of this files, these files can then be manipulated by transformer plugins. An example is the gatsby-source-filesystem which ‘sources’ files in the filesystem of a Gatsby project and creates File Nodes containing information about the file.
- Transformer Plugins: Like we saw earlier, data in Gatsby can come from multiple sources and transformer plugins are responsible for converting these files to formats recognizable by Gatsby. An example is the gatsby-transformer-remark plugin which converts Markdown File Nodes from the filesystem into MarkdownRemark which can be utilized by Gatsby. Other plugins exist for various data sources and you can find them here.
Prerequisites
To build out this blog, knowledge of HTML, CSS, and JavaScript is required with a focus on ES6 Syntax and JavaScript Classes. Basic knowledge of React and GraphQL is also of advantage.
Installation
Since this is a node.js project, Node and its package manager NPM are required. Verify if they are installed on your machine by checking the current version of both tools with:
node -v && npm -v
Else, install Node from here.
Gatsby offers a powerful CLI tool for a faster build of static sites. The Gatsby CLI installs packages known as ‘starters’. These starters come as pre-packaged projects with essential files to speed up the development process of the static site. Install the Gatsby CLI with:
npm install -g gatsby-cli
This installs the CLI tool, then proceed to create a new project with the Gatsby default starter.
gatsby new scotch-blog
This should take a while as the tool downloads the starter and runs
npm install to install all dependencies.
Once the installation is complete change directory to the project folder and start the development server with:
cd scotch-blog && gatsby develop
This starts a local server on port 8000.
The web page looks like:
Gatsby’s default starter comes with all essential files we require for development. You can find other starters here and even create or contribute to a starter.
For a simple blog all we require are:
- Have a blog homepage.
- Write blog posts in markdown.
- Display blog post titles on the homepage.
- View each blog post on a separate page.
For these, we will require the three plugins we stated earlier to which will manipulate the
<head /> element of our blog, source markdown files and transform markdown files respectively. All styling will be done via external CSS files and in-line component styling in React, however, several other methods of styling Gatsby documents exist such as CSS modules, typography.js, and CSS-in-JS. You can read more about them here.
Install required plugins with:
npm install --save gatsby-transformer-remark gatsby-source-filesystem
Note: The gatsby-plugin-react-helmet comes preinstalled with the default Gatsby starter
Configure Plugins Before we go ahead to create pages, let’s configure the installed plugins. Navigate to gatsby-config.js in the root directory of your project and edit it to:
module.exports = { siteMetadata: { title: 'The Gray Web Blog', }, plugins: [ 'gatsby-plugin-react-helmet', 'gatsby-transformer-remark', { resolve: `gatsby-source-filesystem`, options:{ name: `src`, path: `${__dirname}/src/` } }, ], };
Gatsby runs the gatsby-config.js during build and implements all installed plugins. One great thing about Gatsby is that it comes with a hot reload feature so changes made on the source files are immediately visible on the website rendered.
Note the siteMetadata in the gatsby-config module, this can be used to set the value of any element dynamically using GraphQL, for instance - document title and page title.
Layout
One key design feature considered during development is the layout of pages. This consist of any element we would like to be consistent across all pages. They include headers, footers, navbars e.t.c. For our blog, the default Gatsby starter provides a default layout which is found in
src/layouts. To make some changes to the header, edit the index.js file in layouts. first import all required dependencies with:
import React from 'react' import PropTypes from 'prop-types' import Helmet from 'react-helmet' import Header from '../components/Header' import './index.css'
Note the imported CSS file. Gatsby supports the use of external stylesheets to style React components.
Edit the React component to:
const TemplateWrapper = ({ children }) => ( <div> <Helmet title="The Gray Web Blog" meta={[ { name: 'description', content: 'Sample' }, { name: 'keywords', content: 'sample, something' }, ]} /> <Header /> <div style={{ margin: '0 auto', maxWidth: 960, padding: '0px 1.0875rem 1.45rem', paddingTop: 0, }} > {children()} </div> </div> ) TemplateWrapper.propTypes = { children: PropTypes.func, } export default TemplateWrapper
<Helmet/> is a component provided by the react-helmet plugin shipped originally with Gatsby’s default starter. A
Header component is imported and the
div to contain all page elements is styled in-line. Gatsby offers the flexibility of creating custom components in react and these components can as well be stateful or stateless. We will stick to using stateless components in this tutorial, like the
<Header/> component.
Navigate to the header component in
src/components/header/index.js edit it to:
const Header = () => ( <div style={{ background: 'black', marginBottom: '1.45rem', marginTop:'0px', display:'block', boxShadow:'0px 0px 7px black', }} > <div style={{ margin: '0 auto', maxWidth: 960, padding: '1.45rem 1.0875rem', }} > <h1 style={{ margin: 0, textAlign:'center' }}> <Link to="/" style={{ color: 'white', textDecoration: 'none', }} > The Gray Web Blog </Link> </h1> </div> </div> ) export default Header
We simply made some changes to the styling by changing the background color of the header and aligning the header text to the center.
So far we have created the layout of the blog, how about we do some cool stuff by creating blog posts and displaying them on the home page.
Create Blog Posts
Blog posts are created in markdown as earlier stated. In
src, create a folder titled
blog-posts. This will house all blog posts to be served. Create three sample markdown files with titles. We have:
basic-web-development.md
--- title: "Basic Web Development" date: "2018-01-01" author: "Chris Ashî" ---.
in-the-beginning.md
--- title: "The Beginning of The Web" date: "2018-01-10" author: "Chuloo Will" ---. - Wikipedia
and
vue-centered.md
--- title: "Common Vue.js" date: "2017-12-05" author: "Alex Chî" --- Vue.js (commonly referred to as Vue; pronounced /vjuː/, like view) is an open-source progressive JavaScript framework for building user interfaces.[4] Integration into projects that use other JavaScript libraries is made easy with Vue because it is designed to be incrementally adoptable. Vue can also function as a web application framework capable of powering advanced single-page applications. - Wikipedia
The texts between the triple dashes are known as frontmatter and provide basic information about the markdown post. We have our markdown post, to render this data, we would employ GraphQL.
Querying Posts with GraphQL
GraphQL is a powerful yet simple query language. Since its introduction, it is fast gaining popularity and has become a widely used means of consuming data in React. Gatsby ships with GraphQL by default. Since we have previously installed the
gatsby-source-filesystem plugin, all files can be queried with GraphQL and are visible as File Nodes.
GraphQL also comes with an important tool called GraphiQL an IDE with which we visualize and manipulate our data before passing it to React components. GraphiQL is available on while the Gatsby server is running. Open up GraphiQL on that address to visualize data.
Run the query to see all files in
/src/.
{ allFile { edges { node { id } } } }
This returns a list of all files in our
src directory as we already specified that when configuring the
gatsby-source-filesystem in the gatsby-config.js file. We have all the files in our source folder but we need only the markdown files and their accompanying data like frontmatter and size. The
gatsby-transformer-remark plugin earlier installed comes in handy now.
The plugin transforms all markdown file nodes into MarkdownRemark nodes which can be queried for their content.
Run this query in GraphiQL to fetch all MarkdownRemark nodes and usable data in them.
{ allMarkdownRemark { totalCount edges { node { frontmatter { title date author } excerpt timeToRead } } } }
Running this query in GraphiQL will return a list of all markdown files and their corresponding data in a JSON object as requested. To pass this data to our page component, navigate to index.js in
src/pages which holds the homepage. First, import all required dependencies as well as external stylesheets with:
import React from 'react' import Link from 'gatsby-link' import './index.css' ...
Create and export an IndexPage stateless component and pass the data object to it as an argument:
const IndexPage = ({data}) => { console.log(data) return( <div> {data.allMarkdownRemark.edges.map(({node}) => ( <div key={node.id} <h3 className="title">{node.frontmatter.title}</h3> <p className="author">{node.frontmatter.author}</p> <p className="date">{node.frontmatter.date} {node.timeToRead}min read</p> <p className="excerpt">{node.excerpt}</p> </div> ))} </div> ) } export default IndexPage
The
.map() method is used to traverse the data object for data to be passed to the components elements. We passed the title, author, date, time to read and excerpt to various JSX elements. We still haven’t queried this data. After the export statement create a GraphQL query with:
export const query = graphql` query HomePageQuery{ allMarkdownRemark(sort: {fields: [frontmatter___date], order: DESC}) { totalCount edges { node { frontmatter { title date author } excerpt timeToRead } } } } `
The
sort query is used to sort articles by date in an ascending order so we have the earliest article on top.
In
src/pages/, create the CSS file imported with:
.article-box{ margin-bottom: 1.5em; padding: 2em; box-shadow: 0px 0px 6px grey; font-family: 'Helvetica'; } .title{ font-size: 2em; color: grey; margin-bottom: 0px; } .author, .date{ margin:0px; } .date{ color: rgb(165, 164, 164); } .excerpt{ margin-top: 0.6em; }
Restart the development server and we have:
Alas, we have an awesome blog page with details and excerpt from the post content. We need to view each blog post on a separate page, let’s do that next.
Creating Blog Pages
This is just about the best part of building out this blog, but also a bit complex. We could actually create individual pages in
src/pages, pass the markdown content to the document body and link the pages to the blog titles but that would be grossly inefficient. We would be creating these pages automatically from any markdown post in
src/blog-posts.
To accomplish this, we will require two important APIs which ship with Gatsby and they are:
- onCreateNode
- createPages
We will simply be creating a ‘path’ otherwise known as ‘slug’ for each page and then creating the page itself from its slug. APIs in Gatsby are utilized by exporting a function from the Gatsby-node.js file in our root directory.
In Gatsby-node.js, export the
onCreateNode function and create the file path from each File node with:
const { createFilePath } = require(`gatsby-source-filesystem`) exports.onCreateNode = ({ node, getNode, boundActionCreators }) => { const { createNodeField } = boundActionCreators if (node.internal.type === `MarkdownRemark`) { const slug = createFilePath({ node, getNode, basePath: `pages` }) createNodeField({ node, name: `slug`, value: slug, }) } } ...
The
createFilePath function ships with the
gatsby-source-filesystem and enables us to create a file path from the File nodes in our project. First, a conditional statement is used to filter only the markdown file nodes, while the
createFilePath creates the slug for each File node. The
createNodeField function from the API adds the slug as a field to each file node, in this case, Markdown File nodes. This new field created(slug) can then be queried with GraphQL.
While we have a path to our page, we don’t have the page yet. To create the pages, export the
createPages API which returns a Promise on execution.
const path = require(`path`) ... exports.createPages = ({ graphql, boundActionCreators }) => { const { createPage } = boundActionCreators return new Promise((resolve, reject) => { graphql(` { allMarkdownRemark { edges { node { fields { slug } } } } } `).then(result => { result.data.allMarkdownRemark.edges.forEach(({ node }) => { createPage({ path: node.fields.slug, component: path.resolve(`./src/templates/posts.js`), context: { slug: node.fields.slug, }, }) }) resolve() }) }) }
In the
createPages API, a promise is returned which fetches the slugs created using a GrphQL query and then resolves to create a page with each slug. The
createPage method, creates a page with the specified path, component, and context. The path is the slug created, the component is the React component to be rendered and the context holds variables which will be available on the page if queried in GraphQL.
Creating The Blog Template
To create the blog template, navigate to
/src/ and create a folder called templates with a file named posts.js in it. In post.js, import all dependencies and export a functional component with:
import React from "react"; export default ({ data }) => { const post = data.markdownRemark; return ( <div> <h1>{post.frontmatter.title}</h1> <h4 style={{color: 'rgb(165, 164, 164)'}}>{post.frontmatter.author} <span style={{fontSize: '0.8em'}}> -{post.frontmatter.date}</span></h4> <div dangerouslySetInnerHTML = {{ __html: post.html }}/> </div> ); };
You can see GraphQL data already being consumed, query the data using GraphQL with:
export const query = graphql` query PostQuery($slug: String!) { markdownRemark(fields: { slug: { eq: $slug } }) { html frontmatter { title author date } } } `;
We have our blog pages and the content. Lastly, link the post titles in the homepage to their respective pages. In
src/pages/index.js, edit the post title header to include the link to the post content:
... <Link to={node.fields.slug} style={{textDecoration: 'none', color: 'inherit'}}><h3 className="title">{node.frontmatter.title}</h3></Link> ...
Since we require data on the slug, edit the GraphQL query to include the slug:
export const query = graphql` query HomePageQuery{ allMarkdownRemark(sort: {fields: [frontmatter___date], order: DESC}) { totalCount edges { node { fields{ slug } frontmatter { title date author } excerpt timeToRead } } } } `
Yikes, our static blog is ready, restart the development server and we have:
Running
Gatsby build will create a production build of your site in the public directory with static HTML files and JavaScript bundles.
Deploy Blog to Netlify
So far we have built out a simple static blog with blog content and pages. It will be deployed using Netlify and Github for continuous deployment. Netlify offers a free tier which allows you deploy static sites on the web.
Note: Pushing code to Github and deploying to Netlify from Github ensures that once a change is made to the repository on Github, the updated code is served by Netlify on build.
Create an account with Github and Netlify. In Github, create an empty repository and push all files from your project folder to the repository.
Netlify offers a login option with Github. Log into Netlify with your Github account or create a new account with Netlify. Click the ‘New site from Git’ button and select your Git provider.
Github is the chosen Git Provider in this case.
Select Github and choose the repository you wish to deploy, in this case, the repository for the static blog. Next, specify the branch to deploy from, build command, and publish directory.
Click the ‘Deploy site’ Button to deploy the static site. This may take few minutes to deploy after which the static site is deployed to a Netlify sub-domain. Here is the demo of the static blog built earlier..
Conclusion
In this post, you have been introduced to building a static site with Gatsby which utilizes React components to generate static content on build. Gatsby offers a robust approach to static site generation with the ability to parse data from various sources with the help of plugins. The static site was also deployed to the web using Netlify. Feel free to try out other amazing features of Gatsby including the various styling techniques as well. Comments and suggestions are welcome and you can make contributions to the source code here.
|
https://scotch.io/tutorials/zero-to-deploy-a-practical-guide-to-static-sites-with-gatsbyjs
|
CC-MAIN-2018-22
|
refinedweb
| 2,978
| 56.25
|
Hide Forgot
A flaw was found in the Linux kernel ext4 filesystem. An out-of-bound access is possible in the ext4_ext_drop_refs() function when operating on a crafted ext4 filesystem image.
A flaw was found in Linux kernel ext4 filesystem. An out-of-bound access is possible in the ext4_ext_drop_refs() function when operating on a crafted ext4 filesystem image.
References:
An upstream patch:
Created kernel tracking bugs for this issue:
Affects: fedora-all [bug 1596797]
This is fixed for Fedora with the 4.17.6 stable kernel update
Notes:
While the flaw reproducer works when run as a privileged user (the "root"), this requires a mount of a certain filesystem image. An unprivileged attacker cannot do this even from a user+mount namespace:
$ unshare -U -r -m
# mount -t ext4-2018:2948
|
https://bugzilla.redhat.com/show_bug.cgi?id=CVE-2018-10877
|
CC-MAIN-2019-26
|
refinedweb
| 132
| 53.81
|
(A/F,i,N)
(A/F,r,T)
(A/G,i,N)
arithmetic gradientto annuity conversionfactor
(A/P,i,N)
(A/P,r;T)
(F/A,i,N)
(F/A,r,T)
continuous uniformseries compound amountfactor
(F/P,i,N)
(P/A,g,i,N)
geometric gradient topresent worth conversionfactor
(P/A,i,N)
(P/A,r,T)
(P/F,i,N)
A \-
tot
A'
AHP
AW
annual worth
BCR
benefit-cost ratio
BCRM
BVJn)
CCA
CI
consistency index
D (n)
DM
db
a column vector[111 . . . 1 1 1 ]
EAC
ERR
E(X)
MARR
MAUT
FW
future worth
MCDM
multi-criterion decisionmaking
interest amount
PCM
PW
present worth
p(x)
probability distribution
Is
Pr{X=.v,}
alternative expression ofprobability distribution
IRR
Ro.\
actual dollar I R R
real dollar M A R R
IRRR
i*
RI
random index
salvage value
TBF
tax rate
ucc
random variable
an eigenvector
number of subperiods ina period
m i n i m u m acceptable rateof return
an eigenvalue
actual dollar M A R R
^01
max
FOURTH
EDITION
^^J^J^^JEJ^^^^^i
ENGINEERINGECONOMICS
University of Waterloo
PEARSON
Toronto
T A 1 7 7 . 4 . F 7 2 5 2008
658.15
C2008-903776-6
12 11 1 0 0 9 08
CHAPTER 1
E n g i n e e r i n g Decision M a k i n g
CHAPTER 2
CHAPTER 3
1844
Appendix 3A
Appendix 3B
CHAPTER 4Appendix 4ACHAPTER 5Appendix 5ACHAPTER 6
C o m p a r i s o n M e t h o d s Part 1
R e p l a c e m e n t Decisions
CHAPTER 8
Taxes
CHAPTER 9Appendix 9A
123
126
161
D e p r e c i a t i o n and F i n a n c i a l A c c o u n t i n g
CHAPTER 7
Appendix 8A
86
171
220
266
304
306
C o m p u t i n g a Price Index
339
CHAPTER 10
CHAPTER 11
D e a l i n g w i t h U n c e r t a i n t y : S e n s i t i v i t y Analysis
CHAPTER 12
D e a l i n g w i t h Risk: P r o b a b i l i t y A n a l y s i s
CHAPTER 13
Q u a l i t a t i v e C o n s i d e r a t i o n s a n d M u l t i p l e Criteria
Appendix 13A
79
83
343
386
420472
500
APPENDIX A
APPENDIX B
APPENDIX C
505
529
547
APPENDIX D
Glossary
570
Index
577
565
ContentsPreface
xiii
1.1
1.2
What Is E n g i n e e r i n g Economics?
1.3
M a k i n g Decisions
23
1.4
D e a l i n g With A b s t r a c t i o n s
1.5
68
10
1.6
Uncertainty. S e n s i t i v i t y A n a l y s i s , a n d Currencies
1.7
Problems
16
18
2.1
Introduction
2.2
19
20
2.3
C o m p o u n d a n d S i m p l e Interest
2.4
2.5
Continuous Compounding
2.6
Cash Flow D i a g r a m s
2.7
Equivalence
2.7.1
2224
27
28
31
Mathematical Equivalence
2.7.2
Decisional Equivalence
2.7.3
Market Equivalence
Review Problems
Summary
32
33
37
Engineering Economics in Action, Part 2B: You Just Have to Know When
13
14
11
12
38
43
viii
CONTENTS
44
45
3.1
3.2
T i m i n g of Cash Flows a n d M o d e l l i n g
3.3
3.4
4546
3.5
3.6
56
3.7
59
60
3.9
6365
66
69
70
77
CHAPTER4
87
4.2
Relations A m o n g Projects
4.3
4.4
87899192
4.4.1
4.4.2
4.4.3
Projects
95
4.4.4
96
Payback Period
Review ProblemsSummary
102
105
109
CHAPTER 5
110
Appendix 4A
4.1
4.5
47
49
3.8
46
122
C o m p a r i s o n Methods Part 2
5.1
5.2
5.3
I n t e r n a l Rate of Return C o m p a r i s o n s
127127130
127
98
92
5.3.1
130
132
137
139
140
5.4.1
152153
154
CHAPTER6
160
Depreciation and F i n a n c i a l A c c o u n t i n g
6.2
6.2.1
172173
6 . 2 . 2 \ alue of an Asset
173
6 . 2 . 3 Straight-Line Depreciation
774
6 . 2 . 4 Declining-Balance DepreciationE l e m e n t s of F i n a n c i a l A c c o u n t i n g
6.3.1
176
179
180
185
199
200
187'
188
195
172
6.1
6.3
147
149
143
Replacement Decisions
215
7.1
7.2
A R e p l a c e m e n t Example
221222
7.3
Reasons for R e p l a c e m e n t or R e t i r e m e n t
7.4
226
225
221
213
187
7.5
Defender a n d C h a l l e n g e r Are I d e n t i c a l
227
7.6
7.6.1
7.7
7.6.2
7.6.3
234
238240
244
245
246
264
267
8.1
8.2
8.4
B e f o r e - a n d After-Tax MARR
8.5
269270271
8.5.1
8.5.2
272
8.5.3
273
8.6
8.7
IRR Tax C a l c u l a t i o n s
8.8
274
275
277
8.7.1
8.7.2
8.8.2
UK Tax Calculations
281
8.8.3
US Tax Calculations
284
8.8.4
Review ProblemsSummary294
277279
279
288
290
CHAPTER 9
294
295
303
Inflation
268
8.3
9.1
9.2
M e a s u r i n g t h e I n f l a t i o n Rate
307308
231233
308
307
2T7
235
9.3
Economic E v a l u a t i o n With I n f l a t i o n
9.3.19.4
310
326
327
313
313315
317
323
C h a p t e r 10
338
1 0 . 2 M a r k e t Failure
346
34".
344
348350
351
352
353
35".
362
364
369
384
D e a l i n g With U n c e r t a i n t y : S e n s i t i v i t y A n a l y s i s
387
370
3 53
Break-Even A n a l y s i s
388391
398
400
Summary403Problems404Engineering Economics in Action, Part 11B: Where the Risks Lie
404
392394
414
417
12.1
12.2
Basic Concepts of P r o b a b i l i t y
12.3
R a n d o m Variables and P r o b a b i l i t y D i s t r i b u t i o n s
421
421422
420
Decision Criteria
423
430
433
Monte Carlo S i m u l a t i o n
440
1 2 . 7 A p p l i c a t i o n IssuesReview ProblemsSummary
447
448
457
441
442
458
Q u a l i t a t i v e C o n s i d e r a t i o n s and M u l t i p l e Criteria
13.1
13.2
Efticiency
13.3
Decision Matrixes
473
475
477481
481
486
472
Review ProblemsSummary489
470
490
498
Appendix A
Appendix B
Appendix C
GlossaryIndex
Appendix D
PrefaceCourses on engineering economics are found in engineering curricula throughout theworld. T h e courses generally deal with deciding among alternative engineering projectswith respect to expected costs and benefits. For example, in Canada, the CanadianEngineering Accreditation Board requires that all accredited professional engineeringprograms provide studies in engineering economics. Many engineers have found that acourse in engineering economics can be as useful in their practice as any of their moretechnical courses.There are several stages to making a good decision. One stage is being able to determine whether a solution to a problem is technically feasible. This is one of the roles ofthe engineer, who has specialized training to make such technical judgments. Anotherstage is deciding which of several technically feasible alternatives is best. Decidinga m o n g alternatives often does not r e q u i r e the technical c o m p e t e n c e needed todetermine which alternatives are feasible, but it is equally important in making the finalchoice. Some engineers have found that choosing among alternatives can be moredifficult than deciding what alternatives exist.T h e role of engineers in society is changing. In the past, engineers tended to have afairly narrow focus, concentrating on the technical aspects of a problem and on strictlycomputational aspects of e n g i n e e r i n g economics. As a result, many e n g i n e e r i n geconomics texts focused on the mathematics of the subject. Today, engineers are morelikely to be the decision makers, and they need to be able to take into account strategicand policy issues.Society has changed in other ways in recent years. In particular, the world has becomemore interlinked. An engineer may be trained in one part of the world and end up practising somewhere completely different. T h e mathematics of engineering economics, like allof an engineer's technical skills, is the same everywhere.This book is designed for teaching a course on engineering economics to matchengineering practice today. It recognizes the role of the engineer as a decision makerwho has to make and defend sensible decisions. Such decisions must not only take intoaccount a correct assessment of costs and benefits; they must also reflect an understanding of the environment in which the decisions are made.This book is a direct descendant of a book entitled Engineering Economics in Canada,and in some senses is the fourth edition of that book. But given the increasing globalization of many engineering activities, the title and the contents have been updated. This isappropriate because the contents are applicable to engineers everywhere. For Canadianusers of the previous editions, this text retains all of the valued features that made it yourtext of choice. For new users, it is a proven text that can support a course taughtanywhere in the world.This book also relates to students' everyday lives. In addition to examples and problemswith an engineering focus, there are a number that involve decisions that many studentsmight face, such as renting an apartment, getting a job, or buying a car.
xiv
PREFACE
C o n t e n t and O r g a n i z a t i o nBecause the mathematics of finance has not changed dramatically over the past numberof years, there is a natural order to the course material. Nevertheless, a modern view ofthe role of the engineer flavours this entire book and provides a new, balanced exposureto the subject.Chapter 1 frames the problem of engineering decision making as one involvingmany issues. Manipulating the cash flows associated with an engineering project is animportant process for which useful mathematical tools exist. These tools form the bulkof the remaining chapters. However, throughout the text, students are kept aware ofthe fact that the eventual decision depends not only on the cash flows, but also on lesseasily quantifiable considerations of business policy, social responsibility , and ethics.Chapters 2 and 3 present tools for manipulating monetary values over time. Chapters4 and 5 show how the students can use their knowledge of manipulating cash flows tomake comparisons among alternative engineering projects. Chapter 6 provides an understanding of the environment in which the decisions are made by examining depreciationand the role it plays in the financial functioning of a company and in financial accounting.Chapter 7 deals with the analysis of replacement decisions. Chapters 8 and 9 are concerned with taxes and inflation, which affect decisions based on cash flows. Chapter 10provides an introduction to public-sector decision making.Most engineering projects involve estimating future cash flows as well as otherproject characteristics. Since estimates can be in error and the future unknown, it isimportant for engineers to take uncertainty and risk into account as completely as possible. Chapter 11 deals with uncertainty, with a focus on sensitivity analysis. Chapter 12deals with risk, using some of the tools of probability analysis.Chapter 13 picks up an important thread running throughout the book: a goodengineering decision cannot be based only on selecting the least-cost alternative. T h eincreasing influence on decision making of health and safety issues, environmentalresponsibility and human relations, among others, makes it necessary for the engineerto understand some of the basic principles of multi-criterion decision making.7
New to This E d i t i o nIn addition to clarifying explanations, improving readability, updating material, and correcting errors, we have made the following important changes for this new global edition: Throughout the text, the context of the examples and problems has been changedfrom a Canadian orientation to a global environment. Similarly, the currencies usedvaryabout 60% of the examples use dollars (Australian, Canadian, or American) andother currencies such as euros or pounds make up the remainder of the examples. Chapter 8 has been completely rewritten to demonstrate the impact of taxes onengineering decisions independent of the tax regime involved. Detailed examples aregiven for Australia, Canada, the United Kingdom, and the United States. About half of the Mini-Cases, which supplement the chapter material with a realworld example, have been replaced to address issues from around the world. T h e Net Value boxes, which provide chapter-specific examples of how the internetcan be used as a source of information and guidance for decision making, have beenupdated to highlight the global perspective of the book. In many cases, web addressesspecific to countries around the world are provided.
xv
A new M o r e Challenging Problem has been added to each chapter. These arethought-provoking questions that encourage students to stretch their understandingof the subject matter. Additional Problems for Chapters 2-13, with selected solutions, are presented inthe Student C D - R O M that accompanies this book. Students can use those problems for more practice. And instructors can use those problems whose solutions areprovided only in the Instructor's Solutions Manual for assignments.
ecial
Features
We have created special features for this book in order to facilitate the learning of thematerial and an understanding of its applications. Engineering Economics in Action boxes near the beginning and end of eachchapter recount the fictional experiences of a young engineer. T h e s e vignettesreflect and support the chapter material. T h e first box in each chapter usuallyportrays one of the characters trying to deal with a practical problem. T h e secondbox demonstrates how the character has solved the problem by applying materialdiscussed in the chapter. All of these vignettes are linked to form a narrative thatruns throughout the book. T h e main character is Naomi, a recent engineeringgraduate. In the first chapter, she starts her job in the engineering department atGlobal Widget Industries and is given a decision problem by her supervisor. Overthe course of the book, Xaomi learns about engineering economics on the job as thestudents learn from the book. T h e r e are several characters, who relate to oneanother in various ways, exposing the students to practical, ethical, and social issuesas well as mathematical problems.
Close-Up boxes in the chapters present additional material about concepts that areimportant but not essential to the chapter.
CLOSE-UP 6.1
D e p r e c i a t i o n Methods
Method
Description
Straight-line
TheeachTheeach
Declining-balance
Sum-of-the-years'-digits
Double-declining-balance
150%-declining-balance
Units-of-production
In each chapter, a Net Value box provides a chapter-specific example of how theinternet can be used as a source of information and guidance for decision making.
Securities RegulatorsCountries that trade in corporate stocks and bonds(collectively called securities) g e n e r a l l y have aregnlatorv bodv to protect investors, ensure thattrading is fair and orderlv, and facilitate the acquisition of capital bv businesses.In C a n a d a , the C a n a d i a n SecuritiesAdministrators (CSA) coordinates regulatorsfrom each of Canada's provinces and territories,and also educates Canadians about the securitiesindustry, the stock markets, and how to protectinvestors from scams bv providing a variety ofeducational materials on securities and investing.
At the end of each chapter, a Mini-Case, complete with discussion questions, relatesinteresting stories about how familiar companies have used engineering economicprinciples in practice, or how engineering economics principles can help us understandbroader real-world issues.
M I N I - C A S E
XVii
6 . 1
B u s i n e s s E x p e n s e OR C a p i t a l E x p e n d i t u r e ?From the Stabroek Xr^s (Guyana), September 15, 2007:Commissioner-General of the Guyana Revenue Authority (GRA), Khurshid Sattaur, saysthat the GRA has developed an extra-statutory ruling to allow for the depreciation of software over a two-vear period.A release from the Office of the Commissioner-General yesterday quoted Sattaur as sayingthat "the Revenue Authority for the purposes of Section 17 of the Income Tix Act Chapter 81:01and the Income The (Depreciate Rates) Regulation 1992 as amended by the Income (Depreciate Rates)(Amendments) 1999 allow wear and tear at a rate of 50% per annum."He noted that while Guyanas income tax laws adequately provide tor the depreciation ofcomputer equipment (hardware) for 50% write-off over two years, the law does not makeprovision for software.According to Sattaur, the G R \ feels that businesses have been taking advantage of theinadequate provisions in the law and have been treating the software as an expense to bewritten off in the first year or in the year of acquisition.Therefore, the release stated, the G R \ is allowing wear and tear on website developmentcosts and software, whether or not they form part of the installed software over a two-year period.Discussion
Calculating depreciation is made difficult by many factors. First, the value of an assetcan change over time in m a n y complicated ways. Age, wear and tear, and functionalchanges all have their effects, and are often unpredictable. A 30-year old VW Beetle,for example, can suddenlv increase in value because a new Beetle is introduced by the
Two Extended Cases are provided, one directly following Chapter 6 and the otherdirectly following Chapter 11. T h e y concern complex situations that incorporatemuch of the material in the preceding chapters. Unlike chapter examples, which areusually directed at a particular concept being taught, the Extended Cases require thestudents to integrate what they have learned over a number of chapters. They can beused for assignments, class discussions, or independent study.
EXTENDED
CASE:
PART
A.l IntroductionC l e m l o o k e d u p f r o m his c o m p u t e r a s N a o m iwalked into his office. "Hi, X a o m i . Sit down. Justlet me save this stuff.".After a few seconds C l e m turned around, showing a grin. "I'm w o r k i n g on o u r report for the lastquarters operations. T h i n g s went pretty well. Weexceeded our targets on defect reductions and onreducing overtime. And we shipped even-thingrequiredover 9 0 % o n t i m e . "X a o m i caught a bit of C l e m s exuberance."Sounds like a report vou don't mind w r i t i n e . "" l e a h , w e l l , it w a s a t e a m j o b . E v e r y o n e didgood work. Talking about doing good work, Ishould have told y o u this before, but I didn't thinkabout it at the right time. Ed Burns and AnnaKulkowski were really impressed with the reportyou did on the forge project."X a o m i leaned forward. "But the)' didn't followmv recommendation to get a new manna! forgingpress. I assumed there was something w r o n g withwhat I did."
Dave S u l l i v a n c a m e i n w i t h I o n ? s t r i d e s a n ddropped into a chair. "Good morning, evervbodv Itis still morning", barely. S o n y to be late. Y\"hats up?"C l e m looked at Dave and started talking."WTiats up is this. I want you and X a o m i to lookinto our policy about buying or making small alum i n u m parts. We now use about 200 000 pieces am o n t h . .Most of these, like bolts and sleeves, arecold-formed." P r a b h a V a i d y a n a t h a n has just d o n e a m a r k e tp r o j e c t i o n for u s . If she's right, o u r d e m a n d forthese parts will continue to grow. Unfortunately,she wasn't very precise about the rate of g r o w t h .H e r e s t i m a t e was for a n y t h i n g b e t w e e n 5 % and1 5 % a year. We n o w contract this w o r k out. Buteven if growth is onlv 5%, we mav be at the levelw h e r e i t p a y s for u s t o s t a r t d o i n g t h i s w o r kourselves."\bu r e m e m b e r we had a couple of e n g i n e e r sfrom H a m i l t o n Tools looking over o u r processeslast weekr Well, they've come back to us with anoffer to sell us a cold-former. T h e y have two possibilities. One is a high-volume iob that is a version
xviii
Course DesignsThis book is ideal for a one-term course, but with supplemental material it can also beused for a two-term course. It is intended to meet the needs of students in all engineering programs, including, but not limited to, aeronautical, chemical, computer, electrical,industrial, mechanical, mining, and systems engineering. Certain programs emphasizingpublic projects may wish to supplement Chapter 10, "Public Sector Decision Making,"with additional material.A course based on this book can be taught in the first, second, third, or fourth yearof an engineering program. T h e book is also suitable for college technology programs.No more than high school mathematics is required for a course based on this text. T h eprobability theory required to understand and apply the tools of risk analysis isprovided in Chapter 12. Prior knowledge of calculus or linear algebra is not needed,except for working through the appendix to Chapter 13.This book is also suitable for self-study by a practitioner or anybody interested inthe economic aspects of decision making. It is easy to read and self-contained, withmany clear examples. It can serve as a permanent resource for practising engineers oranyone involved in decision making.
xix
AcknowledgmentsT h e authors wish to acknowledge the contributions of a number of individuals whoassisted in the development of this text. First and foremost are the hundreds ofengineering students at the University of W aterloo who have provided us with feedbackon passages they found hard to understand, typographical errors, and examples that theythought could be improved. There are too many individuals to name in person, but weare very thankful to each of them for their patience and diligence.Converting a text with a very Canadian focus to one that has a global perspectiverequired myriad changes to place names, currencies, and so forth. Peggv Fraser was veryhelpful in making sure that every detail was taken care of, with the able assistance ofAndrea Forwell.Other individuals who have contributed strongly to previous editions of the bookinclude Irwin Bernhardt, Peter Chapman, David Fuller, J . B . Moore, T i m Nye, RonPelot, Victor Y\ aese, and Yuri Yevdokimov.During the development process for the new edition, Pearson Education Canadaarranged for the anonymous review of parts of the manuscript by a number of verv ablereviewers. These reviews were extremely beneficial to us, and many of the best ideas incorporated in the final text originated with these reviewers. We can now thank them bv name:Karen Bradbury, University of WarwickEric Croiset, University of Waterloo
XX
PearsonEducationCanada
The Pearson
Education
G r e a t
Way
Canada
to
W E B S I T !
L e a r n
a n d
Instruct
O n l i n e
The Pearson Education Canada Companion Website is easy to na\igate and is organizedto correspond to the chapters in this textbook. Whether you are a student in the classroomor a distance learner you will discover helpful resources for in-depth study and researchthat empower you in your quest for greater knowledge and maximize your potential for
CompanionWebsite
w w w . p e a r s o n e d . c a / f r a s e r
PrenticeHall| JUMP
tO...
CompanionGlobal
P ^G^G
Website
Engineering
Economics:
Financial
Decision
Making
for
Engineers,
STUDENT RESOURCES
The modules in this section provide students with tools for learning course material.These modules include: Multiple Choice Quizzes Spreadsheets Glossary Flashcards Weblinks Interest TablesIn the quiz modules students can send answers to the grader and receive instantfeedback on their progress through the Results Reporter. Coaching comments andreferences to the textbook may be available to ensure that students take advantageof all available resources to enhance their learning experience.
COMPANION
C H A P T E R
EngineeringDecision^MakingEngineering Economics in Action, Part 1A: Naomi Arrives
Making Decisions
CHAPTER
financial constraints on the problem, particularly if resources are very limited. In addition,an engineering project can meet all other criteria, but may cause detrimental environmentaleffects. Finally, any project can be affected by social and political constraints. For example, alarge irrigation project called the Garrison Diversion Unit in North Dakota was effectivelycancelled because of political action bv Canadians and environmental groups, even thoughover S2 000 000 000 had been spent.Engineers today must make decisions in an extremely complex environment. The heartof an engineer's skill set is still technical competence in a particular field. This permits thedetermination of possible solutions to a problem. However, necessary to all engineering isthe ability to choose among several technically feasible solutions and to defend that choicecredibly. The skills permitting the selection of a good choice are common to all engineersand, for the most part, are independent of which engineering field is involved. These skillsform the discipline of engineering economics.
however, companies are global, manufactured goods have components made in differentcountries, the environmental consequences of engineering decisions extend across countriesand continents, and engineers may find themselves working anywhere in the world.Consequently, the modern practice of engineering economics must include the ability towork in different currencies, under varying rates of inflation and different tax regimes.
Making DecisionsAll decisions, except perhaps the most routine and automatic ones or those that areinstitutionalized in large organizations, are made, in the end, on the basis of belief asopposed to logic. People, even highly trained engineers, do what feels like the right thing todo. This is not to suggest that one should trust only one's intuition and not one's intellect,but rather to point out something true about human nature and the function of engineeringeconomics studies.Figure 1.1 is a useful illustration of how decisions are made. At the top of the pyramidare preferences, which directly control the choices made. Preferences are the beliefs aboutwhat is best, and are often hard to explain coherently They sometimes have an emotionalbasis and include criteria and issues that are difficult to verbalize.The next tier is composed of politics and people. Politics in this context means the use ofpower (intentional or not) in organizations. For example, if the owner of a factory has astrong opinion that automation is important, this has a great effect on engineering decisionson the plant floor. Similarly, an influential personality can affect decision making. It's difficultto make a decision without the support, either real or imagined, of other people. Thissupport can be manipulated, for example, by a persuasive salesperson or a persistent lobbyist.Support might just be a general understanding communicated through subtle messages.The next tier is a collection of "facts." T h e facts, which may or may not be valid orverifiable, contribute to the politics and the people, and indirectly to the preferences. At
the bottom of the pyramid are the activities that contribute to the facts. These include thehistory of previous similar decisions, statistics of various sorts, and, among other things, adetermination of costs.In this view of decisions, engineering economics is not very important. It deals essentially with facts and, in particular, with determining costs. Many other facts affect the finaldecision, and even then the decision may be made on the basis of politics, personality, orunstated preferences. However, this is an extreme view.Although preferences, politics, and people can outweigh facts, usually the relationship is the other way around. T h e facts tend to control the politics, the people, andthe preferences. It is facts that allow an individual to develop a strong opinion, whichthen may be used to influence others. Facts accumulated over time create intuitionand experience that control our "gut feeling" about a decision. Facts, and particularlythe activities that develop the facts, form the foundation for the pyramid in Figure 1.1.Without the foundation, the pyramid would collapse.Engineering economics is important because it facilitates the establishment ofverifiable facts about a decision. T h e facts are important and necessary for the decisionto be made. However, the decision eventually made may be contrary to that suggestedby analysis. For example, a study of several methods of treating effluent might determinethat method A is most efficient and moderatelv priced, but method B might in fact bechosen because it requires a visible change to the plant which, it is felt, will contribute tothe company's image in environmental issues. Such a final decision is appropriatebecause it takes into account facts bevond those dealt with in the economic analvsis.
F i g u r e 1.2
Analysis
useful and appropriate for a given purpose. Once the model is developed, it is used toanalyze a situation, and perhaps make some predictions about the real world. The analysisand the predictions are then related back to the real world to make sure the model is valid.As a result, the model might need some modification, so that it more accurately reflectsthe relevant features of the real world.The process illustrated in Figure 1.2 is exacdy what is done in engineering economics.The model is often a mathematical one that simplifies a more complicated situation, butdoes so in a reasonable way. The analysis of the model provides some information, such aswhich solution to a problem is cheapest. This information must always be related back to thereal problem, however, to take into account the aspects of the real world that may have beenignored in the original modelling effort. For example, the economic model might not haveincluded taxes or inflation, and an examination of the result might suggest that taxes andinflation should not be ignored. Or, as already pointed out, environmental, political, or otherconsiderations might modify any conclusions drawn from the mathematical model.E X A M P L E
Naomi's brother Ben has been given a one-year assignment in Alaska, and he wants tobuy a car just for the time he is there. He has three choices, as illustrated in Table 1.1. Foreach alternative, there is a purchase price, an operating cost (including gas, insurance, andrepairs), and an estimated resale value at the end of the year. Which should Ben buy?Table
Buying a Car
1968 CorvettePurchaseOperationResale
S12 000$200/monthS13 000
2001
BiVIW
5-Series
$20 000$150/month$20 000
T h e next few chapters of this book will show how to take the information fromTable 1.1 and determine which alternative is economically best. As it turns out, undermost circumstances, the Corvette is best. However, in constructing a model of the decision, we must make a number of important assumptions.
For example, how can one be sure of the resale value of something until one actually triesto sell it? Along the same lines, who can tell what the actual maintenance costs will be? Thereis a lot of uncertainty about future events that is generally ignored in these kinds of calculations. Despite this uncertainty, estimates can provide insights into the appropriate decision.Another problem for Ben is getting the money to buy a car. Ben is fairly young, andwould find it very difficult to raise even S7000, perhaps impossible to raise S20 000. T h eCorvette might be the best value, but if the money isn't available to take advantage ofthe opportunity it doesn't matter. In order to do an economic analysis, we may assumethat he has the money available.If an economic model is judged appropriate, does that mean Ben should buy theCorvette? Maybe not.A person who has to drive to work every morning would probably not want to drivean antique car. It is too important that the car be reliable (especially in Alaska in thewinter). T h e operating costs for the Corvette are high, reflecting the need for moremaintenance than with the other cars, and there are indirect effects of low reliability thatare hard to capture in dollars.If Ben were very tall, he would be extremely uncomfortable in the compact ToyotaCorolla, so that, even if it were economically best, he would hesitate to resign himself todriving with his knees on either side of the steering wheel.Ben might have strong feelings about the environmental record of one of the carmanufacturers, and might want to avoid driving that car as a way of making a statement.Clearly, there are so many intangibles involved in a decision like this that it isimpossible for anyone but Ben himself to make such a personal choice. An outsider canpoint out to Ben the results of a quantitative analysis, given certain assumptions, butcannot authoritatively determine the best choice for Ben.B
E X A M P L E
T h e process of making sandpaper is similar to that of making a photocopy. A twometre-wide roll of paper is coated with glue and given a negative electric charge. It is thenpassed over sand (of a particular type) that has a positive charge. T h e sand is attracted tothe paper and sticks on the glue. The fact that all of the bits of sand have the same type ofcharge makes sure that the grains are evenly spaced. The paper then passes through a long,heated chamber to cure the glue. Although the process sounds fairlv simple, the machinethat does this, called a maker, is very complicated and expensive. One such machine, costing several million dollars, can support a factory employing hundreds of workers.Preston Sandpapers, a subsidiary of a large firm, was located in a small town. Its makerwas almost 30 years old and desperately needed replacement. However, rather than replaceit, the parent company might have chosen to close down the plant and transfer productionto one of the sister plants located in a different country.
T h e chief engineer had a problem. T h e costs for installing a new maker were extremelyhigh, and it was difficult to justify a new maker economically. However, if he could notdo so, the plant would close and hundreds of workers would be out of a job, includingperhaps himself. What he chose to do was lie. He fabricated figures, ignored importantcosts, and exaggerated benefits to justify the expenditures. T h e investment was made,and the plant is still operating-^
Hespeler Meats is a medium-sized meat processor specializing in deli-style cold cuts andEuropean process meats. Hoping to expand their product offerings, they decided to adda line of canned pates. T h e y were eligible for a government grant to cover some of thepurchase price of the necessarv production equipment.Government support for manufacturing is generally fairly sensible. Support isusually not given for projects that are clearly very profitable, since the company shouldbe able to justify such an expense itself. On the other hand, support is also usually notgiven for projects that are clearly not very profitable, because taxpayers' money shouldnot be wasted. Support is directed at projects that the company would not otherwiseundertake, but that have good potential to create jobs and expand the economy.Hespeler Meats had to provide a detailed justification for the canned pate project inorder to qualify for the government grant. Their problem was that they had to predict boththe expenditures and the receipts for the following five years. This was a product line withwhich they had no experience, and which, in fact, had not been offered on that continent byany meat processor. They had absolutely no idea what their sales would be. Any numbersthev picked would be guesses, but to get the grant thev had to give numbers.\\ nat they did was select an estimate of sales that, given the equipment expendituresexpected, fell exactly within that range of profitability that made the project suitable forgovernment support. They got the money. As it turned out, the product line was a flop,and the canning equipment was sold as scrap five years later.BE X A M P L E
WTien a large metal casting is made, as for the engine block of a car, it has only a roughexterior and often has flashragged edges of metal formed where molten metal seepedbetween the two halves of the mould. T h e first step in finishing the casting is to grindoff the flash, and to grind flat surfaces so that the casting can be held properly for subsequent machining.Gait Casting Grinders (GCG) made the complex specialized equipment for thisoperation. It had once commanded the world market for this product, but lost marketshare to competitors. T h e competitors did not have a better product than GCG, butthey were able to increase market share by adding fancv displav panels with colouredlights, dials, and switches that looked very sophisticated.GCG's problem was that their idea of sensible design was to omit the features thecompetitors included (or the customers wanted). G C G reasoned that these featuresadded nothing to the capability of the equipment, but did add a lot to the manufacturingcost and to the maintenance costs that would be borne by the purchaser. They had nodoubt that it was unwise, and poor engineering design, to make such unnecessarily complicated displays, so they made no changes.GCG went bankrupt several years later.B
In each of these three examples, the technical issues are overwhelmed bv the nontechnical ones. For Preston Sandpapers, the chief engineer was pressured by his socialresponsibility and self-interest to lie and to recommend a decision not justified by thefacts. In the Hespeler Meats case, the engineer had to choose between stating the truththat future sales were unknownwhich would deny the company a very useful grant, andselecting a convenient number that would encourage government support. For GaitCasting Grinders, the issue was marketing. They did not recognize that a product must bemore than technically good; it must also be saleable.Beyond these principles, however, there is a moral component to each of these anecdotes. As guardians of knowledge, engineers have a vital responsibility to society tobehave ethically and responsibly in all ways. W h e n so many different issues must be takeninto account in engineering decision making, it is often difficult to determine what courseof action is ethical.For Preston Sandpapers, most people would probably say that what the chief engineerdid was unethical. However, he did not exploit his position simply for personal gain. Hewas, to his mind, saving a town. Is the principle of honesty more important than severalhundred jobs? Perhaps it is, but when the job holders are friends and family it is understandable that unethical choices might be made.For Hespeler Meats, the issue is subtler. Is it ethical to choose figures that match theideal ones to gain a government grant? It is, strictly speaking, a lie, or at least misleading,since there is no estimate of sales. On the other hand, the bureaucracy demands that somenumbers be given, so why not pick ones that suit your case?In the Gait Casting Grinders case, the engineers apparently did no wrong. T h e ethicalquestion concerns the competitors' actions. Is it ethical to put features on equipment thatdo no good, add cost, and decrease reliability? In this case and for many other products,this is often done, ethical or not. If it is unethical, the ethical suppliers will sometimes goout of business.There are no general answers to difficult moral questions. Practising engineers oftenhave to make choices with an ethical component, and can sometimes rely on no strongerfoundation than their own sense of right and wrong. Alore information about ethicalissues for engineers can be obtained from professional engineering associations.
Malaysia: Zealand: Africa: Kingdom: States: out sections such as M e m b e rDiscipline and Complaints (Australia), andnspe.org/ethics (United States). Understandingethics as enforced by the engineering associations is an excellent basis for making your ownethical decisions.
In this book, all calculations have been done to as many significant digits as could conveniently be carried, even though the intermediate values are shown with three to six digits.As a rule, only three significant digits are assumed in the final value. For decision makingpurposes, this is plenty.Finally, a number of different currencies are used in this book. T h e dollar (S) is themost common currency used because it can represent the currency of Australia, Canada,the United States, and several other countries equally well. But to illustrate the independence of the mathematics from the currency and to highlight the need to be able to workin different currencies, a number of other currency examples are used. For reference,Table 1.2 shows some of the currencies that are used in the text, their symbols, and theircountry of origin.
Table 1.2
Country
Currency name
Symbol
Australia
Dollar
CanadaChina
DollarYuan
Sft
EuropeIndiaJapan
EuroRupeeYen
South AfricaSouth KoreaUnited Kingdom
RandWonPound
United States
Rs
RW
Each chapter begins with a story about Naomi and her experiences at Global Midgets.There are several purposes to these stories. They provide an understanding of engineeringpractice that is impossible to convey with short examples. In each chapter, the story hasbeen chosen to make clear why the ideas being discussed are important. It is also hopedthat the stories make the material taught a little more interesting.There is a two-part Extended Case in the text. Part 1, located between Chapters 6 and 7,presents a problem that is too complicated to include in any particular chapter, but thatreflects a realistic situation likely to be encountered in engineering practice. Part 2, locatedbetween Chapters 11 and 12, builds on the first case to use some of the more sophisticatedideas presented in the later chapters.Throughout the text are boxes that contain information associated with, and complementary to, the text material. One set of boxes contains Close-Ups, which focus on topicsof relevance to the chapter material. These appear in each chapter in the appropriatesection. There are also Net Value boxes, which tie the material presented to internetresources. T h e boxes are in the middle sections of each chapter. Another set of boxespresents Mini-Cases, which appear at the end of each chapter, following the problem set.These cases report how engineering economics is used in familiar companies, and includequestions designed for classroom discussion or individual reflection.End-of-chapter appendices contain relevant but more advanced material. Appendicesat the back of the book provide tables of important and useful values and answers toselected chapter-end problems.
P R O B L E M S1.1
In which of the following situations would engineering economics analysis play a strongrole, and why?(a) Buying new equipment(b) Changing design specifications for a product(c) Deciding on the paint colour for the factor)- floor(d) Hiring a new engineer(e) Deciding when to replace old equipment with new equipment of the same type(f) Extending the cafeteria business hours(g) Deciding which invoice forms to use(h) Changing the 8-hour work shift to a 12-hour one(i) Deciding how much to budget for research and development programs(j)
Starting a new business requires many decisions. List five examples of decisions thatmight be assisted by engineering economics analysis.
For each of the following items, describe how the design might differ if the costs of manufacturing, use, and maintenance were not important. On the basis of these descriptions,is it important to consider costs in engineering design?(a) A car(b) A television set(c) A light bulb(d) A book
Leslie and Sandy, recently married students, are going to rent their first apartment.Leslie has carefully researched the market and has decided that, all things considered,there is only one reasonable choice. T h e two-bedroom apartment in the building at thecorner of University and Erb Streets is the best value for the money, and is also close toschool. Sandy, on the other hand, has just fallen in love with the top half of a duplex onDunbar Road. Which apartment should they move into? W h y ? W h i c h do you thinkthey will move into? W h y ?
Describe the process of using the telephone as you might describe it to a six-year-oldusing it for the first time to call a friend from school. Describe using the telephone to anelectrical engineer who just happens never to have seen one before. What is the correctway to describe a telephone?
15
(a) Karen has to decide which of several computers to buy for school use. Should shebuy the least expensive one? Can she make the best choice on price alone?(b) Several computers offer essentially the same features, reliability, service, etc. Amongthese, can she decide the best choice on price alone?
For each of the following situations, describe what you think you should do. In each casewould you do this?(a) A fellow student, who is a friend, is copying assignments and submitting them as hisown work.(b) A fellow student, who is not a friend, is copying assignments and submitting them asher own work.( c ) A fellow student, who is your only competitor for an important academic award, iscopying assignments and submitting them as his own work.(d) A friend wants to hire you to write an essay for school for her. You are dead brokeand the pay is excellent.(e) A friend wants to hire you to write an essay for school for him. You have lots ofmoney, but the pay is excellent.(f) A friend wants to hire you to write an essay for school for her. You have lots ofmoney, and the pay is poor.(g) Your car was in an accident. T h e insurance adjuster says that the car was totalled andthey will give you only the "blue book" value for it as scrap. They will pick up thecar in a week. A friend points out that in the meantime you could sell the almostnew tires and replace them with bald ones from the scrap yard, and perhaps sellsome other parts, too.(h) T h e CD player from your car has been stolen. T h e insurance adjuster asks you howmuch it was worth. It was a very cheap one, of poor quality.(i) T h e engineer you work for has told you that the meter measuring effluent dischargedfrom a production process exaggerates, and the measured value must be halved forrecordkeeping.(j) T h e engineer you work for has told you that part of your job is to make up realisticlooking figures reporting effluent discharged from a production process.(k) You observe- unmetered and apparently unreported effluent discharged from a production process.(1) An engineer where you work is copying directly from a manufacturer's brochuremachine-tool specifications to be included in a purchase request. These specifications limit the possible purchase to the particular one specified.(m)An engineer where you work is copying directly from a manufacturer's brochuremachine-tool specifications to be included in a purchase request. These specifications limit the possible purchase to the particular one specified. You know that theengineer's 'best friend is the salesman for that manufacturer.
1.8
(Ciel is trying to decide whether now is a good time to expand her manufacturing plant.1T h e viability of expansion depends on the economy (an expanding economy meansmorersales), the relative value of the currency (a lower-valued currency means moreeexports), and changes in international trade agreements (lower tariffs also mean more
exports). These factors may be highly unpredictable, however. W h a t two things can shedo to help make sure she makes a good decision?1.9
Trevor started a high-tech business two years ago, and now wants to sell out to one ofhis larger competitors. T v o different buyers have made firm offers. They are similar inall but two respects. T h e y differ in price: the Investco offer would result in Trevor'swalking away with S2 000 000, while the Venture Corporation offer would give himS3 000 000. T h e other way they differ is that Investco says it will recapitalize Trevor'scompany to increase growth, while Trevor thinks that Venture Corporation will closedown the business so that it doesn't compete with several of Venture Corporation's otherdivisions. W h a t would you do if you were Trevor, and why?
1.10 Telekom Company is considering the development of a new type of cell phone based ona brand new, emerging technology. If successful, Telekom will be able to offer a cellphone that works over long distances and even in mountainous areas. Before proceedingwith the project, however, what uncertainties associated with the new technology shouldthey be aware of? Can sensitivity analysis help address these uncertainties?More Challenging Problem
1.11 In Example 1.1 it is stated that in most circumstances, the Corvette is the right economicchoice. Under what circumstances would either the Toyota or the B M W be the rightchoice?
I m p e r i a l Oil v . Q u e b e c
In 1979, Imperial Oil sold a former petroleum depot in Levis, Quebec, which had beenoperating since the early 1920s. The purchaser demolished die facilities, and sold the landto a real estate developer. The developer conducted a cleanup that was approved by theQuebec Ministry of the Environment, which issued a certificate of authorization in 1987.Following this, the site was developed and a number of houses were built. However, yearslater, residents of the subdivision sued the environment ministrv claiming there was remaining pollution.The ministry, under threat of expensive lawsuits, then ordered Imperial Oil to identifythe pollution, recommend corrective action, and potentially pay for the cost of cleanup. Inresponse, Imperial Oil initiated judicial proceedings against the ministry, claiming violationof principles of natural justice and conflict of interest on its part.In February 2003, the Supreme Court of Canada ruled that the ministry had the right tocompel Imperial Oil to do the cleanup and save public money, because Imperial was the originator of the pollution and the minister did not personally benefit.Source: Imperial Oil v. Quebec (Minister of the Environment), [2003] 2 S.C.R. 624, 2003 SCC 58,Canadian Legal Information Institute (CanLII) site, September 20, 2004.Discussion
the search for profit may result in environmental damage. In a large companv it can bedifficult for one person to know what is happening everywhere in the firm.Older companies have an additional problem. An older company may have beenproducing goods in a certain way for years, and have established ways to dispose of waste.Changes in society make those traditional methods unacceptable. Even when a source ofpollution has been identified, it may not be easy to fix. There may be decades of accumulated damage to correct. A production process may not be easily changed in a way thatwould allow the company to stay in business. Loss of jobs and the effect on the localeconomy may create strong political pressure to keep the company running.The government has an important role to offset the profit motive for large companies, for example, by taking action through the courts. Unfortunately, that alone will notbe enough to prevent some firms from continuing to cause environmental damage.Economics and politics will occasionally win out.Questions
1. There are probably several companies in your city or country that are known to pollute.Name some of these. For each:(a) What sort of damage do they do?(b) How long have they been doing it?(c) Why is this company still permitted to pollute?(d) What would happen if this company were forced to shut down? Is it ethically correctto allow the company to continue to pollute?2. Does it make more sense to fine a company for environmental damage or to finemanagement personally for environmental damage caused by a companv? V\Try?3. Should the fines for environmental damage be raised enough so that no companv istempted to pollute? Why or why not?4. Governments can impose fines, give tax breaks, and take other actions that useeconomics to control the behaviour of companies. Is it necessary to do this whenevera company that pursues profits might do some harm to society as a whole? W h ymight a company do the socially correct thing even if profits are lost?
17
Time Valueof MoneyEngineering Economics in Action, Part 2A: A Steal for Steel
Equivalence2.7.1
Review ProblemsSummaryEngineering Economics in Action, Part 2B: You Just Have to Know WhenProblemsMini-Case 2.1
Time
Value
of
Money
IntroductionEngineering decisions frequently involve evaluating tradeoffs among costs and benefitsthat occur at different times. A typical situation is when we invest in a project today inorder to obtain benefits from the project in the future. T h i s chapter discusses theeconomic methods used to compare benefits and costs that occur at different times. T h ekey to making these comparisons is the use of an interest rate. In Sections 2.2 to 2.5, weillustrate the comparison process with examples and introduce some interest and interestrate terminology. Section 2.6 deals with cash flow diagrams, which are graphical representations of the magnitude and timing of cash flows over time. Section 2.7 explains theequivalence of benefits and costs that occur at different times.
N E T
V A L U E
2 . 1
Interest Rates
use it to make money from their initial investment. Or they may want to buy a consumergood like a new home theatre system and start enjo\ing it immediately. What this means isthat one dollar today is worth more than one dollar in the future. This is because a dollartoday can be invested for productive use, while that opportunity is lost or diminished if thedollar is not available until some time in the future.The observation that a dollar today is worth more than a dollar in the future meansthat people must be compensated for lending money. They are giving up the opportunityto invest their monev for productive purposes now on the promise of getting more moneyin the future. The compensation for loaning money is in the form of an interest payment,say /. More formally, interest is the difference between the amount of money lent and theamount of money later repaid. It is the compensation for giving up the use of the moneyfor the duration of the loan.An amount of money today, P (also called the principal amount), can be related to afuture amount F by the interest amount / or interest rate i. This relationship is illustratedgraphically in Figure 2.1 and can be expressed as F = P + I. The interest / can also beexpressed as an interest rate i with respect to the principal amount so that I = Pi. ThusF
P + PiP(i
F i g u r e 2.1
+oPresent and Future Worth
period
I n t e r e s t r a t e (/)
21
Samuel bought a one-year guaranteed investment certificate (GIC) for S5000 from a bank onMay 15 last year. (The US equivalent is a certificate of deposit, or CD. A GIC is also similarto a guaranteed growth bond in the UK.) The bank was paying 10% on one-year guaranteedinvestment certificates at the time. One year later, Samuel cashed in his certificate for $5500.We mav think of the interest payment that Samuel got from the bank as compensationfor giving up the use of money. "When Samuel bought the guaranteed investment certificate for S5000, he gave up the opportunity to use the money in some other way during thefollowing year. On the other hand, the bank got use of the money for the year. In effect,Samuel lent S5000 to the bank for a year. The S500 interest was payment by the bank toSamuel for the loan. The bank wanted the loan so that it could use the money for the year.(It may have lent the money to someone else at a higher interest rate.) DThis leads to a formal definition of interest rates. Divide time into periods like days,months, or years. If the right to P at the beginning of a time period exchanges for the rightto F at the end of the period, where F = P(l + /'), / is the interest rate per time period. Inthis definition, P is called the present worth of F, and F is called the future worth of P.E X A M P L E
R E S T A T E D
Samuel invested S5000 with the bank on May 15 last year. T h e bank was paying 10% onone-year fixed term investments at the time. T h e agreement gave Samuel the right toclaim S5500 from the bank one year later.Notice in this example that there was a transaction between Samuel and the bank onM a y 15 last year. There was an exchange of S5000 on May 15 a year ago for the right tocollect S5500 on May 15 this year. T h e bank got the S5000 last year and Samuel got theright to collect S5500 one year later. Evidently, having a dollar on M a y 15 last year wasworth more than the right to collect a dollar a year later. Each dollar on May 15 last yearwas worth the right to collect 5500/5000 = 1.1 dollars a year later. This 1.1 may bewritten as 1 +0.1 where 0.1 is the interest rate. T h e interest rate, then, gives the rate ofexchange between money at the beginning of a period (one year in this example) and theright to money at the end of the period. T h e dimension of an interest rate is currency/currencv/time period. For example, a9% interest rate means that for even' dollar lent, 0.09 dollars (or other unit of money) ispaid in interest for each time period. T h e value of the interest rate depends on thelength of the time period. Usually, interest rates are expressed on a y e a r l y basis,although they may be given for periods other than a year, such as a month or a quarter.This base unit of time over which an interest rate is calculated is called the interestperiod. Interest periods are described in more detail in Close-L"p 2.1. T h e longer theinterest period, the higher the interest rate must be to provide the same return.Interest concerns the lending and borrowing of money. It is a parameter that allows anexchange of a larger amount of money in the future for a smaller amount of money in thepresent, and vice versa. As we will see in Chapter 3, it also allows us to evaluate verycomplicated exchanges of money over time.Interest also has a physical basis. Money can be invested in financial instruments thatpay interest, such as a bond or a savings account, and money can also be invested directlyin industrial processes or services that generate wealth. In fact, the money invested infinancial instruments is also, indirecdy, invested in productive activities by the organization
22
CLOSE-UP
The most commonly used interest period is one year. If we say, for example, "6% interest"without specifying an interest period, the assumption is that 6% interest is paid for aone-year period. However, interest periods can be of any duration. Here are some othercommon interest periods:Interest Period
Interest Is Calculated:Tvice per year, or once every six monthsFour times a year, or once every three months12 times per year52 times per year365 times per yearFor infinitesimallv small periods
SemiannuallyQuarterlyMonthlyWeeklyDaily 'Continuous
providing the instrument. Consequently, the root source of interest is the productive use ofmoney, as this is what makes the money actually increase in value. The actual return generated by a specific productive investment varies enormously, as will be seen in Chapter 4.
(2.1)
Beginningof Period
Amount Lent
Interest Amount
M o u n t Owedat Period End
Pi
= P + Pi = P(l + i)
P(l + f>
P(l + i)
P(l + ifi
TV
P(l + i) ~ +
P(i +
[P(l
+i) ~ )i = P(i + /yN
period is
x_1
I = P(l + tf-P
(2.2)
2 . 2
If you were to lend S i 0 0 for three years at 10% per year compound interest, how muchinterest would you get at the end of the three years?If you lend $100 for three years at 10% compound interest per year, you will earnS10 in interest in the first year. That S10 will be lent, along with the original S i 0 0 , forthe second year. Thus, in the second year, the interest earned will be S l l = Si 10(0.10).T h e S l l is lent for the third year. This makes the loan for the third year S121, andSI2.10 = S121(0.10) in interest will be earned in the third year. At the end of the threeyears, the amount you are owed will be Si33.10. T h e interest received is then $33.10.This can also be calculated from Equation (2.2):I = 100(1 + 0 . 1 ) - 100 = 33.103
C o m p o u n d I n t e r e s t C o m p u t a t i o n s f o r E x a m p l e 2.2
Beginningof Year123
Amount Lent100110121
Interest Amount+++
100X0.1110x0.1121 x 0.1
Amount Owedat Year-EndSI 10S121$133.10
If the interest payment for an A"-period loan at the interest rate / per period is computedwithout compounding, the interest amount, 7 is called simple interest. It is computed asI = PiXs
If you were to lend $100 for three years at 10% per year simple interest, how muchinterest would you get at the end of the three years?T h e total amount of interest earned on the S i 0 0 over the three years would be S30.This can be calculated by using 7 = PiX:S
7, = PiX = 100(0.10)(3) - 30
24
Figure 2.2
Year
Interest amounts computed with simple interest and compound interest will yieldthe same results only when the number of interest periods is one. As the number ofperiods increases, the difference between the accumulated interest amounts for the twomethods increases exponentially.When the number of interest periods is significantly greater than one, the differencebetween simple interest and compound interest can be very great. In April 1993, a couplein Nevada, USA, presented the state government with a Si000 bond issued by the state in1865. T h e bond carried an annual interest rate of 24%. The couple claimed the bond wasnow worth several trillion dollars (Newsweek, August 9, 1993, p. 8). If one takes the lengthof time from 1865 to the time the couple presented the bond to the state as 127 vears, thevalue of the bond could have been S732 trillion = $1000(1 + 0 . 2 4 ) .If, instead of compound interest, a simple interest rate given bv iX = (24%)(127) =3048% were used, the bond would be worth only S31 480 = S1000(1 + 30.48). Thus, thedifference between compound and simple interest can be dramatic, especially whenthe interest rate is high and the number of periods is large. The graph in Figure 2.2 showsthe difference between compound interest and simple interest for the first 20 years of thebond example. As for the couple in Nevada, the SI000 bond was worthless after alla statejudge ruled that the bond had to have been cashed by 1872.The conventional approach for computing interest is the compound interest methodrather than simple interest. Simple interest is rarely used, except perhaps as an intuitive(yet incorrect!) way of thinking of compound interest. We mention simple interest primarily to contrast it with compound interest and to indicate that the difference betweenthe two methods can be large.127
25
and the effective interest rate that results from the compounding based on the subperiods. This relation between nominal and effective interest rates must be understood toanswer questions such as: How" would you choose between two investments, one bearing12% per year interest compounded yearly and another bearing 1% per month interestcompounded monthly? Are they the same?Nominal interest rate is the conventional method of stating the annual interestrate. It is calculated by multiplying the interest rate per compounding period bythe number of compounding periods per year. Suppose that a time period is dividedinto vi equal subperiods. Let there be stated a nominal interest rate, r, for the fullperiod. By convention, for nominal interest, the interest rate for each subperiod iscalculated as= rim. For example, a nominal interest rate of 18% per year, compounded monthly, is the same as0.18/12 = 0.015 or 1.5% per monthEffective interest rate is the actual but not usually stated interest rate, found byconverting a given interest rate with an arbitrary compounding period (normally lessthan a year) to an equivalent interest rate with a one-year compounding period. W h a tis the effective interest rate, i , for the fall period that will yield the same amount ascompounding at the end of each subperiod, if: If we compound interest even subperiod, we havec
F= P(l + if)'"We want to find the effective interest rate, i , that yields the same future amount F at theend of the full period from the present amount P. Sete
P ( l + if" = P(l + if1
Then(1 + iff = 1 + i
i = (l + / , ) ' " - 1e
(2.3)
Note that Equation (2.3) allows the conversion between the interest rate over acompounding subperiod, /,., and the effective interest rate over a longer period, i byusing the number of subperiods, m, in the longer period.n
2 . 4
"What interest rate per year, compounded yearly, is equivalent to 1% interest per month,compounded monthly?Since the month is the shorter compounding period, we let /, = 0.01 and m = 12. Theni refers to die effective interest rate per year. Substitution into Equation (2.3) then givese
i = (1 + if" - 1e
= (1 + 0 . 0 1 )
- 1
= 0.126825= 0.127 or 12.7%An interest rate of 1% per month, compounded monthly, is equivalent to an effectiverate of approximately 12.7% per year, compounded yearly. The answer to our previouslyposed question is that an investment bearing 12% per year interest, compounded yearly,pays less than an investment bearing 1 % per month interest, compounded monthly.B
26
Interest rates are normally given as nominal rates. We may get the effective (yearly)rate by substituting i - rim into Equation (2.3). We then obtain a direct means ofcomputing an effective interest rate, given a nominal rate and the number of compounding periods per year:s
<, = ( l + ) " - !
(2-4)
This formula is suitable only for converting from a nominal rate r to an annualeffective rate. If the effective rate desired is for a period longer than a year, thenEquation (2.3) must be used.
Leona the loan shark lends money to clients at the rate of 5% interest per week!YA nat is the nominal interest rate for these loans? W h a t is the effective annual interest rate?T h e nominal interest rate is 5% x 52 = 260%. Recall that nominal interest rates areusually expressed on a yearly basis. T h e effective yearly interest rate can be found bysubstitution into Equation (2.3):i = (1 + 0 . 0 5 )e
52
- 1 = 11.6
2 . 6
i = (1 + 0.00 0 6 5 7 5 )e
3 6 5
= 0.271 or 2 7 . 1 %W i t h a nominal rate of 24% compounded daily, the Cardex Credit Card Companyis actually charging an effective rate of about 2 7 . 1 % per year.BAlthough there are laws which may require that the effective interest rate bedisclosed for loans and investments, it is still very common for nominal interest ratesto be quoted. Since the nominal rate will be less than the effective rate whenever thenumber of compounding periods per year exceeds one, there is an advantage toquoting loans using the nominal rates, since it makes the loan look more attractive.T h i s is p a r t i c u l a r l y true when interest rates are high and c o m p o u n d i n g occursfrequently.
Continuous CompoundingAs has been seen, compounding can be done yearly, quarterly, monthly, or daily. T h eperiods can be made even smaller, as small as desired; the main disadvantage in havingvery small periods is having to do more calculations. If the period is made infinitesimallysmall, we say that interest is compounded continuously. There are situations in which veryfrequent compounding makes sense. For instance, an i m p r o v e m e n t in materialshandling may reduce downtime on machinery. There will be benefits in the form ofincreased output that mav be used immediately. If there are several additional runs a dav,there will be benefits several times a day. Another example is trading on the stockmarket. Personal and corporate investments are often in the form of mutual funds..Mutual funds represent a changing set of stocks and bonds, in which transactions occurvery frequently, often mam" times a dav.A formula for continuous compounding can be developed from Equation (2.3) byallowing the number of compounding periods per year to become infinitely large:/, = H n vm-
1+^1
we set(2.5)
2 . 7
Cash flow at the Arctic Oil Company is continuously reinvested. An investment in a newdata logging system is expected to return a nominal interest of 4 0 % , compoundedcontinuously. \\ nat is the effective interest rate earned by this investment?T h e nominal interest rate is given as r = 0.40. From Equation (2.5),i = ee
0 A
-l
= 1.492 - 1 =0.492 o r 4 9 . 2 %T h e effective interest rate earned on this investment is about 4 9 . 2 % . BAlthough continuous compounding makes sense in some circumstances, it is rarelyused. As with effective interest and nominal interest, in the days before calculators andcomputers, calculations involving continuous compounding were difficult to do.Consequently, discrete compounding is, by convention, the norm. As illustrated inFigure 2.3, the difference between continuous compounding and discrete compoundingis relatively insignificant, even at a fairly high interest rate.
Figure 2.4
C a s h Flow D i a g r a m
periods
(X axis)Negative cash
flow
29
B e g i n n i n g a n d E n d i n g of Periods
As illustrated in a cash flow diagram (see Figure 2.5), the end of one period is exactlythe same point in time as the beginning of the next period. Now is time 0, which is theend of period -1 and also the beginning of period 1. The end of period 1 is the same asthe beginning of period 2, and so on. .V years from now is the end of period .V and thebeginning of period (N + 1).Figure 2.5
Period -1
Period 1
2 . 8
Consider Ashok, a recent university graduate who is trying to summarize typical cashflows for each month. His monthly income is S2200, received at the end of each month.Out of this he pays for rent, food, entertainment, telephone charges, and a credit cardbill for all other purchases. Rent is S700 per month (including utilities), due at the endof each month. Weekly food and entertainment expenses total roughly $120, a typicaltelephone bill is S40 (due at the end of the first week in the month), and his credit cardpurchases average S300. Credit card payments are due at the end of the second week ofeach month.Figure 2.6 shows the timing and amount of the disbursements and the single receiptover a typical month. It assumes that there are exactly four weeks in a month, and it isnow just past the end of the month. Each arrow, which represents a cash flow, is labelledwith the amount of the receipt or disbursement.W h e n two or more cash flows occur in the same time period, the amounts may beshown individually, as in Figure 2.6, or in summary form, as in Figure 2.7. T h e level ofdetail used depends on personal choice and the amount of information the diagram isintended to convey.We suggest that the reader make a practice of using cash flow diagrams whenw o r k i n g on a problem with cash flows that occur at different times. J u s t goingthrough the steps in setting up a cash flow diagram can make the problem structureclearer. Seeing the pattern of cash flow s in the completed diagram gives a "feel" forthe p r o b l e m . r
30
Figure 2,6
C a s h Flow D i a g r a m for E x a m p l e 2 . 8S2200
,$120 IS40
SI20
(Cash inflow)
TimeST 20
S300
S700
(Cash outflows)
Figure 2.7
C a s h Flow D i a g r a m f o r E x a m p l e 2 . 8 i n S u m m a r y F o r mSi 380
S120
S160
S420(Cash outflows.)
EquivalenceWe started this chapter by pointing out that many engineering decisions involve costsand benefits that occur at different times. Making these decisions requires that the costsand benefits at different times be compared. To make these comparisons, we must beable to sav that certain values at different times are equivalent. Equivalence is a condition that exists when the value of a cost at one time is equivalent to the value of therelated benefit received at a different time. In this section we distinguish three conceptsof equivalence that may underlie comparisons of costs and benefits at different times.With mathematical equivalence, equivalence is a consequence of the mathematicalrelationship between time and money. This is the form of equivalence used in F = P(l + i)r.With decisional equivalence, equivalence is a consequence of indifference on thepart of a decision maker among available choices.With market equivalence, equivalence is a consequence of the ability to exchangeone cash flow for another at zero cost.Although the mathematics governing money is the same regardless of which form ofequivalence is most appropriate for a given situation, it can be important to be aware ofwhat assumptions must be made for the mathematical operations to be meaningful.2.7.1
at
t+
t + N + M
= P (l
+ if
= F (l
+ />
t+N
+M
a r e
For any individual, two cash flows, P at time t and F \ at time t + X, are equivalent ifthe individual is indifferent between the two. Here, the implied interest rate relating Pand F +xcalculated from the decision that the cash flows are equivalent, asopposed to mathematical equivalence in which the interest rate determines whether thecash flows are equivalent. This can be illustrated best through an example.t
c a n
De
2.9
would not be able to fill an order for another user whom Mr. Sawada was anxious toimpress with Alpure's reliability. Mr. Sawada suggested that, if Ms. Kehl would wait aweek until August 22, he would show his appreciation by shipping 1100 kilograms thenat the same cost to Bildmet as 1000 kilograms now. In either case, payment would bedue at the end of the month. Should Ms. Kehl accept Alpure's offer?T h e rate of exchange, 1100 to 1000 kilograms, may be written as (1 + 0.1) to 1,where the 0.1 = 10% is an interest rate for the one-week period. (This is equivalent toan effective interest rate of more than 14 000% per year!) Y\ nether or not Ms. Kehlaccepts the offer from M p u r e depends on her situation. T h e r e is some chance ofBildmet's running out of metal if they don't get supplied for a week. This would requireMs. Kehl to do some scrambling to find other sources of metal in order to ship to herown customers on time. Ms. Kehl would prefer the 1000 kilograms on the 15th to 1000kilograms on the 22nd. But there is some minimum amount, larger than 1000 kilograms,that she would accept on the 22nd in exchange for 1000 kilograms on the 15th. Thisamount would take into account both measurable costs and immeasurable costs such asinconvenience and anxiety.Let the minimum rate at which Ms. Kehl would be willing to make the exchange be1 kilogram on the 15th for (1 + x) kilograms on the 22nd. In this case, if x < 10%,Ms. Kehl should accept Alpure's offer of 1100 kilograms on the 22nd. In Example 2.9, the aluminum is a capital good that can be used productively byBildmet. There is value in that use, and that value can be measured bv Greta's willingness topostpone receiving the aluminum. It can be seen that interest is not necessarily a function ofexchanges of money at different points in time. However, money is a convenient measure ofthe worth of a variety of goods, and so interest is usually expressed in terms of money.2.7.3
Market equivalence is based on the idea that there is a market for money that permitscash flows in the future to be exchanged for cash flows in the present, and vice versa.Converting a future cash flow, F, to a present cash flow, P, is called borrowing money,while converting P to F is called lending or investing money. T h e market equivalenceof two cash flows P and F means that they can be exchanged, one for the other, atzero cost.The interest rate associated with an individual's borrowing money is usually a lothigher than the interest rate applied when that individual lends money. For example, theinterest rate a bank pays on deposits is lower than what it charges to lend money toclients. The difference between these interest rates provides the bank with income. Thismeans that, for an individual, market equivalence does not exist. An individual canexchange a present worth for a future worth by investing money, but if he or she were totry to borrow against that future worth to obtain money now, the resulting presentworth would be less than the original amount invested. Moreover, every time eitherborrowing or lending occurred, transaction costs (the fees charged or cost incurred)would further diminish the capital.E X A M P L E
2 . 1 0
This morning, Averill bought a S5000 one-year guaranteed investment certificate (GIC)at his local bank. It has an effective interest rate of 7% per year. At the end of a year, theGIC will be worth $5350. On the way home from the bank, Averill unexpectedly
discovered a valuable piece of art he had been seeking for some time. He wanted to buyit, but all his spare capital was tied up in the GIC. So he went back to the bank, this timeto negotiate a one-year loan for $5000, the cost of the piece of art. He figured that, ifthe loan came due at the same time as the GIC, he would simply pay off the loan withthe proceeds of the GIC.Unfortunately, Averill found out that the bank charges 10% effective interest per yearon loans. Considering the proceeds from the GIC of $5350 one year from now, theamount the bank would give him today is only S5350/1.1 = $4864 (roughly), less any feesapplicable to the loan. He discovered that, for him, market equivalence does not hold. Hecannot exchange $5000 today for $5350 one year from now, and vice versa, at zero cost.BLarge companies with good records have opportunities that differ from those ofindividuals. Large companies borrow and invest money in so many ways, both internallyand externally, that the interest rates for borrowing and for lending are very close to beingthe same, and also the transaction costs are negligible. They can shift funds from thefuture to the present by raising new money or by avoiding investment in a marginalproject that would earn only the rate that they pay on new money. They can shift fundsfrom the present to the future by undertaking an additional project or investing externally.But how large is a "large company"? Established businesses of almost any size, andeven individuals with some wealth and good credit, can acquire cash and invest at aboutthe same interest rate, provided that the amounts are small relative to their total assets. Forthese companies and individuals, market equivalence is a reasonable model assuming thatmarket equivalence makes calculations easier and still generally results in good decisions.For most of the remainder of this book, we will be making two broad assumptionswith respect to equivalence: first, that market equivalence holds, and second, that decisional equivalence can be expressed entirely in monetary terms. If these two assumptionsare reasonably valid, mathematical equivalence can be used as an accurate model of howcosts and benefits relate to one another over time. In several sections of the book, when wecover how firms raise capital and how to incorporate non-monetary aspects of a situationinto a decision, we will discuss the validity of these two assumptions. In the meantime,mathematical equivalence is used to relate cash flows that occur at different points in time.
R E V I E WREVIEW
PROBLEM
P R O B L E M S2.1
Atsushi has had 800 stashed under his mattress for 30 vears. How much money has helost by not putting it in a bank account at 8% annual compound interest all these vears?ANSWER
$ince Atsushi has kept the 800 under his mattress, he has not earned any interest overthe 30 years. Had he put the money into an interest-bearing account, he would have farmore today. We can think of the 800 as a present amount and the amount in 30 years asthe future amount.Given:
P = 800i = 0.08 per yearN = 30 vears
34
Formula:
F = P(l + ;>
= 800(1 + 0.O8)
= 8050.13Atsushi would have 8050.13 in the bank account today had he deposited his 800 at8% annual compound interest. Instead, he has only 800. He has suffered an opportunity cost of 8050.13 - 8 0 0 = 7250.13 by not investing the m o n e y . !REVIEW
You want to buy a new computer, but you are S i 0 0 0 short of the amount you need. Youraunt has agreed to lend you the $1000 you need now, provided you pay her $1200 twoyears from now. $he compounds interest monthly. Another place from which you canborrow $1000 is the bank. There is, however, a loan processing fee of $20, which will beincluded in the loan amount. T h e bank is expecting to receive $1220 two years fromnow based on monthly compounding of interest.(a) "What monthly rate is your aunt charging you for the loan? W h a t is the bankcharging?(b) W h a t effective annual rate is your aunt charging? W h a t is the bank charging?( c ) Would you prefer to borrow from your aunt or from the bank?ANSWER
The formula F = P(l + i)^ must be solved in terms of i to answer the question.i = ^F/P - 1= V1200/1000 - 1= 0.007626Your aunt is charging interest at a rate of approximately 0.76% per month.Fhe bankGiven:
= VT220/1020 - 1= 0.007488T h e bank is charging interest at a rate of approximately 0.75% per month.
35
(b) T h e effective annual rate can be found with the formula i = (1 + rim) " - 1,where r is the nominal rate per year and m is the number of compounding periods per year. Since the number of compounding periods per year is 12, noticethat rim is simply the interest rate charged per month.Your aunte
The hanki = 0.007488 per monthTheni = (1 + r/m) - 1= (1 + 0.007488) - 1= 0.09365e
At the end of four years, you would like to have $5000 in a bank account to purchase aused car. W h a t you need to know is how much to deposit in the bank account now. T h eaccount pays daily interest. Create a spreadsheet and plot the necessary deposit today asa function of interest rate. Consider nominal interest rates ranging from 5% to 15% peryear, and assume that there are 365 days per year.ANSWER
3 6 5 x 4
. This gives
5000 X
1(l + i )
3 6 S x 4
Table 2.3 is an excerpt from a sample spreadsheet. It shows the necessary deposit toaccumulate S5000 over four years at a variety of interest rates. T h e following is thecalculation for cell B2 (i.e., the second row, second column):1
50001 +
365X4f )
1365 /Table 2 . 3 N e c e s s a r y Deposits for a Range of Interest Rates
0.05
4114
0.06
3957
0.07
3805
0.08
3660
0.09
3520
0.10
3385
0.11
3256
0.12
3131
0.13
3011
0.14
2896
0.15
2785
Figure 2.8
4500 -i
20000.05
0.07Annual
interest rate,
0.1
c o m p o u n d e d d a i l y (%)
S U M M A R Y
This chapter has provided an introduction to interest, interest rate terminology, andinterest rate conventions. Through a series of examples, the mechanics of working withsimple and compound interest, nominal and effective interest rates, and continuouscompounding were illustrated. Cash flow diagrams were introduced in order to represent graphically monetary transactions at various points in time. T h e final part of thechapter contained a discussion of various forms of cash flow equivalence: mathematical,decisional, and market. With the assumption that mathematical equivalence can be usedas an accurate model of how costs and benefits relate to one another over time, we nowmove on to Chapter 3, in which equivalence formulas for a variety of cash flow patternsare presented.
pretty expensive raw materials. We would also have the problem of where to store the steel, and other practicaldifficulties. It makes sense mathematically, but I'm pretty sure we just wouldn't do it."Terry looked a little dejected. Naomi continued, "But your figures make sense. The first thing to do is findout why we are carrying that account so long before we pay it off. The second thing to do is see if we can't getthat price break, retroactively. We are good customers, and I'll bet we can convince them to give us the pricebreak anyhow, without changing our ordering pattern. Let's talk to Clem about it.""But, Naomi, why use the mathematical calculations at all, if they don't work?""But they do work, Terry. You just have to know when."
P R O B L E M SFor additional practice, please see the problemsCD-ROM that accompanies this book.
the Student
Using 12% simple interest per year, how much interest will be owed on a loan of S500 atthe end of two years?
If a sum of 3000 is borrowed for six months at 9% simple interest per year, what is thetotal amount due (principal and interest) at the end of six months?
\\Tiat principal amount will yield S150 in interest at the end of three months when theinterest rate is 1% simple interest per month?
Simple interest of $190.67 is owed on a loan of $550 after four years and four months.W h a t is the annual interest rate?
How much will be in a bank account at the end of five years if 2 0 0 0 is invested today at12% interest per annum, compounded yearly?
How much is accumulated in each of these savings plans over two vears?(a) Deposit 1000 yuan today at 10% compounded annually.(b) Deposit 900 yuan today at 12% compounded monthly.
2.8
Greg wants to have $50 000 in five vears. T h e bank is offering five-year investmentcertificates that pay 8% nominal interest, compounded quarterly. How much moneyshould he invest in the certificates to reach his goal?
Greg wants to have $50 000 in five years. He has S20 000 todav to invest. T h e bank isoffering five-year investment certificates that pay interest compounded quarterly. ~V\ natis the minimum nominal interest rate he would have to receive to reach his goal?
2.10 Greg wants to have $50 000. He will invest S20 000 today in investment certificates thatpay 8% nominal interest, compounded quarterly. How long will it take him to reach hisgoal?2.11 Greg will invest $20 000 today in five-year investment certificates that pay 8% nominalinterest, compounded quarterly. How much money will this be in five years?
39
2.12 You bought an antique car three years ago for 500 000 yuan. Today it is worth 650 000 yuan.(a) W h a t annual interest rate did you earn if interest is compounded yearly?(b) W h a t monthly interest rate did you earn if interest is compounded monthly?2.13 You have a bank deposit now worth S5000. How long will it take for your deposit to beworth more than S8000 if(a) the account pays 5% actual interest every half-year, and is compounded even, halfyear?7
40
and the balance of the prize in five years when you intend to purchase a large piece ofwaterfront property. How much will the payment be in five years? Assume that annualinterest is 10%, compounded monthly.2.23 You are looking at purchasing a new computer for your four-year undergraduateprogram. Brand 1 costs S4000 now, and you expect it will last throughout your programwithout any upgrades. Brand 2 costs S2500 now and will need an upgrade at the end oftwo years, which you expect to be S i 7 0 0 . W i t h 8% annual interest, compoundedmonthly, which is the less expensive alternative, if they provide the same level of sendeeand will both be worthless at the end of the four years?2.24 T h e Kovalam Bank advertises savings account interest as 6% compounded daily. Mdiatis the effective interest rate?2.25 T h e Bank of Brisbane is offering a new savings account that pays a nominal 7.99% interest, compounded continuously. Will your money earn more in this account than in adaily interest account that pays 8%?2.26 You are comparing two investments. T h e first pays 1% interest per month, compoundedmonthly, and the second pays 6% interest per six months, compounded every six months.(a) W h a t is the effective semiannual interest rate for each investment?(b) "What is the effective annual interest rate for each investment?( c ) On the basis of interest rate, which investment do you prefer? Does your decisiondepend on whether you make the comparison based on an effective six-month rateor an effective one-year rate?2.27 T h e Crete Credit Union advertises savings account interest as 5.5% compoundedweekly and chequing account interest at 7% compounded monthly. W h a t are the effective interest rates for the two types of accounts?2.28 Victory Visa, Magnificent Master Card, and Amazing Express are credit card companiesthat charge different interest on overdue accounts. Victor}' Visa charges 2 6 % compounded daily, Magnificent M a s t e r Card charges 2 8 % compounded weekly, andAmazing Express charges 30% compounded monthly. On the basis of interest rate,which credit card has the best deal?2.29 April has a bank deposit now worth S796.25. A year ago, it was $750. W n a t was thenominal monthly interest rate on her account?2.30 You have S50 000 to invest in the stock market and have sought the advice of Adam, anexperienced colleague who is willing to advise you, for a fee. Adam has told you that hehas found a one-year investment for you that provides 15% interest, compoundedmonthly.(a) W n a t is the effective annual interest rate, based on a 15% nominal annual rate andmonthly compounding?(b) Adam says that he will make the investment for you for a modest fee of 2% of theinvestment's value one year from now. If you invest the S50 000 today, how muchwill you have at the end of one year (before Adam's fee)?( c ) W nat is the effective annual interest rate of this investment including Adam's fee?2.31 M a y has 2000 yuan in her bank account right now. She wanted to know how much itwould be in one year, so she calculated and came up with 2140.73 yuan. T h e n sherealized she had made a mistake. She had wanted to use the formula for monthly
41
compounding, but instead, she had used the continuous compounding formula. Redothe calculation for M a y and find out how much will actually be in her account a yearfrom now.2.32 Hans now has $6000. In three months, he will receive a cheque for $2000. He must pay$900 at the end of each month (starting exactly one month from now). Draw a singlecash flow diagram illustrating all of these payments for a total of six monthly periods.Include his cash on hand as a payment at time 0.2.33 Margaret is considering an investment that will cost her $500 today. It will pay her $100at the end of each of the next 12 months, and cost her another $300 one year fromtodav. Illustrate these cash flows in two cash flow diagrams. T h e first should show eachcash flow element separately, and the second should show only the net cash flows in eachperiod.2.34 Heddy is considering working on a project that will cost her $20 000 today. It will payher $10 000 at the end of each of the next 12 months, and cost her another $15 000 atthe end of each quarter. An extra $10 000 will be received at the end of the project, oneyear from now. Illustrate these cash flows in two cash flow diagrams. T h e first shouldshow each cash flow element separately, and the second should show only the net cashflow in each period.2.35 Illustrate the following cash flows over 12 months in a cash flow diagram. $how only thenet cash flow in each period.Cash Payments
Cash Receipts
Receive S30 at the end of the first month, and from thatpoint on, receive 10% more than the previous month atthe end of each month
2.36 There are two possible investments, A and B. Their cash flows are shown in the tablebelow. Illustrate these cash flows over 12 months in two cash flow diagrams. Show onlythe net cash flow in each period. Just looking at the diagrams, would you prefer oneinvestment to the other? Comment on this.Investment A
Investment B
Payments
Receipts
2.37 You are indifferent between receiving 100 rand today and 110 rand one year from now.T h e bank pays you 6% interest on deposits and charges you 8% for loans. Name thethree types of equivalence and comment (with one sentence for each) on whether eachexists for this situation and why.
42
2.38 June has a small house on a small street in a small town. If she sells the house now, shewill likely get 1 1 0 000 for it. If she waits for one year, she will likely get more, say, 1 2 0 000. If she sells the house now, she can invest the money in a one-year guaranteedgrowth bond that pays 8% interest, compounded monthly. If she keeps the house, thenthe interest on the mortgage payments is 8% compounded daily. June is indifferentbetween the two options: selling the house now and keeping the house for another year.Discuss whether each of the three types of equivalence exists in this case.2.39 Using a spreadsheet, construct graphs for the loan described in part (a) below.(a) Plot the amount owed (principal plus interest) on a simple interest loan of S i 0 0 for.Vvears for .V = 1, 2, . . . 10. On the same graph, plot the amount owed on a compound interest loan of SI00 for A"years for N = 1, 2, . . . 10. T h e interest rate is6% per year for each loan.(b) Repeat part (a), but use an interest rate of 18%. Observe the dramatic effect compounding has on the amount owed at the higher interest rate.2.40 (a) At 12% interest per annum, how long will it take for a penny to become a milliondollars? How long will it take at 18%?(b) Show the growth in values on a spreadsheet using 10-year time intervals.2.41 Use a spreadsheet to determine how long it will take for a 100 deposit to double invalue for each of the following interest rates and compounding periods. For each, plotthe size of the deposit over time, for as many periods as necessary for the original sumto double.(a) 8% per year, compounded monthly(b) 11 % per year, compounded semiannually( c ) 12% per year, compounded continuously2.42 Construct a graph showing how the effective interest rate for the following nominalrates increases as the compounding period becomes shorter and shorter. Consider arange of compounding periods of your choice from daily compounding to annualcompounding.(a) 6% per year(b) 10% per year( c ) 20% per year2.43 Today, an investment you made three years ago has matured and is now worth 3000r u p e e s . It was a t h r e e - y e a r deposit that bore an interest rate of 10% per year,compounded monthly. You knew at the time that you were taking a risk in makingsuch an investment because interest rates vary over time and you "locked in" at 10%for three years.(a) How much was your initial deposit? Plot the value of your investment over thethree-year period.(b) Looking back over the past three years, interest rates for similar one-year investments did indeed van,-. T h e interest rates were 8% the first year, 10% the second,and 14% the third. Plot the value of your initial deposit over time as if you hadinvested at this set of rates, rather than for a constant 10% rate. Did you lose out byhaving- locked into the 10% investment? If so, bv how much?
2.44 Alarlee has a choice between X pounds today or Y pounds one year from now. X is afixed value, but Yvaries depending on the interest rate. At interest rate /', X and F a r emathematically equivalent for Marlee. At interest ratey, A and Fhave decisional equivalence for Marlee. At interest rate k, A and F h a v e market equivalence for Marlee. W natcan be said about the origins, nature, and comparative values of i,j, and k?
Most major banks offer a credit card sendee for students. Common features of the studentcredit cards include no annual fee, a S500 credit limit, and an annual interest rate of 19.7%(in Canada as of 2007). Also, the student cards often come with many of the perks availablefor the general public: purchase security or travel-related insurance, extended warrantyprotection, access to cash advances, etc. The approval process for getting a card is relativelysimple for university and college students so that thev can start building a credit histon" andenjoy the convenience of having a credit card while still in school.The printed information does not use the term nominal or effective, nor does it define thecompounding period. However, it is common in the credit card business for the annual interest rate to be divided into daily rates for billing purposes. Hence, the quoted annual rate of19.7% is a nominal rate and the compounding period is daily. The actual effective interestrate is then (1 + 0.197/365) - 1 = 0.2 1 77 or21.77%.365
Discussion
Interest information must be disclosed by law. but lenders and borrowers have somelatitude as to how and where they disclose it. Moreover, there is a natural desire to makethe interest rate look lower than it really is for borrowers, and higher than it really is forlenders.In the example of student credit cards, the effective interest rate is 21.77%, roughly2% higher than the stated interest rate. The actual effective interest rate could even endup being higher if fees such as late fees, over-the-limit fees, and transaction fees arecharged.Questions
1.
Go to your local bank branch and find out the interest rate paid for various kinds ofsavings accounts, chequing accounts, and loans. For each interest rate quoted, determine if it is a nominal or effective rate. If it is nominal, determine the compoundingperiod and calculate the effective interest rate.
2.
Have a contest with your classmates to see who can find the organization that willlend money to a student like you at the cheapest effective interest rate, or that willtake investments which provide a guaranteed return at the highest effective interestrate. The valid rates must be generally available, not tied to particular behaviour bythe client, and not secured to an asset (like a mortgage).
3.
If you borrowed S1000 at the best rate you could find and invested it at the best rateyou could find, how much money would you make or lose in a year? Explain why theresult of your calculation could not have the opposite sign.
Review ProblemsSummaryEngineering Economics in Action, Part 3B: No Free LunchProblemsMini-Case 3.1Appendix 3A: Continuous Compounding and Continuous Cash FlowsAppendix 3B: Derivation of Discrete Compound Interest Factors
Cash
Flow
IntroductionChapter 2 showed that interest is the basis for determining whether different patterns ofcash flows are equivalent. Rather than comparing patterns of cash flows from first principles, it is usually easier to use functions that define mathematical equivalence amongcertain common cash flow patterns. These functions are called compound interest factors.We discuss a number of these common cash flow patterns along with their associatedcompound interest factors in this chapter. These compound interest factors are usedthroughout the remainder of the book. It is, therefore, particularly important to understand their use before proceeding to subsequent chapters.This chapter opens with an explanation of how cash flow patterns that engineerscommonly use are simplified approximations of complex reality. Next, we discuss foursimple, discrete cash flow patterns and the compound interest factors that relate themto each other. There is then a brief discussion of the case in which the number of timeperiods considered is so large that it is treated as though the relevant cash flowscontinue indefinitely. Appendix 3A discusses modelling cash flow patterns when theinterval between disbursements or receipts is short enough that we may view the flowsas being continuous. Appendix 3B presents mathematical derivations of the compoundinterest factors.
P(l + />
In the symbolic convention used for compound interest factors, this is writtenF = P(l + ; ) - = P(F/P,i,N)v
F i g u r e 3.1
Single R e c e i p t at End of P e r i o d N
N - 1
N + 1
48
A handy way of thinking of the notation is (reading from left to right): "What is F,given P, i, and N?"T h e compound amount factor is useful in determining the future value of an investment made today if the number of periods and the interest rate are known.T h e present worth factor, denoted by (P/F,i,X), gives the present amount, P, that isequivalent to a fumre amount, F, when the interest rate is i and the number of periods isN. T h e present worth factor is die inverse of the compound amount factor, (F/P,i,X). Thatis, while the compound amount factor gives the fumre amount, F, that is equivalent to apresent amount, P, the present worth factor goes in the other direction. It gives thepresent worth, P, of a fumre amount, F Since (F/P,i,X) = (1 + /)-\(F/F,,,.Y)
(1 + />
T h e compound amount factor and the present worth factor are fundamental toengineering economic analysis. Their most basic use is to convert a single cash flow thatoccurs at one point in time to an equivalent cash flow at another point in time. W h e ncomparing several individual cash flows which occur at different points in time, an analystwould apply the compound amount factor or the present worth factor, as necessary, todetermine the equivalent cash flows at a common reference point in time. In this way,each of the cash flows is stated as an amount at one particular time. Example 3.1 illustrates this process.Although die compound amount factor and the present worth factor are relatively easyto calculate, some of the other factors discussed in this chapter are more complicated, and itis therefore desirable to have an easier way to determine their values. T h e compoundinterest factors are sometimes available as functions in calculators and spreadsheets, butoften these functions are provided in an awkward format that makes them relatively difficultto use. They can, however, be fairly easily programmed in a calculator or spreadsheet.A traditional and still useful method for determining the value of a compound interestfactor is to use tables. Appendix A at the back of this book lists values for all the compoundinterest factors for a selection of interest rates for discrete compounding periods. Thedesired compound interest factor can be determined by looking in the appropriate table.
3 . 1
How much money will be in a bank account at the end of 15 years if S i 0 0 is investedtoday and the nominal interest rate is 8% compounded semiannually?Since a present amount is given and a future amount is to be calculated, theappropriate factor to use is the compound amount factor, (F/P,i,X). There are severalways of choosing / and N to solve this problem. T h e first method is to observe that,since interest is compounded semiannually, the number of compounding periods, A', is30. T h e interest rate per six-month period is 4%. ThenF = 100(F/P,4%,30)= 100(1 + 0 . 0 4 )
= 324.34T h e bank account will hold S324.34 at the end of 15 years.
Alternatively, we can obtain the same results by using the interest factor tables.F = 100(3.2434)
(from Appendix A)
= 324.34A second solution to the problem is to calculate the effective yearly interest rate and thencompound over 15 years at this rate. Recall from Equation (2.4) that the effective interestrate per year isr \m1 + m jwhere i = the effective annual interest rater = the nominal rate per yearvi = the number of periods in a yeari = (1 + 0.08/2) - 1 = 0.0816wherer = 0.08m = 21
\Mien the effective yearly rate for each of 15 years is applied to the future worth computation, the future worth isF = P(F/P,i,X)= P(\ + if= 100(1 + 0 . 0 8 1 6 )
= 324.34Once asrain, we conclude that the balance will be S324.34.B
50
Figure 3.2
A t
N-1
N+1
The sinking fund factor is commonly used to determine how much has to be set asideor saved per period to accumulate an amount F at the end of N periods at an interest rate i.The amount F might be used, for example, to purchase new or replacement equipment, topay for renovations, or to cover capacity expansion costs. In more general terms, thesinking fund factor allows us to convert a single fumre amount into a series of equal-sizedpayments, made over N equally spaced intervals, with the use of a given interest rate i.The uniform series compound amount factor, denoted by (F/A,i,N), gives thefuture value, F, that is equivalent to a series of equal-sized receipts or disbursements,A, when the interest rate is i and the number of periods is N. Since the uniform seriescompound amount factor is the inverse of the sinking fund factor,
The capital recovery factor, denoted by (A/P,i,N), gives the value, A, of the equalperiodic payments or receipts that are equivalent to a present amount, P, when the interestrate is and the number of periods is N. The capital recovery factor is easily derived fromthe sinking fund factor and the compound amount factor:(A/P,i,N) = (A/F,i,N)(F/P,i,N)
= (TtW
( 1 + TR
/(I + if(1+if-lT h e capital recovery factor can be used to find out, for example, how much moneymust be saved over N future periods to "recover" a capital investment of P today. Thecapital recovery factor for the purchase cost of something is sometimes combined with thesinking fund factor for its salvage value after A years to compose the capital recoveryformula. See Close-Up 3 . 1 .T h e series present worth factor, denoted by (P/A,i,N), gives the present amount,P, that is equivalent to an annuity with disbursements or receipts in the amount,A, where the interest rate is / and the number of periods is .V. It is the reciprocal of thecapital recovery factor:7
(1 + tf - 1
51
C a p i t a l Recovery F o r m u l a
Industrial equipment and other assets are often purchased at a cost of P on the basisthat they will incur savings of A per period for the firm. At the end of their usefullife, they will be sold for some salvage value S. The expression to determine A for agiven P and S combines the capital recovery factor (for P) with the sinking fundfactor (for S):A = P(A/P,i,N) - S(A/F,i,N)Since(A/Fj,N)
(l + ip - 1 " (l + if - l + i-
, /[(l + o - - 1 ] _ ,v
(1 + if-I
'
(1 + i) N
/ + /(l + Q- - / _ .v
(1 + /> - 1v
/(i + /)-V(1 + if - 1
(A/P,i,N)-i
thenA = P(A/P,i,X) - S[(A/P,i,N) - i\= (P~S)(A/P,i,X) + SiThis is the capital recovery formula, which can be used to calculate the savingsnecessary to justify a capital purchase of cost P and salvage value S after N periods atinterest rate i.The capital recovery formula is also used to determine an annual amount whichcaptures the loss in value of an asset over the time it is owned. Chapter 7 treats this use ofthe capital recovery formula more fully.7
T h e Hanover Go-Kart Klub has decided to build a clubhouse and track five years fromnow. It must accumulate 5 0 000 by the end of five years by setting aside a uniformamount from its dues at the end of each year. If the interest rate is 10%, how much mustbe set aside each year?Since the problem requires that we calculate an annuity amount given a future value,the solution can be obtained using the sinking fund factor where i = 10%, F = 5 0 000,N = 5, and A is unknown.7
A = 50 000(J/F,10%,5)= 50 000(0.1638)= 8190.00T h e Go-Kart Klub must set aside 8 1 9 0 at the end of each year to accumulate 5 0 000in five vears.B
A car loan requires 30 monthly payments of Si99.00, starting today. At an annual rate of12% compounded monthly, how much money is being lent?This cash flow pattern is referred to as an annuity due. It differs from a standardannuity in that the first of the A payments occurs at time 0 (now) rather than at the endof the first time period. Annuities due are uncommonnot often will one make the firstpayment on a loan on the date the loan is received! Unless otherwise stated, it is reasonable to assume that any annuity starts at the end of the first period.T w o simple methods of analyzing an annuity due will be used for this example.r
Method 1. Count the first payment as a present worth and the next 29 payments as anannuity:P = 199 +A(P/A,i,N)where,-/ - 199, i = 12%/12 = 1 % , and A = 29.T
P = 199 + 199(P/J,1%,29)= 199 + 199(25.066)= 199 + 4988.13= 5187.13T h e present worth of the loan is the current payment, S i 9 9 , plus the present worthof the subsequent 29 payments, S4988.13, a total of about S5187.Method 2. Determine the present worth of a standard annuity at time 1, and then findits worth at time 0 (now). T h e worth at time 1 isP_i = A{P/A,i,N)= 199(PA4,1%,30)= 199(25.807)= 5135.79Then the present worth now (time 0) isP
P- (F/P,i,X)l
= 5135.79(P/P,1%,1)= 5135.79(1.01)= 5187.15T h e second method gives the same result as the first, allowing a small margin for theeffects of r o u n d i n g . !It is worth noting here that although it is natural to think about the symbol P asmeaning a cash flow at time 0, the present, and F as meaning a cash flow in thefuture, in fact these symbols can be more general in meaning. As illustrated in the lastexample, we can consider any point in time to be the "present" for calculationpurposes, and similarly any point in time to be the "future," provided P is some pointin time earlier than F. T h i s observation gives us substantial flexibility in analyzingcash flows.
53
Clarence bought a flat for 94 000 in 2002. He made a 14 000 down payment andnegotiated a mortgage from the previous owner for the balance. Clarence agreed to paythe previous owner 2000 per month at 12% nominal interest, compounded monthly.How long did it take him to pay back the mortgage?Clarence borrowed only 80 000, since he made a 14 000 down payment. T h e2000 payments form an annuity over Nmonths where ./Vis unknown. T h e interest rateper month is 1 %. We must find the value of N such that(1 + /)-
P = A(P/A,i,N) = A
/(l +
z>
i(l + if
A = P(A/P,i,N) = P
,(1 +
0*-
A = P\ (1+if2000 = 80 000
2.52.5/1.5N[/(1.01)].V
0.01(1.01)'1.01- - 1v
(1.01/(1.01)-
(1.01)*/(2.5/1.5)51.34 months
It will take Clarence four years and four months to pay off the mortgage. He willmake 51 full payments of 2000 and will be left with only a fraction of a full payment forhis 52nd and last monthly installment. Problem 3.34 asks what his final payment will be.Note also that mortgages can be confusing because of the different terms used. SeeClose-Up 3.2.BIn Example 3.4, it was possible to use the formula for the compound interest factorto solve for the unknown quantity directly. It is not always possible to do this when thenumber of periods or the interest rate is unknown. We can proceed in several ways. Onepossibility- is to determine the unknown value by trial and error with a spreadsheet.Another approach is to find the nearest values using tables, and then to interpolate linearly to determine an approximate value. Some calculators will perform the interpolation automatically. See Close-Up 3.3 and Figure 3.3 for a reminder of how linearinterpolation works.
54
Flow A n a l y s i s
Mortgages
Mortgages can be a little confusing because of the terminology used. In particular, theword term is used in different ways in different countries. It can mean either the duration over which the original loan is calculated to be repaid (called the amortizationperiod in Canada). It can also mean the duration over which the loan agreement is valid(otherwise called the maturity). The interest rate is a nominal rate, usually compoundedmonthly.For example, Salim has just bought a house for Si35 000. He paid $25 000 down,and the rest of the cost has been obtained from a mortgage. The mortgage has a nominalinterest rate of 9.5% compounded monthly with a 20-year term (amortization period).The maturity (term) of the mortgage is three years. What are Salim's monthly payments?How much does he ow e after three years?Salim's monthly payments can be calculated asr
CLOSE-UP 3.3
Linear Interpolation
x*-xjxi
- xy
_y*-yiyz~y\
55
Clarence paid off an 80 000 mortgage completely in 48 months. He paid 2000 permonth, and at the end of the first year made an extra payment of 7000. W h a t interestrate was he charged on the mortgage?Using the series present worth factor and the present worth factor, this can beformulated for an unknown interest rate:80 000 = 2000(PAi/,48) + 7000(P/F,i,12)
2(P/A,i,48) + 7(P/F,i,U) = 80(1 + / )
4 8
- 1]
/(i + 0
(l+o
(3-1)
Solving such an equation for i directly is generally not possible. However, using aspreadsheet as illustrated in Table 3.1 can establish some close values for the left-hand sideof Equation (3.1), and a similar process can be done using either tables or a calculator.Using a spreadsheet program or calculator, trials can establish a value for the unknowninterest rate to the desired number of significant digits.Once the approximate values for the interest rate are found, linear interpolation can beused to find a more precise answer. For instance, working from the values of the interestrate which give the L H S (left-hand side) value closest to the RHS (ricrfit-hand side) value of80, which are 1.1% and 1.2%,80.4141
.7209 - 80.4141
Table 3.1
Interest Rate i
2(P/A,i,48) + 7(J/iv,12)
0.5%
91.7540
0.6%
89.7128
0.7%
87.7350
0.8%
85.8185
0.9%
83.9608
1.0%
82.1601
1.1%
80.4141
1.2%
78.7209
1.3%
77.0787
1.4%
75.4855
1.5%
73.9398
Bonds are investments that provide an annuity and a fumre value in return for a costtoday. They have a par or face value, which is the amount for which they can be redeemedafter a certain period of time. They also have a coupon rate, meaning that thev pav thebearer an annuity, usually semiannually, calculated as a percentage of the face value. Forexample, a coupon rate of 10% on a bond with an S8000 face value would pay an annuityof S400 each six months. Bonds can sell at more or less than the face value, depending onhow buyers perceive them as investments.To calculate the worth of a bond today, sum together the present worth of the facevalue (a fumre amount) and the coupons (an annuity) at an appropriate interest rate. Forexample, if money can earn 12% compounded semiannually a bond maturing in 15 yearswith a face value of S5000 and a coupon rate of 7% is todav worthP = 5000(P/F,6%,30) + (5000 x 0.07/2) (JP/A,6%,30)= 5000(0.17411) + 175(13.765)= 3279.43The bond is worth about S3 2 79 today.
F i g u r e 3.4
Flow Analysis
57
(N-3)C ' A3C2GC
"A
*%*4
F i g u r e 3.5
N-2
>A/4
2c
;rf>r
(N 3)G(N-2)G
>
(N-1)C
/''""A:\c, ...,/
A'+2GA G
^ 10
58
limited. For example, a company that specializes in outfitting warehouses for grocerychains can expand by adding work crews. But the crews must be trained by managers whohave time to train only one crew member every six months. Hence, we would have a baseamount and a constant amount of growth in cash flows each period.T h e arithmetic gradient to annuity conversion factor, denoted by (A/G,i,N),gives the value of an annuity, A, that is equivalent to an arithmetic gradient serieswhere the constant increase in receipts or disbursements is G per period, the interestrate is /', and the number of periods is A . T h a t is, the arithmetic gradient series, OG,1G, 2G, . . . , (N 1)G is given and the uniform cash flow, A, over A periods is found.Problem 3.29 asks the reader to show that the equation for the arithmetic gradient toannuity factor isr
There is often a base annuity A' associated with a gradient, as illustrated in Figure 3.6.To determine the uniform series equivalent to the total cash flow, the base annuity A' mustbe included to give the overall annuity:A
= A' + G(A/G,i,X)
Susan Xg owns an eight-year-old Jetta automobile. She wants to find the present worthof repair bills over the four years that she expects to keep the car. Susan has the car infor repairs every six months. Repair costs are expected to increase by S50 every sixmonths over the next four years, starting with $500 six months from now, $550 sixmonths later, and so on. W h a t is the present worth of the repair costs over the next fouryears if the interest rate is 12% compounded monthly?First, observe that there will be A = 8 repair bills over four years and that the baseannuity payment, A', is $500. T h e arithmetic gradient component of the bills, G, is $50,and hence the arithmetic gradient series is $0, $50, $100, and so on. T h e present worthof the repair bills can be obtained in a two-step process:T
Step 1. Find the total uniform annuity, A , equivalent to the sum of the base annuity,A' = S500, and the arithmetic gradient series with G = $50 over A = 8periods.tox
Step 2. Find the present worth of A , using the series present worth factor.tot
The 12% nominal interest rate, compounded monthly, is 1% per month. The effectiveinterest rate per six-month period is*6month = (1 + 0.12/12) - 1 = 0.06152 or 6.152%6
Step 1A
500 + 5 0 ( -
(l+/) -l
500 + 50i
- 659.39
0.06152
(1.06152)* - 1
Step 2
P = AUP/A,i,N) = A ^
(1
if - 1;/
(1.06152) - 18
= 659.39
^0.06152(1.06152)*
= 4070.09T h e present worth of the repair costs is about S4070.I
Figure 3.7
A(1
+gY ~ yAN
r!
+g)' - \y"N 2
. A
A(1 + g F "
AO +g):::::::::::::::A:
AO
+gy-
A{1-
F i g u r e 3.8
Pwhere
A(\ + g)x:
1 +i
(1 + /V-
base amountrate of growthinterest ratenumber of periodspresent worth
thethe&theiN- theP the:
(1 + if
IEstimating Growth Rates
Bl
1+*so that1
1 +g1 +i
Then the geometric gradient series to present worth conversion factor is given by
f^
{P/(P/A,g,i,X) =
X)
or
'(l+/)- -l\v
{P/A,g,i,X)
i(i+iT
)i+g
Care must be taken in using the geometric gradient to present worth conversionfactor. Four cases may be distinguished:1. i > g> 0. Growth is positive, but less than the rate of interest. T h e growth adjustedinterest rate, i, is positive. Tables or functions built into software may be used tofind the conversion factor.2. g> i > 0. Growth is positive and greater than the interest rate. T h e growth adjustedinterest rate, i, is negative. It is necessary to compute the conversion factordirectly from the formula.3. g = i > 0. Growth is positive and exactly equal to the interest rate. T h e growthadjusted interest rate i = 0. As with any case where the interest rate is zero, thepresent worth of the series with constant terms, AHA + g), is simply the sum ofall the .V termsP = A
Al +
Tru-Test is in the business of assembling and packaging automotive and marine testingequipment to be sold through retailers to "do-it-yourselfers" and small repair shops.One of their products is tire pressure gauges. This operation has some excess capacityTru-Test is considering using this excess capacity to add engine compression gauges totheir line. T h e y can sell engine pressure gauges to retailers for S8 per gauge. T h e vexpect to be able to produce about 1000 gauges in the first month of production. Thevalso expect that, as the workers learn how to do the work more efficientlv, productivitywill rise by 0.25% per month for the first two years. In other words, each month'soutput of gauges will be 0.25% more than the previous month's. T h e interest rate is1.5% per month. All gauges are sold in the month in which they are produced, andreceipts from sales are at the end of each month. W h a t is the present worth of the salesof the engine pressure gauges in the first two years?7
62
1.015- fir1 = ^1.0025" - r r r - 1 = 0.01247
1 +oi 1.25%
We then make use of the geometric gradient to present worth conversion factorwith the uniform cash flow A = S8000, the growth rate g = 0.0025, the growth adjustedinterest rate i = 0.0125, and the number of periods A" = 24.P = A(P/A,g,i,N) = A
8 0 0 0
>(P/A,i,N)1 +g
1.0025
'20.624^1.0025
P = 164 5iT h e present worth of sales of engine compression gauges over the two-year periodwould be about S i 6 5 000. Recall that we worked with an approximate growth-adjustedinterest rate of 1.25% when the correct rate was a bit less than 1.25%. This means that$164 580 is a slight understatement of the present w o r t h .
3 . 8
Emery's company, Dry-All, produces control systems for drying grain. Proprietarytechnology has allowed Dry-All to maintain steady growth in the U.S. market in spite ofnumerous competitors. Company dividends, all paid to Emery, are expected to rise at arate of 10% per year over the next 10 years. Dividends at the end of this year areexpected to total SI 10 000. If all dividends are invested at 10% interest, how much willEmery accumulate in 10 years?If we calculate the growth adjusted interest rate, we get
and it is natural to think that the present worth is simply the first year's dividends multipliedby 10. However, recall that in the case where g = i the present worth is given by\i+g)
i.i
1 000 000
63
3 . 9
How much is accumulated over 20 years in a fund that pays 4% interest, compoundedyearly, if S i 0 0 0 is deposited at the end of even' fourth year?T h e cash flow diagram for this set of payments is shown in Figure 3.9.Figure 3.9
1000
9 10 11 12 13 14 15 16 17 18 19 20
F = P(F/P,i,X)
Known values:
Future Value
1000(F/P,4%,16)
1000(1.8729)
1873
1000(F/P,4%,12)1000(F/P,4%,8)1000(F/P,4%,4)1000
===
1000(1.6010)1000(1.3685)1000(1.1698)
==
16011369
117010007013
121620
Method 2: Convert the compounding period from yearly to every four years. This can bedone with the effective interest rate formula.i = (1 + 0 . 0 4 ) - 14
= 16.99%
64
F= 235.49(FA4,4%,20)= 235.49(29.777)= 7012Note that each method produces the same amount, allowing for rounding. Y\Tien youhave a choice in methods as in this example, your choice will depend on what you findconvenient, or what is the most efficient computationally.B
3 . 1 0
T h i s year's electrical engineering class has decided to save up for a class party. Eachof the 90 people in the class is to contribute SO.2 5 per day which will be placed in adaily interest (7 days a week, 365 days a year) savings account that pays a nominal8% interest. Contributions will be made five days a week, Monday through Friday,beginning on Monday. T h e money is put into the account at the beginning of eachday, and thus earns interest for the day. T h e class party is in 14 weeks (a full 14 weeksof payments will be made), and the money will be withdrawn on the Monday morning of the 15th week. How much will be saved, assuming everybody makes paymentson time?There are several good ways to solve this problem. One way is to convert each day'scontribution to a weekly amount on Sunday evening/Monday morning, and thenaccumulate the weekly amounts over the 14 weeks:Total contribution per day is 0.25 x 90 = 22.50T h e interest rate per day is V?f363
0.000219
65
lim A{P/A,i,N)N>~
= A lim
~(i + 0 - - rv
[= A lim
I(i + />
1v
AiE X A M P L E
3 . 1 1
T h e town of South Battleford is considering building a bypass for truck traffic around thedowntown commercial area. The bypass will provide merchants and shoppers with benefits that have an estimated value of S500 000 per year. Maintenance costs will be S125 000per year. If the bypass is properly maintained, it will provide benefits for a verv long time.T h e actual life of the bypass will depend on factors like future economic conditions thatcannot be forecast at the time the bypass is being considered. It is, therefore, reasonableto model the flow of benefits as though they continued indefinitely. If the interest rate is10%, what is the present worth of benefits minus maintenance costs?A
P = y =
3 750 000
P R O B L E M S
(a) A = SHOOG = S100i = 0.12/12 = 0.01 per month = 1%PW(end of period 4)
= (P/A,l%,5)[\100 + 100(^/G,1%,5)]= 4.8528[1100 + 100(1.9801)]= 6298.98
PW(at time 0)
= (1 + 0.12/365) - 1 = 0.0099102= PW(end of period 4)(P/F,/,4)30
= (PA4,*',5)[1100 + 100(^/G,/',5)](P/iy,4)= 4.8547[1100 + 100(1.98023)](0.9613)= 6057.80The present worth is about S6058.BREVIEW
It is January 1 of this year. You are starting your new job tomorrow, having just finishedyour engineering degree at the end of last term. Your take-home pay for this year will beS3 6 000. It will be paid to you in equal amounts at the end of each month, starting at theend of January. T h e r e is a cost-of-living clause in your contract that says that eachsubsequent January you will get an increase of 3% in your yearly salary (i.e., your takehome pay for next year will be 1.03 x S3 6 000). In addition to your salary, a wealthyrelative regularly sends you a S2000 birthday present at the end of each June.Recognizing that you are not likely to have any government pension, you havedecided to start saving 10% of your monthly salary and 50% of your birthday presentfor your retirement. Interest is 1% per month, compounded monthly. How much willyou have saved at the end of five years?ANSWER
Yearly pay is a geometric gradient; convert your monthly salary into a yearly amount bythe use of an effective yearly rate. T h e birthday present can be dealt with separately.
67
Salary:The future worth (FW) of the salary at the end of the first year isF W ( s a l a r y , y e a r 1) = 3000(FA4,1%,12) = 38 040.00This forms the base of the geometric gradient; all subsequent years increase by 3%per year. Savings are 10% of salary, which implies that/4 = $3804.00.A = $3804.00
# = 0.03
1+41+0.1268i = - 1 = - 1 = 0.0939811 +g1 + 0.03PW(gradient)
= A (P/A,i,5)/(1 + g) = 3804(3.8498)/l.03= 14218
Birthday
Present:
The present arrives in the middle of each year. To get the total value of the five gifts, wecan find the present worth of an annuity of five payments of S2000(0.5) as of six monthsprior to employment:P W ( - 6 months; = 2000(0.5)(P/.4,/5) = 3544.90T h e future worth at 5 x 1 2 + 6 = 66 months later isF W ( e n d of five years) = 3 5 4 4 . 9 ( 1 . 0 1 ) = 68 3 666
T h e Easy Loan Company advertises a " 1 0 % " loan. You need to borrow 1000, andthe deal you are offered is the following: You pay 1100 (1000 plus 100 interest) in11 equal 100 amounts, starting one month from today. In addition, there is a 25administration fee for the loan, payable immediately, and a processing fee of 10 perpayment. Furthermore, there is a 20 non-optional closing fee to be included in thelast payment. Recognizing fees as a form of interest payment, what is the actual effective interest rate?ANSWER
Since the 25 administration fee is paid immediately, you are only getting 975. Theremaining payments amount to an annuity of 110 per month, plus a 20 future payment11 months from now.Formulas:
P = A(P/A,i,X), P = F{P/F,i,N)
At i = 4%110(PA4,4%,11) + 20(P/T,4%,11)= 110(8.7603) + 20(0.64958)= 976.62At / = 5%110(P/,4,5%,11) + 20(P/F,5%,11)= 110(8.3062) + 20(0.58469)= 925.37Linearly interpolating givesi' = 4 + (5 - 4 ) (975 - 976.62)/(925.37 - 976.62)= 4.03T h e effective interest rate is theni = (1 + 0 . 0 4 0 3 ) - 112
M i n g wants to retire as soon as she has enough money invested in a special bank account(paying 14% interest, compounded annually) to provide her with an annual income of$25 000. She is able to save $10 000 per year, and the account now holds $5000. If shejust turned 20, and expects to die in 50 years, how old will she be when she retires?There should be no money left when she turns 70.ANSWER
S U M M A R YIn Chapter 3 we considered ways of modelling patterns of cash flows that enable easycomparisons of the worths of projects. The emphasis was on discrete models. Four basicpatterns of discrete cash flows were considered:1.2.3.4.
FlowsFlowsFlowsFlows
at a single pointthat are constant over timethat grow or decrease at a constant arithmetic ratethat grow or decrease at a constant geometric rate
Table 3.2
Name
(F/P,i,X) = (1 + if
(P/F,i,X) -
(A/F,ijN)
(F/A,i,X) -
(1 + ifi
(l + o - - iv
(1 + / > - 1v
(A/P,i,X)
(P/Am (1 + iff - 1
{A/G,i,N)
(1 + if - 1i /(l +(1 if + if-11 (P/AJ,X)N(P/A,g,i,X) =1 +g
(P/A,g,i,X =
/(l+/)- -l\ 1v
I /(1 + z')
i =Capitalized value formulaCapital recovery formula
1+i
AA = (P- S)(A/P,i,X) + SI
1 +
P R O B L E M SFor additional practice, please see the problemsCD-ROM that accompanies this book.3.1
St. Agatha Kennels provides dog breeding and boarding sendees for a nearby city. Most ofthe income is derived from boarding, with typical boarding stays being one or two weeks.Customers pay at the end of the dog's stay. Boarding is offered only during the months ofM a y to September. Other income is received from breeding golden retrievers, with twolitters of about eight dogs each being produced per year, spring and fall. Expenses includeheating, water, and sewage, which are paid monthly, and food, bought in bulk e v e n spring.The business has been neither growing nor shrinking over the past few years.Joan, the owner of the kennels, wants to model the cash flows for the business over thenext 10 years. What cash flow elements (e.g., single payments, annuities, gradients) wouldshe likely consider, and how would she estimate their value? Consider the present to be thefirst of May. For example, one cash flow element is food. It would be modelled as an annuitydue over 10 years, and estimated by the amount paid for food over the last few years.
71
It is September, the beginning of his school year, and Marco has to watch his expenseswhile he is going to school. Over the next eight months, he wants to estimate his cashflows. He pays rent once a month. He takes the bus to and from school. A couple of timesa week he goes to the grocery store for food, and eats lunch in the cafeteria at schoolevery school dav. At the end of every four-month term, he will have printing and copvingexpenses because of reports that will be due. After the first term, over the Christmas holidays, he will have extra expenses for buying presents, but will also get some extra cashfrom his parents. Y\ nat cash flow elements (e.g., single payments, annuities, gradients)would Marco likely consider in his estimates? How would he estimate them?
How much money will be in a bank account at the end of 15 years if 100 rand aredeposited today and the interest rate is 8% compounded annually?
How much should you invest today at 12% interest to accumulate 1 000 000 rand in30 years?
Martin and Marcy McCormack have just become proud parents of septuplets. Thevhave savings of S5000. T h e y want to invest their savings so that thev can partiallvsupport the children's university education. Martin and Marcv hope to provide S20 000for each child by the time the children turn 18. W h a t must the annual rate of return beon the investment for Martin and Marcv to meet their sroal?
You have $1725 to invest. You know that a particular investment will double your moneyin five years. How much will you have in 10 years if you invest in this investment,assuming that the annual rate of return is guaranteed for the time period?Morris paid 500 a month for 20 years to pay off the mortgage on his Glasgow house. Ifhis down payment was 5000 and the interest rate was 6% compounded monthlv, whatwas the purchase price of the house?
An investment pays S10 000 every five years, starting in seven years, for a total of fourpayments. If interest is 9%, how much is this investment worth todav?
An industrial juicer costs $45 000. It will be used for five years and then sold to a remarketer for S25 000. If interest is 15%, what net yearly savings are needed to justify itspurchase?
3.10 Fred wants to save up for an automobile. W h a t amount must he put in his bank accounteach month to save 1 0 000 in two years if the bank pays 6% interest compoundedmonthly?3.11 It is M a y 1. You have just bought S2000 worth of furniture. You will pav for it in 24equal monthly payments, starting at the end of M a y next year. Interest is 6% nominalper year, compounded monthly. How much will your pavments be?3.12 W h a t is the present worth of the total of 20 payments, occurring at the end of every fourmonths (the first payment is in four months), which are $400, $500, $600, increasingarithmetically? Interest is 12% nominal per year, compounded continuously.3.13 W h a t is the total value of the sum of the present worths of all the payments and receiptsmentioned in Problem 2.32, at an interest rate of 0.5% per month?3.14 How much is accumulated in each of the following savings plans over two years?(a) $40 at the end of each month for 24 months at 12% compounded monthlv(b) $30 at the end of the first month, $31 at the end of the second month, and so forth,increasing by $1 per month, at 12% compounded monthly
3.15 W h a t interest rate will result in S5000 seven years from now, starting with S2300 today?3.16 Refer back to the Hanover Go-Kart Klub problem of Example 3.2. The members determined that it is possible to set aside only 7 0 0 0 each year, and that they will have to put offbuilding the clubhouse until they have saved the 5 0 000 necessary. How long will it taketo save a total of 5 0 000, assuming that the interest rate is 10%? (Hint: Use logarithms tosimplify the sinking fund factor.)3.17 Gwen just bought a satellite dish, which provides her with exactly the same sendee ascable TV. T h e dish cost S2000, and the cable sendee she has now cancelled cost her$40 per month. How long will it take her to recoup her investment in the dish, if she canearn 12% interest, compounded monthly, on her money?3.18 Yoko has just bought a new computer ($2000), a printer ($350), and a scanner ($210).$he wants to take the monthlv payment option. There is a monthlv interest of 3% onher purchase.(a) If Yoko pays $100 per month, how long does it take to complete her payments?(b) If Yoko wants to finish paving in 24 months, how much will her monthly paymentbe?3.19 Rinku has just finished her first year of university. She wants to tour Europe when shegraduates in three years. By having a part-time job through the school vear and asummer job during the summer, she plans to make regular weekly deposits into a savingsaccount, which bears 18% interest, compounded monthly.(a) If Rinku deposits $15 per week, how much will she save in three years? How about$20 per week?(b) Find out exactly how much Rinku needs to deposit every week if she wants to save$5000 in three years.3.20 Seema is looking at an investment in upgrading an inspection line at her plant. T h einitial cost would be S140 000 with a salvage value of $37 000 after five years. Use thecapital recovery- formula to determine how much money must be saved every year tojustify the investment, at an interest rate of 14%.3.21 Trennv has asked her assistant to prepare estimates of cost of two different sizes of powerplants. The assistant reports that the cost of the 100 MW plant is $200 000 000, while thecost of the 200 MW plant is $360 000 000. If Trenny has a budget of only $300 000 000,estimate how large a power plant she could afford using linear interpolation.3.22 Enrique has determined that investing $500 per month will enable him to accumulate$11 350 in 12 years, and that investing S800 per month will enable him to accumulate$18 950 over the same period. Estimate, using linear interpolation, how much he wouldhave to invest each month to accumulate exactly $15 000.3.23 A UK lottery prize pays 1000 at the end of the first year, 2000 the second, 3000 thethird, and so on for 20 years. If there is only one prize in the lottery , 10 000 tickets aresold, and you could invest your money elsewhere at 15% interest, how much is eachticket worth, on average?7
3.24 Joseph and three other friends bought a $110 000 house close to the university at the endof August last year. At that time they put down a deposit of $10 000 and took out a mortgage for the balance. T h e i r mortgage payments are due at the end of each month(September 30, last year, was the date of the first payment) and are based on the assumption that Joseph and friends will take 20 years to pay off the debt. Annual nominal interest
73
is 12%, compounded monthly. It is now February. Joseph and friends have made all theirfall-term payments and have just made the January 31 payment for this year. How muchdo they still owe?3.25 A new software package is expected to improve productivity at Grand Insurance.However, because of training and implementation costs, savings are not expected tooccur until the third year of operation. At that time, savings of S10 000 are expected,increasing by S i 0 0 0 per year for the following five years. After this time (eight yearsfrom implementation), the software will be abandoned with no scrap value. How muchis the software worth today, at 15% interest?3.26 Clem is saving for a car in a bank account that pays 12% interest, compounded monthly.T h e balance is now $2400. Clem will be saving $120 per month from his salary, andonce every four months (starting in four months) he adds $200 in dividends from aninvestment. Bank fees, currently $10 per month, are expected to increase by $1 permonth henceforth. How much will Clem have saved in two years?3.27 Yogajothi is thinking of investing in a rental house. T h e total cost to purchase the house,including legal fees and taxes, is 115 000. All but 15 000 of this amount will bemortgaged. He will pay 800 per month in mortgage payments. At the end of two years,he will sell the house, and at that time expects to clear 20 000 after paying off theremaining mortgage principal (in other words, he will pay off all his debts for the house,and still have 20 000 left). Rents will earn him 1000 per month for the first year, and1200 per month for the second year. T h e house is in fairly good condition now so thathe doesn't expect to have any maintenance costs for the first six months. For the seventhmonth, Yogajothi has budgeted 200. This figure will be increased by 20 per monththereafter (e.g., the expected month 7 expense will be 200, month 8, 220, month 9,240, etc.). If interest is 6% compounded monthly, what is the present worth of thisinvestment? Given that Yogajothi's estimates of revenue and expenses are correct, shouldYogajothi buy the house?3.28 You have been paying off a mortgage in quarterly payments at a 24% nominal annualrate, compounded quarterly. Your bank is now offering an alternative payment plan, soyou have a choice of two methodscontinuing to pay as before or switching to thenew plan. Under the new plan, you would make monthly payments, 30% of the size ofyour current p a y m e n t s . T h e interest rate would be 24% nominal, compoundedmonthly. T h e time until the end of the mortgage would not change, regardless of themethod chosen.(a) Which plan would you choose, given that you naturally wish to minimize the levelof your payment costs? {Hint: Look at the costs over a three-month period.)(b) Lnder which plan would you be paying a higher effective yearly interest rate?3.29 Derive the arithmetic gradient conversion to a uniform series formula. (Hint: Converteach period's gradient amount to its future value, and then look for a substitution fromthe other compound amount factors.)3.30 Derive the geometric gradient to present worth conversion factor. (Hint: Divide andmultiply the present worth of a geometric series by [1 + g] and then substitute in thegrowth-adjusted interest rate.)3.31 Reginald is expecting steady growth of 10% per year in profits from his new company.All profits are going to be invested at 20% interest. If profits for this year (at the end ofthe year) total 1 000 000, how much will be saved at the end of 10 years?
3.32 Reginald is expecting steady growth in profits from his new company of 20% per year.All profits are going to be invested at 10% interest. If profits for this year (at the end ofthe year) total 1 000 000, how much will be saved at the end of 10 years?3.33 Ruby's business has been growing quickly over the past few years, with sales increasingat about 50% per year. She has been approached by a buyer for the business. She hasdecided she will sell it for 1/2 of the value of the estimated sales for the next five years.This year she will sell products worth SI 456 988. Use the geometric gradient factor tocalculate her selling price for an interest rate of 5%.3.34 In Example 3.4, Clarence bought a 94 000 house with a 14 000 down payment andtook out a mortgage for the remaining 80 000 at 12% nominal interest, compoundedmonthly. We determined that he would make 51 2000 payments and then a finalpayment. WTiat is his final payment?3.35 A new wave-soldering machine is expected to save Brisbane Circuit Boards S i 5 000 peryear through reduced labour costs and increased quality. The device will have a life ofeight years, and have no salvage value after this time. If the company can generallyexpect to get 12% return on its capital, how much could it afford to pay for the wavesoldering machine?3.36 Gail has won a lottery that pays her S100 000 at the end of this year, Si 10 000 at the endof next year, S i 2 0 000 the following year, and so on, for 30 years. Leon has offered GailS2 500 000 today in exchange for all the money she will receive. If Gail can get 8%interest on her savings, is this a good deal?3.37 Gail has won a lottery that pays her S100 000 at the end of this year, and increases by10% per year thereafter for 30 years. Leon has offered Gail $2 500 000 today inexchange for all the money she will receive. If Gail can get 8% interest on her savings, isthis a good deal?3.38 Tina has saved 2 0 000 from her summer jobs. Rather than work for a living, sheplans to buy an annuity from a trust company and become a beachcomber in Fiji. Anannuity will pay her a certain amount each month for the rest of her life, and iscalculated at 7% interest, compounded monthly, over Tina's 55 remaining years. Tinacalculates that she needs at least 5 per day to live in Fiji, and she needs 1 2 0 0 for airfare. Can she retire now? How much would she have available to spend each day?3.39 A regional municipaliy is studying a water supply plan for its tri-city and surroundingarea to the end of year 2055. To satisfy the water demand, one suggestion is to constructa pipeline from a major lake some distance away. Construction would start in 2015 andtake five years at a cost of $20 million per year. The cost of maintenance and repairsstarts after completion of construction and for the first year is $2 million, increasing by1% per year thereafter. At an interest rate of 6%, what is the present worth of thisproject?Assume that all cash flows take place at year-end. Consider the present to be the endof 2010/beginning of 2011. Assume that there is no salvage value at the end of year2055.3.40 Clem has a $50 000 loan. T h e interest rate offered is 8% compounded annually, and therepayment period is 15 years. Payments are to be received in equal installments at theend of each year. Construct a spreadsheet (you must use a spreadsheet program) similarto the following table that shows the amount received each year, the portion that isinterest, the portion that is unrecovered capital, and the amount that is outstanding (i.e.,unrecovered). Also, compute the total recovered capital which must equal the original
75
capital amount; this can serve as a check on your solution. Design the spreadsheet sothat the capital amount and the interest rate can be changed by updating only one cellfor each. Construct:(a) the completed spreadsheet for the amount, interest rate, and repayment periodindicated(b) the same spreadsheet, but for $75 000 at 10% interest (same repayment period)(c) a listing showing the formulas used
S50 000.008.00%15
AnnualPayment
InterestReceived
RecoveredCapital
UnrecoveredCapital
$1841.48
$50 000.0048 158.52
012
$5841.48
$4000.00
15Total
0.00S50 000.00
3.41 A French software genius has been offered 1 0 000 per year for the next five years andthen 2 0 000 per year for the following 10 years for the rights to his new video game.At 9% interest, how much is this worth today?3.42 A bank offers a personal loan called "The Eight Per Cent Plan." T h e bank adds 8% tothe amount borrowed; the borrower pays back 1/12 of this total at the end of eachmonth for a year. On a loan of $500, the monthly payment is 540/12 = $45. There isalso an administrative fee of $45, payable now. W h a t is the actual effective interest rateon a $500 loan?3.43 Coastal $hipping is setting aside capital to fund an expansion project. Funds earmarkedfor the project will accumulate at the rate of $50 000 per month until the projectis completed. T h e project will take two years to complete. Once the project starts,costs will be incurred monthly at the rate of $150 000 per month over 24 months.Coastal currently has $250 000 saved. W nat is the minimum number of months it willhave to wait before it can start if money is worth 18% nominal, compounded monthlv?Assume that1. Cash flows are all at the ends of months2. T h e first $50 000 savings occurs one month from todav
3. T h e first Si 50 000 payment occurs one month after the start of the project4. T h e project must start at the beginning of a month3.44 A company is about to invest in a joint venture research and development project withanother company. T h e project is expected to last eight years, but yearly payments thecompany makes will begin immediately (i.e., a payment is made today, and the lastpayment is eight years from today). Salaries will account for S40 000 of each payment.T h e remainder of each payment will cover equipment costs and facility overhead. T h einitial (immediate) equipment and facility cost is $26 000. Each subsequent year thefigure will drop by $3000 until a cost of $14 000 is reached, after which the costs willremain constant until the end of the project.(a) Draw a cash flow diagram to illustrate the cash flows for this situation.(b) At an interest rate of 7%, what is the total future worth of all project payments atthe end of the eight years?3.45 $hamsir's small business has been growing slowly. He has noticed that his monthly profitincreases by 1% every two months. $uppose that the profit at the end of this month is10 000 rupees. W h a t is the present value of all his profit over the next two years? Annualnominal interest is 18%, compounded monthly.3.46 Xiaohang is conducting a biochemical experiment for the next 12 months. In the firstmonth, the expenses are estimated to be 15 000 yuan. As the experiment progresses,the expenses are expected to increase by 5% each month. Xiaohang plans to pay forthe experiment by a government grant, which is received in six monthlv installments,starting a month after the experiment completion date. Determine the amount of themonthly installment so that the total of the six installments pays for all expensesincurred d u r i n g the experiment. Annual nominal interest is 12%, compoundedmonthly.3.47 City engineers are considering several plans for building municipal aqueduct tunnels.They use an interest rate of 8%. One plan calls for a full-capacity tunnel that will meetthe needs of the city forever. T h e cost is $3 000 000 now, and $100 000 every 10 yearsthereafter for repairs. W h a t is the total present worth of the costs of building andmaintaining the aqueduct?7
3.48 T h e city of Brussels is installing a new swimming pool in the municipal recreationcentre. One design being considered is a reinforced concrete pool which will cost1 500 000 to install. Thereafter, the inner surface of the pool will need to be refinishedand painted even' 10 years at a cost of 2 0 0 000 per refinishing. Assuming that the poolwill have essentially an infinite life, what is the present worth of the costs associated withthis pool design? T h e city uses a 5% interest rate.3.49 Goderich Automotive (GA) wants to donate a vacant lot next door to its plant to the cityfor use as a public park and ball field. T h e city will accept only if GA will also donateenough cash to maintain the park indefinitely. T h e estimated maintenance costs are$18 000 per year and interest is 7%. How much cash must GA donate?3.50 A 7%, 20-year municipal bond has a $10 000 face value. I want to receive at least 10%compounded semiannually on this investment. How much should I pay for the bond?3.51 A Paradorian bond pays $500 (Paradorian dollars) twice each year and $5000 five yearsfrom now. I want to earn at least 300% annual (effective) interest on this investment (tocompensate for the very high inflation in Parador). How much should I pay for thisbond now?
3.52 If money is worth 8% compounded semiannually, how much is a bond maturing in nineyears, with a face value of 10 000 and a coupon rate of 9%, worth today?3.53 A bond with a face value of S5000 pays quarterly interest of 1.5% each period. Twenty-sixinterest payments remain before the bond matures. How much would you be willing topay for this bond today if the next interest payment is due now and you want to earn 8%compounded quarterly on your money?More Challenging Problem
3.54 W nat happens to the present worth of an arithmetic gradient series as the number ofperiods approaches infinity? Consider all four cases:(a)
i>g>0
(b)
g>i>0
(c)
g=i=0
(d)g<0
T h e G o r g o n LNG P r o j e c t i n W e s t e r n A u s t r a l i a
Historically, natural gas was considered a relatively uninteresting by-product of oil production. It was often burned at the site of an oil well, just to get rid of it. But oil supplies are nowdwindling while demand has increased from both developed and developing countries. Also,interest in clean-burning fuels has grown. Consequently, in recent years natural gas hasbecome a kev global resource.One of the largest accessible supplies of natural gas is located off the northwest coast ofAustralia. Within this area, a huge field containing about 40 trillion cubic feet of gasAustralia's largest known undeveloped gas resourcewas discovered in the mid-1990s. It wasnamed "Gorgon" after a vicious monster from Greek mythology.Western Australia is very isolated and unpopulated. There is no local industrial orresidential market for the gas. However, it is relatively conveniently located to the burgeoning markets of Asia. China in particular is rapidly industrializing and has a seeminglyinsatiable demand for energyThere are significant technical challenges to developing die Gorgon gas field. The gashas to be drawn from under as much as 600 m of water and shipped 65 km to shore. Theprocessing site is on Barrow Island, a protected nature reserve. The gas itself contains largequantities of carbon dioxide, which has to be removed and reinjected into the ground so thatit doesn't contribute to global warming. Finally, the gas has to be cooled to -161 C. Thisreduces it to 1/600 of its volume, and it becomes liquefied natural gas, or LNG. It is thentransported in liquid form by specially designed ships to customers, who turn it back into gas.However, given the vast reserves and the eager demand, it was felt by the ownersa jointventure of three large oil companies (Chevron, ExxonMobil, and Shell)that in spite of thechallenges the project was feasible. Serious project planning was done from 2000 through early2003, allowing for the economic viability of a project design to be confirmed. On September 8,2003, a well defined project plan was approved by the Western Australian government.Long-term commercial agreements were concluded by the joint venture partners withcustomers that included China's national oil company. Everything looked like it was on trackfor the S8 billion project (all costs are in Australian dollars) to successfully provide profits for
78
its joint venture partners. Thousands of jobs were to be created and millions of dollars of taxrevenue would be provided to the Australian government. Start-up was planned for 2006 andgas would flow for 60 years to fuel Asian industrialization.However, it didn't work out that way. As of 2008, over Si billion has been spent indrilling, appraisal, and engineering design costs to date. The total project costs haveballooned from S8 billion in 2003 to as much as S30 billion in 2008. Consequently, theeconomics of the project are in disarray. At least one of the joint venture partners is lookingto sell out its share, and there are suggestions that the project will be put off indefinitely.Discussion
One might assume that the Gorgon project is an example of professional incompetence. It isnot. Many very capable people were careful to think through all of die costs in a deep anddetailed manner. The joint venture partners are very experienced at large projects like this.However, no matter how careful the planning process might be, one can never fullyunderstand how the future will turn out. There were two key issues that stronglv affectedthe Gorgon project.The first was the environmental effects of the project. The site of the gas processingplant is to be on Barrow Island, a nature reserve. In spite of the fact that processingfacilities had been located on the island for decades, under modern sensitivities forenvironmental impacts, this caused a great deal of unexpected administrative overhead.Another environmental concern stemmed from the large amount of carbon dioxide thathad to be properly dealt with. These environmental issues were dealt with, and althoughthey caused delay and extra cost, the Australian federal government finally gave itsenvironmental approval to the project on October 10, 2007.However, the most important problem was a confluence of global trends aggravated byWestern Australia's remote location. The global trends include the industrialization ofChina, with a corresponding increased demand for oil and gas. This has consequentlycaused oil companies to attempt to increase supply. This in turn has caused the proliferationof oil and gas developments all over the globe. Consequently, there is tremendous demandfor the manufacturing capacity, technical expertise, and specialized equipment needed fordeveloping a gas field like Gorgon, raising the costs of acquiring these in a timely manner.At the same time, construction projects of other kinds were proliferating, both withinand outside of Australia. With a very small labour pool and an isolated location, costs oflabour in Western Australia skyrocketed, far beyond even the most pessimistic expectations. A similar situation has happened in Canada's tar sands in Alberta.In order to compare alternatives economically, it is necessarv to determine future cashflows. Of course nobody knows for sure what the fumre holds, so future cash flows arealways estimates. In some cases the estimates will turn out to be significantly differentfrom the actual cash flows, and therefore result in an incorrect decision.There are sophisticated ways to deal with uncertainty about fumre cash flows, someof which are discussed in Chapters 11 and 12. In many cases it makes sense to assume thatthe future cash flows are treated as if they were certain because there is no particularreason to think they are not. On the other hand, in some cases even estimating future cashflows can be very difficult or impossible.Questions
For each of the following, comment on how sensible it is to estimate the precise valueof fumre cash flows:(a) Your rent for the next six months(b) Your food bill for the next six months
We now consider compound interest factors for continuous models. Two forms ofcontinuous modelling are of interest. T h e first form has discrete cash flow s withcontinuous compounding. In some cases, projects generate discrete, end-of-period cashflows within an organization in which other cash flows and compounding occur manytimes per period. In this case, a reasonable model is to assume that the project's cashflows are discrete, but compounding is continuous. The second form has continuouscash flows with continuous compounding. Where a project generates many cash flowsper period, we could model this as continuous cash flows with continuous compounding.We first consider models with discrete cash flows with continuous compounding. Wecan obtain formulas for compound interest factors for these projects from formulas fordiscrete compounding simply by substituting the effective continuous interest rate withcontinuous compounding for the effective rate with discrete compounding.Recall that for a given nominal interest rate, r, when the number of compoundingperiods per year becomes infinitely large, the effective interest rate per period is i = e - 1.This implies 1 + i = e and (1 + / )-^ =The various compound interest factors forcontinuous compounding can be obtained by substituting e - 1 for i in the formulas forthe factors.For example, the series present worth factor with discrete compounding is(1 + if - 1r
If we substitute e 1 for / and e''^ for (1 + if, we get the series present worth factorfor continuous compoundingr
(P/A,r,N) = Similar substitutions can be made in each of the other compound interest factorformulas to get the compound interest factor for continuous rather than discretecompounding. The formulas are shown in Table 3A.1. Tables of values for these formulasare available in Appendix B at the end of the book.
80
Table 3A.1
(F/P,r,X) = e
(P/F,r,X) = 4x
(A/F,r,X) =
rX
f - 1e" 1r\ _ J(F/A,rJST) = e' 1
_7 , -
WP,rM=
(P/A,r,X) =
1N(AlG,r,N) = er 1 e'- 1
erV
e - 1{er l)e'r N
3 A . 1
Yoram Gershon is saving to buy a new sound system. He plans to deposit S i 0 0 eachmonth for the next 24 months in the Bank of Montrose. T h e nominal interest rate at theBank of Montrose is 0.5% per month, compounded continuously. How much willYoram have at the end of the 24 months?We start by computing the uniform series compound amount factor for continuouscompounding. Recall that the factor for discrete compounding is(i + if
(F/A,m
- l
= --
Substituting e - 1 for i and e'~- for (1 + /)- gives the series compound amount,when compounding is continuous, asr
e'- - 1x
(F/A,r,X)
e'
F=
10011001
J).005
1.12749:
1.00501 - 1
- 2544.85Yoram will have about $2 545 saved at the end of the 24 months.M
81
T h e formulas for continuous cash flows with continuous compounding are derived usingintegral calculus._The continuous series present worth factor, denoted by (P/A,r,T), for acontinuous How, A, over a period length, T, where the nominal interest rate is r, is given by-leP = A1
rT
1rT
re
so that(P/A,r,T)
e=
- 1y^
It is then easy to d_erive the formula for the continuous uniform series compound amountfactor, denoted by (F/A,r,T), by multiplying the series present worth factor by e to getthe future worth of a present value, P.rT
e'- - 1T
We can get the continuous capital recovery factor, denoted by (A/P,r,T), as theinverse of the continuous series present worth factor. T h e continuous sinking fund factor(F/A,r,T) is the inverse of the continuous uniform series compound amount factor.A summary of the formulas for continuous cash flow and continuous compounding isshown in Table 3A.2. Tables of values for these formulas are available in Appendix C atthe back of the book.Table 3A.2
(A,F,r,T) = re - 1
(F/A,r,T) =
re(A,/P,r,T) = ^f-
(P/A,r,T) =
rrT
e rT
17^-
rl
3 A . 2
Savings from a new widget grinder are estimated to be SI0 000 per year. T h e grinder willlast 20 years and will have no scrap value at the end of that time. Assume that the savingsare generated as a continuous flow. T h e effective interest rate is 15% compounded continuously. W nat is the present worth of the savings?From the problem statement, we know that A = SlO 000, i 0.15, and T = 20. Fromthe relation i f - 1, for / = 0.15 the interest rate to apply for continuously compoundingis r = 0.13976. The present worth computations areP = A(P/A,r,T)
82
,(0.13976)20 _ !
= 10
0 0 0
((o.i3976) (e
1 3 9 7 6
2 0
= 67 180T h e present worth of the savings is S67 180. Note that if we had used discretecompounding factors for the present worth computations we would have obtained alower value.P = A(P/A,i,X)= 10 000(6.2593)= 62 5 9 3 B
REVIEW
3A.1
FOR
APPENDIX
3A
Mr. Big is thinking of buying the M Q M Grand Hotel in Las Vegas. T h e hotel hascontinuous net receipts totalling S120 000 000 per year (Vegas hotels run 24 hours perday). This money could be immediately reinvested in Mr. Big's many other ventures, allof which earn a nominal 10% interest. T h e hotel will likely be out of style in about eightyears, and could then be sold for about S200 000 000. V\ nat is the maximum Mr. Bigshould pay for the hotel today?ANSWERP = 120 000 000(PA-1,10%,8) + 200 000 OOOr^XBe
(0.1)(8) _ j
01
A P P E N D I X
3A.2
Desmond earns 2 5 000 continuously over a year from an investment that pays 8%nominal interest, compounded continuously. How much money does he have at the endof the year?
3A. 3 Gina intently plays the stock market, so that any capital she has can be considered to becompounding continuously. At the end of 2009, Gina had S10 000. How much did shehave at the beginning of 2009, if she earned a nominal interest rate of 18%?3A.4 Gina (from Problem 3A.3) had earned a nominal interest rate of 18% on the stockmarket every year since she started with an initial investment of S100. W h a t year did shestart investing?
F = P(l + if
3B.1
F = P(l + if = P(F/P,i,X)so that the compound amount factor is
3B.2
(3B.1)
P = F(P/F,i,X)= > F
{(P/F,i,X)
Thus the present worth factor is the reciprocal of the compound amount factor. FromEquation (3B.1),
3B.3
F = A(l + if-i
84
+ (1 + i)
(3B.2)
+ ...+ (1 + i)l + 1]
+ o
1](1 + i)
(3B.3)
+ i)-F = A[(l
Fi = A[(\A =F
+ if- 1]
(l+if-
3B.4
i(1 + if
(3B.4)
"A =F4.\(F/A,i,N)1
Thus the uniform series compound amount factor is the reciprocal of the sinking fundfactor. From Equation (3B.4),(F/A,i,N) =
3B.5
(i +
if - i
- ' - .
...
.v , \
85
P=Av
+i)J
(l
+...+\(l+f) ){(1+tf- )
\(l+if
(3B.5)
P(l + i)=A
+ .. .
(1 + , ). V - l
(3B.6)
Pi = A 1 - (1 + ifP=AA=P
(1 + if -
i{\ +if/(l + if
(l+if-l
(A/P,i,N) =
3B.6
1(1 +
if
(1+if-
(3B.7)
A = P\
,(p/Am,
Thus the uniform series compound amount factor is the reciprocal of the sinking fundfactor. From Equation (3B.7),
(l + o - v - 1;(1 + 0 V
3B.7
H A P T E R
ComparisonMethodsL^Part 1Engineering Economics in Action, Part 4A: What's Best?
Review ProblemsSummaryEngineering Economics in Action, Part 4B: Doing It RightProblemsMini-Case 4.1Appendix 4A: The MARR and the Cost of Capital
Comparison
Methods
Part
IntroductionT h e essential idea of investing is to give up something valuable now for the expectationof receiving something of greater value later. An investment may be thought of as anexchange of resources now for an expected flow of benefits in the future. Business firms,other organizations, and individuals all have opportunities to make such exchanges.A company may be able to use funds to install equipment that will reduce labour costs inthe future. These funds might otherwise have been used on another project or returnedto the shareholders or owners. An individual may be able to studv to become anengineer. Studying requires that time be given up that could have been used to earnmoney or to travel. T h e benefit of study, though, is the expectation of a good incomefrom an interesting- job in the future.
88
Not all investment opportunities should be taken. T h e company considering a laboursaving investment may find that the value of the savings is less than the cost of installingthe equipment. Not all investment opportunities can be taken. The person spending thenext four years studying engineering cannot also spend that time getting degrees in lawand science.Engineers play a major role in making decisions about investment opportunities. Inmany cases, they are the ones who estimate the expected costs of and returns from aninvestment. They then must decide whether the expected returns outweigh the costs to seeif the opportunity is potentially acceptable. They may also have to examine competinginvestment opportunities to see which is best. Engineers frequently refer to investmentopportunities as projects. Throughout the rest of this text, the term project will be used tomean investment opportunity.In this chapter and in Chapter 5, we deal with methods of evaluating and comparingprojects, sometimes called comparison methods. We start in this chapter with a scheme forclassifying groups of projects. This classification system permits the appropriate use of anyof the comparison methods. We then turn to a consideration of several widely used methodsfor evaluating opportunities. The present worth method compares projects by looking atthe present worth of all cash flows associated with the projects. The annual worth methodis similar, but converts all cash flows to a uniform series, that is, an annuity. The paybackperiod method estimates how long it takes to "pay back" investments. T h e study ofcomparison methods is continued in Chapter 5, which deals with the internal rate of return.We have made six assumptions about all the situations presented in this chapter and inChapter 5:1. We have assumed that costs and benefits are always measurable in terms ofmoney. In reality, costs and benefits need not be measurable in terms of moneyFor example, providing safe working conditions has many benefits, includingimprovement of worker morale. However, it would be difficult to express thevalue of improved worker morale objectively in dollars and cents. Such otherbenefits as the pleasure gained from appreciating beautiful design may not bemeasurable quantitatively. We shall consider qualitative criteria and multipleobjectives in Chapter 13.2.
We have assumed that future cash flows are known with certainty. In reality,future cash flows can only be estimated. Usually the farther into the future wetry to forecast, the less certain our estimates become. We look at methods ofassessing the impact of uncertainty and risks in Chapters 11 and 12.
4.
LJnless otherwise stated, we have assumed that sufficient funds are available toimplement all projects. In reality, cash constraints on investments may be veryimportant, especially for new enterprises with limited ability to raise capital. Welook at methods of raising capital in Appendix 4A.
5.
We have assumed that taxes are not applicable. In reality, taxes are pervasive. Weshall show how to include taxes in the decision-making process in Chapter 8.Unless otherwise stated, we shall assume that all investments have a cash outflowat the start. These outflows are called first costs. We also assume that projects withfirst costs have cash inflows after the first costs that are at least as great in total asthe first costs. In reality, some projects have cash inflows at the start, but involvea commitment of cash outflows at a later period. For example, a consultingengineer may receive an advance payment from a client, a cash inflow, to cover
6.
89
some of the costs of a project, but to complete the project the engineer will haveto make disbursements over the project's life. We shall consider evaluation ofsuch projects in Chapter 5.
independent,
2.3.
mutually exclusive, orrelated but not mutually exclusive.
T h e simplest relation between projects occurs when they are independent. Twoprojects are independent if the expected costs and the expected benefits of each project donot depend on whether the other one is chosen. A student considering the purchase of avacuum cleaner and the purchase of a personal computer would probably find that theexpected costs and benefits of the computer did not depend on whether he or she boughtthe vacuum cleaner. Similarly, the benefits and costs of the vacuum cleaner would be thesame, whether or not the computer was purchased. If there are more than two projectsunder consideration, they are said to be independent if all possible pairs of projects in theset are independent. WTen two or more projects are independent, evaluation is simple.Consider each opportunity one at a time, and accept or reject it on its own merits.Projects are mutually exclusive if, in the process of choosing one, all other alternatives are excluded. In other words, two projects are mutually exclusive if it is impossible todo both or it clearly would not make sense to do both. For example, suppose BismuthRealty Company wants to develop downtown office space on a specific piece of land. Theyare considering two potential projects. The first is a low-rise poured-concrete building.T h e second is a high-rise steel-frame structure with the same capacity as the low-risebuilding, but it has a small park at the entrance. It is impossible for Bismuth to have bothbuildings on the same site.As another example, consider a student about to invest in a computer printer. She canget an inkjet printer or a laser printer, but it would not make sense to get both. She wouldconsider the options to be mutually exclusive.The third class of projects consists of those that are related but not mutually exclusive. For pairs of projects in this category, the expected costs and benefits of one projectdepend on whether the other one is chosen. For example, Klamath Petroleum may beconsidering a service station at Fourth Avenue and Alain Street as well as one at Twelfthand Alain. The costs and benefits from either station will clearlv depend on whether theother is built, but it may be possible, and may make sense, to have both stations.Evaluation of related but not mutually exclusive projects can be simplified by combiningthem into exhaustive, mutually exclusive sets. For example, the two projects being considered by Klamath can be put into four mutually exclusive sets:1.2.3.4.
90
In general, n related projects can be put into 2" sets including the "do nothing"option. Once the related projects are put into mutually exclusive sets, the analyst treatsthese sets as the alternatives. We can make 2" mutually exclusive sets with n relatedprojects by noting that for any single set there are exactly two possibilities for each project.The project may be in or out of that set. To get the total number of sets, we multiply the77 twos to get 2". In the Klamath example, there were two possibilities for the station atFourth and Alainaccept or reject. These are combined with the two possibilities for thestation at Tvelfth and Alain, to give the four sets that we listed.A special case of related projects is where one project is contingent on another. Considerthe case where project A could be done alone or A and B could be done together, butB could not be done by itself. Project B is then contingent on project A because it cannot betaken unless A is taken first. For example, the Athens and Alanchester DevelopmentCompany is considering building a shopping mall on the outskirts of town. They are alsoconsidering building a parking garage to avoid long outdoor walks by patrons. Clearly, theywould not build the parking garage unless they were also building the mall.Another special case of related projects is due to resource constraints. Usually theconstraints are financial. For example, Bismuth may be considering two office buildings atdifferent sites, where the expected costs and benefits of the two are unrelated, but Bismuthmay be able to finance only one building. The two office-building projects would then bemutually exclusive because of financial constraints. If there are more than two projects, thenall of the sets of projects that meet the budget form a mutually exclusive set of alternatives.W h e n there are several related projects, the number of logically possible combinations becomes quite large. If there are four related projects, there are 2 = 16 mutuallyexclusive sets, including the "do nothing" alternative. If there are five related projects,the number of alternatives doubles to 32. A good way to keep track of these alternativesis to construct a table with all possible combinations of projects. Example 4.1 demonstrates the use of a table.4
4 . 1
T h e Small Street Residential Association wants to improve the district. Four ideas forrenovation projects have been proposed: (1) converting part of the roadway to gardens,(2) adding old-fashioned light standards, (3) replacing the pavement with cobblestones,and (4) making the street one way. However, there are a number of restrictions. Theassociation can afford to do only two of the first three projects together. Also, gardensare possible only if the street is one way. Finally, old-fashioned light standards wouldlook out of place unless the pavement was replaced with cobblestones. The residentialassociation feels it must do something. They do not want simply to leave things the waythey are. W h a t mutually exclusive alternatives are possible?Since the association does not want to "do nothing," only 15 = 2 - 1 alternativeswill be considered. These are shown in Table 4.1. T h e potential projects are listed inrows. T h e alternatives, which are sets of projects, are in columns. An "x" in a cellindicates that a project is in the alternative represented bv that column. Not all logicalcombinations of projects represent feasible alternatives, as seen in the special cases ofcontingent alternatives or budget constraints. A last row, below the potential-projectrows, indicates whether the sets are feasible alternatives.T h e result is that there are seven feasible mutually exclusive alternatives:4
1. Cobblestones (alternative 3)2. One-way street (alternative 4)3.
5.6.
7.
Table 4 . 1
91
PotentialAlternative
Gardens
Lights
Cobblestones
One-wayFeasible?
15X
To summarize our investigation of possible relations among projects, we have a threefold classification system: (1) independent projects, (2) mutually exclusive projects, and(3) related but not mutually exclusive projects. We can, however, arrange related projectsinto mutually exclusive sets and treat the sets as mutually exclusive alternatives. Thisreduces the system to two categories, independent and mutually exclusive. (See Figure 4.1.)Therefore, in the remainder of this chapter we consider only independent and mutuallyexclusive projects.Figure 4 . 1
Set of n projectsRelated but notmutually exclusive:( o r g a n i z e intomutually exclusivesubsets, up to 2in n u m b e r )
M u t u a l l y exclusive:(rank a n d pick thebest o n e )
Independent:(evaluate e a c ho n e separately)
earned elsewhere. Projects that earn less than the MARR are not desirable, since investingmonev in these projects denies the opportunity to use the money more profitablyelsewhere.The ALARR can also be viewed as the rate of return required to get investors to investin a business. If a company accepts projects that earn less than the MARR, investors willnot be willing to put money into the company. This minimum return required to induceinvestors to invest in the company is the company's cost of capital. Alethods for determining the cost of capital are presented in Appendix 4A.T h e ALARR is thus an opportunity cost in two senses. First, investors have investmentopportunities outside any given company. Investing in a given company implies forgoingthe opportunity of investing elsewhere. Second, once a company sets a ALARR, investingin a given project implies giving up the opportunity of using company funds to invest inother projects that pay at least the ALARR.We shall show in this chapter and in Chapter 5 how the MARR is used in calculationsinvoking the present worth, annual worth, or internal rate of return to evaluate projects.Henceforth, it is assumed that a value for the ALARR has been supplied.
Sometimes mutually exclusive projects are compared in terms of present cost or annualcost. That is, the best project is the one with minimum present worth of cost as opposedto the maximum present worth. Tvo conditions should hold for this to be valid: (1) allprojects have the same major benefit, and (2) the estimated value of the major benefitclearly outweighs the projects' costs, even if that estimate is imprecise. Therefore, the"do nothing" option is rejected. The value of the major benefit is ignored in furthercalculations since it is the same for all projects. We choose the project with the lowestcost, considering secondary benefits as offsets to costs.
93
However, the present worth of any money invested at the M A R R is zero, since thepresent worth of future receipts would exactly offset the current disbursement.Consequently, if an independent project has a present worth greater than zero, it isacceptable. If an independent project has a present worth less than zero, it is unacceptable. If an independent project has a present worth of exactly zero, it is consideredmarginally acceptable.
4 . 2
Steve Chen, a third-year electrical engineering student, has noticed that the networkedpersonal computers provided by his university for its students are frequently fullyutilized, so that students often have to wait to get on a machine. T h e university has abuilding plan that will create more space for network computers, but the new facilitieswon't be available for five years. In the meantime, Steve sees the opportunity to createan alternative network in a mall near the campus. The first cost for equipment, furniture, and software is expected to be S70 000. Students would be able to rent time oncomputers by the hour and to use the printers at a charge per page. Annual net cash flowfrom computer rentals and other charges, after paying for labour, supplies, and othercosts, is expected to be S30 000 a year for five years. W h e n the university opens newfacilities at the end of five years, business at Steve's network would fall off and net cashflow would turn negative. Therefore, the plan is to dismantle the network after fiveyears. T h e five-year-old equipment and furniture are expected to have zero value. Ifinvestors in this type of service enterprise demand a return of 20% per year, is this agood investment?T h e present worth of the project isPW = - 7 0 000 + 30 000(P/4,20%,5)= - 7 0 000 + 30 000(2.9906)= 19 718= 20 000T h e project is acceptable since the present worth of about S20 000 is greater than zero.Another way to look at the project is to suppose that, once Steve has set up thenetwork off campus, he tries to sell it. If he can convince potential investors, whodemand a return of 20% a year, that the expectation of a S30 000 per year cash flow forfive years is accurate, how much would they be willing to pay for the network? Investorswould calculate the present worth of a 20% annuity paying $30 000 for five years. Thisis given byPW = 30 000(P/<4,20%,5)= 30 000(2.9906)= 89 718= 90 000Investors would be willing to pay approximately S90 000. Steve will have taken$70 000, the first cost, and used it to create an asset worth almost S90 000. As illustratedin Figure 4.2, the S20 000 difference may be viewed as profit.H
94
Figure 4.2
S70 000
Firstcost
S20 000
Profit
Recoveredcost
V a l u e created
4 . 3
SI5 000S3300S400S2400S300
perperperper
yearyearyearyear
If the ALARR is 9%, which alternative is better? Use a present worth comparison.T h e investment of S i 5 000 can be viewed as yielding a positive cash flow of9200 - (3300 + 400 + 2400 + 300) per year in the form of a reduction in2800cost.PW = - 1 5 000 + [9200 - (3300 + 400 + 2400 + 300)](P//1,9%,10)= - 1 5 000 + 2800(P/^,9%,10)= - 1 5 000 + 2800(6.4176)= 2969.44T h e present worth of the cost savings is approximately S3000 greater than the$15 000 first cost. Therefore, Alternative 2 is worth implementing.B
It is very easy to use the present worth method to choose the best project among a set ofmutually exclusive projects when the service lives are the same. One just computes thepresent worth of each project using the AiARR. T h e project with the greatest presentworth is the preferred project because it is the one with the greatest profit.E X A M P L E
4 . 4
Fly-by-Night Aircraft must purchase a new lathe. It is considering four lathes, each ofwhich has a life of 10 years with no scrap value.LatheFirst costAnnual savings
S100 000
SI50 000
S200 000
S255 000
25 000
34 000
46 000
55 000
PW = - 1 0 0 000 + 25 000(PA4,15%,10)= - 1 0 0 000 + 25 000(5.0187) = 25 468
PW = - 2 0 0 000 + 46 000(PZ4,15%,10)= - 2 0 0 000 + 46 000(5.0187) = 30 860
Lathe 4:
PW = - 2 5 5 000 + 55 000(P//4,15%,10)
Annual worth comparisons are essentially the same as present worth comparisons,except that all disbursements and receipts are transformed to a uniform series at theMARR, rather than to the present worth. Any present worth P can be converted to anannuity A by the capital recovery factor (A/P,i,N). Therefore, a comparison of twoprojects that have the same life by the present worth and annual worth methods willalways indicate the same preferred alternative. Note that, although the method is calledannual worth, the uniform series is not necessarily on a yearly basis.Present worth comparisons make sense because they compare the worth today of eachalternative, but annual worth comparisons can sometimes be more easily grasped mentally.For example, to say that operating an automobile over five years has a present cost ofS20 000 is less meaningful than saying that it will cost about $5300 per year for each of thefollowing five years.
Sometimes there is no clear justification for preferring either the present worthmethod or the annual worth method. Then it is reasonable to use the one that requiresless conversion. For example, if most receipts or costs are given as annuities or gradients,one can more easily perform an annual worth comparison. Sometimes it can be useful tocompare projects on the basis of future worths. See Close-Up 4.2.
F u t u r e Worth
Sometimes it may be desirable to compare projects with the future worth method, onthe basis of the future worth of each project. This is most likely to be true for cases wheremoney is being saved for some future expense.For example, two investment plans are being compared to see which accumulatesmore money for retirement. Plan A consists of a payment of 1 0 000 today and then2000 per year over 20 years. Plan B is 3000 per year over 20 years. Interest for bothplans is 10%. Rather than convert these cash flows to either present worth or annualworth, it is sensible to compare the future worths of the plans, since the actual euro valuein 20 years has particular meaning.F W = 10 000(P/P,10%,20) + 2000(F/.4,10%,20)A
= 10 000(6.7275) + 2000(57.275)= 181 825F W = 3000(F/^,10%,20)B
= 3000(57.275)= 171 825Plan A is the better choice. It will accumulate to 181 825 over the next 20 years.
97
4 . 5
Sweat University is considering two alternative types of bleachers for a new athleticstadium.Alternative 1: Concrete bleachers. T h e first cost is S3 50 000. T h e expected life of theconcrete bleachers is 90 years and the annual upkeep costs are $2500.Alternative 2: Wooden bleachers on earth fill. T h e first cost of $200 000 consists of$ 1 0 0 000 for earth fill and $100 000 for the wooden bleachers. T h e annual paintingcosts are $5000. T h e wooden bleachers must be replaced every 30 years at a cost of$100 000. T h e earth fill will last the entire 90 years.One of the two alternatives will be chosen. It is assumed that the receipts and otherbenefits of the stadium are the same for both construction methods. Therefore, thegreatest net benefit is obtained by choosing the alternative with the lower cost. T h euniversity uses a MARR of 7%. WTiich of the two alternatives is better?For this example, let us base the analysis on annual worth. $ince both alternativeshave a life of 90 years, we shall get the equivalent annual costs over 90 years for both atan interest rate of 7%.Alternative 1: Concrete bleachersThe equivalent annual cost over the 90-year life span of the concrete bleachers isAW = 350 000(^/P,7%,90) + 2500= 350 000(0.07016) + 2500= 27 056 per yearAlternative 2: Wboden bleachers on earth fillT h e total annual costs can be broken into three components: AWi (for the earth fill),AW2 (for the bleachers), and A W 3 (for the painting). T h e equivalent annual cost of theearth fill isAW! = 100 000(^/P,7%,90)T h e equivalent annual cost of the bleachers is easy to determine. T h e first set ofbleachers is put in at the start of the project, the second set at the end of 30 years, andthe third set at the end of 60 years, but the cost of the bleachers is the same at eachinstallation. Therefore, we need to get only the cost of the first installation.AW
- 100 000(^/P,7%,30)
= 5000
T h e total equivalent annual cost for alternative 2, wooden bleachers on earth fill, isthe sum of A W , AWi, and AW3:(
AW = AW! + AW2 + AW
C o m p a r i s o n o f A l t e r n a t i v e s W i t h U n e q u a l Lives
W h e n making present worth comparisons, we must ahvays use the same time period inorder to take into account the hill benefits and costs of each alternative. If the lives ofthe alternatives are not the same, we can transform them to equal lives with one of thefollowing two methods:1. Repeat the service life of each alternative to arrive at a common time periodfor all alternatives. Here we assume that each alternative can be repeatedwith the same costs and benefits in the futurean assumption known asr e p e a t e d lives. Usually we use the least common multiple of the lives of thevarious alternatives. Sometimes it is convenient to assume that the lives ofthe various alternatives are repeated indefinitely. Note that the assumptionof repeated lives may not be valid where it is reasonable to expecttechnological improvements.2. Adopt a specified study perioda time period that is given for the analysis. Toset an appropriate studv period, a company will usually take into account thetime of required service, or the length of time they can be relatively certain oftheir forecasts. T h e study period method necessitates an additional assumptionabout salvage value whenever the life of one of the alternatives exceeds that of thegiven study period. Arriving at a reliable estimate of salvage value may bedifficult sometimes.Because they rest on different assumptions, the repeated lives and the study periodmethods can lead to different conclusions when applied to a particular project choice.
4 . 6
( M O D I F I C A T I O N
O F
4 . 3 )
$15 000S3 300$400S2400$30010
per yearper yearper yearper yearyears
$600
per year
S3075S500
per year15 yearsIf the ALARR is 9%, which alternative is better?
99
L e a s t C o m m o n M u l t i p l e o f the S e r v i c e Lives
Alternative 1
> j <
Alternative 2
Alternative 1>^<
Alternative
Years
W i t h the same time period of 30 years for both alternatives, we can now comparepresent worths.Alternative 1: Build custom automated materials-handling equipment and repeat twiceP W ( 1 ) = - 1 5 000 - 15 000(P/F,9%,10) - 15 000(P/F,9%,20)- (3300 + 400 + 2400 + 300)(PA4,9%,30)= - 1 5 000 - 15 000(0.42241) - 15 000(0.17843) - 6400 (10.273)= - 8 9 760Alternative 2: Buy off-the-shelf standard automated materials-handling equipment andrepeat onceP W ( 2 ) = - 2 5 000 - 25 000(P/F,9%,15)- ( 1 4 5 0 + 600 + 3075 + 500)(P/,4,9%,30)= - 2 5 000 - 25 000(0.27454) - 5625(10.273)= - 8 9 649
100
Using the repeated lives method, we find little difference between the alternatives.An annual worth comparison can also be done over a period of time equal to the leastcommon multiple of the service lives by multiplying each of these present worths by thecapital recovery factor for 30 years.A W ( 1 ) = - 8 9 760(T/P,9%,30)= - 8 9 760(0.09734)= -8737A W ( 2 ) = - 8 9 649(.^f/P,9%,30)= - 8 9 649(0.09734)= -8726As we would expect, there is again little difference in the annual cost between thealternatives. However, there is a more convenient approach for an annual worth comparison if it can be assumed that the alternatives are repeated indefinitely. Since the annualcosts of an alternative remain the same no matter how many times it is repeated, it is notnecessary to determine the least common multiple of the sendee lives. The annual worthof each alternative can be assessed for whatever time period is most convenient for eachalternative.Alternative 1: Build custom automated materials-handling equipmentA W ( 1 ) = - 1 5 000(T/P,9%,10) - 6400= -15 000(0.15582)-6400= -8737Alternative 2: Buy off-the-shelf standard automated materials-handling equipmentA W ( 2 ) = - 2 5 000C4/P,9%,15) - 5625= - 2 5 0 0 0 ( 0 . 1 2 4 0 6 ) - 5625= -8726If it cannot be assumed that the alternatives can be repeated to permit a calculationover the least common multiple of their sendee lives, then it is necessary to use the studyperiod method.Suppose that the given study period is 10 years, because the engineer is uncertainabout costs past that time. T h e sendee life of the off-the-shelf system (15 years) isgreater than the study period (10 years). Therefore, we have to make an assumptionabout the salvage value of the off-the-shelf system after 10 years. Suppose the engineerjudges that its salvage value will be S5000. We can now proceed with the comparison.
101
4 . 7
Joan is renting a flat while on a one-year assignment in England. T h e flat does not havea refrigerator. $he can rent one for a 100 deposit (returned in a year) and 15 permonth (paid at the end of each month). Alternatively, she can buy a refrigerator for300, which she would sell in a year when she leaves. For how much would Joan haveto be able to sell the refrigerator in one year when she leaves, in order to be better offbuying the refrigerator than renting one? Interest is at 6% nominal, compoundedmonthly.Let 5 stand for the unknown salvage value (i.e., the amount Joan will be able tosell the refrigerator for in a year). We then equate the present worth of the rentalalternative with the present worth of the purchase alternative for the one-year studyperiod:PW(rental) = PW(purchase)- 1 0 0 - 15(PA4,0.5%,12) + 100(P/F,0.5%,12) = - 3 0 0 + S(P/F,0.5%,12)- 1 0 0 - 15(11.616) + 100(0.94192) = - 3 0 0 + 5(0.94192)S = 127.35If Joan can sell the used refrigerator for more than about 127 after one year's use,she is better off buying it rather than renting one.H
Payback PeriodT h e simplest method for judging the economic viability of projects is the paybackperiod method. It is a rough measure of the time it takes for an investment to pay foritself. More precisely, the payback period is the number of years it takes for an investment to be recouped when the interest rate is assumed to be zero. W h e n annual savingsare constant, the payback period is usually calculated as follows: , ,. ,r a v b a c k period =
First cost::Annual savings
For example, if a first cost of S20 000 yielded a return of S8000 per year, then the payback period would be 20 000/8000 = 2.5 years.If the annual savings are not constant, we can calculate the payback period bydeducting each year of savings from the first cost until the first cost is recovered.T h e number of years required to pay back the initial investment is the paybackperiod. For example, suppose the saving from a $20 000 first cost is S5000 the firstyear, increasing by $1000 each year thereafter. By adding the annual savings oneyear at a time, we see that it would take a just over three years to pay back the firstcost (5000 + 6000 + 7000 + 8000 = 26 000). T h e payback period would then bestated as either four years (if we assume that the $8000 is received at the end of thefourth year) or 3.25 years (if we assume that the $8000 is received uniformly overthe fourth year).According to the payback period method of comparison, the project with the shorterpayback period is the preferred investment. A company may have a policy of rejectingprojects for which the payback period exceeds some preset number of years. T h e length ofthe maximum payback period depends on the type of project and the company's financialsituation. If the company expects a cash constraint in the near future, or if a project'sreturns are highly uncertain after more than a few periods, the company will set amaximum payback period that is relatively short. As a common rule, a payback period oftwo years is often considered acceptable, while one of more than four years is unacceptable. Accordingly, government grant programs often target projects with payback periodsof between two and four years on the rationale that in this range the grant can justifyeconomically feasible projects that a company with limited cash flow would otherwise beunwilling to undertake.The payback period need not, and perhaps should not, be used as the sole criterion forevaluating projects. It is a rough method of comparison and possesses some glaring weaknesses (as we shall discuss after Examples 4.8 and 4.9). Nevertheless, the payback periodmethod can be used effectively as a preliminary filter. All projects with paybacks within theminimum would then be evaluated, using either rate of return methods (Chapter 5) orpresent/annual worth methods.
4 . 8
Elyse runs a second-hand book business out of her home where she advertises andsells the books over the internet. Her small business is becoming quite successfuland she is considering purchasing an upgrade to her computer system that will giveher more reliable u p t i m e . T h e cost is $ 5 0 0 0 . $ h e expects that the i n v e s t m e n twill bring about an annual savings of $2000, due to the fact that her system will
103
no longer suffer long failures and thus she will be able to sell more books. W h a t isthe payback period on her investment, assuming that the savings accrue over thewhole year? , .. .First cost5000_ravback period = ::== 1.5 vearsHAnnual savings2000
4 . 9
Pizza-in-a-Hurry operates a pizza delivery sendee to its customers with two eightyear-old vehicles, both of which are large, consume a great deal of gas and are startingto cost a lot to repair. T h e owner, Ray, is thinking of replacing one of the cars with asmaller, three-year-old car that his sister-in-law is selling for S8000. Ray figures he cansave $3000, S2000, and S1500 per year for the next three years and $1000 per year forthe following two years by purchasing the smaller car. W h a t is the payback period forthis decision?T h e payback period is the number of years of savings required to pay back the initialcost. After three years, $3000 + $2000 + $1500 = $6500 has been paid back, and thisamount is $7500 after four years and $8500 after five years. T h e payback period wouldbe stated as five years if the savings are assumed to occur at the end of each year, or4.5 years if the savings accrue continuously throughout the year.HT h e payback period method has four main advantages:1. It is very easy to understand. One of the goals of engineering decision making isto communicate the reasons for a decision to managers or clients with a variety ofbackgrounds. T h e reasons behind the payback period and its conclusions are veryeasy to explain.2.
T h e payback period is very easy to calculate. It can usually be done without evenusing a calculator, so projects can be very- quickly assessed.
It accounts for the need to recover capital quickly. Cash flow is almost always aproblem for small- to medium-sized companies. Even large companies sometimes can't tie up their money in long-term projects.
The future is unknown. The future benefits from an investment may be estimatedimprecisely. It may not make much sense to use precise methods like presentworth on numbers that are imprecise to start with. A simple method like thepayback period may be good enough for most purposes.
It ignores the effect of the timing of cash flows within the payback period. Itdisregards interest rates and takes no account of the time value of money(Occasionally, a discounted payback period is used to overcome this disadvantage.$ee Close-Up 4.3.)
It ignores the expected sendee life. It disregards the benefits that accrue after theend of the payback period.
104
D i s c o u n t e d P a y b a c k Period
In a discounted payback period calculation, die present worth of each year's savings issubtracted from the first cost until the first cost is diminished to zero. The number ofyears of savings required to do this is the discounted payback period. The main disadvantages of using a discounted payback period include the more complicated calculationsand the need for an interest rate.For instance, in Example 4.8, Elyse had an investment of S5000 recouped by annualsavings of $2000. If interest were at 10%, the present worth of savings would be:YearYear 1Year 2Year 3Year 4
Cumulative
Present Worth2000(P/F,10%,1)2000(P/F10%,2)2000(P/F10%,3)2000(P/F,10%,4)
2000(0.90909)2000(0.82645)2000(0.75131)2000(0.68301)
====
1818165315031366
1818347149746340
Thus the discounted payback period is over 3 years, compared with 2.5 years calculatedfor the standard payback period.
Example 4.10 illustrates how the payback period method can ignore future cash flows.E X A M P L E
4 . 1 0
Self Defence Systems of Cape Town is going to upgrade its paper-shredding facility.T h e company has a choice between two models. M o d e l 007, with a first cost ofR500 000 and a service life of seven years, would save R100 000 per year. Model MX,with a first cost of R100 000 and an expected service life of 20 years, would save R15 000per year. If the company's ALARR is 8%, which model is the better buy?Using payback period as the sole criterion:Model 007: Payback period = 500 000/100 000 = 5 yearsModel MX: Payback period = 100 000/15 000 = 6.6 yearsIt appears that the 007 model is better.Using annual worth:Model 007: AW = - 5 0 0 000(.^/P,8%,7) + 100 000 = 3965Model MX: AW = -100 000(.-f/P,8%,20) + 15 000 = 4815Here, Model MX is substantially better.T h e difference in the results from the two comparison methods is that the paybackperiod method has ignored the benefits of the models that occur after the models havepaid themselves off. This is illustrated in Figure 4.4. For Model AFX, about 14 years ofbenefits have been omitted, whereas for model 007, only two years of benefits have beenleft out.B
CHAPTER 4
Figure 4.4
Flows I g n o r e d by t h e P a y b a c k Period
<
A A
0 1
(b) Model MX
Ignored
A A A A A A A A A A A A A A A A A A A A
10 11 12 13 14 15 16 17 18 19 20
P R O B L E M S4.1
Project
First Cost
Present Worth
A: Renovate plant 1
$0.8 million
$1.1 million
B: Renovate plant 2
SI.2 million
$1.7 million
C: Renovate plant 3
$1.4 million
$1.8 million
D: Renovate plant 4
$2.0 million
$2.7 million
Table 4.2 shows the possible mutually exclusive projects that Tilson can consider.Tilson should accept projects A, B, and C. T h e y have a combined present worth of$4.6 million. Other feasible combinations that come close to using all available funds areB and D with a total present worth of $4.4 million, and C and D with a total presentworth of $4.5 million.Note that it is not necessary to consider explicitly the "leftovers" of the $3.5 millionbudget when comparing the present worths. T h e assumption is that any leftover part of
106
the budget will be invested and provide interest at the M A R R , resulting in a zeropresent worth for that part. Therefore, it is best to choose the combination of projectsthat has the largest total present worth and stays within the budget c o n s t r a i n t sTable 4 . 2
Total FirstCost
Total PresentWorth
Feasibility
Do nothing
SO.O million
Feasible
S0.8 million
Si.2 million
SI.4 million
S2.0 million
A and B
S2.8 million
A and C
$2.2 million
$2.9 million
A and D
$2.8 million
S3.8 million
B and C
$2.6 million
$3.5 million
BandD
$3.2 million
$4.4 million
CandD
$3.4 million
S4.5 million
A, B,and C
S3.4 million
S4.6 million
A, B,and D
$4.0 million
$5.5 million
Not feasible
A, C, and D
S4.2 million
$5.6 million
B, C,and D
$4.6 million
$6.2 million
A, B, C, and D
$5.4 million
$7.3 million
City engineers are considering two plans for municipal aqueduct tunnels. T h e y are todecide between the two, using an interest rate of 8%.Plan A is a full-capacity tunnel that will meet the needs of the city forever. Its cost is$3 000 000 now, and S i 0 0 000 every 10 years for lining repairs.Plan B involves building a half-capacity tunnel now and a second half-capacity tunnel in 20 years, when the extra capacity will be needed. Each of the half-capacity tunnelscosts $2 000 000. Maintenance costs for each tunnel are $80 000 every 10 years. Thereis also an additional $15 000 per tunnel per year required to pay for extra pumping costscaused by greater friction in the smaller tunnels.(a) Which alternative is preferred? Use a present worth comparison.(b) W h i c h alternative is preferred? Use an annual worth comparison.ANSWER
107
Thus, at 8% interest, Si00 000 every" 10 years is equivalent to S6903 every year.Since the tunnel will have (approximately) an infinite life, the present cost ofthe lining repairs can be found using the capitalized cost formula, giving a totalcost ofPW(Plan A) = 3 000 000 + 6903/0.08 = 3 086 288Plan B: Half-Capacity
Tunnels
For the first tunnel, the equivalent annuity for the maintenance and pumpingcosts isAW = 15 000 + 80 000(0.06903) = 20 522T h e present cost is then found with the capitalized cost formula, giving atotal cost ofP W , = 2 000 000 + 20 522/0.08 = 2 256 525Now, for the second tunnel, basically the same calculation is used, exceptthat the present worth calculated must be discounted by 20 years at 8%, sincethe second tunnel will be built 20 years in the future.P W = {2 000 000 + [15 000 + 80 000(0.06903)]/0.08}(P/F,8%,20)2
Since the tunnel will have (approximately) an infinite life, an annuity equivalentto the initial cost can be found using the capitalized cost formula, giving a totalannual cost ofAW(Plan A) = 3 000 000(0.08) + 6903 = 246 903Plan B: Half-Capacity
For the first tunnel, the equivalent annuity for the maintenance and pumpingcosts isAW = 15 000 - 80 000(0.06903) = 20 522T h e annual equivalent of the initial cost is then found with the capitalizedcost formula, giving a total cost ofA W j = 2 000 000(0.08) + 20 522 = 180 522Now, for the second tunnel, basically the same calculation is used, exceptthat the annuity must be discounted by 20 years at 8%, since the second tunnelwill be built 20 years in the future.7
A W = AWi(P/F,8%,20)= 180 522(0.21455) = 38 7312
108
AW(Plan B) = A W j + A W
Fernando Constantia, an engineer at Brandy River Vineyards, has a $100 000 budget forwinery improvements. He has identified four mutually exclusive investments, all of fiveyears' duration, which have the cash flows shown in Table 4.3. For each alternative, hewants to determine the payback period and the present worth. For his recommendationreport, he will order the alternatives from most preferred to least preferred in each case.Brandy River uses an 8% ALARR for such decisions.Table 4 . 3
5$
- S 1 0 0 000
S25 000
$25 000
- 1 0 0 000
5000
10 000
20 000
40 000
80 000
50 000
ANSWER
T h e payback period can be found by decrementing yearly. The payback periods for thealternatives are thenA: 4 yearsB: 4.3125 or 5 yearsC: 2 yearsD: 4.1 or 5 yearsT h e order of the alternatives from most preferred to least preferred using thepayback period method with yearly decrementing is: C, A, D, B. T h e present worthcomputations for each alternative are:A:
PW = - 1 0 0 000 + 25 000(P/A,S%,5)= - 1 0 0 000 + 25 000(3.9926)= -185
B:
C:
D:
T h e order of the alternatives from most preferred to least preferred using the presentworth method is: D, B, A, C.B
S U M M A R YThis chapter discussed relations among projects, and the present worth, annual worth,and payback period methods for evaluating projects. There are three classes of relationsamong projects, (1) independent, (2) mutually exclusive, and (3) related but not mutuallyexclusive. We then showed how the third class of projects, those that are related but notmutually exclusive, could be combined into sets of mutually exclusive projects. Thisenabled us to limit the discussion to the first two classes, independent and mutuallyexclusive. Independent projects are considered one at a time and are either accepted orrejected. Only the best of a set of mutually exclusive projects is chosen.T h e present worth method compares projects on the basis of converting all cashflows for the project to a present worth. An independent project is acceptable if itspresent worth is greater than zero. T h e mutually exclusive project with the highestpresent worth should be taken. Projects with unequal lives must be compared byassuming that the projects are repeated or by specifying a study period. Annual worth issimilar to present worth, except that the cash flows are converted to a uniform series.T h e annual worth method may be more meaningful, and also does not require morecomplicated calculations when the projects have different service lives.T h e payback period is a simple method that calculates the length of time it takes topay back an initial investment. It is inaccurate but very easy to calculate.
mechanical press. Where potential investments were not independent, it was easiest to form mutually exclusivecombinations as investment options. Naomi came up with seven options. She ranked the options by first cost,starting with the one with the lowest cost:1.
Buy a m a n u a l l y o p e r a t e d m e c h a n i c a l p r e s s .
Buy a m a n u a .
Buy a n a u t o m a t e p l u s i n t e g r a t e i t w i t h t h e m a t e r i a l s - h a n d l i n g e q u i p m e n t .
At this point. Naomi wasn't sure what to do next. There were different ways of comparing the options.Naomi wanted a break from thinking about theory. She decided to take a look at Dave Sullivan's work. Shestarted up her computer and opened up Dave's email. In it Dave apologized for dumping the work on her andinvited Naomi to call him in Florida if she needed help. Naomi decided to call him. The phone was answered byDave's wife, Helena. After telling Naomi that her father was out of intensive care and was in good spirits, Helenaturned the phone over to Dave."Hi, Naomi. How's it going?""Well, I'm trying to finish off the forge project that you started. And I'm taking you up on your offer to consult.""You have my attention. What's the problem?""Well, I've gotten started. I have formed seven mutually exclusive combinations of potential investments."Naomi went on to explain her selection of alternatives."That sounds right. Naomi. I like the way you've organized t h a t . Now, how are you going to make thechoice?""I've just reread the present worth, annual worth, and payback period stuff, and of those three, presentworth makes the most sense to me. I can just compare the present worths of the cash flows for each alternative,and the one whose present worth is highest is the best one. Annual worth is the same, but I don't see any goodreason in this case to look at the costs on an annual basis.""What about internal rate of return?""Well, actually, Dave, I haven't reviewed IRR yet. I'll need it, will I?""You will. Have a look at it, and also remember that your recommendation is for Burns and Kulkowski. Thinkabout how they will be looking at your information.""Thanks, Dave. I appreciate your help.""No problem. This first one is important for you; let's make sure we do it right."
P R O B L E M Si
the
Student
IQ Computer assembles Unix workstations at its plant. The current product line is nearingthe end of its marketing life, and it is time to start production of one or more new products.The data for several candidates are shown below.T h e maximum budget for research and development is S300 000. A minimum ofS200 000 should be spent on these projects. It is desirable to spread out the introductionof new products, so if two products are to be developed together, they should havedifferent lead times. Resource draw refers to the labour and space that are available tothe new products; it cannot exceed 100%.
AResearch anddevelopment costsLead timeResource draw
Potential ProductBC
111
S120 000
S60 000
S75 000
1 year
2 years
60%
50%
40%
30%
On the basis of the above information, determine the set of feasible mutually exclusivealternative projects that IQ Computers should consider.4.2
T h e Alabaster Marble Company (AM) is considering opening three new quarries. One,designated T, is in Tusksarelooser County; a second, L, is in Lefant County; the third,M, is in Marxbro Count} . Marble is shipped mainly within a 500-kilometre range of itsquarry because of its weight. T h e market within this range is limited. T h e returns thatAM can expect from any of the quarries depends on how many quarries AM opens.Therefore, these potential projects are related.-
(a) Construct a set of mutually exclusive alternatives from these three potential projects.(b) The Lefant Count}' quarry has very rich deposits of marble. This makes the purchaseof mechanized cutter-loaders a reasonable investment at this quarry. Such loaderswould not be considered at the other quarries. Construct a set of mutually exclusivealternatives from the set of quarry projects augmented by the potential mechanizedcutter-loader project.(c) AM has decided to invest no more than $2.5 million in the potential quarries. T h efirst costs are as follows:Project
T quarry
S0.9 million
L quarry
1.4 million
M quarry
1.0 million
Cutter-loader
0.4 million
Construct a set of mutually exclusive alternatives that are feasible, given the investment limitation.4.3
Angus Automotive has $100 000 to invest in internal projects. T h e choices are:Project
Cost
1. Line improvements
$20 000
30 000
60 000
4. Overhauling press
112
Only one tester may be bought and the press will not need overhauling if the lineimprovements are not made. W h a t mutually exclusive project combinations are availableif Angus Auto will invest in at least one project?4.4
4.6
Xottawasaga Printing has four printing lines, each of which consists of three printingstations, A, B, and C. They have allocated S20 000 for upgrading the printing stations.Station A costs S7000 and takes 10 days to upgrade. Station B costs S5000 and takes5 days, and station C costs S3000 and takes 3 days. Due to the limited number of technicians, Xottawasaga can only upgrade one printing station at a time. T h a t is, if theydecide to upgrade two Bs, the total downtime will be 10 days. During the upgradingperiod, the downtime should not exceed 14 days in total. Also, at least two printing linesmust be available at all times to satisfy the current customer demand. T h e entire linewill not be available if any of the p r i n t i n g stations is turned off for u p g r a d i n g .Xottawasaga Printing wants to know which line and which printing station to upgrade.Determine the feasible mutually exclusive combinations of lines and stations forXottawasaga Printing.
4.7
Alargaret has a project with a 28 000 first cost that returns 5000 per year over its 10-yearlife. It has a salvage value of 3000 at the end of 10 years. If the MARR is 15%,(a) W h a t is the present worth of this project?(b) W h a t is the annual worth of this project?( c ) W h a t is the future worth of this project after 10 years?
113
Appledale Dairy is considering upgrading an old ice-cream maker. Upgrading is available at two levels: moderate and extensive. Moderate upgrading costs S6500 now andyields annual savings of S3 300 in the first year, S3000 in the second year, $2700 in thethird year, and so on. Extensive upgrading costs $10 550 and saves $7600 in the firstyear. T h e savings then decrease by 20% each year thereafter. If the upgraded ice-creammaker will last for seven years, which upgrading option is better? Use a present worthcomparison. Appledale's MARR is 8%.
4.9
Creamy
First cost
SI5 000
$36 000
Service life
12 years
Annual profit
$4200
$10 800
S1200
$3520
Salvage value
$2250
$5000
(b) It turned out that the sendee life of $moothie was 14 years. MTiich alternative is betteron the basis of the MARR computed in part (a)? Assume that each alternative can berepeated indefinitely.4.10 Xabil is considering buying a house while he is at university. The house costs 1 0 0 000today. Renting out part of the house and living in the rest over his five years at school willnet, after expenses, 1000 per month. He estimates that he will sell the house after five yearsfor 1 0 5 000. If Xabil's MARR is 18%, compounded monthly, should he buy the house?4.11 A young software genius is selling the rights to a new video game he has developed. Twocompanies have offered him contracts. T h e first contract offers $10 000 at the end ofeach year for the next five years, and then $20 000 per year for the following 10 years.T h e second offers 10 payments, starting with $10 000 at the end of the first year,$13 000 at the end of the second, and so forth, increasing by $3000 each year (i.e., thetenth payment will be $10 000 + 9 X $3000). Assume the genius uses a MARR of 9%.Which contract should the young genius choose? Use a present worth comparison.4.12 Sam is considering buying a new lawnmower. He has a choice between a "Lawn Guy"mower and a Bargain Joe's "Clip Job" mower. Sam has a ALARR of 5%. T h e salvagevalue of each mower at the end of its sendee life is zero.(a) Using the information on the next page, determine which alternative is preferable.Use a present worth comparison and the least common multiple of the sendee lives.(b) For a four-year study period, what salvage value for the Lawn Guy mower wouldresult in its being the preferred choice? W h a t salvage value for the Lawn Guy wouldresult in the Clip Job being the preferred choice?
First costLife
Lawn Guy
Clip Job
S3 50
10 years
4 years
Annual gas
S60
S40
Annual maintenance
S30
4.13 Water supply for an irrigation system can be obtained from a stream in some nearbymountains. Two alternatives are being considered, both of which have essentially infinitelives, provided proper maintenance is performed. T h e first is a concrete reservoir with asteel pipe system and the second is an earthen dam with a wooden aqueduct. Below arethe costs associated with each.Compare the present worths of the two alternatives, using an interest rate of 8%.Which alternative should be chosen?
First costAnnual maintenance costsReplacing the wood portionof the aqueduct each 15 years
Concrete Reservoir
Earthen Dam
S500 000
S2000
S12 000
N/A
4.14 CB Electronix needs to expand its capacity. It has two feasible alternatives under consideration. Both alternatives will have essentially infinite lives.Alternative 1: Construct a new building of 20 000 square metres now. T h e first cost willbe S2 000 000. Annual maintenance costs will be $10 000. In addition, the building willneed to be painted every 15 years (starting in 15 years) at a cost of $15 000.Alternative 2: Construct a new building of 12 500 square metres now and an additional".500 square mefres in 10 years. T h e first cost of the 12 500-square-metre building will be$1 250 000. T h e annual maintenance costs will be $5000 for the first 10 years (i.e., untilthe addition is b u i l t ) . T h e 7 5 0 0 - s q u a r e - m e t r e addition will have a first cost of$1 000 000. Annual maintenance costs of the renovated building (the original buildingand the addition) will be $11 000. T h e renovated building will cost $15 000 to repainteven 15 years (starting 15 years after the addition is done).C a r n out an annual worth comparison of the two alternatives. WTiich is preferred ifthe ALARR is 15%?-
4.15 Katie's project has a five-year term, a first cost, no salvage value, and annual savings of$20 000 per year. After doing present worth and annual worth calculations with a 15%interest rate, Katie notices that the calculated annual worth for the project is exactlythree times the present worth. W h a t is the project's present worth and annual worth?$hould Katie undertake the project?4.16 Xighhigh Newsagent wants to replace its cash register and is currently evaluating twomodels that seem reasonable. T h e information on the nvo alternatives, CR1000 andCRX, is shown in the table.
CR1000
CRX
680
1100
Annual savings
Annual maintenancecost
35 in year 1, increasing by10 each year thereafter
Sendee life
6 years
Scrap value
250
115
(a) If Xighhigh Newsagent's MARR is 10%, which type of cash register should theychoose? Use the present worth method.(b) For the less preferred type of cash register found in part (a), what scrap value wouldmake it the preferred choice?4.17 Midland Metalworking is examining a 750-tonne hydraulic press and a 600-tonnemoulding press for purchase. Midland has only enough budget for one of them. IfMidland's MARR is 12% and the relevant information is as given below, which pressshould they purchase? Use an annual worth comparison.Hydraulic Press
Moulding Press
Initial cost
$275 000
$185 000
S33 000
S24 500
Si000, increasing bv$350 each yearthereafter
Life
15 years
S19 250
S14 800
4.18 Westmount Waxworks is considering buying a new wax melter for its line of replicas ofstatues of government leaders. T h e r e are two choices of supplier, Finedetail andSimplicity. Their proposals are as follows:Finedetail
Simplicity
Expected life
7 years
$200 000
S350 000
Maintenance
SlOOOO/year + $0.05/unit
Labour
$1.25/unit
$0.50/unit
Other costs
$6500/year + $0.95/unit
S5000
Management thinks they will sell about 30 000 replicas per year if there is stabilityin world governments. If the world becomes very unsettled so that there are frequentoverturns of governments, sales may be as high as 200 000 units a year. WestmountWaxworks uses a M \ R R of 15% for equipment projects.(a) W h o is the preferred supplier if sales are 30 000 units per year? Use an annualworth comparison.(b) W h o is the preferred supplier if sales are 200 000 units per year? Use an annualworth comparison.(c) How sensitive is the choice of supplier to sales level? Experiment with sales levelsbetween 30 000 and 200 000 units per year. At what sales level will the costs of thetwo melters be equal?4.19 T h e City of Brussels is installing a new swimming pool in the municipal recreationcentre. Two designs are under consideration, both of which are to be permanent(i.e., lasting forever). The first design is for a reinforced concrete pool which has a firstcost of 1 500 000. Even' 10 years the inner surface of the pool would have to be refinished and painted at a cost of 2 0 0 000.T h e second design consists of a metal frame and a plastic liner, which would have aninitial cost of 5 0 0 000. For this alternative, the plastic liner must be replaced every5 years at a cost of 1 0 0 000, and even" 15 years the metal frame would need replacement at a cost of 1 5 0 000. Extra insurance of 5 0 0 0 per year is required for the plasticliner (to cover repair costs if the liner leaks). T h e city's cost of long-term funds is 5%.Determine which swimming pool design has the lower present cost.4.20 Sam is buying a refrigerator. He has two choices. A used one, at $475, should last himabout three years. A new one, at $1250, would likely last eight years. Both have a scrapvalue of $0. T h e interest rate is 8%.(a) Which refrigerator has a lower cost? (Use a present worth analysis with repeatedlives. Assume operating costs are the same.)(b) If Sam knew that he could resell the new refrigerator after three years for $1000, wouldthis change the answer in part (a)? (L se a present worth analysis with a three-year studyperiod. Assume operating costs are the same.)T
4.21 Yal is considering purchasing a new video plasma display panel to use with her notebookcomputer. One model, the XJ3, costs $4500 new, while another, the Y19, sells for $3200.Val figures that the XJ3 will last about three years, at which point it could be sold for$1000, while the Y19 will last for only two years and will also sell for $1000. Both panelsgive similar sendee, except that the Y19 is not suitable for client presentations. If shebuys the Y19, about four times a year she will have to rent one similar to the XJ3, at atotal year-end cost of about $300. L sing present worth and the least common multipleof the sendee lives, determine which display panel Val should buy. Val's MARR is 10%.T
4.22 For Problem 4.21, Val has determined that the salvage value of the XJ3 after two yearsof sendee is $1900. W h i c h display panel is the better choice, on the basis of presentworth with a two-year study period?4.23 Tom is considering purchasing a 24 000 car. After five years, he will be able to sell thevehicle for 8000. Petrol costs will be 2000 per year, insurance 600 per year, and parking 600 per year. Maintenance costs for the first year will be 1000, rising by 400 peryear thereafter.
117
T h e alternative is for Tom to take taxis everywhere. This will cost an estimated6000 per year. Tom will rent a vehicle each year at a total cost (to year-end) of 600 forthe family vacation, if he has no car. If Tom values money at 11 % annual interest, shouldhe buy the car? Use an annual worth comparison method.4.24 A new gizmo costs R10 000. Maintenance costs R2000 per year, and labour savings areR6567 per year. W h a t is the gizmo's payback period?4.25 Building a bridge will cost S65 million. A round-trip toll of $12 will be charged to allvehicles. Traffic projections are estimated to be 5000 per day. T h e operating andmaintenance costs will be 20% of the toll revenue. Find the payback period (in years) forthis project.4.26 A new packaging machine will save Greene Cheese Pty. Ltd. $3000 per year in reducedspoilage, $2500 per year in labour, and $1000 per year in packaging material. T h e newmachine will have additional expenses of $700 per year in maintenance and $200 peryear in energy. If it costs $20 000 to purchase, what is its payback period? Assume thatthe savings are earned throughout the year, not just at year-end.4.27 Diana usually uses a three-year payback period to determine if a project is acceptable.A recent project with uniform y e a r l y savings over a five-year life had a paybackperiod of almost exactly three years, so Diana decided to find the project's presentworth to help determine if the project was truly justifiable. However, that calculationdidn't help either since the present worth was exactly 0. W h a t interest rate was Dianausing to calculate the present worth? T h e project has no salvage value at the end ofits five-year life.4.28 T h e Biltmore Garage has lights in places that are difficult to reach. M a n a g e m e n testimates that it costs about $2 to change a bulb. $tandard 100-watt bulbs with anexpected life of 1000 hours are now used. $tandard bulbs cost $ 1 . A long-life bulb thatrequires 90 watts for the same effective level of light is available. Long-life bulbs cost $3.T h e bulbs that are difficult to reach are in use for about 500 hours a month. Electricitycosts $0.08/kilowatt-hour payable at the end of each month. Biltmore uses a 12%ALARR ( 1 % per month) for projects involving supplies.(a) V\ nat minimum life for the long-life bulb would make its cost lower?(b) If the cost of changing bulbs is ignored, what is the minimum life for the long-lifebulb for them to have a lower cost?( c ) If the solutions are obtained by linear interpolation of the capital recover}' factor,will the approximations understate or overstate the required life?4.29 A chemical recovery system costs 300 000 yuan and saves 52 800 yuan each year of itsseven-year life. T h e salvage value is estimated at 75 000 yuan. T h e ALARR is 9%. W h a tis the net annual benefit or cost of purchasing the chemical recover}' system? Use thecapital recovery formula.4.30 $avings of $5600 per year can be achieved through either a $14 000 machine (A) witha seven-year service life and a $2000 salvage value, or a $25 000 machine (B) with a ten-yearservice life and a $10 000 salvage value. If the ALARR is 9%, which machine is a betterchoice, and for what annual benefit or cost? Use annual worth and the capital recoveryformula.4.31 Ridgley Custom Aletal Products (RCAIP) must purchase a new tube bender. RCA IP'sALARR is 1 1 % . T h e y are considering two models:
Model
FirstCost
EconomicLife
YearlyNet Savings
SalvageValue
$100 000
5 years
S50 000
150 000
( a ) Using the present worth method, which tube bender should they buy?(b) R C M P has discovered a third alternative, which has been added to the table below.Now which tube bender should they buy?
S 20 000
200 000
3 years
75 000
100 000
4.32 R C M P (see Problem 4.31, part (b)) can forecast demand for its products for onlythree years in advance. T h e salvage value after three years is S40 000 for model T and$80 000 for model A. Using the study period method, which of the three alternativesis best?4.33 Using the annual worth method, which of the three tube benders should R C M P buy?T h e MARR is 1 1 % . Use the data from Problem 4.31, part (b).4.34 VTiat is the payback period for each of the three alternatives from the R C M P problem?Use the data from Problem 4.31, part (b).4.35 Data for two independent investment opportunities are shown below.
Machine A
Machine B
1 500 000
2 000 000
Revenues (annual)
900 000
1 100 000
Costs (annual)
600 000
800 000
100 000
200 000
(a) For a ALARR of 8%, should either, both, or neither machine be purchased? Use theannual worth method.(b) For a ALARR of 8%, should either, both, or neither machine be purchased? Use thepresent worth method.
119
(c) W h a t are the payback periods for these machines? Should either, both, or neithermachine be purchased, based on the payback periods? T h e required payback periodfor investments of this type is three years.4.36 Xaviera is comparing two mutually exclusive projects, A and B, that have the same initialinvestment and the same present worth over their sendee lives. Wolfgang points outthat, using the annual worth method, A is clearly better than B. W h a t can be said aboutthe sendee lives for the nvo projects?4.37 Xaviera noticed that two mutually exclusive projects, A and B, have the same paybackperiod and the same economic life, but A has a larger present worth than B does. W h a tcan be said about the size of the annual savings for the two projects?4.38 T v o plans have been proposed for accumulating money for capital projects at BobbinBay Lighting. One idea is to put aside 100 000 rupees per year, independent of growth.T h e second is to start with a smaller amount, 80 000 rupees per year, but to increase thisin proportion to the expected company growth. T h e money will accumulate interest at10%, and the company is expected to grow about 5% per year. Which plan will accumulate more money in 10 years?4.39 Cleanville Environmental Sendees is evaluating two alternative methods of disposing ofmunicipal waste. T h e first involves developing a landfill site near the city. Costs of thesite include Si 000 000 start-up costs, S i 0 0 000 closedown costs 30 years from now, andoperating costs of S20 000 per year. Starting in 10 years, it is expected that there will berevenues from user fees of S30 000 per year. T h e alternative is to ship the waste out ofthe region. An area firm will agree to a long-term contract to dispose of the waste forS13 0 000 per year. Using the ammal worth method, which alternative is economicallypreferred for a ALARR of 11%? Would this likely be the actual preferred choice?4.40 Alfredo Auto Parts is considering investing in a new forming line for grille assemblies.For a five-year study period, the cash flows for two separate designs are shown below.Create a spreadsheet that will calculate the present worths for each project for a variableALARR. Through trial and error, establish the ALARR at which the present worths of thetwo projects are exactly the same.Cash Flows for Grille Assembly ProjectAutomated LineYear
Disbursements
Receipts0
Manual LineNet CashFlow
1 500 000
300 000
250 000
70 000
Net CashFlow
- 1 000 000
180 000
240 000
175 000
230 000
170 000
220 000
35 000
165 000
90 000
800 000
710 000
160 000
C o m p a r i s o n Methods Part 1
monthly basis. Warehouse space is rented monthly, and revenue is generated monthly.T h e items purchased will be sold at the end of the year, but the salvage values are somewhat uncertain. Given below are the known or expected cash flows for the project.
MonthJanuary (beginning)
Purchase
LabourExpenses
WarehouseExpenses
S 2000
S30003000
Revenue
January (end)FebruaryMarchApril
200020002000
2000200020002000
MayJune
400010 000
3000300030006000
July
6000
110 000
August
4000200020002000
3000
30 00010 00050002000
SeptemberOctoberNovemberSalvage?
December
300030003000
10 00040 000
For an interest rate of 12% compounded monthly, create a spreadsheet that calculates and graphs the present worth of the project for a range of salvage values of thepurchased items from 0% to 100% of the purchase price. Should Stayner Catering goahead with this project?4 . 4 2 Alfredo Auto Parts has two options for increasing efficiency. They can expand the currentbuilding or keep the same building but remodel the inside layout. For a five-year studyperiod, the cash flows for the two options are shown below. Construct a spreadsheet thatwill calculate the present worth for each option for a variable ALARR. By trial and error,determine the ALARR at which the present worths of the two options are equivalent.Expansion Option
Remodelling Option
850 000
- 8 5 0 000
225 000
- 2 3 0 000
9000
71 000
195 000
11 700
68 300
215 000
15 210
64 790
275 000
235 000
19 773
60 227
45 000
255 000
25 705
54 295
121
4.43 Derek has two choices for a heat-loss prevention system for the shipping doors atKirkland Manufacturing. He can isolate the shipping department from the rest of theplant, or he can curtain off each shipping door separately. Isolation consists of building apermanent wall around the shipping area. It will cost S60 000 and will save $10 000 inheating costs per year. Plastic curtains around each shipping door will have a total costof about S5000, but will have to be replaced about once every two years. Savings inheating costs for installing the curtains will be about S3000 per year. Use the paybackperiod method to determine which alternative is better. Comment on the use of thepayback period for making this decision.4.44 Assuming that the wall built to isolate the shipping department in Problem 4.43 will lastforever, and that the curtains have zero salvage value, compare the annual worths of thetwo alternatives. The MARR for Kirkland Manufacturing is 1 1 % . Which alternative isbetter?4.45 Cleanville Environmental Services is considering investing in a new water treatmentsystem. On the basis of the information given below for two alternatives, a fullyautomated and a partially automated system, construct a spreadsheet for computingthe annual worths for each alternative with a variable M A R R . T h r o u g h trial anderror, determine the M A R R at which the annual worths of the two alternatives areequivalent.Fully Automated SystemYear
SI 000 000
- S I 000 000
S650 000
- S650 000
270 000
190 000
185 000
4.46 Fred has projects to consider for economic feasibility. All of his projects consist of a firstcost P and annual savings A. His rule of thumb is to accept all projects for which theseries present worth factor (for the appropriate ALARR and sen-ice life) is equal to orgreater than the payback period. Is this a sensible rule?
Rockwell International
The Light \ ehicle Division of Rockwell International makes seat-slide assemblies for theautomotive industry. They have two major classifications for investment opportunities:developing new products to be manufactured and sold, and developing new machines toimprove production. The overall approach to assessing whether an investtnent should bemade depends on the nature of the project.In evaluating a new product, they consider the following:1. Marketing strategy: Does it fit the business plan for the company?2. Work force: How will it affect human resources?3. Margins: The product should generate appropriate profits.4. Cash flow: Positive cash flow is expected within two years.In evaluating a new machine, thev consider the following:1.2.
Cost avoidance: Savings should pay back an investment within one year.
All companies consider more than just the economics of a decision. Most take intoaccount the other issuesoften called intangiblesby using managerial judgment in aninformal process. Others, like Rockwell International, explicitly consider a selection ofintangible issues.The trend today is to carefully consider several intangible issues, either implicitly orexplicitly. Human resource issues are particularly important since employee enthusiasmand commitment have significant repercussions. Environmental impacts of a decision canaffect the image of the companv. Health and safety is another intangible with significanteffects.However, the economics of the decision is usually (but not always) the single mostimportant factor in a decision. Also, economics is the factor that is usually the easiest tomeasure.Questions
1. Why do you think Rockwell International has different issues to consider dependingon whether an investment was a new product or a new machine?2. For each of the issues mentioned, describe how it would be measured. How wouldyou determine if it was worth investing in a new product or new machine with respectto that issue?3.
There are two kinds of errors that can be made. The first is that an investment ismade when it should not be, and the second is that an investment is not made when itshould be. Describe examples of both kinds of errors for both products and machines(four examples in total) if the issues listed for Rockwell International are strictlyfollowed. \Miat are some sensible ways to prevent such errors?
For a business to survive, it must be able to earn a high enough return to induce investorsto put money into the company. T h e minimum rate of return required to get investors toinvest in a business is that business's cost of capital. A company's cost of capital is also itsminimum acceptable rate of return for projects, its ALARR. This appendix reviews howthe cost of capital is determined. We first look at the relation between risk and the cost ofcapital. Then, we discuss sources of capital for large businesses and small businesses.
4A.1
Table 4 A . 1
10 000100 000
12 000
36 000
18 000
54 000
Debt (S)
327 273
Xet operating income per year is revenue per year minus cost per vear.
124
nncc
18 000 \
16.5% ^ . . 6 5 ^ 1 ,,27.5%
0.275
OR
90 000327 273
These three possibilities average out to 16.5%. If things are good, owners do betterthan lenders. If things are bad, owners do worse. But their average return is greater thanreturns to lenders.The lower rate of return to lenders means that companies would like to get their capitalwith debt. However, reliance on debt is limited for two reasons.1. If a company increases the share of capital from debt, it increases the chance thatit will not be able to meet the contractual obligations to lenders. This means thecompany will be bankrupt. Bankruptcy may lead to reorganizing the company orpossibly closing the company. In either case, bankruptcy costs may be high.2.
4A.2
Lenders are aware of the dangers of high reliance on debt and will, therefore,limit the amount they lend to the company.
100 000427 273
n 1 , - / ^ 2 7 273
0.150
125
loans are limited because banks are usually not willing to lend more than some fraction ofthe amount an owner(s) puts into a business.If bank loans do not add up to sufficient funds, then the company usually has twooptions. One option is the sale of financial securities such as stocks and bonds throughstock exchanges that specialize in small, speculative companies. Another option is venturecapitalists. Venture capitalists are investors who specialize in investing in new companies.T h e cost of evaluating new- companies is usually high and so is the risk of investing inthem. Together, these factors usually lead venture capitalists to want to put enough moneyinto a small company so that they will have enough control over the company.In general, new equity investment is very expensive for small companies. Studies haveshown that venture capitalists typically require the expectation of at least a 35% rate ofreturn after tax. Raising funds on a stock exchange is usually even more expensive thangetting funding from a venture capitalist.
ComparisonMethods^Part2Engineering Economics in Action, Part 5A: What's Best? Revisited
5.4
5.3.3
Multiple IRRs
5.3.4
5.3.5
5.4.2
Review ProblemsSummaryEngineering Economics in Action, Part 5B: The Invisible HandProblemsMini-Case 5.1Appendix 5A: Tests for Multiple IRRs
IntroductionIn Chapter 4, we showed how to structure projects so that they were either independentor mutually exclusive. T h e present worth, annual worth, and payback period methodsfor evaluating projects were also introduced. This chapter continues on the theme ofcomparing projects by presenting a commonly used but somewhat more complicatedcomparison method called the internal rate of return, or IRR..Although the IRR method is widely used, all of the comparison methods have value inparticular circumstances. Selecting which method to use is also covered in this chapter. It isalso shown that the present worth, annual worth, and IRR methods all result in the samerecommendations for the same problem. We close this chapter with a chart summarizing thestrengths and weaknesses of the four comparison methods presented in Chapters 4 and 5.
Suppose S i 0 0 is invested today in a project that returns $ 1 1 0 in one year. We can calculatethe IRR by finding the interest rate at which S i 0 0 now is equivalent to Si 10 at the end ofone year:
128
P = F(P/F,i*,l)100 = 110(P/F,/*,1)110100
1+ i*where i* is the internal rate of return.Solving this equation gives a rate of return of 10%. In a simple example like this, theprocess of finding an internal rate of return is finding the interest rate that makes thepresent worth of benefits equal to the first cost. This interest rate is the IRR.BOf course, cash flows associated with a project will usually be more complicated thanin the example above. A more formal definition of the IRR is stated as follows. T h einternal rate of return (IRR) on an investment is the interest rate, /'*, such that, when allcash flows associated with the project are discounted at /*, the present worth of the cashinflows equals the present worth of the cash outflows. That is, the project just breaks even.An equation that expresses this isTv
(R - D ) _w~tjQ(1 + ijt
(5.1)
whereR = the cash inflow (receipts) in period rD = the cash outflow (disbursements) in period tT = the number of time periodsi* = the internal rate of returnt
1D (l + iTt=ot
it can be seen that, in order to calculate the IRR, one sets the disbursements equal to thereceipts and solves for the unknown interest rate. For this to be done, the disbursementsand receipts must be comparable, as a present worth, a uniform series, or a future worth.That is, usePW(disbursements) = PW(receipts) and solve for the unknown /*AW(disbursements) AW(receipts) and solve for the unknown /*, orFW(disbursements) = FW(receipts) and solve for the unknown i*.The IRR is usually positive, but can be negative as well. A negative IRR means thatthe project is losing money rather than earning it.We usually solve the equations for the IRR by trial and error, as there is no explicitmeans of solving Equation (5.1) for projects where the number of periods is large. Aspreadsheet provides a quick way to perform trial-and-error calculations; most spreadsheetprograms also include a built-in IRR function.E X A M P L E
Clem is considering buying a tuxedo. It would cost S500, but would save him S i 6 0 peryear in rental charges over its five-vear life. W h a t is the IRR for this investment?
129
As illustrated in Figure 5.1, Clem's initial cash outflow for the purchase would beS500. This is an up-front outlay relative to continuing to rent tuxedos. The investmentwould create a saving of S i 6 0 per year over the five-year life of the tuxedo. Thesesavings can be viewed as a series of receipts relative to rentals. The IRR of Clem's investment can be found by determining what interest rate makes the present worth of thedisbursements equal to the present worth of the cash inflows.Present worth of disbursements = 500Present worth of receipts= \60(P/A,i*,5)Setting the two equal,500 = l60(P/A,i*,5)(P/A,i*,5) = 500/160= 3.125F i g u r e 5.1
Clem's Tuxedo$160
>k
Jk
Ik
An interpolation givesi*= 15% + 5 % [ ( 0 . 3 2 - 0 . 2 9 8 3 2 ) / ( 0 . 3 3 4 3 8 - 0.29832)]= 18.0%Note that there is a slight difference in the answers, depending on whether thedisbursements and receipts were compared as present worths or as annuities. T h i sdifference is due to the small error induced by the linear interpolation-^
IRR f o r I n d e p e n d e n t P r o j e c t s
Recall from Chapter 4 that projects under consideration are evaluated using the MARR,and that anv independent project that has a present or annual worth equal to or exceeding zero should be accepted. T h e principle for the IRR method is analogous. We willinvest in anv project that has an IRR equal to or exceeding the AIARR. Just as projectswith a zero present or annual worth are marginally acceptable, projects with IRR =ALARR have a marginally acceptable rate of return (by definition of the ALARR).A s o analogous to Chapter 4, when we perform a rate of return comparison on severalindependent projects, the projects must have equal lives. If this is not the case, then theapproaches covered in Section 4.4.4 (Comparison of Alternatives With Unequal Lives)must be used.E X A M P L E
T h e High Society Baked Bean Co. is considering a new canner. T h e canner costsS120 000, and will have a scrap value of $5000 after its 10-year life. Given the expectedincreases in sales, the total savings due to the new canner, compared with continuingwith the current operation, will be $15 000 the first year, increasing by $5000 each yearthereafter. Total extra costs due to the more complex equipment will be $10 000 peryear. T h e M A R R for High $ociety is 12%. $hould they invest in the new canner?T h e cash inflows and outflows for this problem are summarized in Figure 5.2. Weneed to compute the internal rate of return in order to decide if High Society shouldbuy the canner. There are several ways we can do this. In this problem, equating annualoutflows and receipts appears to be the easiest approach, because most of the cash flowsare already stated on a yearly basis.
(A/F,i*,l0) + 1 + (A/G,i*,10)-2MA/P,i*,l0) = 0
Figure 5.2
131
S60 000000 P .er
d i e t *
Ak
/k
Nr
>r
>'
ik
\r
S15 000
10rS10 000
-$120 000
T h e IRR can be found by trial and error alone, by trial and error and linear interpolation, or by a spreadsheet IRR function. A trial-and-error process is particularly easyusing a spreadsheet, so this is often the best approach. A good starting point for theprocess is at zero interest. A graph (Figure 5.3) derived from the spreadsheet indicatesthat the IRR is between 13% and 14%. This mav be good enough for a decision, since itexceeds the MARR of 12 %.If finer precision is required, there are two ways to proceed. One way is to use afiner grid on the graph, for example, one that covers 13% to 14%. T h e other way is tointerpolate between 13% and 14%. We shall first use the interest factor tables to showFigure 5.3
E s t i m a t i n g t h e IRR f o r E x a m p l e 5 . 3
- i
140 -
0.25
interest rate
that the IRR is indeed between 13% and 14%. Next we shall interpolate between 13%and 14%.First, at i = 13%, we have(4/F,13%,10) + 1 + ( 4 / G , 1 3 % , 1 0 ) - 2 4 ( 4 / P , 1 3 % , 1 0 )= 0.05429 + 1 + 3.5161 - 2 4 ( 0 . 1 8 4 2 9 )= 0.1474T h e result is a bit too high. A higher interest rate will reduce the annual worth ofthe benefits more than the annual worth of the costs, since the benefits are spread overthe life of the project while most of the costs are early in the life of the project.At i 14%, we have(4/F,14%,10) + 1 + ( 4 / G , 1 4 % , 1 0 ) - 2 4 ( 4 / P , 1 4 % , 1 0 )= 0.05171 + 1 + 3 . 4 4 8 9 - 2 4 ( 0 . 1 9 1 7 1 )= -0.1004This confirms that the IRR of the investment is between 13% and 14%. A goodapproximation to the IRR can be found by linearly interpolating:i*= 1 3 % + ( 0 - 0 . 1 4 7 4 ) / ( 0 . 1 0 0 4 - 0.1474)= 13.6%T h e IRR for the investment is approximately 13.6%. Since this is greater than theALARR of 12%, the company should buy the new canner. Note again that it was notactually necessary to determine where in the range of 13% to 14% the IRR fell. It wasenough to demonstrate that it was 12% or more.BIn summary, if there are several independent projects, the IRR for each is calculatedseparately and those having an IRR equal to or exceeding the ALARR should be chosen.5.3.2
IRR f o r M u t u a l l y E x c l u s i v e P r o j e c t s
Choice among mutually exclusive projects using the IRR is a bit more involved. Someinsight into the complicating factors can be obtained from an example that involves twomutually exclusive alternatives. It illustrates that the best choice is not necessarily thealternative with the highest IRR.E X A M P L E
Consider two investments. T h e first costs $1 today and returns $2 in one year. T h esecond costs $1000 and returns S i 9 0 0 in one year. Y\ nich is the preferred investment?Your ALARR is 70%.T h e first project has an IRR of 100%:-1 + 2(P/P,/*,1) = 0(P/F,**,l) = 1/2 = 0.5/* = 100%
133
5.5
Alonster Aleats can buy a new meat sheer system for 5 0 000. They estimate it will savethem 1 1 000 per year in labour and operating costs. T h e same system with anautomatic loader is 6 8 000, and will save approximately 1 4 000 per year. The life ofeither system is thought to be eight years. Alonster Aleats has three feasible alternatives:Alternative
"Do nothing"
Annual Savings
11 000
68 000
14 000
nich alternative is
We first consider the system without the loader. Its IRR is 14.5%, which exceeds theALARR of 12%. This can be seen by solving for /'* in- 5 0 000 + 11 000(P/A,i*,8) = 0(P/A,i*,8) = 50 000/11 000(P/A,i*,S) = 4.545
134
From the interest factor tables, or by trial and error with a spreadsheet,( P / 4 , 1 4 % , 8 ) = 4.6388
(P/A,IS%,8) = 4.4873By interpolation or further trial and error,
i*= 14.5%T h e slicer alone is thus economically justified and is better than the "do nothing"alternative.We now consider the system with the slicer and loader. Its IRR is 12.5%, which maybe seen by solving for /* in- 6 8 000 + 14 000(PA4,/*,8) = 0
(P/A,i*,%) = 4.857( P / 4 , 1 2 % , 8 ) = 4.9676( P / 4 , 1 3 % , 8 ) = 4.7987/*= 12.5%T hthe extra, or incremental, 1 8 000 spent on the loader.
(P/A,i*,S) = 1 8 000/3000(P/A,i*,8) = 6i*=7%This is less than the ALARR; therefore, Alonster Aleats should not buy the automated loader.W h e n the IRR was calculated for the system including the loader, the surplus returnon investment earned by the slicer alone essentially subsidized the loader. T h e slicerinvestment made enough of a return so that, even when it was coupled with the moneylosing loader, the whole machine still seemed to be a good buy. In fact, the extra 1 8 000would be better spent on some other project at the M A R R or higher. T h e relationbetween the potential projects is shown in Figure SAMFigure 5.4
Monster Meats
Loader
H R R as 7 %>r IRR = 1 2 . 5 %
Slicer
H R R = 14.5%
andSlicer->
135
T h e fundamental principle illustrated by the two examples is that, to use the IRR tocompare two or more mutually exclusive alternatives properly, we cannot make thedecision on the basis of the IRRs of individual alternatives alone; we must takethe IRRs of the incremental investments into consideration. In order to properly assessthe worthiness of the incremental investments, it is necessary to have a systematic way toconduct pair-wise comparisons of projects. Note that before undertaking a systematicanalysis of mutually exclusive alternatives with the IRR method, you should ensure thatthe alternatives have equal lives. If they do not have equal lives, then the methods ofSection 4.4.4 (study period or repeated lives methods) must be applied first to set upcomparable cash flows.T h e first step in the process of comparing several mutually exclusive alternativesusing the IRR is to order the alternatives from the smallest first cost to the largest firstcost. Since one alternative must be chosen, accept the alternative with the smallestfirst cost (which may be the "do nothing" alternative with SO first cost) as the currentbest alternative regardless of its IRR exceeding the ALARR. This means that the currentbest alternative may have an IRR less than the ALARR. Even if that's the case, a properanalysis of the IRRs of the incremental investments will lead us to the coirect best overallalternative. For this reason, we don't have to check the IRR of any of the individualalternatives.T h e second step of the analysis consists of looking at the incremental investments ofalternatives that have a higher first cost than the current best alternative. Assume thatthere are ;/ projects and they are ranked from 1 (the current best) to n, in increasing orderof first costs. T h e current best is "challenged" by the project ranked second. One of twothings occurs:1. T h e incremental investment to implement the challenger does not have an IRRat least equal to the ALARR. In this case, the challenger is excluded from furtherconsideration and the current best is challenged by the project ranked third.2. T h e incremental investment to implement the challenger has an IRR at least ashigh as the ALARR. In this case, the challenger replaces the current best. It thenis challenged by the alternative ranked third.T h e process then continues with the next alternative challenging the current best untilall alternatives have been compared. The current best alternative remaining at the end ofthe process is then selected as the best overall alternative. Figure 5.5 summarizes the incremental investment analysis for the mutually exclusive projects.
5.6
( R E P R I S E
4 . 4 )
Fly-by-Xight .Aircraft must purchase a new lathe. It is considering one of four newlathes, each of which has a life of 10 years with no scrap value. Given a AIARR of 15%,which alternative should be chosen?LatheFirst costAnnual savings
T h e alternatives have already been ordered from lathe 1, which has the smallest firstcost, to lathe 4, which has the greatest first cost. Since one lathe must be purchased,
136
accept lathe 1 as the current best alternative. Calculating the IRR for lathe 1, althoughnot necessary, is shown as follows:100 000 = 25 000(P/4,/*,10)(P/4,/*,10) = 4An approximate IRR is obtained by trial and error with a spreadsheet,i* =21.4%T h e current best alternative is then challenged by the first challenger, lathe 2, whichhas the next-highest first cost. The IRR of the incremental investment from lathe 1 tolathe 2 is calculated as follows:
i*= 12.4%Since the IRR of the incremental investment falls below the ALARR, lathe 2 fails thechallenge to become the current best alternative. T h e reader can verify that lathe 2alone has an IRR of approximately 18.7%. Even so, lathe 2 is not considered a viablealternative. In other words, the incremental investment of $50 000 could be put tobetter use elsewhere. Lathe 1 remains the current best and the next challenger is lathe 3.As before, the incremental IRR is the interest rate at which the present worth oflathe 3 less the present worth of lathe 1 is 0:[200 000 - 46 000(P/A,i ,10)] - [100 000 - 25 000(PA4,/*,10)] = 0(P/A,i*,10) = 100 000/21 000 = 4.762An approximate IRR is obtained by trial and error.i*=
16.4%
T h e IRR on the incremental investment exceeds the ALARR, and therefore lathe 3 ispreferred to lathe 1. Lathe 3 now becomes the current best. T h e new challenger islathe 4. The IRR on the incremental investment is[255 000 - 55 000(PA4,/*,10)] - [200 000 - 46 000(P/4,/*,10)] = 0(P/A,i*,10) = 55 000/9000 = 6.11
i*= 1 0 . 1 %The additional investment from lathe 3 to lathe 4 is not justified. The reader can verifythat the IRR of lathe 4 alone is about 17%. Once again, we have a challenger with an IRRgreater than the ALARR, but it fails as a challenger because the incremental investment fromthe current best does not have an IRR at least equal to the ALARR. The current best remainslathe 3. There are no more challengers, and so the best overall alternative is lathe 3 .In the next section, the issue of multiple IRRs is discussed, and methods for identifyingand eliminating them are given. Note that the process described in Figure 5.5 requires that
Figure 5.5
Rank m u t u a l l y e x c l u s i v eprojects f r o m 1 to n, ini n c r e a s i n g o r d e r of first cost.C u r r e n t best = Smallestfirst cost
a single IRR (or ERR, as discussed later) be determined for each incremental investment. Ifthere are multiple IRRs, they must be dealt with for each increment of investment.5.3.3
M u l t i p l e IRRs
A problem with implementing the internal rate of return method is that there may bemore than one internal rate of return. Consider the following example.E X A M P L E
5.7
A project pays S1000 today, costs S5000 a year from now, and pays S6000 in two years.(See Figure 5.6.) \A nat is its IRR?Equating the present worths of disbursements and receipts and solving for the IRRgives the following:1000 - 5000(P/F,/'*,1) + 6000(P/iy'*,2) = 0Recalling that (P/F,i*N) stands for 1/(1 + z'*)-\ we have1
i +
+ (i + i*y: r
= 0
(1 + / * ) - 5(1 + ; * ) + 6 = 02
138
Figure 5.6
M u l t i p l e IRR E x a m p l e$6000
$1000
Y-$5000
(1 + 2i* + i* ) - 5;* + 1 = 02
/ * - 3/*+ 2 = 02
(/* - 1)(* - 2) = 0T h e roots of this equation are i\ = 1 and i*i = 2. In other words, this project has twoIRRs: 100% and 200% !T h e multiple internal rates of return problem may be stated more generally.Consider a project that has cash flows over T periods. T h e net cash flow, A , associatedwith period t is the difference between cash inflows and outflows for the period(i.e., A = R - D where R is cash inflow in period t and D is cash outflow in period t).We set the present worth of the net cash flows over the entire life of the project equal tozero to find the IRR(s). We havet
(5.2)
Any value of i that solves Equation (5.2) is an internal rate of return for that project.T h a t there may be multiple solutions to Equation (5.2) can be seen if we rewrite theequation asA + A x + A x + . .. + A x = 00
(5.3)
where x = (1 +Solving the Tth degree polynomial of Equation (5.3) is the same as solving for theinternal rates of return in Equation (5.2). In general, when finding the roots ofEquation (5.3), there may be as many positive real solutions for x as there are sign changes inthe coefficients, the A's. Thus, there may be as many IRRs as there are sign changes in the A's.We can see the meaning of multiple roots most easily with the concept of projectbalance. If a project has a sequence of net cash flows AQ, A\, A , . . , Aj, and the interestrate is /", there are T + 1 project balances, BQ, B\, B , . . . , Bj, one at the end of eachperiod t, t = 0, 1, . . . , T. A project balance, B , is the accumulated future value of all cashflows, up to the end of period t, compounded at the rate, /'. That is,2
BQ
AQ
B =AQ{\x
+i')+A
= A (l + i) + A {\ + /') + A
B = A (l + i) + Ai(\ + i) ~T
+ ... + A
Table 5.1 shows the project balances at the end of each year for both 100% and200% interest rates for the project in Example 5.7. T h e project starts with a cash inflowof S1000. At a 100% interest rate, the S1000 increases to S2000 over the first year. At theend of the first year, there is a S5000 disbursement, leaving a negative project balance ofS3000. At 100% interest, this negative balance increases to $6000 over the second year.This negative S6000 is offset exactly by the S6000 inflow. This makes the project balancezero at the end of the second year. T h e project balance at the end of the project is thefuture worth of all the cash flows in the project. Y\ nen the future worth at the end of theproject life is zero, the present worth is also zero. This verifies that the 100% is an IRR.Table 5.1
Project B a l a n c e s for E x a m p l e 5 . 7
At r = ioo%
A t i' = 200%
-3000(1 + 1) + 6000 = 0
-2000(1 + 2) + 6000 = 0
End of Year
Now consider the 200% interest rate. Over the first year, the S1000 inflow increasesto S3000. At the end of the first year, $5000 is paid out, leaving a negative project balanceof S2000. This negative balance grows at 200% to S6000 over the second year. This isoffset exactly by the S6000 inflow so that the project balance is zero at the end of thesecond year. This verifies that the 200% is also an IRR!
ICapital Budgeting and FinancialManagement Resources
The internet can be an excellent source of information about the project comparison methods presented in Chapters 4 and 5. A broad search formaterials on the PW, AW, and IRR comparisonmethods might use key words such -AS financial management or capital budgeting. Such a search can yieldvery useful supports for practising engineers orfinancial managers responsible for making investment decisions. For example, one can find shortcourses on the process of project evaluation usingpresent worth or IRR methods and how to determine the cost of capital in the Education Centre at. Investopedia() provides online investment resources, including definitions for a widenumber of commonly used financial terms.
Looking at Table 5.1, it's actually fairly obvious that an important assumption is beingmade about the initial $1000 received. T h e IRR computation implicitly assumes that theSI000 is invested during the first period at either 100% or 200%, one of the two IRRs.However, during the first period, the project is not an investment. T h e project balance ispositive. The project is providing money, not using it. This money cannot be reinvestedimmediatelv in the project. It is simply cash on hand. T h e $1000 must be investedelsewhere for one year if it is to earn any return. It is unlikely, however, that the $1000provided by the project in this example would be invested in something else at 100% or200%. More likely, it would be invested at a rate at or near the company's MYRR.
External Rate of R e t u r n M e t h o d s
To resolve the multiple IRR difficulty, we need to consider what return is earned bymonev associated with a project that is not invested in the project. T h e usual assumption is that the funds are invested elsewhere and earn an explicit rate of return equal tothe MARR. This makes sense, because when there is cash on hand that is not investedin the project under study, it will be used elsewhere. These funds would, by definition,gain interest at a rate at least equal to the ALARR. T h e external rate of r e t u r n (ERR),denoted by i* , is the rate of return on a project where any cash flows that are notinvested in the project are assumed to earn interest at a predetermined explicit rate(usually the ALARR). For a given explicit rate of return, a project can have only onevalue for its ERR.It is possible to calculate a precise ERR that is comparable to the IRRs of other projectsusing an explicit interest rate when necessary. Because the cash flows of Example 5.7 arefairly simple, let us use them to illustrate how to calculate the ERR precisely.e
5.8
( E X A M P L E
R E V I S I T E D :
E R R )
A project pays $1000 today, costs $5000 a year from now, and pays $6000 in two years.W h a t is its rate of return? Assume that the ALARR is 2 5 %.T h e first S i 0 0 0 is not invested immediately in the project. Therefore, we assumethat it is invested outside the project for one year at the ALARR. Thus, the cumulativecash flow for year 1 is1000(F/P,25%,1) - 5000 = 1250 - 5000 = - $ 3 7 5 0With this calculation, we transform the cash flow diagram representing this problemfrom that in Figure 5.7(a) to that in Figure 5.7(b). These cash flows provide a single(precise) ERR, as follows:- 3 7 5 0 + 6000(P/F,/*,1)
=0
= 0.625
i* = 0.6e
ERR = 6 0 %
Figure 5.7
Methods Part 2
141
M u l t i p l e IRR S o l v e d
(a)
S6000A
$6000A
S1000
ro
-S375C
ea
E X A M P L E 5.9 ( E X A M P L EA NA P P R O X I M A T EE R R )
R E V I S I T E D
A G A I N :
To approximate the ERR, we compute the interest rate that gives a zero future worth atthe end of the project when all receipts are brought forward at the ALARR. In Example 5.7,the S1000 is thus assumed to be reinvested at the ALARR for two years, the life of theproject. The disbursements are taken forward to the end of the two years at an unknowninterest rate, i* . With a ALARR of 25%, the revised calculation isea
142
1 + i*
1.51250.5125 or 5 1 . 2 5 %
ea
ERR = 5 1 % T h e ERR calculated using this method is an approximation, since all receipts, not justthose that occur when the project balance is positive, are assumed to be invested at theMARR. Note that the precise ERR of 60% is different from the approximate ERR of5 1 % . Fortunately, it can be shown that the approximate ERR will always be between theprecise ERR and the ALARR. This means that whenever the precise ERR is above theALARR, the approximate ERR will also be above the MARR and whenever the preciseERR is below the ALARR, the approximation will be below the M A R R as well. Thisimplies that using the approximate ERR will always lead to the correct decision. It shouldalso be noted that an acceptable project will earn at least the rate given by the approximateERR. Therefore, even though an approximate ERR is inaccurate, it is often used inpractice because it provides the correct decision as well as a lower bound on the return onan investment, while being easy to calculate.5.3.5
W h e n to Use t h e ERR
T h e ERR (approximate or precise) must be used whenever there are multiple IRRspossible. Unfortunately, it can be difficult to know in advance whether there will bemultiple IRRs. On the other hand, it is fortunate that most ordinary projects have astructure that precludes multiple IRRs.Most projects consist of one or more periods of outflows at the start, followed onlyby one or more periods of inflows. Such projects are called simple investments. T h ecash flow diagram for a simple investment takes the general form shown in Figure 5.8. Interms of Equations (5.2) and (5.3), there is only one change of sign, from negative topositive in the A's, the sequence of coefficients. Hence, a simple investment always has aunique IRR.If a project is not a simple investment, there may or may not be multiple IRRsthereis no way of knowing for sure without further analysis. In practice, it may be reasonable touse an approximate ERR whenever the project is not a simple investment. Recall fromF i g u r e 5.8
Section 5.3.4 that the approximate ERR will always provide a correct decision, whether itsuse is required or not, since it will understate the true rate of return.However, it is generally desirable to compute an IRR whenever it is possible to do so,and to use an approximate ERR only when there may be multiple IRRs. Ln this way, thecomputations will be as accurate as possible. W nen it is desirable to know for sure whetherthere will be only one IRR, there are several steps of analysis that can be undertaken.These are covered in detail in Appendix 5A.To reiterate, the approximate ERR can be used to evaluate any project, whether it is asimple investment or not. However, the approximate ERR will tend to be a less accuraterate than the IRR. The inaccuracy will tend to be similar for projects with cash flows of asimilar structure, and either method will result in the same decision in the end.
If an independent project has a unique IRR, the IRR method and the present worthmethod give the same decision. Consider Figure 5.9. It shows the present worth as afunction of the interest rate for a project with a unique IRR. T h e maximum of the curvelies at the vertical axis (where the interest rate = 0) at the point given by the sum of allFigure
5.9
a._o
0 .
Netfirstcost
P r e s e n t W o r t h ( P W ) as a F u n c t i o n of I n t e r e s t R a t e (i)for a Simple Investment
144
undiscounted net cash flows. (We assume that the sum of all the undiscounted net cashflows is positive.) As the interest rate increases, the present worth of all cash flows afterthe first cost decreases. Therefore, the present worth curve slopes down to the right. Todetermine what happens as the interest rate increases indefinitely, let us recall thegeneral equation for present worthP W = ^A (lt=ot
(5.4)
wherei = the interest rateA = the net cash flow in period fT = the number of periodst
= 0 for f = 1, 2, . . ., T+
0'
Therefore, as the interest rate becomes indefinitely large, all terms in Equation (5.4)approach zero except the first term (where t = 0), which remains at/4n. In Figure 5.9, thisis shown by the asymptotic approach of the curve to the first cost, which, being negative, isbelow the horizontal axis.T h e interest rate at which the curve crosses the horizontal axis (/* in Figure 5.9),where the present worth is zero, is, by definition, the IRR.To demonstrate the equivalence of the rate of return and the present/annual worthmethods for decision making, let us consider possible values for the AIARR. First,suppose the ALARR = i\, where i\ < i*. In Figure 5.9, this ALARR would lie to the leftof the IRR. From the graph we see that the present worth is positive at i\. In otherwords, we haveIRR > ALARRandPW > 0Thus, in this case, both the IRR and PW methods lead to the same conclusion: Accept theproject.Second, suppose the ALARR = /i, where h > i*. In Figure 5.9, this ALARR would lie tothe right of the IRR. From the graph we see that, at ii, the present worth is negative. Thuswe haveIRR < M A R RandPW < 0Here, too, the IRR and the PW method lead to the same conclusion: Reject the project.Now consider two simple, mutually exclusive projects, A and B, where the first costof B is greater than the first cost of A. If the increment from A to B has a unique IRR,then we can readily demonstrate that the IRR and PW methods lead to the samedecision. See Figure 5.10(a), which shows the present worths of projects A and B as afunction of the interest rate. Since the first cost of B is greater than that of A, the curve
Figure 5 . 1 0
145
P r e s e n t W o r t h a s a F u n c t i o n o f I n t e r e s t R a t e (i) f o r TwoSimple, Mutually Exclusive Projects
Interestrate (/)>PW(A)PW(B)
Interestrate (/)P W (B - A)
for project B asymptotically approaches a lower present worth than does the curve forproject A as the interest rate becomes indefinitely large, and thus the two curves mustcross at some point.To apply the IRR method, we must consider the increment (denoted by B - A). T h epresent worth of the increment (B - A) will be zero where the two curves cross. This pointof intersection is marked by the interest rate, /'*. We have plotted the curve for the increment(B - A) in Figure 5.10(b) to clarify the relationships.Let us again deal with possible values of the ALARR. First, suppose the ALARR (;'i) isless than i*. Then, as we see in Figure 5.10(b), the present worth of (B - A) is positive at i\.That is, the following conditions hold:IRR(B - A) > ALARRa n d
P W ( B - A) > 0Thus, according to both the IRR method and the PW method, project B is better thanproject A.
146
Second, suppose the MARR = /i> where ii > i*. Then we see from Figure 5.10(b) thatthe present worth of the increment (B - A) is negative at ij. In other words, the followingconditions hold:IRR(B - A) < M A R RandP W ( B - A) < 0Thus, according to both methods, project A is better than project B.In a similar fashion, we could show that the approximate ERR method gives the samedecisions as the PW method in those cases where there may be multiple IRRs.We already noted that the annual worth and present worth methods are equivalent.Therefore, by extension, our demonstration of the equivalence of the rate of returnmethods and the present worth methods means that the rate of return and the annualworth methods are also equivalent.E X A M P L E
5 . 1 0
= - 1 0 000 + 2000(P/,4,10%,15)= - 1 0 000 + 2000(7.6061)= 5212.20T h e parasailing venture has a higher present worth at about $14 000 and isthus preferred.(b) The IRRs of the two projects are calculated as follows:Parasailing100 000 = 15 000(PA4,/*,15)(P/A,i*,\S) = 100 000/15 000 = 6.67 - /*
para
= 12.4%
Kayaking10 000 = 2000(PA4,/*,15)(P/A,i\15) = 5^i\, , =18.4%y k
One might conclude that, because I R R ^ k is larger, the resort should investin the kayaking project, but this is wrong. Wnen done correctly, a present worthanalysis and an IRR analysis will always agree. The error here is that the parasailing
project was assessed without consideration of the increment from the kayaking project. Checking the IRR of the increment (denoted by the subscript "kayak-para"):(100 0 0 0 - 10 000) = (15 000-2000)(PA-l,/*,15)(P/A,i*,15) = 90 000/13 000 = 6.923 -> / \
avak
= 11.7%
Since the increment from the kayaking project also exceeds the AIARR, thelarger parasailing project should be t a k e n . 5.4.2
W h y C h o o s e One M e t h o d O v e r t h e O t h e r ?
Although rate of return methods and present worth/annual worth methods give thesame decisions, each set of methods has its own advantages and disadvantages. T h echoice of method may depend on the way the results are to be used and the sort of datathe decision makers prefer to consider. In fact, many companies, by policy, require thatseveral m e t h o d s be applied so that a more complete picture of the situation ispresented. A summary of the advantages and disadvantages of each method is given inTable 5.2.Rate of return methods state results in terms of rates, while present/annual worthmethods state results in absolute figures. Many managers prefer rates to absolute figuresbecause rates facilitate direct comparisons of projects whose sizes are quite different. Forexample, a petroleum company comparing performances of a refining division and adistribution division would not look at the typical values of present or annual worthfor projects in the two divisions. A refining project may have first costs in the rangeof hundreds of millions, while distribution projects may have first costs in the range ofthousands. It would not be meaningful to compare the absolute profits between a refiningproject and a distribution project. T h e absolute profits of refining projects will almostcertainly be larger than those of distribution projects. Expressing project performance interms of rates of return permits understandable comparisons. A disadvantage of rate ofreturn methods, however, is the possible complication that there may be more than onerate of return. Under such circumstances, it is necessary to calculate an ERR.Table 5.2
Advantages
Disadvantages
Facilitates comparisons ofprojects of different sizesCommonlv used
Presentworth
Annualworth
Paybackperiod
148
5 . 1 1
Ramesh works for a large power company and must assess the viability of locating a transformer station at various sites in the city . He is looking at the cost ofthe building lot, power lines, and power losses for the various locations. He hasfairly accurate data about costs and future demand for electricity.As part of a large firm, Ramesh will probably be obliged to use a specificcomparison method. This would probably be IRR. A power company makesmany large and small investments, and the IRR method allows them to becompared fairly. Ramesh has the data necessary for the IRR calculations.7
Sehdev must buy a relatively inexpensive log splitter for his agricultural firm. Thereare several different types that require a higher or lower degree of manual assistance.He has only rough estimates of how this machine will affect future cash flows.This relatively inexpensive purchase is a good candidate for the paybackperiod method. The fact that it is inexpensive means that extensive data gathering and analysis are probably not warranted. Also, since future cash flows arerelatively uncertain, there is no justification for using a particularly precisecomparison method.
Ziva will be living in the Arctic for six months, testing her company's equipmentunder hostile weather conditions. She needs a field office and must determinewhich of the following choices is economically best: (1) renting space in anindustrial building, (2) buying and outfitting a trailer, (3) renting a hotel roomfor the purpose.For this decision, a present worth analysis would be appropriate. T h e cashflows for each of the alternatives are of different types, and bringing them topresent worth would be a fair way to compare them. It would also provide anaccurate estimate to Ziva's firm of the expected cost of the remote office forplanning purposes.B
P R O B L E M S5.1
Wei-Ping's consulting firm needs new quarters. A downtown office building is ideal. T h ecompany can either buy or lease it. To buy the office building will cost 60 000 000 yuan.If the building is leased, the lease fee is 4 000 000 yuan payable at the beginning of eachyear. In either case, the company must pay city taxes, maintenance, and utilities.W e i - P i n g figures that the company needs the office space for only 15 y e a r s .Therefore, they will either sign a 15-year lease or buy the building. If they buy thebuilding, they will then sell it after 15 years. T h e value of the building at that time isestimated to be 150 000 000 yuan.W h a t rate of return will Wei-Ping's firm receive by buying the office buildinginstead of leasing it?ANSWER
T h e rate of return can be calculated as the IRR on the incremental investment necessaryto buy the building rather than lease it.T h e IRR on the incremental investment is found by solving for i*in(60 000 000 - 4 000 000) - 150 000 000(P/F,/*,15) = 4 000 000(P/,4,z*,14)4(P/J,/*,14) + 150(P/F,z'*,15) = 56For i* = 11 %, the result is4(P/,4,11%,14) + 150(P/F,11%,15)= 4(6.9819) + 150(0.20900)= 59.2781For/*= 12%,4(P/^,12%,14) + 150(P/F,12%,15)= 4(6.6282) + 150(0.1827)= 53.9171A linear interpolation between 1 1 % and 12% gives the IRRi * = 1 1 % + (59.2781 - 5 6 ) / ( 5 9 . 2 7 8 1 - 53.9171) = 11.6115%By investing their money in buying the building rather than leasing, Wei-Ping's firmis earning an IRR of about 11.6%.BREVIEW
The Real S. Tate Company is considering investing in one of four rental properties. Real S.Tate will rent out whatever property they buy for four years and then sell it at the end ofthat period. The data concerning the properties is shown on the next page.
150
RentalProperty
PurchasePrice
Net AnnualRental Income
SlOO 000
S 7200
120 000
9600
130 000
10 800
On the basis of the purchase prices, rental incomes, and sale prices at the end of thefour years, answer the following questions.(a) Which property, if any, should Tate invest in? Real S. Tate uses a ALARR of 8%for projects of this type.(b) Construct a graph that depicts the present worth of each alternative as a functionof interest rates ranging from 0% to 20%. (A spreadsheet would be helpful inanswering this part of the problem.)(c) From your graph, determine the range of interest rates for which your choice inpart (a) is the best investment. If the ALARR were 9%, which rental propertywould be the best investment? Comment on the sensitivity of your choice to theALARR used by the Real S. Tate Company.ANSWER
(a) Since the "do nothing" alternative is feasible and it has the least first cost, itbecomes the current best alternative. T h e IRR on the incremental investmentfor property 1 is given by:- 1 0 0 000 + 100 000(P/F,/*,4) + 7200(PA4,/*,4) = 0T h e IRR on the incremental investment is 7.2%. Because this is less thanthe ALARR of 8%, property 1 is discarded from further consideration.Next, the IRR for the incremental investment for property 2, the alternativewith the next-highest first cost, is found by solving for i* in- 1 2 0 000 + 130 000(P/F,/*,4) + 9600(P/14,/'*,4) = 0T h e interest rate that solves the above equation is 9.8%. Since an IRR of 9.8%exceeds the ALARR, property 2 becomes the current best alternative. Now theincremental investments over and above the first cost of property 2 are analyzed.Next, property 3 challenges the current best. T h e IRR in the incrementalinvestment to property 3 is(-150 000 + 120 000) + (160 000 - 130 000)(P/F,/*,4)+ (10 800 - 9600)(PAd,/*,4) = 0- 3 0 000 + 30 000(P/F,/*,4) + 1200(PA4,/*,4) = 0T h i s gives an IRR of only 4%, which is below the ALARR. Property 2remains the current best alternative and property 3 is discarded.Finally, property 4 challenges the current best. T h e IRR on the incrementalinvestment from property 2 to property 4 is(-200 000 + 120 000) + (230 000 - 130 000)(P/F,/*,4)+ (12 000 - 9600)(P/^,/*,4) = 0- 8 0 000 + 100 000(P/F,/*,4) + 2400(PA4,/*,4) = 0
Figure 5.11
151
Interest rate
The IRR on the incremental investment is 8.5%, which is above the ALARR.Property 4 becomes the current best choice. Since there are no further challengers,the choice based on IRR is the current best, property 4.(b) T h e graph for part (b) is shown in Figure 5.11.(c) From the graph, one can see that property 4 is the best alternative provided thatthe AIARR is between 0% and 8.5%. This is the range of interest rates overwhich property 4 has the largest present worth.If the ALARR is 9%, the best alternative is property 2. This can be seen bygoing back to the original IRR computations and observing that the results ofthe analysis are essentially the same, except that the incremental investmentfrom property 2 to property- 4 no longer has a return exceeding the ALARR.T h i s can be confirmed from the diagram (Figure 5.11) as well, since theproperty with the largest present worth at 9% is property 2.W i t h respect to sensitivity analysis, the graph shows that, for a M A R Rbetween 0% and 8.5%, property 4 is the best choice and, for a ALARR between8.5% and 9.8%, property- 2 is the best choice. If the ALARR is above 9.8%, noproperty has an acceptable return on investment, and the "do nothing" alternativewould be chosen.REVIEW
You are in the process of arranging a marketing contract for a new Java applet youare writing. It still needs more development, so your contract will pay you 5000today to finish the prototype. You will then get royalties of 10 000 at the end of each
of the second and third years. At the end of each of the first and fourth years, you willbe required to spend 20 000 and 10 000 in upgrades, respectively. W h a t is the(approximate) ERR on this project, assuming a M A R R of 20%? Should you acceptthe contract?ANSWER
(F/P,i* ,3) =ea
1.3384
S U M M A R YThis chapter presented the IRR method for evaluating projects and also discussed therelationship among the present worth, annual worth, payback period, and IRR methods.T h e IRR method consists of determining the rate of return for a sequence of cashflows. For an independent project, the calculated IRR is compared with a ALARR, and ifit is equal to or exceeds the ALARR it is an acceptable project. To determine the bestproject of several mutually exclusive ones, it is necessary to determine the IRR of eachincrement of investment.T h e IRR selection procedure is complicated by the possibility of having more thanone rate of return because of a cash flow structure that, over the course of a project,requires that capital, eventually invested in the project at some point, be invested externally. Under such circumstances, it is necessary to calculate an ERR.T h e present worth and annual worth methods are closely related, and both giveresults identical to those of the IRR method. Rate of return measures are readilyu n d e r s t a n d a b l e , especially when c o m p a r i n g projects of u n e q u a l sizes, w h e r e a spresent/annual worth measures give an explicit expression of the profit contributionof a project. T h e main advantage of the payback period method is that it is easyto i m p l e m e n t and u n d e r s t a n d , and takes into account the need to have capitalrecovered quickly.7
153
P R O B L E M SFor additional practice, please see the problemsCD-ROM that accompanies this book.5.1
W h a t is the IRR for a $1000 investment that returns $200 at the end of each of the next(a) 7 years?(b) 6 years?(c) 100 years?(d) 2 years?
New windows are expected to save 400 per year in energy costs over their 30-year lifefor Fab Fabricating. At an initial cost of 8000 and zero salvage value, are they a goodinvestment? Fab's AIARR is 8%.
An advertising campaign will cost 200 000 000 for planning and 40 000 000 in each ofthe next six years. It is expected to increase revenues permanently by 40 000 000 peryear. Additional revenues will be gained in the pattern of an arithmetic gradient with20 000 000 in the first year, declining by 5 000 000 per year to zero in the fifth year.W h a t is the IRR of this investment? If the company's AIARR is 12%, is this a goodinvestment?
Aline has three contracts from which to choose. T h e first contract will require anoutlay of $100 000 but will return $150 000 one year from now. T h e second contractrequires an outlay of $200 000 and will return $300 000 one year from now. T h ethird contract requires an outlay of $250 000 and will return $355 000 one year fromnow. Only one contract can be accepted. If her AIARR is 2 0 % , which one should shechoose?
Refer to Review Problem 4.3. Assuming the four investments are independent, use theIRR method to select which, if any, should be chosen. Use a ALARR of 8%.
Fantastic Footwear can invest in one of two different automated clicker cutters. T h efirst, A, has a 100 000 yuan first cost. A similar one with many extra features, B, hasa 400 000 yuan first cost. A will save 50 000 yuan per year over the cutter now in use.B will save 150 000 yuan per year. Each clicker cutter will last five years. If the ALARR is10%, which alternative is better? Use an IRR comparison.
155
IRR onOverallInvestment
19%
15%
9%
18%
17%
23%
16%
12%
13%
There are several mutually exclusive ways Grazemont Dairy can meet a requirement fora filling machine for their creamer line. One choice is to buy a machine. This would cost 6 5 000 and last for six years with a salvage value of 1 0 000. Alternatively, they couldcontract with a packaging supplier to get a machine free. In this case, the extra costs forpackaging supplies would amount to 1 5 000 per year over the six-year life (after whichthe supplier gets the machine back with no salvage value for Grazemont). T h e thirdalternative is to buy a used machine for 3 0 000 with zero salvage value after six years.T h e used machine has extra maintenance costs of 3 0 0 0 in the first year, increasing by 2 5 0 0 per year. In all cases, there are installation costs of 6 0 0 0 and revenues of 2 0 000 per vear. Using the IRR method, determine which is the best alternative. T h eALARR is 10%.
5.10 Project X has an IRR of 16% and a first cost of S20 000. Project Y has an IRR of 17%and a first cost of S i 8 000. The ALARR is 15%. W h a t can be said about which (if either)of the two projects should be undertaken if (a) the projects are independent and (b) theprojects are mutually exclusive?5.11 Charlie has a project for which he had determined a present worth of R56 740. He nowhas to calculate the IRR for the project, but unfortunately he has lost complete information about the cash flows. He knows only that the project has a five-year sendee life anda first cost of R180 000, that a set of equal cash flows occurred at the end of each year,and that the ALARR used was 10%. W h a t is the IRR for this project?5.12 Lucy's project has a first cost P, annual savings A, and a salvage value of S i 0 0 0 at the endof the 10-year sendee life. She has calculated the present worth as $20 000, the annualworth as $4000, and the payback period as three years. W h a t is the IRR for this project?5.13 Patti's project has an IRR of 15%, first cost P, and annual savings A. She observed thatthe salvage value S at the end of the five-year life of the project was exactly half of the
156
purchase price, and that the present worth of the project was exactly double the annualsavings. W h a t was Patti's ALARR?5.14 Jerry has an opportunity to buy a bond with a face value of S10 000 and a coupon rate of14%, payable semiannually.(a) If the bond matures in five years and Jerry can buy one now for S3500, what is hisIRR for this investment?(b) If his ALARR for this type of investment is 20%, should he buy the bond?5.15 T h e following cash flows result from a potential construction contract for ErstwhileEngineering.1. Receipts of 500 000 at the start of the contract and 1 200 000 at the end of thefourth year2. Expenditures at the end of the first year of 400 000 and at the end of the secondyear of 900 0003. A net cash flow of 0 at the end of the third yearUsing an appropriate rate of return method, for a ALARR of 2 5 % , should ErstwhileEngineering accept this project?5.16 Samiran has entered into an agreement to develop and maintain a computer program forsymbolic mathematics. Under the terms of the agreement, he will pay 9 000 000 rupeesin royalties to the investor at the end of the fifth, tenth, and fifteenth years, with theinvestor paying Samiran 4 500 000 rupees now, and then 6 500 000 rupees at the end ofthe twelfth year.Samiran's AIARR for this type of investment is 2 0 % . Calculate the ERR of thisproject. Should he accept this agreement, on the basis of these disbursements andreceipts alone? Are you sure that the ERR you calculated is the only ERR? W h y ? Areyou sure that your recommendation to Samiran is correct? Justify your answer.5.17 Refer to Problem 4.12. Find which alternative is preferable using the IRR method and aALARR of 5%. Assume that one of the alternatives must be chosen. Answer the followingquestions by using present worth computations to find the IRRs. Use the least commonmultiple of sendee lives.(a) What are the cash flows for each year of the comparison period (i.e., the least commonmultiple of sendee lives)?(b) Are you able to conclude that there is a single IRR on the incremental investment?W h y or why not?(c) Y\ nich of the two alternatives should be chosen? Use the ERR method if necessary.5.18 Refer to Example 4.6 in which a mechanical engineer has decided to introduce automated materials-handling equipment to a production line. Use a present worth approachwith an IRR analysis to determine which of the two alternatives is best. T h e ALARR is9%. Use the repeated lives method to deal with the fact that the sendee lives of the twoalternatives are not equal.5.19 Refer to Problem 4.20. Use an IRR analysis to determine which of the two alternativesis best. T h e AIARR is 8%. Use the repeated lives method to deal with the unequalsendee lives of the two alternatives.
157
5.20 Refer to Problem 4.21. Yal has determined that the salvage value of the XJ3 after twoyears of sendee is S i 9 0 0 . Using the IRR method, which display panel is the betterchoicer Use a two-year study period. She must choose one of the alternatives.5.21 Yee Swian has received an advance of 200 000 yuan on a software program she iswriting. She will spend 1 200 000 yuan this year writing it (consider the money to havebeen spent at the end of vear 1), and then receive 1 000 000 yuan at the end of thesecond year. The AIARR is 12%.(a) \\ nat is the IRR for this project? Does the result make sense?(b) W h a t is the precise ERR?(c) W h a t is the approximate ERR?5.22 Zhe develops truss analysis software for civil engineers. He has the opportunity to contractwith at most one of two clients who have approached him with development proposals.One contract pays him S i 5 000 immediately, and then S22 000 at the end of the projectthree years from now. The other possibility pays S20 000 now and S5000 at the end ofeach of the three years. In either case, his expenses will be S10 000 per year. For a ALARRof 10%, which project should Zhe accept? Use an appropriate rate of return method.5.23 T h e following table summarizes cash flows for a project:Year
-5000
4000
-1000
(a) Write out the expression you need to solve to find the IRR(s) for this set of cashflows. Do not solve.(b) W h a t is the maximum number of solutions for the IRR that could be found inpart (a)? Explain your answer in one sentence.(c) You have found that an IRR of 14.58% solves the expression in part (a). Computethe project balances for each year.(d) Can you tell (without further computations) if there is a unique IRR from this set ofcash flows? Explain in one sentence.5.24 Pepper Properties screens various projects using the payback period method. Forrenovation decisions, the minimum acceptable payback period is five years. Renovationprojects are characterized by an immediate investment of P dollars which is recouped asan annuity of A dollars per year over 20 years. T h e y are considering changing to theIRR method for such decisions. If they changed to the IRR method, what ALARR wouldresult in exactly the same decisions as their current policy using payback period?5.25 Six mutually exclusive projects, A, B, C, D, E, and F, are being considered. T h e y havebeen ordered by first costs so that project A has the smallest first cost, F the largest. T h edata in the table on the next page applies to these projects. T h e data can be interpretedas follows: the IRR on the incremental investment between project D and project C is6%. \\ nich project should be chosen using a ALARR of 15%?
20%
24%
35%
22%
6%
21%
11%
5.26 Three mutually exclusive designs for a bypass are under consideration. T h e bypass has a10-year life. T h e first design incurs a cost of Si.2 million for a net savings of S300 000per annum. T h e second design would cost S i . 5 million for a net savings of S400 000 perannum. T h e third has a cost of S2.1 million for a net savings of S500 000 per annum.For each of the alternatives, what range of values for the ALARR results in its beingchosen? It is not necessary that any be chosen.5.27 Linus's project has cash flows at times 0, 1, and 2. He notices that for a ALARR of 12%,the ERR falls exactly halfway between the ALARR and the IRR, while for a ALARR of18%, the ERR falls exactly one-quarter of the way between the ALARR and the IRR. Ifthe cash flow is S2000 at time 2 and negative at time 0, what are the possible values ofthe cash flow at time 1 ?5.28 T h r e e construction jobs are being considered by Clam City Construction (see thefollowing table). Each is characterized by an initial deposit paid by the client to C C C , ayearly cost incurred by C C C at the end of each of three years, and a final payment toC C C by the client at the end of three years. C C C has the capacity' to do only one ofthese contracts. Use an appropriate rate of return method to determine which theyshould do. Their ALARR is 10%.Job
Deposit ($)
5.29 Kool Karavans is considering three investment proposals. Each of them is characterizedby an initial cost, annual savings over four years, and no salvage value, as illustrated inthe following table. They can only invest in two of these proposals. If their ALARR is12%, which two should they choose?Proposal
159
CheckweigherFirst costAnnual costsAnnual benefitsSalvage value
305148
000000000000
Scheduler 1 0 00012 00017 0000
5.31 Jacob is considering the replacement of the heating system for his building. There aret h r e e a l t e r n a t i v e s . All are n a t u r a l - g a s - f i r e d furnaces, but they vary in e n e r g yefficiency. A'lodel A is leased at a cost of $500 per year over a 10-vear study period.There are installation charges of S500 and no salvage value. It is expected to provideenergy savings of $200 per year. M o d e l B is purchased for a total cost of $3600,including installation. It has a salvage value of S i 0 0 0 after 10 years of service, and isexpected to provide energy savings of S500 per year. Model C is also purchased, for atotal cost of $8000, including installation. However, half of this cost is paid now, andthe other half is paid at the end of two years. It has a salvage value of S i 0 0 0 after10 years, and is expected to provide energy savings of $1000 per year. For a ALARR of12% and using a rate of return method, which heating system should be installed?One model must be chosen.5.32 Corral Cartage leases trucks to sendee its shipping contracts. Larger trucks have cheaperoperating costs if there is sufficient business, but are more expensive if thev are not full.CC has estimates of monthly shipping demand. W nat comparison method(s) would beappropriate for choosing which trucks to lease?5.33 T h e bottom flaps of shipping cartons for Yonge Auto Parts are fastened with industrialstaples. Yonge needs to buy a new stapler. W h a t comparison method(s) would be appropriate for choosing which stapler to buy?5.34 Joan runs a dog kennel. She is considering installing a heating system for the interiorruns which will allow her to operate all year. \\"hat comparison method(s) would beappropriate for choosing which heating system to buy?5.35 A large food company is considering replacing a scale on its packaging line with a moreaccurate one. W h a t comparison method(s) would be appropriate for choosing whichscale to buy?5.36 Alona runs a one-person company producing custom paints for hobbyists. She is conside r i n g b u y i n g p r i n t i n g e q u i p m e n t to produce her own labels. W h a t comparisonmethod(s) would be appropriate for choosing which equipment to buy?
5.37 Peter is the president of a rapidly growing company. There are dozens of importantthings to do, and cash flow is tight. Y\ nat comparison method(s) would be appropriatefor Peter to make acquisition decisions?5.38 Lemuel is an engineer working for the electric company. He must compare severalroutes for transmission lines from a distant nuclear plant to new industrial parks north ofthe city. W h a t comparison method(s) is he likely to use?5.39 Vicky runs a music store that has been suffering from thefts. She is considering installinga magnetic tag system. W h a t comparison method(s) would be best for her to use tochoose among competing leased systems?5.40 Thanh's company is growing very fast and has a hard time meeting its orders. An opportunity to purchase additional production equipment has arisen. What comparison method(s)would Thanh use to justify to her manager that the equipment purchase was prudent?More Challenging Problem
The Galore C r e e k P r o j e c t
XovaGold Resources is a former gold exploration company that has recently been transforming itself into a gold producer. Its first independent development is the Galore CreekProject. It is also involved as a partner with Placer Dome in another project, and with RioTinto in a third. Galore Creek is expected to produce an average of 7650 kilograms of gold,51 030 kilograms of silver, and 5 670 000 kilograms of copper over its first five years.In a news release, XovaGold reported that an independent engineering sendees company calculated that the project would pay back the USS500 million mine capital costs in3.4 years of a 23-year life. They also calculated a pre-tax rate of return of 12.6% and anundiscounted after-tax X P V of USS329 million. All of these calculations were done atlong-term average metal prices. At then-current metal prices the pre-tax rate of returnalmost doubles to 24.3% and the X P V (net present value = present worth) increases toUS$1,065 billion."Higher Grades and Expanded Tonnage Indicated by Drilling at Galore CreekGold-Silver-Copper Project," news release, August 18, 2004, XovaGold Resources Inc. site,, accessed May 11, 2008.Source:
Companies have a choice of how to calculate the benefits of a project in order to determine ifit is worth doing. They also have a choice of how to report the benefits of a project to others.
XovaGold is a publicly traded company. Because of this, when a large and veryimportant project is being planned, not only does NovaGold want to make good businessdecisions, but it also must maintain strong investor confidence and interest.In this news release, payback period, IRR, and NPV were used to communicate the valueof the Galore Creek project. However, you need to look carefully at the wording to ensurethat you can correcdy interpret the claims about the economic viability of the project.Questions
"[A]n independent engineering sendees company calculated that the project would pavback the USS500 million mine capital costs in 3.4 years of a 23-year life." There are avariety of costs associated with any project. The payback period here is calculated withrespect to "mine capital costs." This suggests that there might be "non-mine" capitalcostsfor example, administrative infrastructure, transportation system, etc. It alsomeans that operating costs are not included in this calculation. What do vou think isthe effect of calculating the payback period on "mine capital costs" alone?
"They also calculated a pre-tax rate of return of 12.6%. . . . " Taxes reduce the profitfrom an enterprise, and correspondingly reduce the rate of return. As will be seen inChapter 8, a 50% corporate tax rate is fairly common. Thus if the pre-tax rate is12.6%, the after-tax rate would be about 6.3%. Does 6.3% seem to you a sufficientreturn for a capital-intensive, risky project of this nature, given other investmentopportunities available?3. "[A]nd an 'undiscounted' after-tax X P Y of USS329 million." The term undiscountedmeans that the present worth of the project was calculated with an interest rate of 0%.Using a spreadsheet, construct a graph showing the present worth of the project for arange of interest rates from 0% to 20%, assuming the annual returns for the projectare evenly distributed over the 2 3-year life of the project. Does the reported value ofSUS329 million fairly represent a meaningful XPA for the project?
The returns for the Galore Creek Project are much more attractive at then-currentmetal prices, which were significantly higher than long-term average metal prices.Which metal prices are more sensible to use when evaluating the worth of the project?5. Did XovaGold report its economic evaluation of the Galore Creek Project in anethical manner?
The tests are applied sequentially. The second test is applied only if the outcome ofthe first test is not clear. The third test is applied only if the outcomes of the first two arenot clear. Keep in mind that, even after all three tests have been applied, the test outcomesmay remain inconclusive.The first test examines whether the project is simple. Recall that most projects consistof one or more periods of outflows at the start, followed only by one or more periods ofinflows; these are called simple investments. Although simple investments guarantee asingle IRR, a project that is not simple may have a single IRR or multiple IRRs. Someinvestment projects have large cash outflows during their lives or at the ends of their livesthat cause net cash flows to be negative after years of positive net cash flows. For example,a project that involves the construction of a manufacturing plant may involve a plannedexpansion of the plant requiring a large expenditure some years after its initial operation.As another example, a nuclear electricity plant may have planned large cash outflows fordisposal of spent fuel at the end of its life. Such a project may have a unique IRR, but itmav also have multiple IRRs. Consequently we must examine such projects further.Where a project is not simple, we go to the second test. The second test consists ofmaking a graph plotting present worth against interest rate. Points at which the presentworth crosses or just touches the interest-rate axis (i.e., where present worth = 0) areIRRs. (We assume that there is at least one IRR.) If there is more than one such point, weknow that there is more than one IRR. A convenient way to produce such a graph is usinga spreadsheet. See Example 5A.1.E X A M P L E
5 A . 1
R E S T A T E D )
A project pays S1000 today, costs S5000 a year from now, and pays S6000 in two years.Are there multiple IRRs?Table 5A. 1 was obtained by computing the present worth of the cash flows inExample 5.7 for a variety of interest rates. Figure 5A. 1 shows the graph of the values inTable 5A. 1.W h i l e finding multiple IRRs in a plot ensures that the project does indeed havemultiple IRRs, failure to find multiple IRRs does not necessarily mean that multipleIRRs do not exist. Any plot will cover only a finite set of points. There may be values ofthe interest rate for which the present worth of the project is zero that are not in therange of interest rates used.Table 5 A . 1
Interest Rate, i
0.6
218.8
0.8
74.1
1.0
0.0
-33.1
-41.7
-35.5
-20.4
2.0
23.4
48.4
Figure 5A.1
163
I l l u s t r a t i o n o f Two IRRs f o r E x a m p l e 5 A . 1
250 -
200-
100|
50 -
00
-50Interest rate, /
W h e r e the project is not simple and a plot does not show multiple IRRs, we applythe third test. T h e third test entails calculating the project balances. As we mentionedearlier, project balances refer to the cumulative net cash flows at the end of each timeperiod. For an IRR to be unique, there should be no time when the project balances,computed using that IRR, are positive. T h i s means that there is no extra cash notreinvested in the project. This is a sufficient condition for there to be a unique IRR.(Recall that it is the cash generated by a project, but not reinvested in the project, thatcreates the possibility of multiple IRRs.)We now present three examples. All three examples involve projects that are notsimple investments. In the first, a plot shows multiple IRRs. In the second, the plotshows only a single IRR. This is inconclusive, so project balances are computed. Noneof the project balances is positive, so we know that there is a single IRR. In the thirdexample, the plot shows only one IRR, so the project balances are computed. One ofthese is positive, so the results of all tests are inconclusive.
5 A . 2
Wellington Woods is considering buying land that they will log for three years. In thesecond year, they expect to develop the area that they clear as a residential subdivisionthat will entail considerable costs. Thus, in the second year, the net cash flow will benegative. In the third year, they expect to sell the developed land at a profit. The netcash flows that are expected for the project are:End of Year
Cash Flow
440 000
- 6 3 9 000
306 000
The negative net cash flow in the second period implies that this is not a simple project.Therefore, we apply the second test. We plot the present worth against interest rates to
Figure 5A.2
0.3
0.4
0.5
Interest rate, i
search for IRRs. (See Figure 5A.2.) At 0% interest, the present worth is a small positiveamount, S7000. The present worth is then 0 at 20%, 50%, and 70%. Each of these values isan IRR. The spreadsheet cells that were used for the plot are shown in Table 5A.2.Table 5 A . 2
InterestRate
PresentWorth
0%
S7000.00
28%
- 352.48
56%
$ 79.65
2%
5536.33
- 364.13
58%
92.49
4%
4318.39
32%
- 356.87
97.66
3310.12
34%
- 335.15
62%
94.84
8%
2480.57
36%
- 302.77
64%
83.79
10%
1803.16
38%
- 263.01
66%
64.36
1255.01
- 218.66
68%
36.44
14%
816.45
42%
- 172.11
70%
0.00
470.50
44%
- 125.39
72%
- 44.96
202.55
46%
- 80.20
74%
- 98.41
48%
- 38.00
76%
- 160.24
- 148.03
78%
- 230.36
- 250.91
52%
32.80
26%
- 316.74
54%
59.58
1B5
Try 15% for i* . Using the tables for the left-hand side of the above equation, we haveea
5 A . 3
A rebate of $30 from the supplier is given immediately for an exclusive six-monthcontract.
3.4.
Supplies will cost S20 per month, payable at the beginning of each month.Income from sales will be S30 per month, received at the end of each month.
+ S30
- S40 + (- S20)
- S30
+ 30
40 + (-
+ 10
20)
As illustrated in Figure 5A.3, the net cash flows for this problem do not follow thepattern of a simple investment. Therefore, there may be more than one IRR for thisproblem. Accordingly, we apply the second test.
166
Figure 5A.3
S 1 0
$ 1 0
$10
1_J
(Months)
$ 3 0
A plot of present worth against the interest rate is shown in Figure 5A.4. T h e plotstarts with a zero interest rate where the present worth is just the arithmetic sum of allthe net cash flows over the project's life. This is a positive $10. T h e present worth as afunction of the interest rate decreases as the interest rate increases from zero. T h e plotcontinues down, and passes through the interest-rate axis at about 5.8%. There is onlyone IRR in the range plotted. We need to apply the third test by computing projectbalances at the 5.8% interest rate.
Figure 5A.4
IRR f o r N e w C o f f e e m a k e r-N,
0 . 0 2
0 . 0 4
0 . 0 6 \ 0 . 0 8
0 . 1
0 . 1 2
0 . 1 4
0 . 1 6
0 . 1 8
0 . 2 0
-10
- 1 5
T h e project balances at the 5.8% interest rate are shown on the next page.$ince all project balances are negative or zero, we know that this investment hasonly one IRR. It is 5.8% per month or about 69.3 % per y e a r . B
Month
167
B = -30
B = -30.0(1.058) + 10 == - 2 1 . 7
B = -21.7(1.058) + 10 == - 1 3 . 0
B = -13.0(1.058) - 30 == - 4 3 . 7
Z? = -43.7(1.058) + 10 == -36.3
B = -36.3(1.058) + 10 == - 2 8 . 4
B = -28.4(1.058) + 30 == 0
5 A . 4
Green Woods, like Wellington Woods, is considering buying land that they will log forthree years. In the second year, they also expect to develop the area that they have loggedas a residential subdivision, which again will entail considerable costs. Thus, in the secondyear, the net cash flow- will be negative. In the third year, they expect to sell the developedland at a profit. But Green Woods expects to do much better than Wellington Woods inthe sale of the land. T h e net cash flows that are expected for the project are:Year
- $ 1 0 0 000
455 000
- 6 6 7 500
650 000
T h e negative net cash flow in the second period implies that this is not a simpleproject. We now plot the present worth against interest rate. $ee Figure 5A.5. At zerointerest rate, the present worth is a positive $337 500.The present worth falls as the interest rate rises. It crosses the interest-rate axis atabout 206.4%. T h e r e are no further crossings of the interest-rate axis in the rangeplotted, but since this is not conclusive we compute project balances.Year
5 = - 1 0 0 000
We note that the project balance is positive at the end of the first period. Thismeans that a unique IRR is not guaranteed. We have gone as far as the three tests can
168
Figure 5A.5
350 -]
-100
take us. On the basis of the three tests, there may be only the single IRR that we havefound, 206.4%, or there may be multiple IRRs.In this case, we use the approximate ERR to get a decision. Suppose the AL\RR is30%. T h e approximate ERR, then, is the interest rate that makes the future worth ofoutlays equal to the future worth of receipts when the receipts earn 30%. That is, theapproximate ERR is the value of / that solves the following:100 000(1 + 0 + 667 500(1 + /) = 455 000(1.3) + 650 000Trial and error with a spreadsheet gives the approximate ERR as i* = 57%. This isabove the ALARR of 30%. Therefore, the investment is acceptable.It is possible, using the precise ERR, to determine that the IRR that we got with theplot of present worth against the interest rate, 206.4%, is, in fact, unique. T h e preciseERR equals the IRR in this case. Computation of the precise ERR may be cumbersome,and we do not cover this computation in this book. Note, however, that we got the samedecision using the approximate ERR as we would have obtained with the precise ERR.Also note that the approximate ERR is a conservative estimate of the precise ERR,which is equal to the unique IRR.B3
Figure 5A.6
169
with the IRR method. If one or more of the project balances are positive, we don't knowwhether there is a unique IRR. Accordingly, we use the approximate ERR method whichalwavs will yield a correct decision.
P R O B L E M S5A.1
- $ 3 0 0 000
- 500 000
700 000
- 400 000
- 100 000
900 000
5A.2
For the cash flows associated with the projects below, determine whether there is aunique IRR, using the project balances method.
End of Period
5A.3
Project2
-$3000
-S1500
900
7000
3S 600-
2000
2900
V-
fli
Depreciationrj and Financia.^Accounting
6.2.2
Value of an Asset
6.2.3
Straight-Line Depreciation
6.2.4
Declining-Balance Depreciation
6.3.2
6.3.3
6.3.4
6.3.5
6.3.6
Financial Ratios
Review ProblemsSummaryEngineering Economics in Action, Part 6B: Usually the TruthProblemsMini-Case 6.1
Depreciation
and
Accounting
B.1
IntroductionEngineering projects often involve an investment in equipment, buildings, or other assetsthat are put to productive use. As time passes, these assets lose value, or depreciate. T h efirst part of this chapter is concerned with the concept of depreciation and severalmethods that are commonly used to model depreciation. Depreciation is taken intoaccount when a firm states the value of its assets in its financial statements, as seen in thesecond half of this chapter. It also forms an important part of the decision of when toreplace an aging asset and when to make cyclic replacements, as will be seen in Chapter 7,and has an important impact on taxation, as we will see in Chapter 8.W i t h the growth in importance of small technology-based enterprises, manyengineers have taken on broad managerial responsibilities that include financialaccounting. Financial accounting is concerned with recording and organizing thefinancial data of businesses. T h e data cover both flovs over time, like revenues andexpenses, and levels, like an enterprise's resources and the claims on those resources ata given date. Even engineers who do not have broad managerial responsibilities needto know the elements of financial accounting to understand the enterprises withwhich they work.In the second part of this chapter, we explain two basic financial statements used tosummarize the financial dimensions of a business. We then explain how these statementscan be used to make inferences about the financial health of the firm.
CHAPTER 6
D e p r e c i a t i o n and
Financiai Accounting
An asset starts to lose value as soon as it is purchased. For example, a car bought forS20 000 today may be worth S i 8 000 next week, S15 000 next year, and Si000 in 10 years.This loss in value, called depreciation, occurs for several reasons.Use-related physical loss: As something is used, parts wear out. An automobile engine hasa limited life span because the metal parts within it wear out. This is one reason why a cardiminishes in value over time. Often, use-related physical loss is measured with respect tounits of production, such as thousands of kilometres for a car, hours of use for a light bulb, orthousands of cycles for a punch press.Time-related physical loss: Even if something is not used, there can be a physical lossover time. This can be due to environmental factors affecting the asset or to endogenousphysical factors. For example, an unused car can rust and thus lose value over time. Timerelated physical loss is expressed in units of time, such as a 10-year-old car or a 40-year-oldsewage treatment plant.Functional loss: Losses can occur without any physical changes. For example, a car canlose value over time because styles change so that it is no longer fashionable. Other examplesof causes of loss of value include legislative changes, such as for pollution control or safetydevices, and technical changes. Functional loss is usually expressed simply in terms of theparticular unsatisfied function.6.2.2
V a l u e of an A s s e t
Models of depreciation can be used to estimate the loss in value of an asset over time,and also to determine the remaining value of the asset at any point in time. This remaining value has several names, depending on the circumstances.Market value is usually taken as the actual value an asset can be sold for in an openmarket. Of course, the onlv way to determine the actual market value for an asset is to sellit. Consequently, the term market value usually means an estimate of the market value. Oneway to make such an estimation is by using a depreciation model that reasonably capturesthe true loss in value of an asset.Book value is the depreciated value of an asset for accounting purposes, as calculatedwith a depreciation model. T h e book value may be more or less than market value. T h edepreciation model used to arrive at a book value might be controlled by regulation forsome purposes, such as taxation, or simply by the desirability of an easy calculationscheme. There might be several different book values for the same asset, depending on thepurpose and depreciation model applied. We shall see how book values are reported infinancial statements later in this chapter.Scrap value can be either the actual value of an asset at the end of its physical life(when it is broken up for the material value of its parts) or an estimate of the scrap valuecalculated using a depreciation model.Salvage value can be either the actual value of an asset at the end of its useful life(when it is sold) or an estimate of the salvage value calculated using a depreciation model.It is desirable to be able to construct a good model of depreciation in order to state abook value of an asset for a variety of reasons:1.
174
loan, a credible estimate of the assets' value must be made. A depreciation modelpermits this to be done. The use of depreciation for this purpose is exploredmore thoroughly in the second part of this chapter.2.
One needs an estimate of the value of owned assets for planning purposes. Inorder to decide whether to keep an asset or replace it, you have to be able tojudge how much it is worth. More than that, you have to be able to assess howmuch it will be worth at some time in the future. T h e impact of depreciation inreplacement studies is covered in Chapter 7.3. Government tax legislation requires that taxes be paid on company profits.Because there can be many ways of calculating profits, strict rules are madeconcerning how to calculate income and expenses. These rules include aparticular scheme for determining depreciation expenses. This use ofdepreciation is discussed more thoroughly in Chapter 8.
To match the way in which certain assets depreciate and to meet regulator} or accuracy requirements, many different depreciation models have been developed over time. Ofthe large number of depreciation schemes available (see Close-Up 6.1), straight-line anddeclining-balance are certainly the most commonly used. Straight-line depreciation ispopular primarily because it is particularly easy to calculate. The declining-balance methodis required by tax law in many jurisdictions for determining corporate taxes, as is discussed inChapter 8. In particular, straight-line and declining-balance depreciation are the only onesnecessary for corporate tax calculations in Canada, the UK, Australia, and the United States.Consequently, these are the only depreciation methods presented in detail in this book.-
Depreciation Methods
150%-declining-balanceUnits-of-production
F i g u r e 6.1
Financial Accounting
175
10Years
Si000 at the time of purchase and S200 eight years later. Graphically the book value ofthe asset is determined by drawing a straight line between its first cost and its salvage orscrap value.Algebraically, the assumption is that the rate of loss in asset value is constant and isbased on its original cost and salvage value. This gives rise to a simple expression for thedepreciation charge per period. We determine the depreciation per period from the asset'scurrent value and its estimated salvage value at the end of its useful life, .V periods fromnow, byP - SD (n) = iv
(6.1)
sl
whereD i(n) = the depreciation charge for period n using the straight-line methods
-p - sX
(6.2)
BV^n) = the book value at the end of period n using straight-line depreciation
A laser cutting machine was purchased four years ago for 380 000. It will have a salvagevalue of 30 000 two years from now. If we believe a constant rate of depreciation is areasonable means of determining book value, what is its current book value?From Equation (6.2), with P = 380 000, 5 = 30 000, A" = 6, and n = 4,380 000 - 30 000BV 0) = 380 000 - 4S
800
~ ^ ^ ^ d =
400 \ .200
d =I1
II
= 3 0 % ^
5 0 % ^ ^ ^ ^ _ _ _ _1I
1I
Ii
6Years
1 0
177
Algebraically, the depreciation charge for period n is simply the depreciation ratemultiplied by the book value from the end of period (n - 1). Noting that BV n,(0) = P,(
DM = BVjtin - 1) x d
(6.3)
whereDS(JI)
BV n,(n) the book value at the end of period n using the declining-balancemethodt
(6.4)
Jh
whereP = the purchase price or current market valueIn order to use the declining-balance method of depreciation, we must determine areasonable depreciation rate. By using an asset's current value, P, and a salvage value, S,77 periods from now, we can use Equation (6.4) to find the declining balance rate thatrelates P and S.BV {n) = S = P(l- d)dh
d)
dE X A M P L E
[s \ P1
fs
(6.5)
Paquita wants to estimate the scrap value of a smokehouse 20 years after purchase. Shefeels that the depreciation is best represented using the declining-balance method, butshe doesn't know what depreciation rate to use. She observes that the purchase price ofthe smokehouse was 2 4 5 000 three years ago, and an estimate of its current salvagevalue is 1 8 0 000. What is a good estimate of the value of the smokehouse after 20 years?From Equation (6.5),
, 1 8 0 000
V 245 000
= 0.097663Then, by using Equation (6.4), we haveBV (20) - 245 000(1 - 0 . 0 9 7 6 6 3 ) = 31 372An estimate of the salvage value of the smokehouse after 20 years using thedeclining-balance method of depreciation is 3 1 372.Bdh
178
Sherbrooke Data Sendees has purchased a new mass storage system for S250 000. It isexpected to last six years, with a SlO 000 salvage value. Using both the straight-line anddeclining-balance methods, determine the following:(a) The depreciation charge in vear 1(b) The depreciation charge in year 6(c) The book value at the end of year 4(d) The accumulated depreciation at the end of vear 4This is an ideal application for a spreadsheet solution. Table 6.1 illustrates a spreadsheetthat calculates the book value, depreciation charge, and accumulated depreciation for bothdepreciation methods over the six-year life of the system.Table 6 . 1
S p r e a d s h e e t for Example 6 . 3
Straight-Line DepreciationYear
DepreciationCharge
AccumulatedDepreciation
BookValue$250 000
S40 000
S 40 000
210 000
"}
Declining-Balance DepreciationYear
BookValueS250 000
S103 799
146 201
60 702
164 501
85 499
35 499
20 760
220 760
29 240
12 140
232 900
17 100
7 100
The depreciation charge for each year with the straight-line method is S40 000:D in) = (250 0 0 0 - 10 000)/6 = 40 000s
d = 1 - n = i - 6
I 10 000= 0.4152
V 250 000
V P
dh
managerial responsibilities that include financial accounting. Even engineers who do nothave broad managerial responsibilities need to know the elements of financial accountingto understand the enterprises in which they work. Management accounting is not coveredin this text because it is difficult to provide useful information without taking more than asingle chapter. Instead, we focus on financial accounting.The object of financial accounting is to provide information to internal managementand interested external parties. Internally, management uses financial accounting information for processes such as budgeting, cash management, and management of long-termdebt. External users include actual and potential investors and creditors who wish to makerational decisions about an enterprise. External users also include government agenciesconcerned with taxes and regulation.Areas of interest to all these groups include an enterprise's revenues and expenses, andassets (resources held by the enterprise) and liabilities (claims on those resources).In the next few sections, we discuss two basic summary financial statements thatgive information about these matters: the balance sheet and the income statement. Thesestatements form the basis of a financial report, which is usually produced on a monthly,quarterly, semiannual, or yearly basis. Following the discussion of financial statements,we shall consider the use of information in these statements when making inferencesabout an enterprise's performance compared with industry standards and with its ownperformance over time.
M e a s u r i n g t h e P e r f o r m a n c e of a F i r m
T h e flow of money in a company is much like the flow of water in a network of pipes orthe flow of electricity- in an electrical circuit, as illustrated in Figure 6.3. In order tomeasure the performance of a water sy-stem, we need to determine the flow through thesystem and the pressure in the system. For an electrical circuit, the analogous parameters are current and voltage. Flow and current are referred to as through variables, andare measured with respect to time (flow is litres per second and current is amperes,which are coulombs per second). Pressure and voltage are referred to as across variables,and are measured at a point in time.T h e flow of money in an organization is measured in a similar way with the incomestatement and balance sheet. The income statement represents a through variable because itsummarizes revenues and expenses over a period of time. It is prepared by listing therevenues earned during a period and the expenses incurred during the same period, and bysubtracting total expenses from total revenues, arriving at a net income. An income statement is always associated with a particular period of time, be it a month, quarter, or year.T h e balance sheet, in contrast to the income statement, is a snapshot of the financialposition of a firm at a particular point in time, and so represents an across variable. T h efinancial position is summarized by listing the assets of the firm, its liabilities (debts), andthe equity of the owner or owners.7
The B a l a n c e S h e e t
F i g u r e 6.3
181
W a t e r systemFlow in
Electrical system
Current
Voltage
A Circuit
Financial system
I n c o m e Statement
Assets
Liabilities+ O w n e r s ' Equity
T h e B a l a n c e SheetT h e Firm
6.4
Table 6.2 shows a balance sheet for the Major Electric Company, a manufacturer ofsmall electrical appliances.T h e first category of financial information in a balance sheet reports the assets ofthe enterprise. These are the economic resources owned by the enterprise, or moresimply, everything that the enterprise owns. Assets are classified on a balance sheet ascurrent assets and long-term assets. Current assets are cash and other assets that couldbe converted to cash within a relatively short period of time, usually a year or less.Inventor} and accounts receivable are examples of non-cash current assets. Long-termassets (also called fixed assets or non-current assets) are assets that are not expected tobe converted to cash in the short term, usually taken to be one year. Indeed, it may be-
182
Table 6.2
392752683S 801
000000000000000
2 500 0001 600 000500 000S 4 600 000S5 401 000
15 00075 00090 000
1 000 000SI 090 000
S 3 000 0001311 000S4 311 000S5 401 000
difficult to convert long-term assets into cash without selling the business as a goingconcern. Equipment, land, and buildings are examples of long-term assets.An enterprise's liabilities are claims, other than those of the owners, on a business'sassets, or simply put, everything that the enterprise owes. Debts are usually the mostimportant liabilities on a balance sheet. There may be other forms of liabilities as well.A commitment to the employees' pension plan is an example of a non-debt liability. Aswith assets, liabilities may be classified as current or long-term. Current liabilities areliabilities that are due within some short period of time, usually a year or less. Examplesof current liabilities are debts that are close to maturity, accounts payable to suppliers,and taxes due. Long-term liabilities are liabilities that are not expected to draw on thebusiness's current assets. Long-term loans and bonds issued by the business are examplesof long-term liabilities.T h e difference between a business's assets and its liabilities is the amount due to theownerstheir equity in the business. That is, owners' equity is what is left over fromassets after claims of others are deducted. We have, therefore,
6.5
Ian Claymore is the accountant at Major Electric. He has just realized that he forgot toinclude in the balance sheet for November 30, 2010, a government loan of SlO 000 to helpin the purchase of a S25 000 test stand (which he also forgot to include). T h e loan is due tobe repaid in two years. Y\ Tien he revises the statement, what changes should he make?T h e government loan is a long-term liability because it is due in more than one year.Consequently, an extra SlO 000 would appear in long-term liabilities. This extra SlO 000must also appear as an asset for the balance to be maintained. T h e $25 000 value of thetest stand would appear as equipment, increasing the equipment amount to S6 525 000.T h e S i 5 000 extra must come from a decrease in cash from S39 000 to S24 000.Depending on the timing of the purchase, depreciation for the test stand might alsobe recognized in the balance sheet. Depreciation would reduce the net value of theequipment by the depreciation charge. T h e same amount would be balanced in theliabilities section by a reduction in retained e a r n i n g s . 6.3.3
The I n c o m e S t a t e m e n t
An income statement summarizes an enterprise's revenues and expenses over a specified accounting period. Months, quarters, and years are commonly used as reportingperiods. As with the balance sheet, the heading of an income statement gives the nameof the enterprise and the reporting period. T h e income statement first lists revenues, bytype, followed by expenses. Expenses are then subtracted from revenues to give income(or profit) before taxes. Income taxes are then deducted to obtain net income. SeeClose-Up 6.3 for a measure used for operating profit.T h e income statement summarizes the revenues and expenses of a business over aperiod of time. However, it does not directly give information about the generation ofcash. For this reason, it may be useful to augment the income statement with a statementof changes in financial position (also called a cash flow statement, a statement of sourcesand uses of funds, or a funds statement), which shows the amounts of cash generated by acompany's operation and by other sources, and the amounts of cash used for investmentsand other non-operating disbursements.CLOSE-UP
Income before taxes and before interest payments, that is, total revenue minus operatingexpenses (all expenses except for income tax and interest), is commonly referred to as theearnings before interest and taxes (EBIT). EBIT measures the company's operatingprofit, which results from making sales and controlling operating expenses. Due to itsfocus on operating profit, EBIT is often used to judge whether there is enough profit torecoup the cost of capital (see Appendix 4A).
6.6. The largest
184
and F i n a n c i a l A c c o u n t i n g
investments the proceeds of which have been reinvested in the business (i.e., not paid outas dividends). Firms retain earnings mainly to expand operations through the purchase ofadditional assets. Contrary to what one may think, retained earnings do not representcash. They may be invested in assets such as equipment and inventor) .T h e balance sheet gets its name from the idea that the total assets are equal in valueto or balanced by the sum of the total liabilities and the owners' equity . A simple way ofthinking about it is that the capital used to buy each asset has to come from debt(liabilities) and/or equity (owners' equity). At a company's start-up, the originalshareholders may provide capital in the form of equity , and there will also likely be debtcapital. T h e general term used to describe the markets in which short or long-term debtand equitv are exchanged is the financial m a r k e t . T h e capital provided through afinancial market finances the assets and working capital for production. As the companyundertakes its business activities, it will make or lose money. As it does so, assets will riseor fall, and equity and/or debt will rise or fall correspondingly. For example, if thecompany makes a profit, the profits will either pay off debts, be invested in new assets,or be paid as dividends to shareholders. Figure 6.4 provides an overview of the sourcesand uses of capital in an organization.7
Figure 6.4
Financial markets p r o v i d ecapital: e.g., short- a n dl o n g - t e r m debt, shares.
Capital for i n v e s t m e n t
R e p a y m e n t of debt
F i r m invests capital inp r o d u c t i v e assets.
Profits m a y alsobe reinvestedinto the firm.
Ian Claymore is the accountant at Major Electric. He has just realized that he forgot toinclude in the balance sheet for November 30, 2010, a government loan of $10 000 to helpin the purchase of a $25 000 test stand (which he also forgot to include). T h e loan is due tobe repaid in two years. \\Ten he revises the statement, what changes should he make?T h e government loan is a long-term liability' because it is due in more than one year.Consequently an extra S10 000 would appear in long-term liabilities. This extra S10 000must also appear as an asset for the balance to be maintained. T h e S25 000 value of thetest stand would appear as equipment, increasing the equipment amount to $6 525 000.T h e $15 000 extra must come from a decrease in cash from S39 000 to S24 000.Depending on the timing of the purchase, depreciation for the test stand might alsobe recognized in the balance sheet. Depreciation would reduce the net value of theequipment bv the depreciation charge. T h e same amount would be balanced in theliabilities section by a reduction in retained e a r n i n g s . 6.3.3
E a r n i n g s Before I n t e r e s t a n d I n c o m e Tax. T h e largest
186
T a b l e 6.3
$7 536 000106 000
ExpensesCost of goods soldSelling costsAdministrative expensesInterest paidTotal Expenses
S6 00728575786
S7 642 000000000000000S7 135 000
S507 000202 800S304 200
expense was the cost of the goods sold. This includes the cost of raw materials, productioncosts, and other costs incurred to produce the items sold. Sometimes firms choose to listcost of goods sold as a negative revenue. The cost of goods sold will be subtracted from thesales to give a net sales figure. The net sales amount is the listed revenue, and the cost ofgoods sold does not appear as an expense.T h e particular entries listed as either revenues or expenses will van , depending onthe nature of the business and the activities carried out. All revenues and expensesappear in one of the listed categories. For Major Electric, for example, the next item onthe list of expenses, selling costs, includes deliver} cost and other expenses such assalespersons' salaries. Administrative expenses include those costs incurred in runningthe company that are not directly associated with manufacturing. Payroll administrationis an example of an administrative expense.Subtracting the expenses from the revenues gives a measure of profit for the company over the accounting period, one year in the example. However, this profit is taxedat a rate that depends on the company's particular characteristics. For Major Electric,the tax rate is 4 0 % , so the company's profit is reduced by that a m o u n t . !7
6.7
Refer back to Example 6.5. Ian Clapnore also forgot to include the effects of the loanand test stand purchase in the income statement shown in Example 6.6. W h e n he revisesthe statement, what changes should he make?Neither the loan nor the purchase of the asset appears direcdy in the income statement.The loan itself is neither income nor expense; if interest is paid on it, this is an expense. Thetest stand is a depreciable asset, which means that only the depreciation for the test standappears as an expense.
Performance measures are calculated values that allow conclusions to be drawn fromdata. Performance measures drawn from financial statements can be used to answer suchquestions as:1. Is the firm able to meet its short-term financial obligations?2. Are sufficient profits being generated from the firm's assets?3. How dependent is the firm on its creditors?Financial ratios are one kind of performance measure that can answer these questions.They give an analyst a framework for asking questions about the firm's liquidity, assetmanagement, leverage, and profitability. Financial ratios are ratios between key amountstaken from the financial statements of the firm. While financial ratios are simple to compute,they do require some skill to interpret, and they may be used for different purposes. Forexample, internal management may be concerned with the firm's ability to pa}- its currentliabilities or the effect of long-term borrowing for a plant expansion. An external investormay be interested in past and current earnings to judge the wisdom of investing in the firm'sstock. A bank will assess the riskiness of lending money to a firm before extending credit.To properly i n t e r p r e t financial ratios, analysts c o m m o n l y make comparisonswith ratios computed for the same company from previous financial statements (a trendanalysis) and with industry standard ratios. This is referred to as financial ratio analysis.Industry standards can be obtained from various commercial and government websitesand publications. In Canada, Statistics Canada () publishes Financial and
V A L U EIn the United States, the Securities ExchangeCommission (SEC) regulates securities for thecountry. The SEC has been particularly active inenforcement in recent years. In the UnitedKingdom, the Financial Sendees Authority (FSA)regulates the securities industry as well as otherfinancial sendees such as banks. In Australia, ther e g u l a t o r is the Australian S e c u r i t i e s andInvestments Commission (ASIC).Australia:: Kingdom: States:
Securities Regulators
Taxation Statistics for Enterprises, which lists financial data from the balance sheets andincome statements as well as selected financial ratios for numerous industries. In theUnited States, Standard & Poor's Industry Surveys or Dun & Bradstreet's Industry Handbookare classic commercial sources of information, and less recent information for some industries can be found at the US Census Bureau site (). In the UnitedKingdom, the Centre for Interfirm Comparison () is a commercial sourcefor industry norms. Finally, in Australia, industry norms are available on a tax-year basisfrom the Australian Taxation Office website (). Examples of a pastindustry-total balance sheet and income statement (in millions of dollars) for the electronic products manufacturing industry are shown in Tables 6.4 and 6.5. These statisticsallow an analyst to compare an individual firm's financial statements with those of theappropriate industry.We shall see in the next section how the financial ratios derived from industry-totalfinancial data can be used to assess the health of a firm.6.3.6
Numerous financial ratios are used in the financial analysis of a firm. Here we shallintroduce six commonly used ratios to illustrate their use in a comparison with ratiosfrom the industry-total data and in trend analysis. To facilitate the discussion, we shalluse Tables 6.6 and 6.7, which show the balance sheets and income statements forElectco Electronics, a small electronics equipment manufacturer.The first two financial ratios we address are referred to as Hquidity ratios. Liquidityratios evaluate the ability of a business to meet its current liability obligations. In otherwords, they help us evaluate its ability to weather unforeseen fluctuations in cash flows.A company that does not have a resene of cash, or other assets that can be converted intocash easily, may not be able to fulfill its short-term obligations.A company's net resen-e of cash and assets easily converted to cash is called its workingcapital. Working capital is simply the difference between total current assets and totalcurrent liabilities:7
Table 6.4
189
E x a m p l e o f I n d u s t r y - T o t a l B a l a n c e S h e e t (in M i l l i o n s o f $ )
S 2 5479 1694 34410 0661 2998394 9662 898S36 128
$ 8 4873 6451 4081 3452322 487137(247)1 931S19 426
Owners' EquityShare capitalContributed surplus and otherRetained earningsTotal owners' equity
S16 702
Current assetsCurrent liabilities
S17 66311 692
9 1774157 110
T h e adequacy of working capital is commonly measured with two ratios. T h e first, thecurrent ratio, is the ratio of all current assets relative to all current liabilities. The currentratio may also be referred to as the working capital ratio.Current ratio
Electco Electronics had a current ratio of 4314/2489 = 1.73 in 2008 (Table 6.6).Ordinarily, a current ratio of 2 is considered adequate, although this determination maydepend a great deal on the composition of current assets. It also may depend on industrystandards. In the case of Electco, the industry standard is 1.51, which is listed in Table 6.8.It would appear that Electco had a reasonable amount of liquidity in 2008 from theindustry's perspective.
190
T a b l e 6.5
E x a m p l e of Industry-Total I n c o m e S t a t e m e n t
(Millions of $)
$50 68149 357132448 091150146 5902590309309
Other expensesInterest on short-term debtInterest on long-term debtGains (Losses)On sale of assetsOthers
646168478(122)25(148)
21307151231538
1538
A second ratio, the acid-test ratio, is more conservative than the current ratio. T h eacid-test ratio (also known as the quick ratio) is the ratio of quick assets to currentliabilities:Quick assetsAcid-test ratio = , ... .Current liabilitiesT h e acid-test ratio recognizes that some current assets, for example, inventory andprepaid expenses, may be more difficult to turn into cash than others. Quick assets are cash,accounts receivable, notes receivable, and temporary investments in marketable securitiesthose current assets considered to be highly liquid.The acid-test ratio for Electco for 2008 was (431 + 2489)/2489 = 1.17. Normally, anacid-test ratio of 1 is considered adequate, as this indicates that a firm could meet all itscurrent liabilities with the use of its quick current assets if it were necessary. Electcoappears to meet this requirement.T h e current ratio and the acid-test ratio provide important information about howliquid a firm is, or how well it is able to meet its current financial obligations. The extentto which a firm relies on debt for its operations can be captured by what are called leverageor debt-management ratios. An example of such a ratio is the equity ratio. It is the ratioof total owners' equity to total assets. The smaller this ratio, the more dependent the firm ison debt for its operations and the higher are the risks the company faces.
Table 6.6
191
Electco ElectronicsYear-End Balance Sheets(in thousands of dollars)2008
2009
2010
431248912441504314
340272320341455242
320275629651496190
346152139828296
290752134288670
246452129859175
1493971252489
1780984272791
2245992273264
24894978
24555246
24175681
Share capitalRetained earningsTotal Owners' Equity
182514933318
182515993424
182516693494
8296
8670
9175
AssetsCurrent assetsCashAccounts receivableInventoriesPrepaid servicesTotal current assetsLong-term assetsBuildings and equipment(net of depreciation)LandTotal long-term assetsTotal AssetsLiabilitiesCurrent liabilitiesAccounts payableBank overdraftAccrued taxesTotal current liabilitiesLong-termliabilitiesMortgageTotal LiabilitiesOwners' Equity
192
Table 6.7
Electco ElectronicsIncome Statements(in thousands of dollars)2008
RevenuesSalesTotal Revenues
12 44012 440
11 93411 934
12 10012 100
ExpensesCost of goods sold(excluding depreciation)DepreciationInterest paidTotal Expenses
10 10069234611 138
10 87955434411 777
11 20044334111 984
1302521781
1576394
1164670
70851
Financial RatioCurrent ratioQuick ratioEquitv ratioInventory-turnover ratioReturn-on-total-assets ratioReturn-on-equity ratio
IndustryStandard1.51
0.4611.364.26%9.21%
Electco Electronics20081.731.170.4010.009.41%23.53%
20091.881.100.395.871.09%2.75%
20101.900.940.384.080.76%2.00%
Sales
;Inventories
Electco's turnover ratio for 2008 was 12 440/1244 = 10 turns per year. T h i s isreasonably close to the industry standard of 11.36 turns per year as shown in Table 6.8.
193
In 2008, Electco invested roughly the same amount in inventory per dollar of sales as theindustry did, on average.Two points should be observed about the inventory-turnover ratio. First, the salesamount in the numerator has been generated over a period of time, while the inventor}'amount in the denominator is for one point in time. A more accurate measure of inventor}turns would be to approximate the average inventory over the period in which sales weregenerated.A second point is that sales refer to market prices, while inventories are listed at cost.The result is that the inventory-turnover ratio as computed above will be an overstatementof the true turnover. It may be more reasonable to compute inventory turnover based onthe ratio of cost of goods sold to inventories. Despite this observation, traditional financialanalysis uses the sales-to-inventories ratio.The next two ratios give evidence of how productively assets have been employed inproducing a profit. The return-on-assets (ROA) ratio or net-profit ratio is the firstexample of a profitability' ratio:7
.Return-on-assets ratio =
lotal assets
Electco had a return on assets of 781/8296 = 0.0941 or 9.41% in 2008. Table 6.8shows that the industry-total ROA for 2008 was 4.26%. Xote the comments on extraordinary items in Close-Up 6.4.T h e second example of a profitability- ratio is the return-on-equity (ROE) ratio:
..Keturn-on-equity ratio =
lotal equity
The return-on-equity ratio looks at how much profit a company has earned in comparison to the amount of capital that the owners have tied up in the company. It is oftencompared to how much die owners could have earned from an alternative investment andused as a measure of investment performance. Electco had a ROE of 781/3318 = 0.2354 or23.54% in 2008, whereas the industry-standard ROE was 9.21% as shown in Table 6.8. Theyear 2008 was an excellent one for the owners at Electco from their investment point of view.Overall, Electco's performance in 2008 was similar to that of the electronic productmanufacturing industry as a whole. One exception is that Electco generated higher profitsthan the norm; it may have been extremely efficient in its operations that year.T h e rosy profit picture painted for Electco in 2008 does not appear to extend into2009 and 2010, as a trend analysis shows. Table 6.8 shows the financial ratios computed for2009 and 2010 with those of 2008 and the industry standard.For more convenient reference, we have summarized die six financial ratios w~e havedealt with and their definitions in Table 6.9.CLOSE-UP
Extraordinary Items
Extraordinary items are gains and losses that do not typically result from a company'snormal business activities, are not expected to occur regularly, and are not recurringfactors in any evaluations of the ordinary operations of the business. For example, cost orloss of income caused by natural disasters (floods, tornados, ice storms, etc.) would beextraordinary loss. Revenue created by the sale of a division of a firm is an example ofextraordinary gain. Extraordinary items are reported separately from regular items andare listed net of applicable taxes.
194
Table 6.9
Definition
RatioCurrent ratio(Working capital ratio)
Acid-test ratio(Quick ratio)
Quick assetsCurrent liabilities
CommentsA liquidity- ratioA liquidity ratio(Quick assets= Current assets Inventories Prepaid items)
Equity ratio
Inventoryturnover ratio
SalesInventories
Return-on-assetsratio (Net-profitratio)
Net incomeTotal assets
A profitability ratio(excludes extraordinary items)
Return-on-equityratio
Net incomeTotal equity-
A profitability- ratio(measure of investmentperformance; excludesextraordinary items)
Electco's return on assets has dropped significantly over the three-year period.Though the current and quick ratios indicate that Electco should be able to meet itsshort-term liabilities, there has been a significant buildup of inventories over the period.Electco is not selling what it is manufacturing. This would explain the drop in Electco'sinventory turns.Coupled with rising inventory levels is a slight increase in the cost of goods sold overthe three years. From the building and equipment entries in the balance sheet, we knowthat no major capital expenditures on new equipment have occurred during the period.Electco's equipment may be aging and in need of replacement, though further analysis ofwhat is happening is necessary- before any conclusions on this issue can be drawn.A final observation is that Electco's accounts receivable seems to be growing over thethree-year period. Since there may be risks associated with the possibility of bad debt,Electco should probably investigate the matter.In summary , Electco's main problem appears to be a mismatch between productionlevels and sales levels. Other areas deserving attention are the increasing cost of goods soldand possible problems with accounts receivable collection. These matters need investigation if Electco is to recover from its current slump in profitability-.We close the section on financial ratios with some cautionary notes on their use. First,since financial statement values are often approximations, we need to interpret the financial ratios accordingly. In addition, accounting practices van- from firm to firm and maylead to differences in ratio values. Y\ nerever possible, look for explanations of how valuesare derived in financial reports.7
P R O B L E M S6.1
Joan is the sole proprietor of a small lawn-care service. Last year, she purchased aneight-horsepower chipper-shredder to make mulch out of small tree branches andleaves. At the time it cost S760. She expects that the value of the chipper-shredder willdecline by a constant amount each year over the next six years. At the end of six years,she thinks that it will have a salvage value of Si 00.Construct a table that gives the book value of the chipper-shredder at the end ofeach year, for six years. Also indicate the accumulated depreciation at the end of eachyear. A spreadsheet may be helpful.ANSWER
760 - 100
=110
;; = 1 , . . . , 6
Book Value
0123456
$110110110110110110
S760650540430320210100
$110220330440550660
19B
A three-year-old extruder used in making plastic yogurt cups has a current book value of168 750. T h e declining-balance method of depreciation with a rate d = 0.25 is used todetermine depreciation charges. \\"hat was its original price? W h a t will its book value betwo years from now?ANSWER
Let the original price of the extruder be P. T h e book value three years after purchase is168 750. This means that the original price wasBV Q)db
P(\-dj
P = 400 000T h e original price was 400 000.T h e book value two years from now can be determined either from the original purchase price (depreciated for five years) or the current value (depreciated for two years):BV (5) = 400 000(1 - 0 . 2 5 )
= 94 921.88
orS
You have been given the following data from the Fine Fishing Factory for the yearending December 31, 2010. Construct an income statement and a balance sheet fromthe data.Accounts payableAccounts receivableAdvertising expenseBad debts expenseBuildings, netCashCommon stockCost of goods soldDepreciation expense, buildingsGovernment bondsIncome taxesInsurance expenseInterest expenseInventory, December 31, 2010Land.Machinery, netMortgage due May 30, 2012Office equipment, netOffice supplies expenseOther expenses
$ 27 50032 0002500110014 00045 250125 00031125090025 000935060050042 00025 00034005000525020257000
Prepaid expensesRetained earningsSalaries expenseSalesTaxes payableWages payable
197
3000?69 02542 1 4002500600
Solving this problem consists of sorting through the listed items and identifying whichare balance sheet entries and which are income statement entries. Then, assets can beseparated from liabilities and owners' equity, and revenues from expenses.Fine Fishing FactoryBalance Sheetas of December 31, 2010AssetsCurrent assetsCashAccounts receivableInventor}', December 31, 2010Prepaid expensesTotal current assetsLong-term assetsLandGovernment bondsMachinery, netOffice equipment, netBuildings, netTotal long-term assetsTotal assetsLiabilitiesCurrent liabilitiesAccounts payableTaxes payableY\ ages payableTotal current liabilitiesLong-term liabilitiesMortgage due May 30, 2012Total long-term liabilitiesTotal liabilities
S 45 25032 00042 0003000S 122 25025 00025 0003400525014 000$ 72 650$ 1 9 4 900S 27 5002500600S 30 6005000S5000S 35 600
Owners' EquityCommon stockRetained earningsTotal owners' equity
S 125 00034300$ 159300
$194 900
198
RevenuesSalesCost of goods soldXet revenue from sales
S421 400311 250Si 10 150
ExpensesSalaries expenseBad debts expenseAdvertising expenseInterest expenseInsurance expenseOffice supplies expenseOther expensesDepreciation expense, buildingsDepreciation expense, office equipmentTotal Expenses
69 0251100250050060020257000900850S 84 500
S 25 6509350
S 16 300
Perform a financial ratio analysis for the Major Electric Company using the balancesheet and income statement from Sections 6.3.2 and 6.3.3. Industry standards for theratios are as follows:Ratio
Industry Standard7
Current ratioAcid-test ratioEquity ratioInventory-turnover ratioReturn-on-assets ratioReturn-on-equity ratio
1.800.920.7114.217.91%11.14%
.Current assetsCurrent ratio = .Current liabilities
801 000= 8.990 000nA A r i n
Quick assets66 000Acid-test ratio = . == 0.73Current liabilities90 000
Total equity4 311 000Equity ratio =.' = ^ 7 7 ^ 7 ^ = 0.7982 = 0.80^ 'Total assets3 401 0004
Inventory-turnover ratio =
7 536 000
Inventories
683 000
304 2005 401 000
'Total equity4 311 0001
Industry Standard1.800.920.7114.217.91%11.14%
Major Electric8.900.730.8011.035.63%7.06%
Major Electric's current ratio is well above the industry standard and well above thegeneral guideline of 2. T h e firm appears to be quite liquid. However, the acid-test ratio,with a value of 0.73, gives a slightly different view of Major Electric's liquidity. Most ofM a j o r Electric's current assets are inventory; thus, the current ratio is somewhatmisleading. If we look at the acid-test ratio, Major Electric's quick assets are only 73% oftheir current liabilities. T h e firm may have a difficult time meeting their current debtobligations if they have unforeseen difficulties with their cash flow.Major Electric's equity ratio of 0.80 indicates that it is not heavily reliant on debtand therefore is not at high risk of going bankrupt. Major Electric's inventory turns arelower than the industry norm, as are its ROA and ROE.Taken together, Major Electric appears to be in reasonable financial shape. Onematter they should probably investigate is why their inventories are so high. With lowerinventories, they could improve their inventory turns and liquidity, as well as theirreturn on assets. B
S U M M A R YT h i s chapter opened with a discussion of the concept of depreciation and variousreasons why assets lose value. Two popular depreciation models, straight-line anddeclining-balance, were then presented as methods commonly used to determine bookvalue of capital assets and depreciation charges.T h e second part of the chapter dealt with the elements of financial accounting. Wefirst presented the two main financial statements: the balance sheet and the income
statement. Xext, we showed how these statements can be used to assess the financialhealth of a firm through the use of ratios. Comparisons with industry norms and trendanalysis are normally part of financial analysis. We closed with cautionary notes on theinterpretation of the ratios.The significance of the material in this chapter is twofold. First, it sets the groundworkfor material in Chapters 7 and 8, replacement analysis and taxation. Second, and perhapsmore importantly, it is increasingly necessary for all engineers to have an understanding ofdepreciation and financial accounting as they become more and more involved in decisionsthat affect the financial positions of the organizations in which they work.
P R O B L E M SFor additional practice, please see the problemsCD-ROM that accompanies this book.6.1
For each of the following, state whether the loss in value is due to use-related physicalloss, time-related physical loss, or functional loss:(a) -Albert sold his two-year-old computer for S500, but he paid S4000 for it new. Itwasn't fast enough for the new software he wanted.(b) Beatrice threw out her old tennis shoes because the soles had worn thin.( c ) Claudia threw out her old tennis shoes because she is jogging now instead.
201
For each of the following, state whether the value is a market value, book value, scrapvalue, or salvage value:(a) Inta can buy a new stove for S800 at Joe's Appliances.(b) Jacques can sell his used stove to Inta for 2 0 0 .(c) Kitty can sell her used stove to the recyclers for S20.(d) Liam can buy Jacques' used stove for 2 0 0 .(e) Xoriko is adding up the value of the things she owns. She figures her stove is worthat least 20 000.
A new industrial sewing machine costs in the range of S5000 to SlO 000. Technologicalchange in sewing machines does not occur very quickly, nor is there much change in thefunctional requirements of a sewing machine. A machine can operate well for manyyears with proper care and maintenance. Discuss the different reasons for depreciationand which you think would be most appropriate for a sewing machine.
Ryan owns a five-hectare plot of land in the countryside. He has been planning to builda cottage on the site for some time, but has not been able to afford it yet. However, fiveyears ago, he dug a pond to collect rainwater as a water supply for the cottage. It hasnever been used, and is beginning to fill in with plant life and garbage that has beendumped there. Ryan realizes that his investment in the pond has depreciated in valuesince he dug it. Discuss the different reasons for depreciation and which you thinkwould be most appropriate for the pond.
A company that sells a particular type of web-indexing software has had two larger firmsapproach it for a possible buyout. T h e current value of the company, based on recentfinancial statements, is $4.5 million. T h e two bids were for S4 million and S7 million,respectively. Both bids were bona fide, meaning they were real offers. W h a t is the market value of the company? W h a t is its book value?
An asset costs $14 000 and has a scrap value of $3000 after seven years. Calculate itsbook value using straight-line depreciation(a) After one year(b) After four years(c) After seven years
202
6.8
An asset costs $14 000. At a depreciation rate of 20%, calculate its book value using thedeclining-balance method( a ) After one year(b) After four years( c ) After seven years
6.9
6.10 Using a spreadsheet program, chart the book value of a $14 000 asset over a seven-yearlife using declining-balance depreciation (d = 0.2). On the same chart, show the bookvalue of the S14 000 asset using straight-line depreciation with a scrap value of $3000after seven years.6.11 Using a spreadsheet program, chart the book value of a $150 000 asset for the first10 years of its life at declining-balance depreciation rates of 5%, 20%, and 30%.6.12 A machine has a life of 30 years, costs 2 4 5 000, and has a salvage value of 1 0 000using straight-line depreciation. WTiat depreciation rate will result in the same bookvalue for both the declining-balance and straight-line methods at the end of year 20?6.13 A new press brake costs York $teel 780 000. It is expected to last 20 years, with a60 000 salvage value. VTiat rate of depreciation for the declining-balance method willproduce a book value after 20 years that equals the salvage value of the press?6.14 ( a ) Using straight-line depreciation, what is the book value after four years for an assetcosting $150 000 that has a salvage value of $25 000 after 10 years? W h a t is thedepreciation charge in the fifth year?(b) Using declining-balance depreciation with d = 20%, what is the book value afterfour years for an asset costing $150 000? W h a t is the depreciation charge in the fifthyear?( c ) W h a t is the depreciation rate using declining-balance for an asset costing $150 000that has a salvage value of $25 000 after 10 years?6.15 Julia must choose between two different designs for a safety enclosure, which will be inuse indefinitely. Model A has a life of three years, a first cost of $8000, and maintenanceof $1000 per year. Model B will last four years, has a first cost of $10 000, and hasmaintenance of $800 per year. A salvage value can be estimated for model A using adepreciation rate of 40% and declining-balance depreciation, while a salvage valuefor model B can be estimated using straight-line depreciation and the knowledge thatafter one year its salvage value will be $7500. Interest is at 14%. Using a present worthanalysis, which design is better?7
6.16 Adventure Airline's new baggage handling conveyor costs $250 000 and has a sendee lifeof 10 years. For the first six years, depreciation of the conveyor is calculated using thedeclining-balance method at the rate of 30%. During the last four years, the straightline method is used for accounting purposes in order to have a book value of 0 at the endof the service life. W h a t is the book value of the conveyor after 7, 8, 9, and 10 years?6.17 Molly inherited $5000 and decided to start a lawn-mowing service. With her inheritanceand a bank loan of $5000, she bought a used ride-on lawnmower and a used truck. For
203
five years, Molly had a gross income of S30 000, which covered the annual operatingcosts and the loan payment, both of which totalled S4500. She spent the rest of herincome personally. At the end of five years, Molly found that her loan was paid off butthe equipment was wearing out.(a) If the equipment (lawnmower and truck) was depreciating at the rate of 50%according to the declining-balance method, what is its book value after five years?(b) If Molly wanted to avoid being left with a worthless lawnmower and truck and withno money for renewing them at the end of five years, how much should she havesaved annually toward the second set of used lawnmower and used truck of the sameinitial value as the first set? Assume that Molly's first lawnmower and truck could besold at their book value. Use an interest rate of 7%.6.18 Enrique is planning a trip around the world in three years. He will sell all of his possessions at that time to fund the trip. Two years ago, he bought a used car for 1 2 500. Heobserves that the market value for the car now is about 8 3 0 0 . He needs to know howmuch money his car will add to his stash for his trip when he sells it three years fromnow. Use the declining-balance depreciation method to tell him.6.19 Ben is choosing between two different industrial frvers using an annual worth calculation. Fryer 1 has a five-year sendee life and a first cost of S400 000. It will generate netyear-end savings of SI28 000 per year. Fryer 2 has an eight-year sendee life and a firstcost of S600 000. It will generate net year-end savings of S135 000 per vear. If thesalvage value is estimated using declining-balance depreciation with a 20% depreciationrate, and the MARR is 12%, which fryer should Ben buy?6.20 Dick noticed that the book value of an asset he owned was exactly S500 higher if thevalue was calculated by straight-line depreciation over declining-balance depreciation,exactly halfway through the asset's sendee life, and the scrap value at the end of thesenice life was the same by either method. If the scrap value was S i 0 0 , what was thepurchase price of the asset?6.21 A company had net sales of S20 000 last month. From the balance sheet at the end oflast month, and an income statement for the month, you have determined that thecurrent ratio was 2.0, the acid-test ratio was 1.2, and the inventor} turnover was two permonth. W nat was the value of the company's current assets?7
6.22 In the last quarter, the financial-analysis report for XYZ Company revealed that thecurrent, quick, and equity ratios were 1.9, 0.8, and 0.37, respectively. In order toimprove the firm's financial health based on these financial ratios, the following strategies are considered by XYZ for the current quarter:(i) Reduce inventory(ii) Pay back short-term loans(iii) Increase retained earnings(a) Which strategy (or strategies) is effective for improving each of the three financialratios?(b) If only one strategy is considered by XYZ, which one seems to be most effective?Assume no other information is available for analysis.6.23 T h e end-of-quarter balance sheet for XYZ Company indicated that the current ratio was1.8 and the equity ratio was 0.45. It also indicated that the long-term assets were twice asmuch as the current assets, and half of the current assets were highly liquid. T h e total
equitv was S68 000. Since the current ratio was close to 2, XYZ feels that the companyhad a reasonable amount of liquidity in the last quarter. However, if XYZ wants moreassurance, which financial ratio would provide further information? Using the information provided, compute the appropriate ratio and comment on XYZ's concern.6.24 A potentially very large customer for Milano Metals wants to fully assess the financialhealth of the company in order to decide whether to commit to a long-term, highvolume relationship. You have been asked by the company president, Roch, to reviewthe company's financial performance over the last three years and make a completereport to him. He will then select from your report information to present to thecustomer. Consequently, your report should be as thorough and honest as possible.Research has revealed that in your industry (sheet metal products), the average valueof the current ratio is 2.79, the equity ratio is 0.54, the inventory turnover is 4.9, and thenet-profit ratio is 3.87. Beyond that information, you have access to only the balancesheet (on the next page) and the income statement shown here, and should make no further assumptions. Your report should be limited to the equivalent of about 300 words.Milano MetalsIncome Statementfor the Years Ending December 31, 2008, 2009, and 2010(in thousands of dollars)Total revenueLess: CostsNet revenueLess:DepreciationInterestIncome taxesNet income from operationsAdd: Extraordinary itemNet income
2008
935582811074
99619632329
84707654816
44741211798770868
43133421(457)
398426156(164)(1832)
(457)
(1996)
6.25 T h e Milano Metals income statement and balance sheets shown for Problem 6.24 werein error. A piece of production equipment was sold for S i 0 0 000 cash in 2010 and wasnot accounted for. V nich items on these statements must be changed, and (if known) byhow much?6.26 The Milano Metals income statement and balance sheet shown for Problem 6.24 werein error. An extra S i 0 0 000 in sales was made in 2010 and not accounted for. Only halfof the payments for these sales have been received. W nich items on these statementsmust be changed, and (if known) by how much?6.27 At the end of last month, Paarl Alanufacturing had 45 954 rand (R45 954) in the bank. Itowed the bank, because of the mortgage, R224 000. It also had a working capital loan ofR30 000. Its customers owed R22 943, and it owed its suppliers R12 992. The companyowned property worth R250 000. It had R123 000 in finished goods, R102 000 in rawmaterials, and R40 000 in work in progress. Its production equipment was worth R450 000when new (partially paid for by a large government loan due to be paid back in three years)but had accumulated a total of R240 000 in depreciation, R34 000 worth last month.
205
Milano MetalsConsolidated Balance SheetsDecember 31, 2008, 2009, and 2010(in thousands of dollars)AssetsCurrent AssetsCashAccounts receivableInventoriesFixed AssetsLandBuildings and equipment
1977935634361
1988431554058
24117627223922
113623863552
106446825746
24328013044
9804
36969
34138296
Other AssetsTotal Assets
Current LiabilitiesDue to bankAccounts payableY\ ages payableIncome tax payableLong-Tenn Debt
143116443415622338
1 9291 3493123624743
20404553331472528
Total Liabilities
6316
8695
5503
119478619808296
1191(82)1109
109137514666969
Owners'' EquityCapital stockRetained earningsTotal Owners' EquityTotal Liability and Owners ' Equity
T h e company has investors who put up R100 000 for their ownership. It has beenreasonably profitable; this month the gross income from sales was R220 000, and thecost of the sales was only R40 000. Expenses were also relatively low; salaries wereR45 000 last month, while the other expenses were depreciation, maintenance at R1500,advertising at R3400, and insurance at R300. In spite of R32 909 in accrued taxes (Paarlpays taxes at 55%), the company had retained earnings of R135 000.Construct a balance sheet (as at the end of this month) and income statement (forthis month) for Paarl Manufacturing. Should the company release some of its retainedearnings through dividends at this time?6.28 Salvador Industries bought land and built its plant 20 years ago. T h e depreciation on thebuilding is calculated using the straight-line method, with a life of 30 years and a salvagevalue of $50 000. Land is not depreciated. T h e depreciation for the equipment, all of
206
which was purchased at the same time the plant was constructed, is calculated usingdeclining-balance at 20%. Salvador currently has two outstanding loans: one for S50 000due December 31,2010, and another one for which the next payment is due in four years.Salvador IndustriesBalance Sheet as of June 30, 2010Assetsi1
CashAccounts receivableInventoriesPrepaid servicesTotal Current AssetsLong-Term AssetsBuildingLess accumulated depreciationEquipmentLess accumulated depreciationLand
S 3502 8202 003160
S200 0001
S480 0001
540 0001
S 921 534
Accrued taxes
29 000
Total LZLong-Term LiabilitiesMortgage1
SI 200 000318 000
1SI 920 0001
During April 2010, there was a flood in the building because a nearby river overflowed its banks after unusually heavy rain. Pumping out the water and cleaning up thebasement and the first floor of the building took a week. Manufacturing was suspendedduring this period, and some inventory was damaged. Because of lack of adequate insurance, this unusual and unexpected event cost the company S i 0 0 000 net.(a) Fill in the blanks and complete a copy of the balance sheet and income statementhere, using any of the above information you feel is necessary.
207
Salvador IndustriesIncome Statement for the Year Ended June 30, 2010IncomeGross income from salesLess 1Total income
S8 635 0007 490 000
70 000240 000100 000
DepreciationInterest paidOther expensesTotal expensesIncome before taxesTaxes at 40%
Xet income
(b) Show how information from financial ratios can indicate w h e t h e r SalvadorIndustries can manage an unusual and unexpected event such as the flood withoutthreatening its existence as a viable business.6.29 Movit Manufacturing has the following alphabetized income statement and balancesheet entries from the year 2010. Construct an income statement and a balance sheetfrom the information given.
Accounts payableAccounts receivableAccrued wagesCashCommon sharesContributed capitalCost of goods soldCurrent assetsCurrent liabilitiesDeferred income taxesDepreciation expenseGeneral expenseGICsIncome taxesInterest expenseInventoriesLand
S 750015 00028502100150300057 000
225075081004501800150018 0003000
208
10 9504350945027004500750076 500
450465046 50036 00015 00015 00046 50010 50016 05015 4504650
6.30 Calculate for Movit Manufacturing in Problem 6.29 the financial ratios listed in thetable below. Using these ratios and those provided for 2008 and 2009, conduct a shortanalysis of Movit's financial health.Movit ManufacturingFinancial RatiosRatioCurrent ratioAcid-test ratioEquity ratioInventory-turnover ratioReturn-on-assets ratioReturn-on-equity ratio
20091.900.900.407.000.080.20
20081.600.750.5512.000.100.18
209
AssetsCurrent AssetsCashAccounts receivableInventoriesTotal Current AssetsLong-Term AssetsLandPlant and equipmentLess: Accumulated depreciationXet plant and equipmentTotal Long-Term AssetsTotal Assets
223172126
500250500250
125040 000113 750155 000
5017570105155281
000000000000000250
6525095155220375
000000000000000000
26 25042 50068 750
55 000117 500172 500
71 87571 875
57 37557 375
7861140281
750875625250
7866145375
750375125000
210
156 25093 75062 500
200 000120 00080 000
ExpensesOperating expensesDepreciation expenseInterest expenseTotal expenses
41 8755625375051 250
46 25012 500762566 375
11 2505625
13 6256813
5625
6813
RevenuesSalesCost of goods soldNet revenue from sales
Net income
6.32 A friend of yours is thinking of purchasing shares in Petit Ourson SA in the nearfuture, and decided that it would be prudent to examine its financial statements for thepast two years before making a phone call to his stockbroker. T h e statements areshown below.Your friend has asked you to help him conduct a financial ratio analysis. Fill out thefinancial ratio information on a copy of the third table on the next page. After comparisonwith industry standards, what advice would you rive your friend?Petit Ourson SAComparative Balance Sheetsfor the Years Ending 2009 and 2010
500112513753000
375106315633000
55002500300030006000
65003000350035006500
AssetsCurrent AssetsCashAccounts receivableInventoriesTotal Current AssetsLon<y-Tei~m AssetsPlant and equipmentLess: Accumulated depreciationXet plant and equipmentTotal Long-Term AssetsTotal Assets
375375750
Long-Term LiabilitiesBondsTotal Long-Term Liabilities
15001500
Owners' EquityCommon sharesContributed capitalRetained earningsTotal Owners' Equity
750150017504000
750150020004250
6500
Petit Ourson SAIncome Statementsfor the Years Ending 2009 and 2010(in thousands of euros)RevenuesSalesCost of goods soldXet revenue from salesExpensesOperating expensesDepreciation expenseInterest expenseTotal expensesIncome Before TaxesIncome taxesNet Income
300017501250
362521251500
75550125"50500200300
100500150"50750300450
Petit Ourson SAFinancial RatiosCurrent ratioAcid-test ratioEquity ratio
Inventorv-turnover ratioReturn-on-assets ratioReturn-on-equitv ratio
Industry Norm4.502.750.602.200.090.15
211
212
6.33 Construct an income statement and a balance sheet from the scrambled entries forParadise Pond Company from the years 2009 and 2010 shown in the table below.Paradise Pond CompanyAccounts receivableLess: Accumulated depreciationAccounts payableBondsCashCommon sharesContributed capitalCost of goods soldDepreciation expenseIncome taxesInterest expenseInventoriesXet plant and equipmentXet revenue from salesOperating expensesPlant and equipmentProfit after taxesProfit before taxesRetained earningsSalesTotal assetsTotal current assetsTotal current liabilitiesTotal expensesTotal liabilities and owners' equitvTotal long-term assetsTotal long-term liabilitiesTotal owners' equitvWorking capital loan
S 675150030090030045090017505502001258251800125007533003005001050300036001800300750360018009002400000
S 638180022590022545090021255003001509382100150010039004507501200362539001800450750390021009002550225
6.34 Like all companies, Exco has to pay taxes on its profits. However, for each additionaldollar in depreciation Exco claims, Exco's taxes are reduced bv t, since the depreciationexpense offsets income, thus reducing profits subject to tax. Exco is required bv tax lawto use declining-balance depreciation to calculate the depreciation of assets on ayear-by-year basis, with a depreciation rate of d. This depreciation calculation continuesforever, even if the asset is sold or scrapped.T h e actual depreciation for a particular asset is best represented as straight-line overy years, with zero salvage value. If the asset costs P dollars, and interest is i, what is thepresent worth of all tax savings Exco will incur by purchasing the asset? (Hint: T h edepreciation savings in the first year is Ptd.)
Calculating depreciation is made difficult by many factors. First, the value of an assetcan change over time in many complicated ways. Age, wear and tear, and functionalchanges all have their effects, and are often unpredictable. A 30-vear old VW Beetle,for example, can suddenly increase in value because a new Beetle is introduced by themanufacturer.A second complication is created by tax laws that make it desirable for companies todepreciate things quickly, while at the same time restricting the way thev calculatedepreciation. Tax laws require that companies, at least for tax purposes, use specificmethods of calculating depreciation that may bear little relevance to market value orremaining life.A third complication is that, in real life, it is sometimes hard to determine what is anasset and what is not. If some costly item is recognized as an expense, a company canclaim the costs early and offset profits to reduce taxes. However, as in the case of thesoftware in Guyana, new rules can suddenly change an expense into an asset, which thenhas to be depreciated over time at higher cost to the company. Companies and tax departments often conflict because of ambiguity about assets and expenses.In the end, depreciation calculations are simply estimates that are useful only with aclear understanding of the assumptions underlving them.Questions
For each of the following, indicate whether the straight-line method or the decliningbalance method would likely give the most accurate estimate of how the asset's valuechanges over time, or explain why neither method is suitable.( a ) A S20 bill(b) A S2 bill
214
( c ) A pair of shoes(d) A haircut(e) An engineering degree(f) A Van Gogh painting2.
V"hat differences occur in the balance sheet and income statement of a company inGuyana now that a software acquisition is considered to be a capital expenditure asopposed to an expense? Is the company's profit greater or less in the first year? Howdoes the total profit over the life of the asset compare?
S-4
216
W e l c o m e to
Real
World
A.2
Problem Definition
1. Businesses are required to pay tax on their earnings. Determining the effect of taxes on before-tax earnings may involve extensivecomputation. Managers frequently approximate the effect of taxes on decisions by increasing the MARR. However, it is goodpractice to do precise calculations before actually making a decision.
Table A . l
Model E2 (Large)
125 000
35.00
61.25
Hours/year
3600
217
Xaomi was sitting in her office thinking about structuring the cash flows for the two-small-machinessequence. Dave knocked and came in.He handed Xaomi a sheet of paper."Here's the table. Shall we meet tomorrowmorning to compare results?" (See Table A.l.)X a o m i glanced at the sheet of paper, andmotioned for Dave to stay. "This is a bit new tome. Would it be okay if we get all of our assumptions down before we go too far?""Sure, we can do that," replied Dave as hegrabbed a seat beside Xaomi's desk. Xaomi alreadyhad a pad and pencil out.Dave went on, "OK, first, what's our goal?""Well, right now we are faced with a 'make orbuy' decision," suggested Xaomi. "We need to findout if it is cheaper to make these parts or to continue to buy them, and if making them is cheaperwe need to choose which machine or machines weshould buy.""Pretty close, Xaomi, but I think that may bemore than we need at this point. Remember, Clemis primarily interested in whether this project isworth pursuing as a full-blown proposal to topmanagement. So we can use a greatly simplifiedmodel now to answer that question, and get intothe details if Clem decides it's worth pursuing.""Right. If we look at the present worths of thethree options we came up with at lunch, we shouldsee quickly enough if investing in our ownmachines is feasible. Positive present worths
Model El (Small)
A. 3 C r u n c h T i m e
Characteristics
Market facts
218
E X T E N D E D C A S E : PART
indicate buying machines is the best course; negative values would suggest it's probably not worthpursuing further."Dave nodded. "OK," continued Xaomi, "so wewant to do a 'first approximation' calculation ofpresent worths of each of our three options. Xow,what assumptions should we use?""Let's see. We want to consider only a 10-yearstudy period for the moment. I think we canassume the machines will have no salvage value atthe end of the study period, so we don't have toworn about estimating depreciation and salvagevalues. This will be a consenative estimate in anycase."Next," Dave continued, "we will ignore taximplications, and use a before-tax MARR of 25%.The 'sequence of machines' option has a complexcash flow, but by only considering present worthswe can avoid dealing with possible multiple IRRs.""You know," i n t e r j e c t e d N a o m i , "it justoccurred to me that the small machine makes 1000pieces per hour at an operating cost of S35.""And this is news to you?" said a bemused Dave."No, Dave. What I mean is that the operatingcost is SO.03 5 per part on this machine, while onescenario calls for our selling excess capacity at only$0.03. We'll be losing half a cent on every partmade for sale.""Hmmm. You know, you're right. And look atthis. Even the bigger machine's operating cost isS0.030625 per piece. We'd be losing money on thatone too.""When we run the different cases, it looks likewe'll have to consider whether excess capacity willbe sold or whether the machine will just be shutdown. Just when I thought this was going to beeasy . . . ," trailed Naomi."Maybe, but maybe not. Look at this anotherway. If the small machine sells its excess capacity ata loss of half a cent per piece, that comes to fivebucks per hour. On the other hand, if the machineis shut down, we'll have an operator standingaround at a cost of a lot more than that.""But can't an idle operator be given other workto do?""Again, maybe, but maybe not. With the jobsecurity clause the union has now, if we lay theoperator off for any period of time, the companyhas to pay most of the wages anyway, so there isn'tmuch savings that way. On the other hand, the7
$0,035, and SO.04 selling price (nine combinations in all). Present the results in tabular and/orgraphical format to support your analysis. Aportion of a sample spreadsheet layout is givenin Table A.2.
219
2. Write a memo to Clem presenting vour findings. The goal of the analysis is to determine if
Table A.2
5%
/year
$0.03
/piece
->
2 400 000
2 520 000
2 646 000
2 778 300
Capacity (units)
3 600 000
1 200 000
1 080 000
954 000
821 700
Purchases (units)Sales (units)
Operating Cost
SO
-$126 000
-S126 000
Purchasing Savings
$0
$120 000
$126 000
S132 300
$138 915
Sales Revenue
$32 400
$28 620
S24 651
Capital Expenditure
-$125 000
S30 000
$34 920
$37 566
$8490
A Replacement Example
ls,37.7
Review ProblemsSummaryEngineering Economics in Action, Part 7B: Decision TimeProblemsMini-Case 7.1
Replacement
Decisions
IntroductionSurvival of businesses in a competitive environment requires regular evaluation of theplant and equipment used in production. As these assets age, they may not provide adequate quality, or their costs may become excessive. WTien a plant or piece of equipmentis evaluated, one of four mutually exclusive choices will be made.1.
An existing asset may be kept in its current use without major change.
3. An existing asset may be removed from use without replacement by another asset.4.
This chapter is concerned with methods of making choices about possible replacement of long-lived assets. "While the comparison methods developed in Chapters 4 and 5for choosing between alternatives are often used for making these choices, the issues ofreplacement deserve a separate chapter for several reasons. First, the relevant costs formaking replacement decisions are not always obvious, since there are costs associated withtaking the replaced assets out of service that should be considered. This was ignored in the
replacement
studies in Chapters 4 and 5. Second, the service lives of assets were provided to the readerin Chapters 4 and 5. As seen in this chapter, the principles of replacement allow thecalculation of these sendee lives. Third, assumptions about how an asset might be replacedin the future can affect a decision now. Some of these assumptions are implicit in themethods analysts use to make the choices. It is therefore important to be aware of theseassumptions when making replacement decisions.The chapter starts with an example to introduce some of the basic concepts involvedin replacement decisions. Following this is a discussion of the reasons why a long-livedasset may be replaced. We then develop the idea of the economic life of an assetthe servicelife that minimizes the average cost of using the asset. This is followed bv a discussion ofreplacement with an asset that differs from the current asset, in which the built-in costadvantage of existing assets is revealed. Finally, we look at the case of replacement wherethere may be a series of replacements for a current asset, each of which might be different.We shall not consider the implications of taxes for replacement decisions in thischapter. This is postponed until Chapter 8. We shall assume in this chapter that no futureprice changes due to inflation are expected. T h e effect of expected price changes onreplacement decisions will be considered in Chapter 9.
A Replacement ExampleWe introduce some of the basic concepts involved in replacement decisions through anexample.
7 . 1
Sergio likes hiring engineering students to work in his landscaping business during thesummer because they are such hard workers and have a lot of common sense. T h estudents are always complaining about maintenance problems with the lawnmowers,which are subject to a lot of use and wear out fairly quickly. His routine has been toreplace the machines every five years. Clarissa, one of the engineering student workers,has suggested that replacing them more often might make sense, since so much time islost when there is a breakdown, in addition to the actual repair cost."I've checked the records, and have made some estimates that might help us figureout the best time to replace the machines," Clarissa reports. "Even' time there is abreakdown, the average cost to fix the machine is S60. In addition to that, there is anaverage loss of two hours of time at S20 per hour. As far as the number of repairsrequired goes, the pattern seems to be zero repairs the first season we use a newlawnmower. However, in the second season, you can expect about one repair, two repairsin the third season, four repairs in the fourth, and eight in the fifth season. I can see whyyou only keep each mower five years!""Given that the cost of a new lawnmower has averaged about S600 and that theydecline in value at 40% per year, and assuming an interest rate of 5%, I think we haveenough information to determine how often the machines should be replaced," Clarissaconcludes authoritativelv.How often should Sergio replace his lawnmowers? How much money will he save?T o keep things simple for now, let's assume that Sergio has to have l a w n s m o w e devery year, for an indefinite number of years into the future. If he keeps each lawnmowerfor, say, three years rather than five years, he will end up buying lawnmowers more
223
frequently, and his overall capital costs for owning the lawnmowers will increase.However, his repair costs should decrease at the same time since newer lawnmowersrequire fewer repairs. We want to find out which replacement period results in the lowestoverall coststhis is the replacement period Sergio should adopt and is referred to as theeconomic life of the lawnmowers.We could take any period of time as a study period to compare the various possiblereplacement patterns using a present worth approach. T h e least common multiple of theservice lives method (see Chapter 3), suggests that we would need to use a 3 x 4 x 5 =60-vear period if we were considering sendee lives between one and five vears. This is anawkward approach in this case, and even worse in situations where there are more possibilities to consider. It makes much more sense to use an annual worth approach.Furthermore, since we typically analyze the costs associated with owning and operatingan asset, annual worth calculated in the context of a replacement study is commonlyreferred to as equivalent annual cost (EAC). In the balance of the chapter, we willtherefore use EAC rather than annual worth. However, we should not lose sight of thefact that EAC computations are nothing more than the annual worth approach with adifferent name adopted for use in replacement studies.Returning to Sergio's replacement problem, if we calculate the EAC for the possibilityof a one-year, two-year, three-year (and so on) replacement period, the pattern that has thelowest EAC would indicate which is best for Sergio. It would be the best because he wouldbe spending the least, keeping both the cost of purchase and the cost of repairs in mind.T h i s can be done in a spreadsheet, as illustrated in Table 7.1. T h e first column,"Replacement Period," lists the possible replacement periods being considered. In thiscase, Sergio is looking at periods ranging from one to five years. T h e second columnlists the salvage value of a lawnmower at the end of the replacement period, in this caseestimated using the declining-balance method with a rate of 4 0 % . T h i s is used tocompute the entries of the third column. "EAC Capital Costs" is the annualized cost ofpurchasing and salvaging each lawnmower, assuming replacement periods ranging fromone to five years. Using the capital recovery' formula (refer back to Close-Cp 3.1), thisannualized cost is calculated as:EAC(capital costs) = (P-S)(A/P, /, X) + SiwhereEAC(capital costs) = annualized capital costs for an TV-year replacement periodP = purchase priceS = salvage value of the asset at the end of TV yearsTable 7.1
ReplacementPeriod (Years)
S360.00216.00
345
129.6077.7646.66
EAC CapitalAnnualEAC RepairCostsRepair CostsCostsS270.00217.32179.21151.17130.14
0.00100.00
200.00400.00800.00
0.0048.78
96.75167.11281.64
EACTotalS270.00266.10275.96318.27411.79
LL*
U H A P T E R
P(l-d)
- ( 6 0 0 - 129.60)(0.36721) + (129.60)(0.05)= 179.21T h e "average" annual cost of repairs (under the heading "EAC Repair Costs"), assuming for simplicity that the cash flows occur at the end of the vear in each case, can becalculated as:EAC(repairs) = [(60 + 40)(P/F,5%,2) + (60 + 40)(2)(P/F,5%,3)](^/P,5%,3)= [100(0.90703) + 200(0.86584)](0.36721)= 96.75T h e total EAC is then:EAC(total) = EAC(capital costs) + EAC(repairs) = 179.22 + 96.75 = 275.96Examining the EAC calculations in Table 7.1, it can be seen that the EAC is minimizedwhen the replacement period is two years (and this is only slightly cheaper than replacingthe lawnmowers every year). So this is saying that if Sergio keeps his lawnmowers for twoyears and then replaces them, his average annual costs over time will be minimized. We canalso see how much money Clarissa's observation can save him, by subtracting the expectedyearly costs from the estimate of what he is currently paying. This shows that on averageSergio saves S411.79 - S266.10 = S145.69 per lawnmower per year bv replacing his lawnmowers on a two-year cycle over replacing them every five y e a r s . T h e situation illustrated in Example 7.1 is the simplest case possible in replacementstudies. We have assumed that the physical asset to be replaced is identical to the onereplacing it, and such a sequence continues indefinitely into the future. By asset, wemean any machine or resource of value to an enterprise. An existing physical asset iscalled the defender, because it is currently performing the value-generating activity.T h e potential replacement is called the challenger. However, it is not always the casethat the challenger and the defender are the same. It is generally more common that thedefender is outmoded or less adequate than the challenger, and also that new challengerscan be expected in the future.This gives rise to several cases to consider. Situations like Sergio's lawnmower problem are relatively uncommonwe live in a technological age where it is unlikely that areplacement for an asset will be identical to the asset it is replacing. Even lawnmowersimprove in price, capability, or quality in the space of a few years. A second case, then, isthat of a defender that is different from the challenger, with the assumption that thereplacement will continue in a sequence of identical replacements indefinitely into thefuture. Finally, there is the case of a defender different from the challenger, which is itselfdifferent from another replacing it farther in the future. All three of these cases will beaddressed in this chapter.Before we look at these three cases in detail, let's look at why assets have to be replacedat all and how to incorporate various costs into the replacement decision.
Specialist Companies
ER
existing piece of equipment or replacing it with equipment that will yield the higher quality.In either case, contracting out the work to a specialist is one possibilitv.In summary, there are two main reasons for replacing an existing asset. First, an existing asset will be replaced if there is a cheaper way to get the service that the asset provides.T h i s can occur because the asset ages or because of technological or organizationalchanges. Second, an existing asset will be replaced if the service it provides is inadequate ineither quantity or quality.
regardless of actual units of production. For example, capital costs are usually fixedoncean asset is purchased, the cost is incurred even if there is zero production. Variable costsare costs that change depending on the number of units produced. The costs of the rawmaterials used in production are certainly variable costs, and to a certain degree operatingand maintenance costs are as well.With this background, we now look at the three different replacement cases:1. Defender and challenger are identical, and repeat indefinitely2. Challenger repeats indefinitely, but is different from defender3. Challenger is different from defender, but does not repeat
The lives of these identical assets are assumed to be short relative to the timehorizon over which the assets are required.Relative prices and interest rates are assumed to be constant over the company'stime horizon.
These assumptions are quite restrictive. In fact, there are onlv a few cases where theassumptions strictly hold (cable used for electric power delivery is an example).Nonetheless, the idea of economic life of an asset is still useful to our understanding ofreplacement analysis.Assumptions 1 and 2 imply that we may model the replacement decision as beingrepeated an indefinitely large number of times. T h e objective is then to determine a
228
minimum-cost lifetime for the assets, a lifetime that will be the same for all the assets inthe sequence of replacements over the company's time horizon.We have seen that the relevant costs associated with acquiring a new asset are thecapital costs, installation costs (which are often pooled with the capital costs), and operating and maintenance costs. It is usually true that operating and maintenance costs ofassetsplant or equipmentrise with the age of the asset. Offsetting increases in operating and maintenance costs is the fall in capital costs per year that usually occurs as the assetlife is extended and the capital costs are spread over a greater number of years. The rise inoperating and maintenance costs per year, and the fall in capital costs per year as the life ofan asset is extended, work in opposite directions. In the early years of an asset's life, thecapital costs per year (although decreasing) usually, but not always, dominate total yearlycosts. As the asset ages, increasing operating and maintenance costs usually overtakethe declining annual capital costs. This means that there is a lifetime that will minimizethe average cost (adjusting for the time value of money) per year of owning and using longlived assets. This is referred to as the economic life of the asset.These ideas are illustrated in Figure 7.1. Here we see the capital costs per perioddecrease as the number of periods the asset is kept increases because assets tend to depreciate in value by a smaller amount each period of use. On the other hand, the operating andmaintenance costs per period increase because older assets tend to need more repairs andhave other increasing costs with age. The economic life of an asset is found at the pointwhere the rate of increase in operating and maintenance costs per period equals the rate ofdecrease in capital costs per period, or equivalently where the total cost per period isminimized.F i g u r e 7.1
Capital c o s t s \ ^
Operating andm a i n t e n a n c e costs
PeriodsE c o n o m i c life
229
at the rate of 5% per year. Jiffy estimates depreciation with a declining-balance modelusing a rate of 40%, and uses a ALARR of 15% for capital investments. Assuming thatthere will be an ongoing need for the moulder, and assuming that the technology doesnot change (i.e., no cheaper or better method will arise), how long should Jiffv keep amoulder before replacing it with a new model? In other words, what is the economic lifeof the automated moulding system?Determining the economic lifeTable 7.2 shows the developmentplastic moulding system of ExampleIn general, the EAC for an asset
Table 7.2
Lifein Years
EACCapital Costs
EACTotal
2 0 000.00
12 000.00
1 6 750.00
3 0 000.00
4 6 750.00
7200.00
12 029.07
30 697.67
42 726.74
4320.00
9705.36
31 382.29
41 087.65
2592.00
8237.55
32 052.47
40 290.02
1555.20
7227.23
32 706.94
39 934.17
933.12
6499.33
33 344.56
39 843.88
559.87
5958.42
33 964.28
39 922.70
335.92
5546.78
34 565.20
40 111.98
201.55
5227.34
35 146.55
40 373.89
120.93
4975.35
35 707.69
40 683.04
230
giving the estimated salvage values listed in Table 7.2. For example, the salvage value atthe end of the fourth year is:51^,(4) = 20 000(1 - 0 . 4 )
= 2592T h e next column gives the equivalent annual capital costs if the asset is kept forN years, N = 1, . . . , 10. This captures the loss in value of the asset over the time it iskept in sendee. As an example of the computations, the equivalent annual capital cost ofkeeping the moulding system for four years isEAC(capital costs) = ( P - S)(A/P,\S%,A) + Si= (20 000 + 5 0 0 0 - 2 5 9 2 ) ( 0 . 3 5 0 2 7 ) + 2592(0.15)= 8238Note that the installation costs have been included in the capital costs, as these areexpenses incurred at the time the asset is o r i g i n a l l y put into service. Table 7.2illustrates that the equivalent annual capital costs decline as the asset's life is extended.Next, the equivalent annual operating and maintenance costs are found by convertingthe stream of operating and maintenance costs (which are increasing by 5% per year)into a stream of equal-sized annual amounts. Continuing with our sample calculations,the EAC of operating and maintenance costs when the moulding system is kept forfour years isEACfoperating and maintenance costs)= 30 000 [(P/P,15%,1) + (1.05)(P/P,15%,2) + (1.05) (P/P,15%,3)2
+ (1.05)V/P,15%,4)] (^/P,15%,4)= 32 052Notice that the equivalent annual operating and maintenance costs increase as thelife of the moulding system increases.Finally, we obtain the total equivalent annual cost of the moulding system bv addingthe equivalent annual capital costs and the equivalent annual operating and maintenancecosts. This is shown in the last column of Table 7.2. We see that at a six-year life thedeclining equivalent annual installation and capital costs offset the increasing operatingand maintenance costs. In other words, the economic life of the moulder is six vears,with a total EAC of 3 9 844.BWhile it is usually true that capital cost per year falls with increasing life, it is notalways true. Capital costs per year can rise at some point in the life of an asset if thedecline in value of the asset is not smooth or if the asset requires a major overhaul.If there is a large drop in the value of the asset in some year during the asset's life, thecost of holding the asset over that year will be high. Consider the following example.E X A M P L E
An asset costs $50 000 to buy and install. T h e asset has a resale value of $40 000 afterinstallation. It then declines in value by 20% per year until the fourth vear when itsvalue drops from over S20 000 to $5000 because of a predictable wearing-out of a majorcomponent. Determine the equivalent annual capital cost of this asset for lives rangingfrom one to four years. T h e MARR is 15%.
231
T h e computations are summarized in Table 7.3. T h e first column gives the life ofthe asset in years. T h e second gives the salvage value of the asset as it ages. T h e assetloses 20% of its previous year's value each year except in the fourth, when its value dropsto $5000. T h e last column summarizes the equivalent annual capital cost of the asset.Sample computations for the third and fourth vears are:EAC(capital costs, three-year life)=
(P-S)(A/P,15%,3)
Si
(P-S)(A/P,15%,4)
Life in Years
Salvage Value
32 000
S25 500
25 600
18 849
20 480
16 001
16 512
T h e large drop in value in the fourth year means that there is a high cost of holdingthe asset in the fourth year. This is enough to raise the average capital cost per year.BIn summary, when we replace one asset with another with an identical technology, itmakes sense to speak of its economic life. This is the lifetime of an individual asset thatwill minimize the average cost per year of owning and using it. In the next section, wedeal with the case where the challenger is different from the defender.
Determine the remaining economic life of the defender and its associated EAC.
If the EAC of the defender is greater than the EAC of the challenger, replace thedefender now. Otherwise, do not replace now.
In many cases, the computations in step 2 can be reduced somewhat. For assets thathave been in use for several years, the yearly capital costs will typically be low compared tothe yearly operating coststhe asset's salvage value won't change much from year to yearbut the operating costs will continue to increase. If this is true, as it often is for assets beingreplaced, the one y e a r principle can be used. This principle states that if the capital costsfor the defender are small compared to the operating costs, and the yearly operating costsare monotonically increasing, the economic life of the defender is one vear and its totalEAC is the cost of using the defender for one more year.T h e principle thus says that if the EAC of keeping the defender one more vearexceeds the EAC of the challenger at its economic life, the defender should be replacedimmediately. The advantage of the one year principle is that there is no need to find theservice life for the defender that minimizes the EACit is known in advance that the EACis minimized in a one-year period. The principle is particularly useful because for mostassets the operating costs increase smoothly and monotonically as the asset is kept forlonger and longer periods of time, while the capital costs decrease smoothly and monotonically. For a defender that has been in use for some time, the EAC(operating costs) willtypically dominate the EAC(capital costs), and thus the total EAC will increase overany additional years that the asset is kept. This is illustrated in Figure 7.2, which can becompared to Figure 7.1 earlier in this chapter.Figure 7.2
T o t a l costs
Operating andm a i n t e n a n c e costsu
Capital costs
Periods
For older assets that conform to this pattern of costs, it is only necessary to checkwhether the defender needs replacing due to costs over the next year, because in subsequentyears the case for the defender will only get worse, not better. If there is an uneven yearlypattern of operating costs, the one year principle cannot be used, because the current yearmight give an unrealistic value due to the particular expenses in that year.E X A M P L E
7 . 4
An asset is three years old. Yearly operating and maintenance costs are currendy 5000 randper year, increasing by 10% per year. The salvage value for the asset is currendy 60 000 randand is expected to be 50 000 rand one year from now. Can the one year principle be used?
233
T h e capital costs are not low (and thus the EAC(capital costs) for any given servicelife is not low) compared to the operating and maintenance costs. Even though costshave a regular pattern, the one year principle cannot be u s e d . i l
An asset is 10 years old. Yearly operating and maintenance costs are currently S5000 peryear, increasing by 10% per year. T h e salvage value of the asset is currently S8000 and isexpected to be S7000 one year from now. Can the one year principle be used?T h e capital costs are low compared to the operating and maintenance costs, andcosts have a regular pattern. T h e one year principle can be used.[3
7 . 6
An asset is 10 years old. Operating and maintenance costs average 5000 per year,increasing by 10% per year. However, most of the operating and maintenance costsconsist of a periodic overhaul costing 15 000 that occurs even three years. T h e salvagevalue of the asset is currently 8000 and is expected to be 7000 one year from now. Canthe one year principle be used?-
T h e capital costs are low compared to the operating and maintenance costs but theoperating and maintenance costs do not have an even pattern from year to year. T h e oneyear principle cannot be used.BT h e one year principle can be used when it is clear that the key conditionslowcapital costs and a regular year-to-year pattern of monotonically increasing operatingand maintenance costsare satisfied. W h e r e a situation is ambiguous, it is alwaysprudent to fully assess the EAC of the defender.To fully explore the case of a defender being replaced by a challenger that repeats, aswell as to explore some other ideas useful in replacement analysis, the next three subsections cover examples to illustrate the analysis steps. In the first, we examine the situation ofreplacing subcontracted capacity with in-house production. This is an example of replacing a service with an asset. In the second example, the issue of sunk costs is examined byconsidering the replacement of an existing productive asset with a different challenger. Inthe final example, we look at the situation of making replacement decisions when there areirregular cash flows.7.6.1
Currently, the Jiffy Printer Company of Example 7.2 pays a custom moulder 0.25 perpiece (excluding material costs) to produce parts for its printers. Demand is forecast tobe 200 000 parts per year. Jiffy- is considering installing the automated plastic mouldingsystem described in Example 7.2 to produce the parts. Should it do so now?In Jiffy's situation, the defender is the current technology: a subcontractor. T h echallenger is the automated plastic moulding system. In order to decide whether Jiffy isbetter off with the defender or the challenger, we need to compute the unit cost (cost
per piece) of production with the automated moulder and compare it to the unit cost forthe subcontracted parts. If the automated system is better, the challenger wins andshould replace the defender.From Example 7.2:EAC(moulder) = 39 844Dividing the EAC bv the expected number of parts needed per vear allows us tocalculate the unit cost as 39 838/200 000 = 0.1992.When the unit cost of in-house production is compared with the 0.25 unit cost ofsubcontracting the work, in-house production is cheaper, so Jiffy should replace thesubcontracting with an in-house automated plastic moulding s y s t e m . This example has illustrated the basic idea behind a replacement analysis when weare considering the purchase of a new asset as a replacement to current technology. Thecost of the replacement must take into account the capital costs (including installation)and the operating and maintenance costs over the life of the new asset.Ln the next subsection, we see how some costs are no longer relevant in the decision toreplace an existing asset.7.6.2
T h e I r r e l e v a n c e of S u n k C o s t s
Once an asset has been installed and has been operating for some time, the costs ofinstallation and all other costs incurred up to that time are no longer relevant to anydecision to replace the current asset. These costs are called sunk costs. Only those coststhat will be incurred in keeping and operating the asset from this time on are relevant.This is best illustrated with an example.E X A M P L E
7 . 8
Two years have passed since the Jiffy Printer Company from Example 7.7 installed anautomated moulding system to produce parts for its printers. At the time of installation,they expected to be producing about 200 000 pieces per year, which justified the investment. However, their actual production has turned out to be only about 150 000 piecesper year. Their unit cost is 3 9 844/150 000 = 0.2656 rather than the 0.1992 theyhad expected. The}' estimate the current market value of the moulder at 7 2 0 0 . In thiscase, maintenance costs do not depend on the actual production rate. Should Jiffy sell themoulding system and go back to buying from the custom moulder at 0.25 per piece?In the context of a replacement problem, Jiffy is looking at replacing the existingsystem (the defender) with a different technology (the challenger). Since Jiffv already hasthe moulder and has already expended considerable capital on putting it into place, itmay be better for Jiffy to keep the current moulder for some time longer. Let us calculate the cost to Jiffy of keeping the moulding system for one more year. This may not bethe optimal length of time to continue to use the system, but if the cost is less than 0 . 2 5 per piece it is cheaper than retiring or replacing it now.T h e reason that the cost of keeping the moulder an additional year may be low isthat the capital costs for the two-year-old system are now low compared with thecosts of putting the capacity in place. T h e capital cost for the third year is simply theloss in value of the moulder over the third year. This is the difference between whatJiffy can get for the system now, at the end of the second year, and what it can get ayear from now when the system will be three years old. Jiffy can get 7 2 0 0 for the
= (P - S){A/P,\S%,\) + Si= [7200 - 0.6(7200)](1.15) + 0.6(7200)(0.15)= 3960
Recall that the operating and maintenance costs started at 3 0 000 and rose at 5%each year. T h e operating and maintenance costs for the third year areE A Q o p e r a t i n g and maintenance, third year) = 30 0 0 0 ( 1 . 0 5 )
= 33 075T h e total cost of keeping the moulder for the third year is the sum of the capitalcosts and the operating and maintenance costs:EAC(third year) = EAC(capital costs, third year) +EAC (operating and maintenance, third year)= 3960 + 33 075= 37 035Dividing the annual costs for the third year by 150 000 units gives us a unit cost of0.247 for moulding in-house during the third year. Not only is this lower than the average cost over a six-year life of the system, it is also lower than what the subcontractedcustom moulder charges. Similar computations would show that Jiffy could go two moreyears after the third year with in-house moulding. Only then would the increase in operating and maintenance costs cause the total unit cost to rise above 0 . 2 5 .Given the lower demand, we see that installing the automated moulding svstemwas a mistake for Jiff}'. T h e average lifetime costs for in-house moulding were greaterthan the cost of subcontracting, but once the system was installed, it was not optimalto go back to subcontracting immediately. This is because the capital cost associatedwith the purchase and installation of an asset (which becomes sunk after its installation) is disproportionately large as compared with the cost of using the asset once it isin p l a c e . That a defender has a cost advantage over a challenger, or over contracting out duringits planned life, is important. It means that if a defender is to be removed from sendeeduring its life for cost reasons, the average lifetime costs for the challenger or the costs ofcontracting out must be considerably lower than the average lifetime costs of the defender.Just because well-functioning defenders are not often retired for cost reasons does notmean that they will not be retired at all. Changes in markets or technology may make thequantity or quality of output produced by a defender inadequate. This can lead to itsretirement or replacement even when it is functioning well.7.6.3
Sometimes operating costs do not increase smoothly and monotonically over time. T h esame can happen to capital costs. Y\Ten the operating or capital costs are not smoothand monotonic, the one year principle does not apply. T h e reason that the principle
236
does not apply is that there may be periodic or one-time costs that occur over the courseof the next year (as in the case where periodic overhauls are required). These costs maymake the cost of keeping the defender for one more year greater than the cost ofinstalling and using the challenger over its economic life. However, there may be a lifelonger than one year over which the cost of using the defender is less than the cost ofinstalling and using a challenger. Consider this example concerning the potentialreplacement of a generator.E X A M P L E
7.9
S9500
8000
1200
1500
Should Colossal replace the existing generator with the new type? T h e M A R Ris 12%.We first determine the economic life for the challenger. T h e calculations are shownin Table 7.5.Sample calculations for the EAC of keeping the challenger for one, two, and threeyears are as follows:EAC(1 year) = (P - S)(A/P,U%,\) + Si + 1000= (9500 - 8000)(1.12) + 8000(0.12) + 1000= 3640
T a b l e 7.5
237
E c o n o m i c Life of the N e w G e n e r a t o r
Operating Costs
S8000
SI 000
S3640.00
3319.25
3236.50
3233.07*
3290.81
3314.16
3318.68
3393.52
8Lowest equivalent annual cost.
238
Table 7,6
Additional Lifein Years
S2400
OperatingCosts
1400
S3288
980
2722
686
2630
480
3500
2872
336
2924
3013
7 . 1 0
Rita is examining the possibility of replacing the kiln controllers at the Burnabv Insulatorsplant. She has information about the existing controllers and the best replacement on themarket. She also has information about a new controller design that will be available inthree years. Rita has a five-year time horizon for the problem. W h a t replacement alternatives should Rita consider?One way to determine the minimum cost over the five-year horizon is to determinethe costs of all possible combinations of the defender and the two challengers. This isimpossible, since the defender and challengers could replace one another at any time.However, it is reasonable to consider only the combinations of the period length of oneyear. Any period length could be used, but a year is a natural choice because investmentdecisions tend, in practice, to follow a yearly cycle. These combinations form a mutuallyexclusive set of investment opportunities (see Section 4.2). If no dme horizon were givenin the problem, we would have had to assume one, to limit the number of possiblealternatives.T h e possible decisions that need to be evaluated in this case are shown in Table 7.7.For example, the first row in Table 7.7 (Alternative 1) means to keep the defender forthe whole five-year period. .Alternative 2 is to keep the defender for four years, and thenpurchase the challenger four years from now, and keep it for one year. Alternative 15 is toreplace the defender now with the first challenger, keep it three years, then replace it withthe second challenger, and keep the second challenger for the remaining two years.
Table 7.7
DefenderLife in Years
First ChallengerLife in Years
Second ChallengerLife in Years
5i
45->
DecisionAlternative
239
To choose among these possible alternatives, we need information about the followingfor the defender and both challengers:1. Costs of installing the challengers2. Salvage values for different possible lives for all three kiln controllers3. Operating and maintenance costs for all possible ages for all threeW i t h this information, the minimum-cost solution is obtained by computing thecosts for all possible decision alternatives. Since these are mutually exclusive projects,any of the comparison methods of Chapters 4 and 5 are appropriate, including presentworth, annual worth, or IRR. T h e effects of sunk costs are already included in theenumeration of the various replacement possibilities, so looking at the benefits ofkeeping the defender is already automatically taken into account.The difficulty with this approach is that the computational burden becomes great ifthe number of years in the time horizon is large. On the other hand, it is unlikely thatinformation about a future challenger will be available under normal circumstances. InExample 7.10, Rita knew about a controller that wouldn't be available for three years. Inreal life, even if somehow Rita had inside information on the supplier research and marketing plans, it is unlikely that she would be confident enough of events three years away to usethe information with complete assurance. Normally, ii the information were available, thechallenger itself would be available, too. Consequently, in many cases it is reasonable toassume that challengers in the planning future will be identical to the current challenger,and the decision procedure to use is the simpler one presented in the previous section.
240
P R O B L E M S7.1
Kenwood Limousines runs a fleet of vans that ferry people from several outlying citiesto a major international airport. X e w vans cost 45 000 each and depreciate at adeclining-balance rate of 30% per year. Maintenance for each van is quite expensive,because thev are in use 24 hours a dav, seven davs a week. Maintenance costs, which areabout 3000 the first year, double each year the vehicle is in use. Given a ALARR of 8%,what is the economic life of a van?ANSWER
Table 7.8 shows the various components of this problem for replacement periods from oneto five years. It can be seen that the replacement period with the minimum equivalentannual cost is two years. Therefore, the economic life is two years.Table 7.8
MaintenanceCosts
31 500
3000
20 100
22 050
14 634
4442
19 076
15 435
12 707
6770
19 477
10 805
24 000
11 189
10 594
21 783
7563
48 000
9981
16 970
26 951
Global Widgets makes rocker arms for car engines. The manufacturing process consistsof punching blanks from raw stock, forming the rocker arm in a 5-stage progressive die,
241
and finishing in a sequence of operations using hand tools. A recently developed 10-stagedie can eliminate many of the finishing operations for high-volume production.T h e existing 5-stage die could be used for a different product, and in this case wouldhave a salvage value of S20 000. Maintenance costs of the 5-stage die will total $3500this year, and are expected to increase by $3500 per year. T h e 10-stage die will cost$89 000, and will incur maintenance costs of $4000 this vear, increasing by $2700 peryear thereafter. Both dies depreciate at a declining-balance rate of 20% per year. T h enet yearly benefit of the automation of the finishing operations is expected to be $16 000per year. The MARR is 10%. Should the 5-stage die be replaced?ANSWER
(P-S)(A/P,10%,2)
+ Si
Total
S89 000
71 200
S 4000
S26 700
S30 700
56 960
6700
24 157
5286
29 443
45 568
9400
22 021
6529
28 550
36 454
12 100
20 222
7729
27 951
29 164
14 800
18 701
8887
27 589
23 331
17 500
17 411
10 004
27 415
18 665
20 200
16 314
11 079
27 393
14 932
22 900
15 377
12 113
27 490
242
Completing similar computations for other lifetimes shows that the economic life ofthe 10-stage die is seven years and the associated equivalent annual costs are $27 393.T h e next step in the replacement analysis is to consider the annual cost of the5-stage die (the defender) over the next year. T h i s cost is to be compared with theeconomic life EAC of the 10-stage die, that is, $27 393. Note that the cost analysis ofthe defender should include the benefits generated by the 10-stage die as an operatingcost for the 5-stage die as this S16 000 is a cost of not changing to the 10-stage die. $incethe capital costs are low, and operating costs are monotonically increasing, the one yearprinciple applies. T h e EAC of the capital and operating costs of keeping the defenderone additional year are found as follows:Salvage value of 5-stage die after one year = 20 000(1 - 0.2) = $16 000EACfcapital costs, one additional year)= ( P - S)(A/P, 10%,1) + Si= (20 000 - 16 000)(1.10) + 16 000(0.10)= 6000EAC(maintenance and operating costs, one additional year)= 3500 + 16 000= 19 500EAC(total, one additional year)= 19 500 + 6000= 25 500T h e 5-stage die should not be replaced this year because the EAC of keeping it oneadditional year ($25 500) is less than the optimal EAC of the 10-stage die ($27 393).T h e knowledge that the 5-stage die should not be replaced this year is usually sufficientfor the immediate replacement decision. However, if a different challenger appears inthe future, we would want to reassess the replacement decision.It may also be desirable to estimate when in the future the defender might be replaced,even if it is not being replaced now. This can be done by calculating the equivalent annualcost of keeping the defender additional years until the time we can determine when itshould be replaced. Table 7.10 summarizes those calculations for additional years ofoperating the 5-stage die.As an example of the computations, the EAC of keeping the defender for two additional years is calculated asSalvage value of 5-stage die after two years = 16 000(1 - 0.2) = 12 800EAC(capital costs, two additional years)=
Table 7 . 1 0
243
AdditionalLifein Years
Maintenanceand OperatingCosts
Capital
Operating
16 000
S19 500
S6000
12 800
23 000
5429
21 167
26 595
10 240
26 500
4949
22 778
27 727
8192
4544
24 334
28 878
6554
33 500
4202
25 836
30 038
5243
37 000
3913
27 283
31 196
4194
40 500
3666
28 677
32 343
3355
44 000
3455
30 018
33 473
Avril bought a computer three years ago for $3000, which she can now sell on the openmarket for $300. T h e local Mr. Computer store will sell her a new HAL computer forS4000, including the new accounting package she wants. Her own computer will probably last another two years, and then would be worthless. T h e new computer would havea salvage value of S300 at the end of its economic life of five years. T h e net benefits toAvril of the new accounting package and other features of the new computer amount toS800 per year. An additional feature is that Mr. Computer will give Avril a $500 trade-inon her current computer. Interest is 15%. W h a t should Avril do?ANSWER
There are a couple of things to note about this problem. First, the cost of the newcomputer should be taken as $3800 rather than $4000. This is because, although the pricewas quoted as $4000, the dealer was willing to give Avril a $500 trade-in on a usedcomputer that had a market value of only $300. This amounts to discounting the price ofthe new computer to $3800. Similarly, the used computer should be taken to be worth$300, and not $500. The $500 figure does not represent the market value of the used computer, but rather the value of the used computer combined with the discount on the newcomputer. One must sometimes be careful to extract from the available information thebest estimates of the values and costs for the various components of a replacement study.First, we need to determine the EAC of the challenger over its economic life. We aretold that the economic life is five years and hence the EAC computations are as follows:
EAC(capital costs)
EAC(operating costs)
= 800
S U M M A R YThis chapter is concerned with replacement and retirement decisions. Replacement canbe required because there may be a cheaper way to provide the same sendee, or thenature of the sendee may have changed. Retirement can be required if there is no longera need for the asset.If an asset is replaced by a stream of identical assets, it is useful to determine theeconomic life of the asset, which is the replacement intenal that provides the minimumannual cost. T h e asset should then be replaced at the end of its economic life.If there is a challenger that is different from the defender, and future changes intechnology are not known, one can determine the minimum EAC of the challenger andcompare this with the cost of keeping the defender. If keeping the defender for anyperiod of time is cheaper than the minimum EAC of the challenger, the defender shouldbe kept. Often it is sufficient to assess the cost of keeping the defender for one moreyear.Defenders that are still functioning well have a significant cost advantage overchallengers or over obtaining the sendee performed by the defender from anothersource. This is because there are installation costs and because the capital cost per vearof an asset diminishes over time.W h e r e future changes in technology are expected, decisions about when andwhether to replace defenders are more complex. In this case, possible replacementdecisions must be enumerated as a set of mutually exclusive alternatives and subjected toany of the standard comparison methods.Figure 7.3 provides a summary of the overall procedure for assessing a replacementdecision.
Figure 7.3
Is there as e q u e n c e ofidentical challengers?Yes
No
Structure thep r o b l e m as aset of m u t u a l l yexclusivealternatives.
C o m p u t e thee c o n o m i c lifea n d E A C ofchallengers.
Is the d e f e n d e ridentical to thechallengers?NoC o m p u t e the E A Cof the r e m a i n i n g e c o n o m i c lifeof the defender.
Keep the d e f e n d e r .Yes
Yes
R e p l a c e thedefender n o w .
P R O B L E M SFor additional practice, please see the problemsCD-ROM that accompanies this book.7.1
S4500 eachS6000SI 1.40 per metreS188
Last year, Clairbrook Canning Co. bought a fancy colour printer, which cost S20 000,for special printing jobs. Fast changes in colour printing technology have resulted inalmost identical printers being available today for about one-quarter of the cost. ShouldC C C consider selling its printer and buying one of the new ones?
Maryhill Alines has a pelletizer that it is considering for replacement. Every three yearsit is overhauled at considerable cost. It is due for an overhaul this year. Evelyn, thecompany's mining engineer, has calculated that the sum of the operating and capitalcosts for this year for the pelletizer are significantly more than the EAC for a newpelletizer over its service life. Should the existing pelletizer be replaced?
Determine the economic life for each of the items listed below. Salvage values can be estimated by the declining-balance method using an annual rate of 20%. T h e ALARR is 8%.
Installation
Item 1
Item 2
Item 3
A new bottle-capping machine costs S45 000, including S5000 for installation. T h emachine is expected to have a useful life of eight years with no salvage value at that time(assume straight-line depreciation). Operating and maintenance costs are expected to beS3000 for the first year, increasing by SI000 each year thereafter. Interest is 12%.
247
( a ) Construct a spreadsheet that has the following headings: Year, Salvage Value,Maintenance Costs, EAC(Capital Costs), EAC(Operating Costs), and EACfTotalCosts). Compute the EAC(Total Costs) if the bottle capper is kept for n years,n = 1 , . . . , 8.(b) Construct a chart showing the EAC(Capital Costs), EAC(Operating Costs), andEACfTotal Costs) if the bottle capper were to be kept for n vears, n = 1, . . . , 8.( c ) W h a t is the economic life of the bottle capper?7.6
Gerry likes driving small cars and buys nearly identical ones whenever the old one needsreplacing. Typically, he trades in his old car for a new one costing about S i 5 000. A newcar warranty covers all repair costs above standard maintenance (standard maintenancecosts are constant over the life of the car) for the first two years. After that, his recordsshow an average repair expense (over standard maintenance) of S2500 in the third year(at the end of the year), increasing by 50% per year thereafter. If a 30% decliningbalance depreciation rate is used to estimate salvage values, and interest is 8%, howoften should Gerry get a new car?
Gerry (see Problem 7.6) has observed that the cars he buys are somewhat more reliablenow than in the past. A better estimate of the repair costs is $1500 in the third year,increasing by 50% per year thereafter, with all other information in Problem 7.6 beingthe same. Now how often should Gerry get a new car?
7.8
For each of the following cases, determine whether the one year principle would apply.( a ) A defender has been in use for seven years and has negligible salvage value.Operating costs are 4 0 0 per year for electricity. Once every five years it is overhauled at a cost of 1 0 0 0 .(b) A defender has been in use for seven years and has negligible salvage value.Operating costs are 4 0 0 per year for electricity. Once a year it is overhauled at acost of 1 0 0 0 .( c ) A defender has been in use for two years and has negligible salvage value. Operatingcosts are 4 0 0 per year for electricity. Once a year it is overhauled at a cost of 1 0 0 0 .(d) A defender has been in use for seven years and has current salvage value of 4 0 0 0 .Its value one year from now is estimated to be 4 0 0 0 . Operating costs are 4 0 0 peryear for electricity. Once a year it is overhauled at a cost of 1 0 0 0 .( e ) A defender has been in use for seven years and has current salvage value of 4 0 0 0 .Its value one year from now is estimated to be 2 0 0 0 . Operating costs are 4 0 0 peryear for electricity. Once a year it is overhauled at a cost of 1 0 0 0 .
If the operating costs for an asset are S500 x 2" and the capital costs are $10 000 x (0.8)",where n is the life in years, what is the economic life of the asset?
7.10 A roller conveyor system used to transport cardboard boxes along an order-filling linecosts S i 0 0 000 plus S20 000 to install. It is estimated to depreciate at a declining-balancerate of 25% per year over its 15-year useful life. Annual maintenance costs are estimatedto be $6000 for the first year, increasing by 20% every year thereafter. In addition, everythird year, the rollers must be replaced at a cost of $7000. Interest is at 10%.( a ) Construct a spreadsheet that has the following headings: Year, Salvage Value,Maintenance Costs, EAC(Capital Costs), EAQMaintenance Costs), and EAC(TotalCosts). Compute the EACfTotal Costs) if the conveyor were to be kept for n vears,; ? = ! , . . . , 15.
(b) Construct a chart showing the EAC(Capital Costs), EAC(Maintenance Costs), andEAC(Total Costs) if the conveyor were to be kept for n years, n = 1 , . . . , 15.(c) W h a t is the economic life of the roller conveyor system?7.11 Brockville Brackets (BB) has a three-year-old robot that welds small brackets onto carframe assemblies. At the time the robot was purchased, it cost S300 000 and an additional$50 000 was spent on installation. BB acquired the robot as part of an eight-year contractto produce the car-frame assemblies. T h e useful life of the robot is 12 years, and its valueis estimated to decline by 20% of current value per year, as shown in the first table below.Operating and maintenance costs estimated when the robot was purchased are alsoshown in the table.BB has found that the operating and maintenance costs for the robot have beenhigher than anticipated. At the end of the third year, new estimates of the operating andmaintenance costs are shown in the second table.Defender, When NewOperating andMaintenance Costs
Life (Years)
S300 000
192 000
153 600
122 880
98 304
78 643
48 400
62 915
53 240
50 332
58 564
40 265
64 420
32 212
70 862
25 770
77 949
20 616
85 744
SI53 600
60 500
66 550
73 205
249
BB has determined that the reason the operating and maintenance costs were inerror was that the robot was positioned too close to existing equipment for the mechanics to repair it easily and quickly. BB is considering moving the robot farther away fromsome adjacent equipment so that mechanics can get easier access for repairs. To movethe robot will cause BB to lose valuable production time, which is estimated to have acost of $25 000. However, once complete, the move will lower maintenance costs towhat had originally been expected for the remainder of the contract (e.g., $40 000 forthe fourth year, increasing by 10% per year thereafter). Moving the robot will not affectits salvage value.If BB uses a MARR of 15%, should it move the robot? If so, when? Remember thatthe contract exists only for a further five years.7.12 Consider Brockville Brackets from Problem 7.11 but assume that it has a contract toproduce the car assemblies for an indefinite period. If it does not move the robot, theoperating and maintenance costs will be higher than expected. If it moves the robot (at acost of $25 000), the operating and maintenance costs are expected to be what wereoriginally expected for the robot. Furthermore, BB expects to be able to obtain newversions of the existing robot for an indefinite period in the future; each is expected tohave an installation cost of $50 000.( a ) Construct a spreadsheet table showing the EAC(total costs) if BB keeps the currentrobot in its current position for n more years, n = I, . . . ,9.(b) Construct a spreadsheet table showing the EAC(total costs) if BB moves the currentrobot and then keeps it for more years, n = 1, . . . , 9.( c ) Construct a spreadsheet table showing the EAC(total costs) if BB is to buy a newrobot and keep it for ;? years, n = 1, . . . , 9.(d) On the basis of your answers for parts (a) through (c), what do you advise BBto do?7.13 Nico has a 20-year-old oil-fired hot air furnace in his house. He is consideringreplacing it with a new high-efficiency natural gas furnace. T h e oil-fired furnace hasa scrap value of $500, which it will retain indefinitely A maintenance contract costs$300 per year, plus parts. Nico estimates that parts will cost $200 this year, increasingby $100 per year in subsequent years. T h e new gas furnace will cost $4500 to buy and$500 to install. It will save $500 per year in energy costs. T h e maintenance costs forthe gas furnace are covered under guarantee for the first five years. T h e market valueof the gas furnace can be estimated from straight-line depreciation with a salvagevalue of $500 after 10 years. U s i n g a M A R R of 10%, should the oil furnace bereplaced?7.14 A certain machine costs 25 000 to purchase and install. It has salvage values andoperating costs as shown in the table on the next page. T h e salvage value of 20 000listed at time 0 reflects the loss of the installation costs at the time of installation.T h e M A R R is 12%.( a ) W h a t is the economic life of the machine?(b) W h a t is the equivalent annual cost over that life?
20 000.00
16 000.00
3000.00
12 800.00
3225.00
t3
10 240.00
3466.88
8192.00
3726.89
6553.60
4006.41
5242.88
4306.89
4194.30
4629.90
3355.44
4977.15
2684.35
5350.43
2147.48
5751.72
1717.99
6183.09
1374.39
6646.83
1099.51
7145.34
879.61
7681.24
703.69
8257.33
562.95
8876.63
450.36
9542.38
360.29
10 258.06
251
85 000
1 5 000
72 250
61 413
52 201
44 371
37 715
32 058
27 249
23 162
19 687
16 734
14224
12 091
10 277
8735
(a) Construct a spreadsheet that gives, for each year, the EAC(operating and maintenancecosts), EAC(capital costs), and EAC(total costs) for the turbines. Interest is 15%. Howlong should Ener-G keep each turbine before replacing it, given a five-year overhaulschedule? WTiat are the associated equivalent annual costs?(b) If Ener-G were to overhaul its turbines every six years (at the same cost), the salvagevalue and operating and maintenance costs would be as shown in the table on thenext page. Should Ener-G switch to a six-year overhaul cycle?
'2 250
14 224
7.17 T h e BBBB .Machine Company makes a group of metal parts on a turret lathe for a localmanufacturer. T h e current lathe is now six years old. It has a planned further life ofthree years. T h e contract with the manufacturer has three more years to run as well. Anew, improved lathe has become available. T h e challenger will have lower operatingcosts than the defender.T h e defender can now be sold for S i 2 0 0 in the used-equipment market. T h echallenger will cost S25 000 including installation. Its salvage value after installation, butbefore use, will be $20 000. Further data for the defender and the challenger are shownin the tables that follow.DefenderAdditionalLife in Years
$1200
600
~>
300
20 500
21 012.50
253
ChallengerLifein Years
Operating CostS13 875
9800
14 360.63
6860
14 863.25
ChallengerLife in Years
S20 000.00
14 000.00
S13 875.00
9800.00
14 369.63
6860.00
4802.00
15 383.46
3361.40
15 921.88
2352.98
16 479.15
1647.09
17 055.92
1152.96
17 652.87
807.07
18 270.73
564.95
18 910.20
395.47
19 572.06
276.83
20 257.08
Defender W h e n NewLife in Years
SI5 000.00
9846.45
SI7 250.00
6463.51
17 681.25
4242.84
18 123.28
2785.13
18 576.36
1828.24
19 040.77
1200.11
19 516.79
600.00
20 004.71
300.00
20 504.83
150.00
21 017.45
21 542.89
22 081.46
22 633.49
23 199.33
255
7.19 You own several copiers that are currently valued at RIO 000 all together. .Annualoperating and maintenance costs for all copiers are estimated at R9000 next year,increasing by 10% each year thereafter. Salvage values decrease at a rate of 2 0 %per year.You are considering replacing your existing copiers with new ones that have as u g g e s t e d r e t a i l p r i c e of R25 0 0 0 . O p e r a t i n g and m a i n t e n a n c e costs for thenew equipment will be R6000 over the first year, increasing by 10% each year thereafter. T h e salvage value of the new equipment is well approximated bv a 20% dropfrom the s u g g e s t e d r e t a i l p r i c e per y e a r . F u r t h e r m o r e , vou can g e t a t r a d e in allowance of R12 000 for your equipment if you purchase the new equipmentat its suggested retail price. Your M A R R is 8%. Should vou replace vour existingequipment now?7.20 An existing piece of equipment has the following pattern of salvage values and operatingand maintenance costs:
Defender
EACCapitalCosts
EACOperating andMaintenanceCosts
$2000
$3500
$5500
6400
2500
3174
2233
5407
5120
2905
2454
5359
4096
2682
2663
5345
3277
2497
2861
2621
4500
2343
3049
5391
-j
2097
2214
3225
5439
1678
5500
2106
3391
5497
1342
2016
3546
5562
AdditionalLife(Years)
S10 000
A replacement asset is being considered. Its relevant costs over the next nine years areshown on the next page.There is a need for the asset (either the defender or the challenger) for the next nineyears.(a) W h a t replacement alternatives are there?(b) W h a t replacement timing do vou recommend?
256
Challenger
$1500
S5700
7680
1900
3809
1686
5495
6144
2300
3486
1863
5349
4915
2700
3219
2031
5249
3932
3100
2997
2189
5186
3146
2811
2339
5150
2517
3900
2657
2480
5137
2013
4300
2528
2613
5140
1611
|
https://de.scribd.com/document/332490607/Niall-M-Fraser-Elizabeth-M-Jewkes-Irwin-Bernh-BookFi-org-pdf
|
CC-MAIN-2021-17
|
refinedweb
| 78,340
| 63.9
|
This Bugzilla instance is a read-only archive of historic NetBeans bug reports. To report a bug in NetBeans please follow the project's instructions for reporting issues.
it is allowed to create diagrams, e.g class diagram, with same name, namespace
and diagram type.
To reproduce:
1.create a UML project.
2. add a clasee diagram with a name.
3. add another class diagram with same name.
observe: two class diagram with same name and namespace.
Targeted in drawing area redesign.
Restoring original priority and using the standard NB waiver process.
Diagram area bugs waived for 6.0 will also be waived for 6.1.
is there any reasons to disable creation of same name diagrams? it may be enhancment for usability (if anybody would
like to have less abilities)
|
https://bz.apache.org/netbeans/show_bug.cgi?id=83002
|
CC-MAIN-2020-40
|
refinedweb
| 131
| 71.51
|
Creating Windows 7 Jump Lists With The API Code Pack and Visual Studio 2008
Introduction
Now that Windows 7 is readily available at every computer store, it's only a matter of time until the new operating system becomes mainstream in both homes and corporations. Especially this will happen once new computers start replacing old ones.
From a developer perspective, Windows 7 brings many possibilities. One of the most visible and prominent new features is the improved taskbar, through which applications are launched and even managed. In this article, the focus is on a feature called jump lists, which can be thought of as being a mini Start menu when right-clicking an icon on the taskbar (Figure 1).
Figure 1. A basic jump list.
Jump lists are active both when right-clicking an icon on the taskbar, but also when pointing at an application icon in the Start menu's initial view (Figure 2). Thus, there are two ways to make jump lists visible; however these menus have a different focus: jump lists on the Start menu are about the recent documents, whereas the taskbar-activated jump list contains more options to manage the application and its windows.
Figure 2. Jump lists in the Start menu.
Programming both instances of jump lists requires only a single implementation. Under the hood, jump lists use a COM based API, just like many other features in the Windows shell. Although it is possible to access these COM interfaces directly from your application, there is an easier way. Microsoft has developed a free package for .NET developers called the Windows API Code Pack (Figure 3), which contains many ready-made classes to access Windows features, such as Windows 7's jump lists.
Figure 3. The Windows API Code Pack download page.
Next, you are going to see how you can use Visual Studio 2008 and C# to enable custom jump lists in your own .NET applications with a WinForms sample application (Figure 4). A similar method could be used with Visual Studio 2010 Beta 2. With Visual Studio 2010 however, you can also use WPF 4.0's new support for Windows 7 shell integration. Even so, these classes are out the scope of this article, but the topic will likely be addressed in the near future.
Figure 4. The sample application.
Briefly About Jump List Features
Jump lists on Windows 7 can be considered streamlined mini versions of the Windows Start menu. Furthermore, they are tailored for each application. Just like in all Windows versions after Windows 95, you can right-click an icon on the taskbar, and see a popup menu. Jump lists in Windows 7 are an evolution of this menu.
Indeed, even if you don't do anything special, Windows 7 will display a popup menu for your application when its icon is available on the taskbar (see again Figure 1). If you have pinned an application to the taskbar, the default menu will give you the option to unpin it or launch the application. If the application is running, the default menu contains options to pin the program to the taskbar, close it, or launch another instance.
If an application has associated a file type (file
extension) with itself in the registry--for instance, Word
with .doc and .docx files--Windows will collect a list of
recent files opened with the application. This happens
automatically if the application uses Windows common file
dialogs to open files, or uses the
SHAddToRecentDocs API function to let Windows
know that files were opened. Windows will also keep track of
which files are used most frequently.
Files opened with an application from two so-called known lists. These are the Recent and Frequent lists. The difference between these two is that Recent will collect the most recently opened files (say, five of them), and the Frequent list will on the other hand collect files that are most commonly used over time. The application can control whether one of these lists is shown in the jump list, or neither.
These known lists are said to contain destinations, or nouns. Destinations are always files, and because of this, a file handler for a given file type (or types) must be registered. Windows will also make sure the files are available before showing them on the list.
Another important part of jump lists, and the focus of this article, is the support for verbs. Verbs allow your application to freely add custom commands to the jump list, and then allow users to quickly interact with your application while it's running. Unlike nouns, verbs do not require you to associate a file extension with your application.
Verbs are file based commands that point back to your application, and instruct it to run certain commands. For example, if you were writing a sales application, then the jump list verbs could start a new order, find a customer, and so on. Since these lists are customized for each application, every application has its own set of verbs.
Using the Windows API Code Pack
The freely downloadable Windows API Code Pack (see the Links section at the end for the URL) is a set of .NET classes compiled into several different assemblies. You can easily reference these from your own projects, and thus benefit from the classes.
To get started with the code pack, you first need to download it. It comes in a regular zip file, which you should extract to a convenient location, such as under your Visual Studio projects folder. Then, navigate inside the newly extracted folders, and open a solution named
Shell.sln with Visual Studio. Build the whole thing, and then note the location of the resulting DLL files, usually under the
bin\Debug folder.
After a successful build, you should see two assemblies,
Microsoft.WindowsAPICodePack.Shell.dll and
Microsoft.WindowsAPICodePack.dll in the output
folder. The latter file is automatically created, as the
Shell project depends on a project called Core. The Core
project is also part of the code pack.
The next step is to start a new project (or open one, if you already have one) in Visual Studio, and add the two code pack DLLs as references to your project (Figure 5). With the proper references in place, you can start writing code. The assembly filenames already give a hint of the correct namespaces; to use the code pack for jump lists, add the following using statements to your C# code:
using Microsoft.WindowsAPICodePack.Shell; using Microsoft.WindowsAPICodePack.Taskbar;
Figure 5. References have been to the sample project.
Inside the latter namespace, you can find a class called JumpList, which is a great starting point to begin exploring the features in jump lists. For instance, let's see how you could add a custom jump list verb to your application's menu.
The first step is to create an instance of the JumpList
class. After this, you need to construct an object
supporting the
IJumpListTask interface for each
custom verb you wish to add to your jump list. This can be
done with the help from the
JumpListLink class,
also part of the
Microsoft.WindowsAPICodePack.Taskbar
namespace.
For instance, you might want to add commands into your application's jump list to quickly launch Notepad or Calculator. To do this, you could use the following code:
JumpList list = JumpList.CreateJumpList(); string systemFolder = Environment.GetFolderPath( Environment.SpecialFolder.System); string notepadPath = System.IO.Path.Combine( systemFolder, "notepad.exe"); JumpListLink notepadTask = new JumpListLink( notepadPath, "Open Notepad"); notepadTask.IconReference = new IconReference( notepadPath, 0); string calculatorPath = System.IO.Path.Combine( systemFolder, "calc.exe"); JumpListLink calculatorTask = new JumpListLink( calculatorPath, "Open Calculator"); calculatorTask.IconReference = new IconReference( calculatorPath, 0); list.AddUserTasks(notepadTask, calculatorTask); list.Refresh(); MessageBox.Show("Custom tasks have been added!");
Here you are creating a new jump list object, and then
constructing two verbs with the JumpListLink class. The
constructor requires a file-based command, and in this case
this is the full pathname to Notepad.exe (and Calc.exe) in
the Windows\System32 directory. The
System.IO.Path class helps in the process.
Also, menu icons are added using the
IconReference class, which takes in a full path
and an icon index. Zero means the first icon in the file,
which is commonly the main icon.
Finally, the
AddUserTasks method of the
JumpList class is called to add the new verbs to the menu.
Windows 7 will create the commands under the Tasks generic
group, and thus the verbs added here can also be called
tasks. Note that Windows will keep a record of the tasks you
create. Thus, you will only need to create your tasks
once.
There are no comments yet. Be the first to comment!
|
http://www.codeguru.com/csharp/.net/net_general/tipstricks/article.php/c16621/Creating-Windows-7-Jump-Lists-With-The-API-Code-Pack-and-Visual-Studio-2008.htm
|
CC-MAIN-2014-42
|
refinedweb
| 1,454
| 65.01
|
-2017 03:06 AM
Hello everyone,
I recently switched to SDx 2017.2. After trying to import and build a project, SDx prints out the following error messages regarding "hls_half.h":
C:/Xilinx/SDx/2017.2/Vivado_HLS/include/hls_half.h:2187:17: error: no member named 'fmax' in namespace 'std'; did you mean simply 'fmax'? return expr(std::fmax(x, y)); ^~~~~~~~~ fmax
This happens for every c++11 function included from cmath. I tried specifying "-std=c++11" in the compiler options, but without success.
I currently using a workaround by hardcoding the functions into "half_hls.h"....
Thanks a lot,
Seek
12-04-2017 09:53 PM
12-06-2017 01:20 AM
Hello zhch7777,
try adding
#define HALF_ENABLE_CPP11_CMATH 0
at the top of the "hls_half.h" file. Not a 100% clean solution, but worked for me. :)
Regards,
Seek
12-07-2017 10:11 PM
12-07-2017 11:41 PM
Hello,
no unfortunately I do not get this error, so I don't know how to fix it. :/
I also do not get the warnings before.
I had another workaround before I found this by replacing the hls_half.h from 2017.2 with the one from 2017.1.
There is the one from 2017.1 attached, maybe this will help you.
Regards,
Seek
12-11-2017 12:11 AM
hello
thanks
i have the same problem by the 2017.01 hls_half.h
i cant do any thing,but waiting for the new SDX
12-27-2018 09:37 AM
12-27-2018 10:00 AM - edited 12-27-2018 10:03 AM
Here are two things to try...
1) remove the std:: (and any using namespace std)... e.g. just call fmax with no namespace (you should include the the math include file)
OR
2) define your own FMAX macro, and call that instead e.g. #define FMAX(_a, _b) ((_a) >= (_b)) ? (_a) : (_b)
Hope that helps
12-28-2018 02:39 AM
Thanks for your reply @xilinxacct, but same project works good on another PC without any code change. Both are SDSoC 2018.2 and the only difference between them is Ubuntu versions (16.04 and 18.04). I checked includes and libraries. I tried -std=c++11 flag but still it can't build.
12-28-2018 06:20 AM
With both of those suggestions, you should not need the std=c++11 flag any more, since it is as basic as it gets at that point. Using 2018.2 The compiler worked fine for both of those methods. Suggestion #2 is just code, so doesn't even count on a library. Maybe you have some other issue (especially, as you say, it works elsewhere)
01-03-2019 02:15 AM
Hi,
I fixed the problem with updating the petalinux platform file which I was downloaded from Avnet Ultra96 support page. I think sw part of the platform folder is updated in the new version and it works ok in SDSoC 2018.2.
05-29-2019 08:32 PM
Hi, I also have this problem when working with SDSoC 2018.2 on Windows 10.
#define HALF_ENABLE_CPP11_CMATH 0 can compile but can not create elf file.
Do you know how to fix it on SDSoC 2018.2 Windows
|
https://forums.xilinx.com/t5/SDSoC-Environment-and-reVISION/quot-hls-half-h-quot-Error-no-member-named-in-namespace-std/td-p/810297
|
CC-MAIN-2019-43
|
refinedweb
| 540
| 83.56
|
This post is inspired by Kevin Markham's course Introduction to Machine Learning with scikit-learn on Data School. If you're a beginner looking to get started with Machine Learning using scikit-learn, I would highly recommend this course to gain all the required foundational skills.
In just a few hours, you'd be able to understand and build basic regression, and classification models with the optimal hyperparameters.
📌If this sounds interesting, please be sure to check the course at this link.
That said, we shall cover the following in this post.
- How to Use Cross-Validation to Evaluate a Machine Learning Model
- How to Use Cross-Validation to Search for the Best Model Hyperparameters
- How to Use Grid Search for Hyperparameter Search
- How to Search for Hyperparameters More Efficiently Using Randomized Search
How to Use Cross-Validation to Evaluate a Machine Learning Model
How do we validate a machine learning model?
When evaluating a machine learning model, training and testing on the same dataset is not a great idea. Why? Let us draw a relatable analogy.
Ever since school days, we’ve been giving exams, and how are our exams designed?
- Well, they’ve been designed so as to test our understanding of the concepts rather than our ability to memorize!
- The same analogy can be transposed to our machine learning model as well!
Here’s the answer to the question ‘Why can we not evaluate a model on the same data that it was trained on?’
It is because this process inherently encourages the model to memorize the training data. So, the model performs extremely well on the training data.
However, it generalizes rather poorly to data that it has never seen before.
What does
train_test_split do?
As a model's performance on data that it has never seen before is a more reliable estimate of its performance, we usually validate the model by checking how it performs on out-of-sample data, that is, on data that it has never seen before.
If you remember, it is for this reason, we use the
train_test_split method, in our very friendly and nifty library, scikit-learn.
This
train_test_split splits the available data into two sets: the train and test sets in certain proportions.
For example, train on 70% of the available data and test on the remaining 30% of the data. This way, we can ensure that every record in the dataset can either be in the training set or the test set but not both!
And in doing so, we are making sure that we test the model’s performance on unseen data.
But, is this good enough? Or do we take this with a pinch of salt?
Let us train a simple
KNeighborsClassifier in scikit-learn on the iris dataset.
▶ Necessary imports
As shown below, we import the necessary modules.
from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier from sklearn import metrics
▶ Load the data
Let us load the iris data and separate out the features(Sepal Length, Sepal Width, Petal Length and Petal Width) and the target variables which are the class labels indicating the iris type. (Setosa, Versicolour, and Virginica)
# read in the iris data iris = load_iris() # create X (features) and y (response) X = iris.data y = iris.target
▶ Create train_test_split
Let’s create the train and test sets with
random_state= 4. Setting the
random_state ensures reproducibility.
In this case, it ensures that the records that go into the train and test sets stay the same every time our code is run.
# use train/test split with different random_state values X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 4)
▶ Check Classification Accuracy
We now instantiate the
KNeighborsClassifier with
n_neighbors=9 and fit the classifier on the training set and predict on the test set.
knn = KNeighborsClassifier(n_neighbors=9) knn.fit(X_train, y_train) y_pred = knn.predict(X_test) print(metrics.accuracy_score(y_test, y_pred)) # Output 0.9736842105263158
Now, let us change the
random_state to a different value. What do you think the accuracy score would be?
Well, please feel free to insert your favorite number in the
random_state and check for yourselves. It'd be a different accuracy score this time.
Setting the
random_state to another value, we would get another value for the accuracy score.
The evaluation metric thus obtained is therefore susceptible to high variance.
- The accuracy score may depend heavily on which data points end up in the training set and which end up in the test set.
- Thus the accuracy score may be significantly different depending on how the division is made. Clearly, this doesn’t seem like the best way to validate our model’s performance!
How do we reach a consensus on how to calculate the accuracy score?
One very natural thing to do would be to create multiple train/test splits, calculate the accuracy for each such split, and compute the average of all the accuracy scores thus obtained. This definitely seems like a better estimate of the accuracy, doesn’t it?
This is precisely the essence of cross-validation, which we shall see in the subsequent section.
Understanding K-fold cross-validation
Steps in K-fold cross-validation
- Split the dataset into K equal partitions (or “folds”).
- Use fold 1 for testing and the union of the other folds as the training set.
- Calculate accuracy on the test set.
- Repeat steps 2 and 3 K times, using a different fold for testing each time.
- Use the average accuracy on different test sets as the estimate of out-of-sample accuracy.
Let us try to visualize this by splitting a dataset of 25 observations into 5 equal folds as shown below.
The dataset contains 20 observations (numbered 0 through 24).
5-fold cross-validation runs for 5 iterations.
Let's see how the folds are created
# simulate splitting a dataset of 25 observations into 5 folds from sklearn.model_selection import KFold kf = KFold(n_splits=5, shuffle = False).split(range(25)) # print the contents of each training and testing set print('{} {:^61} {}'.format('Iteration', 'Training set observations', 'Testing set observations')) for iteration, data in enumerate(kf, start=1): print('{:^9} {} {:^25}'.format(iteration, data[0], str(data[1]))) # Output]
We observe the following:
- For each iteration, every observation is either in the training set or the testing set, but not both.
- Every observation is in the test set exactly once.
- Each fold is used as the test set exactly once and in the training set (K-1) times.
- The average accuracy thus obtained is a more accurate estimate of out-of-sample accuracy.
This process uses data more efficiently as every observation is used for both training and testing.
It is recommended to use stratified sampling for creating the folds, as this ensures that all class labels are represented in equal proportions in each fold. And, scikit-learn’s
cross_val_score does this by default.
In practice, we can even do the following:
- “Hold out” a portion of the data before beginning the model building process.
- Find the best model using cross-validation on the remaining data, and test it using the hold-out set.
- This gives a more reliable estimate of out-of-sample performance since the hold-out set is truly out-of-sample.
How to Use Cross-Validation to Search for the Best Model Hyperparameters
Cross-validation for hyperparameter tuning
For the KNN classifier on the iris dataset, can we possibly use cross-validation to find the optimal value for
K? That is, to search for the optimal value of
n_neighbors?
Remember,
K in KNN classifier is the number of neighbors (
n_neighbors) that we take into account for predicting the class label of the test sample. Not to be confused with the
K in K-fold cross-validation.
from sklearn.model_selection import cross_val_score # 10-fold cross-validation with K=5 for KNN (the n_neighbors parameter) knn = KNeighborsClassifier(n_neighbors=5) scores = cross_val_score(knn, X, y, cv=10, scoring='accuracy') print(scores) # Output [1. 0.93333333 1. 1. 0.86666667 0.93333333 0.93333333 1. 1. 1. ] # use average accuracy as an estimate of out-of-sample accuracy print(scores.mean()) # Output 0.9666666666666668
Now, we shall run the K fold cross-validation for the models with different values of
n_neighbors, as shown below.
# search for an optimal value of K for KNN k_range = list(range(1, 31)) k_scores = [] for k in k_range: knn = KNeighborsClassifier(n_neighbors=k) scores = cross_val_score(knn, X, y, cv=10, scoring='accuracy') k_scores.append(scores.mean()) print(k_scores) # Output k_scores [0.96, 0.9533333333333334, 0.9666666666666666, 0.9666666666666666, 0.9666666666666668, 0.9666666666666668, 0.9666666666666668, 0.9666666666666668, 0.9733333333333334, 0.9666666666666668, 0.9666666666666668, 0.9733333333333334, 0.9800000000000001, 0.9733333333333334, 0.9733333333333334, 0.9733333333333334, 0.9733333333333334, 0.9800000000000001, 0.9733333333333334, 0.9800000000000001, 0.9666666666666666, 0.9666666666666666, 0.9733333333333334, 0.96, 0.9666666666666666, 0.96, 0.9666666666666666, 0.9533333333333334, 0.9533333333333334, 0.9533333333333334]
Let us plot the values to get a better idea.')
We see that
n_neighbors (K) values from 13 to 20 yield higher accuracy, especially
K=13,18 and 20.As a larger value of
K yields a less complex model, we choose
K=20.
This process of searching for the optimal values of hyperparameters is called hyperparameter tuning.
In this example, we chose the values of
K that resulted in higher mean accuracy score under 10-fold cross validation.
This is how cross-validation can be used to search for the best hyperparameters and this can be done much more efficiently in scikit-learn.
In KNN classifiers, setting a very small value for
Kwill make the model needlessly complex, and a very large value of
Kwould result in a model with high bias that yields suboptimal performance.
As
K=13,18 and 20 gave the highest accuracy score, close to 0.98, we decided to choose
K=20 as a larger value of
K would yield a less complex model.
While it is not particularly difficult to write the for loop, we do realize that we may have to do it often.
Therefore, it would be good to have a more convenient way of doing the hyperparameter search, without having to write a loop every time and identify the best parameter through inspection.
Grid Search class in scikit-learn helps us do this all the more easily. Let's learn about it in the next section.
How to Use Grid Search for Hyperparameter Search
▶ Import GridSearchCV Class
from sklearn.model_selection import GridSearchCV
▶ Define the Parameter Grid
We now define the parameter grid (
param_grid), a Python dictionary, whose key is the name of the hyperparameter whose best value we’re trying to find and the value is the list of possible values that we would like to search over for the hyperparameter.
# define the parameter values that should be searched k_range = list(range(1, 31)) # create a parameter grid: map the parameter names to the values that should be searched param_grid = dict(n_neighbors=k_range) print(param_grid) # param_grid {'n_neighbors': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]}
We now instantiate
GridSearchCV. Note that we specify the
param_grid instead of the
n_neighbors argument that we had specified for
cross_val_score earlier.
Why is this valid?
Remember, the parameter grid,
param_grid is a dictionary whose key is
n_neighbors and the value is a list of possible values of
n_neighbors. Therefore, specifying the
param_grid ensures that the value at index
i is fetched as the value of
n_neighbors in the i_th run.
▶ Instantiate, fit the grid and view the results
# instantiate the grid grid = GridSearchCV(knn, param_grid, cv=10, scoring='accuracy', return_train_score=False)
We now go ahead and fit the grid with data, and access the
cv_results_ attribute to get the mean accuracy score after 10-fold cross-validation, standard deviation and the parameter values.
For convenience, we may store the results in a pandas DataFrame. The mean and standard deviation of the accuracy scores for
n_neighbors=1 to 10 are shown below.
# fit the grid with data grid.fit(X, y) # view the results as a pandas DataFrame import pandas as pd pd.DataFrame(grid.cv_results_)[['mean_test_score', 'std_test_score', 'params']] # Output mean_test_score std_test_score params 0 0.960000 0.053333 {'n_neighbors': 1} 1 0.953333 0.052068 {'n_neighbors': 2} 2 0.966667 0.044721 {'n_neighbors': 3} 3 0.966667 0.044721 {'n_neighbors': 4} 4 0.966667 0.044721 {'n_neighbors': 5} 5 0.966667 0.044721 {'n_neighbors': 6} 6 0.966667 0.044721 {'n_neighbors': 7} 7 0.966667 0.044721 {'n_neighbors': 8} 8 0.973333 0.032660 {'n_neighbors': 9} 9 0.966667 0.044721 {'n_neighbors': 10}
When using
cross_val_score, we tried eyeballing the accuracy scores to identify the best hyperparameters and to make it easier, we plotted the value of hyperparameters vs the respective cross-validated accuracy scores!
Sounds good but doesn’t seem to be a great option though!
Once we’ve completed the grid search, the following attributes can be very useful! We can choose to examine:
☑ the
best_score_ , the highest cross-validated accuracy score
☑ the
best_params_, the optimal value for the hyperparameters, and
☑ the
best_estimator_, which is the best model that has the best hyperparameter.
Let's now examine these for our example.
▶ Examine the best score and best hyperparameters
# examine the best model print(grid.best_score_) print(grid.best_params_) print(grid.best_estimator_) # Output 0.9800000000000001 {'n_neighbors': 13} KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski', metric_params=None, n_jobs=None, n_neighbors=13, p=2, weights='uniform')
K=13 has been chosen, remember,
K=13 was one of the values of
K that gave highest cross-validated accuracy score.✔
So far so good!
Searching for Multiple Hyperparameters
In this example, the only hyperparameter that we searched for was
n_neighbors.
What if there were many such hyperparameters?
We may think, “Why not tune each hyperparameter independently?”
Well, we may independently search for the optimal values for each of the hyperparameters; but the model may perform best at some values of the parameters that are very different from the individual best values.
So, we have to search for the combination of the parameters that optimizes performance rather than the individual best parameters.
Let's build on the same example of KNNClassifier.
In addition to
n_neighbors, let's search for the optimal weighting strategy as well.
- The default weighting option is
‘uniform’where all points are weighted equally and
‘distance’option weights points by the inverse of their distance.
In this case, closer neighbors of a query point will have a greater influence than neighbors which are far away.
▶ Define the Parameter Grid
# define the parameter values that should be searched k_range = list(range(1, 31)) weight_options = ['uniform', 'distance'] # create a parameter grid: map the parameter names to the values that should be searched param_grid = dict(n_neighbors=k_range, weights=weight_options) print(param_grid) # param_grid {'n_neighbors': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30], 'weights': ['uniform', 'distance']}
Let us instantiate and fit the grid and view results, as before.
# instantiate and fit the grid grid = GridSearchCV(knn, param_grid, cv=10, scoring='accuracy', return_train_score=False) grid.fit(X, y) # view the results pd.DataFrame(grid.cv_results_)[['mean_test_score', 'std_test_score', 'params']] # Results mean_test_score std_test_score params 0 0.960000 0.053333 {'n_neighbors': 1, 'weights': 'uniform'} 1 0.960000 0.053333 {'n_neighbors': 1, 'weights': 'distance'} 2 0.953333 0.052068 {'n_neighbors': 2, 'weights': 'uniform'} 3 0.960000 0.053333 {'n_neighbors': 2, 'weights': 'distance'} 4 0.966667 0.044721 {'n_neighbors': 3, 'weights': 'uniform'} 5 0.966667 0.044721 {'n_neighbors': 3, 'weights': 'distance'} 6 0.966667 0.044721 {'n_neighbors': 4, 'weights': 'uniform'} 7 0.966667 0.044721 {'n_neighbors': 4, 'weights': 'distance'} 8 0.966667 0.044721 {'n_neighbors': 5, 'weights': 'uniform'} 9 0.966667 0.044721 {'n_neighbors': 5, 'weights': 'distance'} 10 0.966667 0.044721 {'n_neighbors': 6, 'weights': 'uniform'} 11 0.966667 0.044721 {'n_neighbors': 6, 'weights': 'distance'} 12 0.966667 0.044721 {'n_neighbors': 7, 'weights': 'uniform'} 13 0.966667 0.044721 {'n_neighbors': 7, 'weights': 'distance'} 14 0.966667 0.044721 {'n_neighbors': 8, 'weights': 'uniform'} 15 0.966667 0.044721 {'n_neighbors': 8, 'weights': 'distance'} 16 0.973333 0.032660 {'n_neighbors': 9, 'weights': 'uniform'} 17 0.973333 0.032660 {'n_neighbors': 9, 'weights': 'distance'} 18 0.966667 0.044721 {'n_neighbors': 10, 'weights': 'uniform'}
We see that we have 30*2=60 models.(As we had 30 possible values for
n_neighbors and 2 possible values for weights)
As we chose 10-fold cross-validation, there will be 60*10=600 predictions made!
Time to look at our model’s best score and parameters that yielded the best score.
▶ Examine the best score and best hyperparameters
# examine the best model print(grid.best_score_) print(grid.best_params_) # best score and best parameters 0.9800000000000001 {'n_neighbors': 13, 'weights': 'uniform'}
We obtain the same best cross-validated accuracy score of 0.98, with
n_neighbors=13 and
weights= ‘uniform’.
Now, let's suppose we have to tune 4 hyperparameters and we have a list of 10 possible values for each of the hyperparameters.
This process creates 10*10*10*10 =10,000 models and when we run 10 fold cross-validation, there are 100,000 predictions made.
Clearly, things do scale up very quickly and can soon become computationally infeasible.
How to Search for Hyperparameters More Efficiently Using Randomized Search
We shall now try to rephrase the limitations of Grid Search better, in a more formal way.
- Say we have to search for
Mparameters; Let
p_1, p_2,p_3, …, p_Mbe the
Mparameters.
- Let the number of values that we would like to search over for
p_1be
n1, for
p_2be
n2, and so on, with
nMvalues for
p_M.
Grid Search considers all possible hyperparameter settings (combinations) into account and creates a model for each possible setting to choose the best model with optimal hyperparameters.
- To understand it better, assume that out of
Mparameters, we decide to freeze the values of all hyperparameters except one, say the M_th parameter
p_M. So, Grid Search involves searching through the list of
nMvalues for the M_th hyperparameter; And
nMmodels are created.
- Suppose we now freeze the values of all hyperparameters except two, say the last two (
p_Mand
p_(M-1)). We now have to search through all possible combinations of
p_Mand
p_(M-1), each having
nMand
n_(M-1)possible values that we could search over.
- We now take a step back and freeze the value of
p_M-1and search through all values for
p_M; To account for all possible combinations, we should repeat the procedure for all
n_M-1values for
p_M-1. So, this process would leave us with
n_(M-1) * nMmodels.
Hope it’s clear how the complexity scales with increase in the number of values each hyperparameter could take.
- For the above example with
Mhyperparameters, we would have
n1*n2*n3*…*n_Mmodels. This is why we said that things could scale up quickly and become computationally intractable with Grid Search.
With this motivation to make hyperparameter search computationally more efficient, let us proceed to understand Randomized Search.
Understanding RandomizedSearchCV
In contrast to
GridSearchCV, not all parameter values are tried out in
RandomizedSearchCV, but rather a fixed number of parameter settings is sampled from the specified distributions/ list of parameters.
If some of the hyperparameters that we’re searching for are continuous, then we should specify the distribution rather than the list of values, while defining the parameter grid. How do we define the fixed number of parameter settings?
The number of parameter settings that are tried is given by
n_iter. There's a quality vs computational cost trade-off in picking
n_iter.
A very small value of
n_iterwould imply that we’re more likely to find a suboptimal solution, because we are actually considering too few combinations.
A very high value of n_iter would mean we can ideally get closer to finding the best hyperparameters that yield the best model, but this again comes with a high computation cost as before.
In fact, if we set
n_iter= n1*n2*n3*…*n_Mfrom the previous example, then, we’re essentially considering all possible hyperparameter combinations and now Randomized Search and Grid Search are equivalent.
Let us build on the same example of KNNClassifier from the previous section.
Let us search for the optimal weighting strategy and
n_neighbors. And now, let us implement Randomized Search in scikit-learn and do the following steps, as we did for Grid Search.
▶ Import RandomizedSearchCV class
from sklearn.model_selection import RandomizedSearchCV
▶ Define the parameter grid
# specify "parameter distributions" rather than a "parameter grid" param_dist = dict(n_neighbors=k_range, weights=weight_options)
▶ Instantiate the grid; Set n_iter=10, Fit the grid & View the results
# n_iter controls the number of searches rand = RandomizedSearchCV(knn, param_dist, cv=10, scoring='accuracy', n_iter=10, random_state=5, return_train_score=False) rand.fit(X, y) pd.DataFrame(rand.cv_results_)[['mean_test_score', 'std_test_score', 'params']] #DataFrame mean_test_score std_test_score params 0 0.973333 0.032660 {'weights': 'distance', 'n_neighbors': 16} 1 0.966667 0.033333 {'weights': 'uniform', 'n_neighbors': 22} 2 0.980000 0.030551 {'weights': 'uniform', 'n_neighbors': 18} 3 0.966667 0.044721 {'weights': 'uniform', 'n_neighbors': 27} 4 0.953333 0.042687 {'weights': 'uniform', 'n_neighbors': 29} 5 0.973333 0.032660 {'weights': 'distance', 'n_neighbors': 10} 6 0.966667 0.044721 {'weights': 'distance', 'n_neighbors': 22} 7 0.973333 0.044222 {'weights': 'uniform', 'n_neighbors': 14} 8 0.973333 0.044222 {'weights': 'distance', 'n_neighbors': 12} 9 0.973333 0.032660 {'weights': 'uniform', 'n_neighbors': 15}
▶ Examine the best score and best hyperparameters
# examine the best model print(rand.best_score_) print(rand.best_params_) # Output 0.9800000000000001 {'weights': 'uniform', 'n_neighbors': 18}
▶ Parameters of the best model
- Surprisingly, we see that the highest accuracy score obtained in this case, where we only looked at 10 different parameter settings instead of 60 in Grid Search, is the same as before: 0.98 ✔
- And the value for
n_neighbors= 18, which is also one of the optimal values that we got when we initially searched for the optimal value of
n_neighbors.
Maybe we just got lucky?
What is the guarantee that we will always get the best results?
Ah, this question makes perfect sense, doesn’t it?
Let us do the following now: Let us run
RandomizedSearchCV for multiple times and see how many times we really end up getting lucky!
➡️Run RandomizedSearchCV 20 times and see what happens; We log the best_score_ for every run.
# run RandomizedSearchCV 20 times (with n_iter=10) and record the best score best_scores = [] for _ in range(20): rand = RandomizedSearchCV(knn, param_dist, cv=10, scoring='accuracy', n_iter=10, return_train_score=False) rand.fit(X, y) best_scores.append(round(rand.best_score_, 3)) Let us examine all the 20 best scores now. print(best_scores) # Output: Best Scores [0.973, 0.98, 0.98, 0.98, 0.973, 0.98, 0.98, 0.973, 0.98, 0.973, 0.973, 0.98, 0.98, 0.98, 0.98, 0.973, 0.98, 0.98, 0.98, 0.973]
Upon examining the best scores above for all the 20 runs, we see that we get the best accuracy score of 0.98 about 13 times.
Looks like we’re lucky indeed! What about the other 7 times when we didn't quite get the best accuracy score? These accuracy scores are around 0.973 which is pretty close to 0.98.
This observation convinces us that even though Randomized Search may not always give the hyperparameters of the best performing model, the models obtained by using these hyperparameters do not perform much worse compared to the best model obtained from Grid Search.
This means, the best models thus obtained, with the hyperparameters from randomized search are clearly very close to the optimal model.
In essence, these may not be the best hyperparameters, but certainly close to the best hyperparameters, except that these are found under resource-constrained settings.
Hope you all understood how we could use Randomized Search for hyperparameter tuning.
Hope you all enjoyed reading this post.😀
Happy Learning! Until next time!✨
References
[1]
[2]
[3]
[4]
Cover Image: Photo by Ross Sneddon on Unsplash
Note: This post is a comprehensive post for understanding model evaluation, and hyperparameter search. This is a compiled, and improved version of a few of my earlier shorter posts.
Discussion (0)
|
https://practicaldev-herokuapp-com.global.ssl.fastly.net/balapriya/cross-validation-and-hyperparameter-search-in-scikit-learn-a-complete-guide-5ed8
|
CC-MAIN-2021-43
|
refinedweb
| 4,041
| 55.64
|
This control simulates a particle swarm dynamic system. Each particle has different weight and electronic charge. So they implement different attract and dispel forces on each other as they move around with changing velocity and acceleration. The system also simulates dump forces and other attenuation characteristics, so that they can finally get into a stable status after a while.
The particles in this system also have attributes such as background and front color, picture, font, text, shape etc.. The control detects mouse events and changes the color of the corresponding particle. When a user clicks on one of the particles, the control can trigger several events. In fact, I make it a very useful button control like what you might see in Britica 2000, which serves as an excellent navigating tool with keyword buttons jumping out one by one like bubbles blown out of a pipe.
Double buffering and other techniques to accelerate the animation are also demonstrated in this control. System timers are used as the engine of this simulation instead of the idle thread.
Besides the programming stuff, some problem concerned with the discreet time sampling in computer simulation are also addressed and solved in this control. You might get a discussion with me if you'd ever made high calculus points .
Let's demonstrate the usage in VB first for the simplicity (thanks to Microsoft). Create a new project and import the component SmartGravityBubbleCtrl. Then drag it onto your form and place it anywhere you like. Now, in the object browser, you'll see two classes CSmartGravityBubbleCtrl and CSmartBubble. The first one is our dynamic system container, i.e., the playground of our particles, and the latter is our player - the particle itself. When you drag the control onto your form, you've already setup a playground for our players. What you have to do next is to create CSmartBubble objects (the players) and add them to the playground. The source code looks like this:
SmartGravityBubbleCtrl
CSmartGravityBubbleCtrl
CSmartBubble
Dim b As CSmartBubble
Set b = New CSmartBubble
b.Shape = RoundedRect
b.id = 1
CSmartGravityBubble1.AddBubble b
Really easy, right? The electronic and gravity parameters are tuned thoroughly that you don't have to specify values other than the default one. But if you want something special, just go ahead and specify your own parameters. You can add as many particles as you like, and watch them moving and jumping until they all get tired and move into a beautiful and regular pattern. But one thing you shall be careful: in this edition, every CSmartBubble object added into the container shall have distinct ID values. This might be a stupid idea because when I wrote the control, I decided that every bubble shall be identified by their ID, so I can trigger an event when the user clicks on one of them and tell the client which one is clicked with this ID. You may get rid of the guard code in the source.
The control is not just a toy of codes. It is full fledged with many properties and events. The extensive description and reference has been packed into the source packet.
Besides that, there are two demos, demo1 and xmlDemo, all written in VB6. Demo1 handles the LeftButtonDown event of the control and adds a particle where the user clicks, the code in the handler is below:
LeftButtonDown
Private Sub Bubble1_OnLeftButtonDown(ByVal X As Long, ByVal Y As Long)
Dim b As CSmartBubble
Set b = New CSmartBubble
b.xPos = X 'set the coordinates of the particle to where the user clicks
b.yPos = Y
b.Width = 50 'set the size of the particle
b.Height = 20
b.Text = "Green" 'text
b.ElectronicCharge = 1
b.Shape = RoundedRect
b.id = id + 1
b.Weight = 2
b.TextHighlightColor = RGB(255, 255, 255)
'color when the particle is highlighted by mouse
id = id + 1 'ensures that we get unique id for every particle
Bubble1.AddBubble b
End Sub
xmlDemo is much more complicated and I built it to mimic Britica 2000 knowledge navigator. It is used for navigating a tree structure such as disk directories, and creates fascinating effects. I wrote a tree structure in XML and parsed it with Microsoft XML 4.0. The content of this tree structure is mainly a self introduction of myself.
At initialization, the program creates a particle with text and style specified in the root node of this XML file, and this root particle is fixed in the center of the control. Then its children were popped out from it one after another with 500 ms delay time triggered by a timer. So the whole process looks like blowing out bubbles with a pipe. When user clicks one of them, and this particle is also a parent node, then it is fixed to the center and all other bubbles are eliminated while its children are pumping out continuously. To compile and run this demo, you have to install MS XML 4.0.
The basic idea of this dynamic system comes from the Kulun's law and Newton's gravity law. We give each particle positive electronic charge and weight, so they expel each other by their electronic charge while attract each other by their gravity. These forces make the system dynamic. According to Kulun's law, the electronic force between two particles p1 and p2 is:
The formula is in vector form, and I omitted the Kulun parameter. Q1 and Q2 are their electronic charge and P1 and P2 are their pos vector. The gravity between the particles is originally in the same form, but this won't make the system stable because expel force will always be greater than the gravity, so particles will run further and further, the system goes stable, but that's not what I want. So, I use the gravity in the form:
W1 and W2 are the weights of the two particles.
Obviously, the expel forces go smaller when the distance between particles increases while gravity forces become greater. So if the distance between particles are too small, the expel forces push them apart while the distance exceeds a value, the gravity forces dominates and bound them closer.
The relationship between the two kinds of forces can be demonstrated as below:
Clearly, they got joint points, that's where the particles should stop. Well, one may simply think that as we implement these forces and calculate the acceleration and speed at every sample time, the system would go fine and go stable as we wish. However, this is wrong, because the forces we discussed do not even confirm to the energy law, i.e., the energy of the system goes bigger and bigger with time, the particles pump like mad with acceleration greater and greater until they finally jump out of our sight.
The system we simulate never exists in the real world. We shall give it attenuation characteristics to cut down its energy slowly and make it stable. Dump forces is the first thing I chose. As an object moving in the air, its dump force can be expressed as:
S is the speed vector of this object and k is a constant. The negative sign before it means the dump force has opposite direction with speed.
Simulation of the dump force makes the whole process more realistic. But it still cannot stabilize the system. So we use another method which attenuates the gravity and expel forces by a function of simulation time. As the time passes by, the gravity and expel forces are attenuated with a speed linear to the square root of the simulation time. When a particle is added into the container, the simulation time will be reset to zero and the system restarts simulation.
Much has been said about the theory stuff. Let's take a look at the source now. I enjoy developing ActiveX controls in Visual Studio .Net with ATL7, because everything becomes simple and neat, especially the support for COM events. I need to just type in a few attributes before the COM class and say: "be there!". Then everything is done like magic. The source is too much to be explained in detail here. I just give some points and leave it to you to check it out: The whole design used a simple container pattern because I can't find a suitable container for my particles in STL.
Double buffering is used in this control for better performance. A complex number template class in STL is used for vector calculation. A helper class from one of The Code Project contributors is used and extended for the implementation of font and picture property of the control. You can find it in the VCUE namespace. All the background pictures in the control are implemented as IPicture interfaces for easy usage and supporting transparent pictures like GIF. The simulation is driven by a timer, not an idle thread. You may correct this with ease.
IPicture
We may all know that speed is the integration of acceleration and distance is the integration of speed. In our simulation, the integration is in fact a summation of discrete samples. As we have to do the integration twice, and the acceleration of particles can be very huge if they are close, the bias between the summation and integration can be extraordinarily large that the system looks flakey. So you may see much "round off" and "cut off" in my program. These codes are hard to understand, you can just forget about.
|
http://www.codeproject.com/Articles/8798/An-Example-of-ATL-7-0-ActiveX-Control-Simulating-A?fid=126882&df=10000&mpp=50&sort=Position&spc=Relaxed&select=1196442&tid=1009605
|
CC-MAIN-2016-07
|
refinedweb
| 1,587
| 63.7
|
This action might not be possible to undo. Are you sure you want to continue?
[ contents | #winprog ]
Welcome to Version 2.0 of theForger's Win32 API Tutorial
This. I have also added some solutions to common errors in Appendix A. If you ask me a question that is answered on this page, you will look very silly.
q
q
Download the complete example Source Code which is refered to throughout this document. Or Download the entire tutorial (source included) for browsing in the convenience of your own harddrive. This file may not include minor changes such as spelling corrections that are present on the website.
If you are viewing this locally or on another website, visit the #winprog website for the current official copy.
q q
Feeling generous? Need more help?
Contents
q
Basics 1. Getting Started 2. A Simple Window 3. Handling Messages 4. Understanding The Message Loop 5. Using Resources 6. Menus and Icons 7. Dialogs, GUI coders best friend 8. Modeless Dialogs (1 of 3) [7/8/2003 4:34:43 PM]
theForger's Win32 API Tutorial
q
q
q
q
9. Standard Controls: Button, Edit, List Box, Static 10. But what about... (Dialog FAQ) Creating a simple application 1. App Part 1: Creating controls at runtime 2. App Part 2: Using files and the common dialogs 3. App Part 3: Tool and Status bars 4. App Part 4: Multiple Document Interface Graphics Device Interface 1. Bitmaps, Device Contexts and BitBlt 2. Transparent Bitmaps 3. Timers and Animation 4. Text, Fonts and Colours Tools and Documentation 1. Recommended Books and References 2. Free Visual C++ Command Line Tools 3. Free Borland C++ Command Line Tools Appendices r Appendix A: Solutions to Common Errors r Appendix B: Why you should learn the API before MFC r Appendix C: Resource file notes
I've had reports that the source code presented in the documents itself doesn't display line breaks properly in very old versions of Netscape, if you encounter this problem please refer to the code in the source files included in the zip download.
Feeling generous?
You may use this tutorial for absolutely no charge, however there are costs associated with hosting it on the web. If you found it to be of use to you and want to give something back, I would be grateful for donations of any amount to help pay for this website. This page gets approximately (2 of 3) [7/8/2003 4:34:43 PM]!
Need more help?
In general I will freely answer any questions that I receive by email, or point you in the direction of a resource that may be of assistance. At the moment I am busy with a couple of large ongoing projects and don't have the time to work on custom examples or small software projects. I would however be willing to entertain job offers :) Feel free to contact me.
Copyright © 1998-2003, Brook Miles (theForger). All rights reserved. (3 of 3) [7/8/2003 4:34:43 PM]
Tutorial: Getting Started
[ contents | #winprog ]
Getting Started
What this tutorial is all about
This tutorial is intended to present to you the basics (and common extras) of writing programs using the Win32 API. The language used is C, most C++ compilers will compile it as well. As a matter of fact, most of the information is applicable to any language that can access the API, inlcuding Java, Assembly and Visual Basic. I will not however present any code relating to these languages and you're on your own in that regard, but several people have previously used this document in said languages with quite a bit of success. This.
Important notes
Sometimes throughout the text I will indicate certain things are IMPORANT to read. Because they screw up so many people, if you don't read it, you'll likely get caught too. The first one is this:. (1 of 4) [7/8/2003 4:34:43 PM]
Tutorial: Getting Started.
The simplest Win32 program
If you are a complete beginner lets make sure you are capable of compiling a basic windows application. Slap the following code into your compiler and if all goes well you should get one of the lamest programs ever written.) (2 of 4) [7/8/2003 4:34:43 PM]
Tutorial: Getting Started (3 of 4) [7/8/2003 4:34:43 PM]
Tutorial: Getting Started.
Copyright © 1998-2003, Brook Miles (theForger). All rights reserved. (4 of 4) [7/8/2003 4:34:43 PM]
Tutorial: A Simple Window
[ contents | #winprog ].); (1 of 8) [7/8/2003 4:34:44 PM]
Tutorial: A Simple Window; } (2 of 8) [7/8/2003 4:34:44 PM]
Tutorial: A Simple Window. = = = = = = = = = = = = sizeof(WNDCLASSEX); (3 of 8) [7/8/2003 4:34:44 PM]
Tutorial: A Simple Window", (4 of 8) [7/8/2003 4:34:44 PM]
Tutorial: A Simple coordinates. Next ) { (5 of 8) [7/8/2003 4:34:44 PM]
Tutorial: A Simple Window.
Step 3: The Message Loop.
Step 4: the Window Procedure (6 of 8) [7/8/2003 4:34:44 PM]
Tutorial: A Simple Window
If the message loop is the heart of the program, the window procedure is the brain. This is where all the messages that are sent to our window get processed..
Step 5: There is no Step 5
Phew. Well that's it! If I haven't explained stuff clearly enough yet, just hang in there and hopefully things will become more clear as we get into more usefull programs. (7 of 8) [7/8/2003 4:34:44 PM]
Tutorial: A Simple Window
Copyright © 1998-2003, Brook Miles (theForger). All rights reserved. (8 of 8) [7/8/2003 4:34:44 PM]
Tutorial: Handling Messages
[ contents | #winprog ] respectively). If I or someone else refers to handling a message they mean to add it into the WndProc() of your window class as follows: (1 of 5) [7/8/2003 4:34:45 PM]
Tutorial: Handling Messages_PATH]; HINSTANCE hInstance = GetModuleHandle(NULL); (2 of 5) [7/8/2003 4:34:45 PM]
Tutorial: Handling Messages <windows.h> that is defined to the maximum length of a buffer needed to. (3 of 5) [7/8/2003 4:34:45 PM]
Tutorial: Handling Messages <windows.h>; wc.style wc.lpfnWndProc wc.cbClsExtra = = = = sizeof(WNDCLASSEX); 0; WndProc; 0; (4 of 5) [7/8/2003 4:34:45 PM]
Tutorial: Handling Messages
wc.cbWndExtra wc.hInstance wc.hIcon wc.hCursor wc.hbrBackground wc.lpszMenuName wc.lpszClassName wc.hIconSm
= = = = = = = =; }
Copyright © 1998-2003, Brook Miles (theForger). All rights reserved. (5 of 5) [7/8/2003 4:34:45 PM]
Tutorial: Understanding the Message Loop
[ contents | #winprog ]
Understanding the Message Loop
Understanding.
What is a Message?
A message is an integer value. If you look up in your header files (which is good and common practice when investigating the workings of API's) you can find things like: #define WM_INITDIALOG #define WM_COMMAND #define WM_LBUTTONDOWN 0x0110 0x0111 (1 of 4) [7/8/2003 4:34:45 PM]
Tutorial: Understanding the Message Loop.
Dialogs.
What is the Message Queue. (2 of 4) [7/8/2003 4:34:45 PM]
Tutorial: Understanding the Message Loop, (3 of 4) [7/8/2003 4:34:45 PM]
Tutorial: Understanding the Message Loop.
Copyright © 1998-2003, Brook Miles (theForger). All rights reserved. (4 of 4) [7/8/2003 4:34:45 PM]
Tutorial: Using Resources
[ contents | #winprog ]
Using Resources
You. (1 of 3) [7/8/2003 4:34:45 PM]
Tutorial: Using #define ID_FILE_EXIT 101)); The first parameter of LoadIcon() and many other resource using functions is the handle to the (2 of 3) [7/8/2003 4:34:45 PM]
Tutorial: Using Resources
current instance (which we are given in WinMain() and can also be retreived by using GetModuleHandle() as demonstrated in previous sections). The second is the identifier of the resource.. For example, this doesn't work for menu commands like ID_FILE_EXIT, since they can only be integers.
Copyright © 1998-2003, Brook Miles (theForger). All rights reserved. (3 of 3) [7/8/2003 4:34:45 PM]
Tutorial: Menus and Icons
[ contents | #winprog ]" (1 of 6) [7/8/2003 4:34:46 PM]
Tutorial: Menus and IconsICON));; (2 of 6) [7/8/2003 4:34:46 PM]
Tutorial: Menus and Icons; (3 of 6) [7/8/2003 4:34:46 PM]
Tutorial: Menus and Icons; (4 of 6) [7/8/2003 4:34:46 PM]
Tutorial: Menus and Icons message. (5 of 6) [7/8/2003 4:34:46 PM]
Tutorial: Menus and Icons
and assign it a very low ID... like 1. You don't even need to refer to the file in your program, and you can load completely different icons for your windows if you choose.
Copyright © 1998-2003, Brook Miles (theForger). All rights reserved. (6 of 6) [7/8/2003 4:34:46 PM]
Tutorial: Dialogs, GUI coders best friend
[ contents | #winprog ]. On this first line, IDD_ABOUTDLG is the id of the resource. DIALOG is the resource type, and the four (1 of 5) [7/8/2003 4:34:46 PM]
Tutorial: Dialogs, GUI coders best friend tells) (2 of 5) [7/8/2003 4:34:46 PM]
Tutorial: Dialogs, GUI coders best friend
{: { (3 of 5) [7/8/2003 4:34:46 PM]
Tutorial: Dialogs, GUI coders best friend is the id of the dialog resource. hwnd (4 of 5) [7/8/2003 4:34:46 PM]
Tutorial: Dialogs, GUI coders best friend.
Copyright © 1998-2003, Brook Miles (theForger). All rights reserved. (5 of 5) [7/8/2003 4:34:46 PM]
Tutorial: Modeless Dialogs
[ contents | #winprog ]); } (1 of 4) [7/8/2003 4:34:47 PM]
Tutorial: Modeless Dialogs
else { MessageBox(hwnd, "CreateDialog returned NULL", "Warning!", MB_OK | MB_ICONINFORMATION); }: (2 of 4) [7/8/2003 4:34:47 PM]
Tutorial: Modeless Dialogs. It's also worth noting that IsDialogMessage() can also be used with windows that aren't dialogs in order to to give them dialog-like behaviour. Remember, a dialog is a window, and most (if not all) dialog APIs will work on any window.. (3 of 4) [7/8/2003 4:34:47 PM]
Tutorial: Modeless Dialogs
Copyright © 1998-2003, Brook Miles (theForger). All rights reserved. (4 of 4) [7/8/2003 4:34:47 PM]
Standard Controls: Button, Edit, List Box, Static
[ contents | #winprog ]
Standard Controls: Button, Edit, List Box
Example:.
Controls
One thing to remember about controls is that they are just windows. Like any other window they have a window procedure, a window class etc... that is registered by the system. Anything you can do with a normal window you can do with a control.
Messages.
Edits
One of the most commonly used controls in the windows environment, the EDIT control, is used to allow the user to enter, modify, copy, etc... text. Windows Notepad is little more than a plain old window with a big edit control inside it. (1 of 5) [7/8/2003 4:34:47 PM]
Standard Controls: Button, Edit, List Box, Static? :) (2 of 5) [7/8/2003 4:34:47 PM]
Standard Controls: Button, Edit, List Box, Static.
Edits with Numbers).
List Boxes
Another handy control is the list box. This is the last standard control that I'm going to cover for now, cause frankly they aren't that interesting, and if you aren't bored yet well, I am :)
Adding Items style,, (3 of 5) [7/8/2003 4:34:47 PM]
Standard Controls: Button, Edit, List Box, Static
(LPARAM)nTimes);
Notifications;
Getting Data from the ListBox
Now that we know the selection has changed, or at the request of the user, we need to get the selection from the listbox and do something useful with it.. (4 of 5) [7/8/2003 4:34:47 PM]
Standard Controls: Button, Edit, List Box, Static););
Copyright © 1998-2003, Brook Miles (theForger). All rights reserved. (5 of 5) [7/8/2003 4:34:47 PM]
Tutorial: Dialog FAQ
[ contents | #winprog ]
Dialog FAQ
Example: dlg_three Now don't get me wrong, this is a Tutorial, not a Reference, but some questions people ask SO often that I figured I might as well include them here.
Changing Colours
In general, the only reason you'd want to do this is to simulate an link on a dialog box or some similar task, because otherwise you're probably just making your program ugly and hard on the eyes if you go adding a bunch of colors to the dialogs, but that doesn't stop people from doing it, and there are actually a few valid reasons, so here you go :); } (1 of 3) [7/8/2003 4:34:47 PM]
Tutorial: Dialog FAQ.
Giving the Dialog an Icon
A fairly simple task, you just need to send WM_SETICON to (2 of 3) [7/8/2003 4:34:47 PM]
Tutorial: Dialog FAQ
why the list doesn't show up when they run their program and click the little arrow. This is understandable, since the solution is not very intuitive...
Copyright © 1998-2003, Brook Miles (theForger). All rights reserved. (3 of 3) [7/8/2003 4:34:47 PM]
App Part 1: Creating controls at runtime
[ contents | #winprog ]
App Part 1: Creating controls at runtime
Example:, 101 (1 of 3) [7/8/2003 4:34:48 PM]
App Part 1: Creating controls at runtime
SWP_NOZORDER); } break;
Creating controls
Creating controls, like creating any other window, is done through the CreateWindowEx() API. We pass in preregistered., (2 of 3) [7/8/2003 4:34:48 PM]
App Part 1: Creating controls at runtime..
Copyright © 1998-2003, Brook Miles (theForger). All rights reserved. (3 of 3) [7/8/2003 4:34:48 PM]
App Part 2: Using files and the common dialogs
[ contents | #winprog ]
App Part 2: Using files and the common dialogs
Example: app_two
The Common File Dialogs. (1 of 5) [7/8/2003 4:34:48 PM]
App Part 2: Using files and the common dialogs: lStructSize Specifies the length, in bytes, of the structure..
Reading and Writing Files (2 of 5) [7/8/2003 4:34:48 PM]
App Part 2: Using files and the common dialogs.
Reading); } } (3 of 5) [7/8/2003 4:34:48 PM]
App Part 2: Using files and the common dialogs.
Writing; (4 of 5) [7/8/2003 4:34:48 PM]
App Part 2: Using files and the common dialogs.
Copyright © 1998-2003, Brook Miles (theForger). All rights reserved. (5 of 5) [7/8/2003 4:34:48 PM]
App Part 3: Tool and Status bars
[ contents | #winprog ]
App Part 3: Tool and Status bars
Example: app_three
An IMPORTANT Word on Common Controls.
Toolbars.
Toolbar buttons
Button bitmaps on basic toolbars come in two varieties, standard buttons that are provided by comctl32, and user defined buttons that you create yourself. NOTE: Buttons and bitmaps are added to toolbars seperately... first you add (1 of 4) [7/8/2003 4:34:49 PM]
App Part 3: Tool and Status bars. = tbb[1].fsState = tbb[1].fsStyle = tbb[1].idCommand tbb[2].iBitmap = tbb[2].fsState = tbb[2].fsStyle = tbb[2].idCommand STD_FILEOPEN; TBSTATE_ENABLED; TBSTYLE_BUTTON; = ID_FILE_OPEN; STD_FILESAVE; TBSTATE_ENABLED; TBSTYLE_BUTTON; =. (2 of 4) [7/8/2003 4:34:49 PM]
App Part 3: Tool and Status bars.
Status bars
Something often found in apps with toolbars are status bars, the little things at the bottom of the window that display information. They're pretty simple to use, just create... to.
Proper Sizing
Unlike menus, tool and status bars are seperate controls that live inside the parent window's client area. Therefor if we just leave our WM_SIZE code; (3 of 4) [7/8/2003 4:34:49 PM]
App Part 3: Tool and Status bars).
Copyright © 1998-2003, Brook Miles (theForger). All rights reserved. (4 of 4) [7/8/2003 4:34:49 PM]
App Part 4: Multiple Document Interface
[ contents | #winprog ]: (1 of 9) [7/8/2003 4:34:50 PM]
App Part 4: Multiple Document Interface; (2 of 9) [7/8/2003 4:34:50 PM]
App Part 4: Multiple Document InterfaceSCROLL | commands (3 of 9) [7/8/2003 4:34:50 PM]
App Part 4: Multiple Document Interface) { = = = = = = = = = sizeof(WNDCLASSEX); CS_HREDRAW | CS_VREDRAW; MDIChildWndProc; 0; 0; hInstance; LoadIcon(NULL, IDI_APPLICATION); LoadCursor(NULL, IDC_ARROW); (HBRUSH)(COLOR_3DFACE+1); (4 of 9) [7/8/2003 4:34:50 PM]
App Part 4: Multiple Document Interface, (5 of 9) [7/8/2003 4:34:50 PM]
App Part 4: Multiple Document Interface_MDIACTIVATE: { HMENU hMenu, hFileMenu; UINT EnableFlag; hMenu = GetMenu(g_hMainWindow); if(hwnd == (HWND)lParam) { /); (6 of 9) [7/8/2003 4:34:50 PM]
App Part 4: Multiple Document Interface) (7 of 9) [7/8/2003 4:34:50 PM]
App Part 4: Multiple Document Interface
{: (8 of 9) [7/8/2003 4:34:50 PM]
App Part 4: Multiple Document Interface;
Copyright © 1998-2003, Brook Miles (theForger). All rights reserved. (9 of 9) [7/8/2003 4:34:50 PM]
Bitmaps, Device Contexts and BitBlt
[ contents | #winprog ]
Bitmaps, Device Contexts and BitBlt
Example: bmp_one
GDI.
Device Contexts.
Bitmaps
Bitmaps can be loaded much like icons in earlier examples, there is LoadBitmap() for the most basic functionality of simply loading a bitmap resource, and LoadImage() can be used to load bitmaps from a *.bmp file (1 of 5) [7/8/2003 4:34:50 PM]
Bitmaps, Device Contexts and BitBlt.
GDI Leaks.
Displaying Bitmaps (2 of 5) [7/8/2003 4:34:50 PM]
Bitmaps, Device Contexts and BitBlt;
Getting the Window DC (3 of 5) [7/8/2003 4:34:50 PM]
Bitmaps, Device Contexts and BitBlt.
Setting up a Memory DC for the Bitmap.
Drawing.
Cleanup (4 of 5) [7/8/2003 4:34:50 PM]
Bitmaps, Device Contexts and BitBlt
you got it in the first place. Here's a list of the common methods of gaining an HDC, and how to release it when you're done.
q q q
GetDC() - ReleaseDC() BeginPaint() - EndPaint() CreateCompatibleDC() - DeleteDC();
Copyright © 1998-2003, Brook Miles (theForger). All rights reserved. (5 of 5) [7/8/2003 4:34:50 PM]
Transparent Bitmaps
[ contents | #winprog ]
Transparent Bitmaps
Example: bmp_two
Transparency
Giving bitmaps the appearance of having transparent sections is quite simple, and involves the use of a black and white Mask image in addition to the colour image that we want to look transparent..
BitBlt operations...
q
q (1 of 5) [7/8/2003 4:34:51 PM]
Transparent Bitmaps
way involves from BitBlt() trickery, and so I will show one way of accomplishing this.
Mask Creation); (2 of 5) [7/8/2003 4:34:51 PM]
Transparent BitmapsDC at a time, so make sure the bitmap isn't selected in to another HDC when. (3 of 5) [7/8/2003 4:34:51 PM]
Transparent Bitmaps
How does all this work?
.. you may be asking. Well hopefully your experience with C or C++.
SRCAND
The SRCAND r
SRCPAINT uses.
SRCINVERT
This is the XOR operation.
Example (4 of 5) [7/8/2003 4:34:51 PM]
Transparent Bitmaps-2003, Brook Miles (theForger). All rights reserved. (5 of 5) [7/8/2003 4:34:51 PM]
Timers and Animation
[ contents | #winprog ]. { int int int int struct _BALLINFO width; height; x;)); (1 of 5) [7/8/2003 4:34:51 PM]
Timers and Animation.
Setting the Timer
The easiest way to add a simple timer into a window program is with handler of our main window. Each time the timer elapses, it will send a WM_TIMER message.
Animating in WM_TIMER
Now when we get WM_TIMER we); (2 of 5) [7/8/2003 4:34:51 PM]
Timers and Animation
}); (3 of 5) [7/8/2003 4:34:51 PM]
Timers and AnimationINFO structure. There is however one important difference...
Double Buffering
When doing your drawing directly to the HDC of instead of hdc (the window) and the results are stored on the bitmap in memory untill we are complete. We can now copy the whole thing over to the window in one shot. (4 of 5) [7/8/2003 4:34:51 PM]
Timers and Animation);
Copyright © 1998-2003, Brook Miles (theForger). All rights reserved. (5 of 5) [7/8/2003 4:34:51 PM]
Text and Fonts
[ contents | #winprog ]
Text and Fonts
Example: font_one
The Win32 GDI has some remarkable capabilites for dealing with vastly different typefaces, styles, languages and characters sets. One of the drawbacks of this is that dealing with fonts can look rather intimidating to the newcomer. CreateFont(), the primary API when it comes to fonts, has 14 parameters for specifying height, style, weight, family, and various other attributes. Fortunately, it's not really has hard as it might appear, and a large portion of the work involved is taken care of my sensible default values. All but 2 of the parameters to CreateFont() can be set to 0 or NULL, and the system will simply use a default value giving you a plain ordinary font. CreateFont() creates an HFONT, a handle to a Logical Font in memory. The data held by this handle can be retreived into a LOGFONT structure using GetObject() just as a BITMAP struct can be filled from an HBITMAP. The members of the LOGFONT are identical to the parameters to CreateFont() and for convenience you can create a font directly from an existing LOGFONT structure using CreateFontIndirect(). This is very handy, since it makes it simple to create a new font from an existing font handle when you only want to alter certain aspects of it. Use GetObject() to fill a LOGFONT, alter the members that you wish, and create a new font with CreateFontIndirect(). HFONT hf; HDC hdc; long lfHeight; hdc = GetDC(NULL); lfHeight = -MulDiv(12, GetDeviceCaps(hdc, LOGPIXELSY), 72); ReleaseDC(NULL, hdc); hf = CreateFont(lfHeight, 0, 0, 0, 0, TRUE, 0, 0, 0, 0, 0, 0, 0, "Times New Roman"); if(hf) { DeleteObject(g_hfFont); g_hfFont = hf; } else { (1 of 6) [7/8/2003 4:34:52 PM]
Text and Fonts
MessageBox(hwnd, "Font creation failed!", "Error", MB_OK | MB_ICONEXCLAMATION); } This is the code used to create the font in the example image. This is Times New Roman at 12 Point with the Italics style set. The italics flag is the 6th parameter to CreateFont() which you can see we have set to TRUE. The name of the font we want to use is the last parameter. The one bit of trickery in this code is the value used for the size of the font, the lfHeight parameter to CreateFont(). Usually people are used to working with Point sizes, Size 10, Size 12, etc... when dealing with fonts. CreateFont() however doesn't accept point sizes, it wants Logical Units which are different on your screen than they are on your Printer, and even between Printers and screens. The reason this situation exists is because the resolution of different devices is so vastly different... Printers can easily display 600 to 1200 pixels per inch, while a screen is lucky to get 200... if you used the same sized font on a printer as on a screen, you likely wouldn't even be able to see individual letters. All we have to do is convert from the point size we want, into the appropriate logical size for the device. In this case the device is the screen, so we get the HDC to the screen, and get the number of logical pixels per inch using GetDeviceCaps() and slap this into the formula so generously provided in MSDN which uses MulDiv() to convert from our pointsize of 12 to the correct logical size that CreateFont() expects. We store this in lfHeight and pass it as the first parameter to CreateFont().
Default Fonts
When you first call GetDC() to get the HDC to your window, the default font that is selected into it is System, which to be honest isn't all that attractive. The simplest way to get a reasonable looking font to work with (without going through the CreateFont() hassle) is to call GetStockObject() and ask for the DEFAULT_GUI_FONT. This is a system object and you can get it as many times as you want without leaking memory, and you can call DeleteObject() on it which won't do anything, which is good because now you don't need to keep track of whether your font is one from CreateFont() or GetStockObject() before trying to free it.
Drawing Text
Now that we have a handy-dandy font, how do we get some text on the screen? This is assuming that we don't just want to use an Edit or Static control. Your basic options are TextOut() and DrawText(). TextOut() is simpler, but has less options and doesn't do word wrapping or alignment for you. char szSize[100]; char szTitle[] = "These are the dimensions of your client area:"; HFONT hfOld = SelectObject(hdc, hf); SetBkColor(hdc, g_rgbBackground); SetTextColor(hdc, g_rgbText); (2 of 6) [7/8/2003 4:34:52 PM]
Text and Fonts
if(g_bOpaque) { SetBkMode(hdc, OPAQUE); } else { SetBkMode(hdc, TRANSPARENT); } DrawText(hdc, szTitle, -1, prc, DT_WORDBREAK); wsprintf(szSize, "{%d, %d, %d, %d}", prc->left, prc->top, prc->right, prc>bottom); DrawText(hdc, szSize, -1, prc, DT_SINGLELINE | DT_CENTER | DT_VCENTER); SelectObject(hdc, hfOld); First thing we do is use SelectObject() to get the font we want to use into our HDC and ready for drawing. All future text operations will use this font untill another one is selected in. Next we set the Text and Background colours. Setting the background colour doesn't actually make the whole background this colour, it only affects certain operations (text being one of them) that use the background colour to draw with. This is also dependant on the current Background Mode. If it is set to OPAQUE (the default) then any text drawn is filled in behing with the background colour. If it is set to TRANSPARENT then text is drawn without a background and whatever is behind will show through and in this case the background colour has no effect. Now we actually draw the text using DrawText(), we pass in the HDC to use and the string to draw. The 3rd parameter is the length of the string, but we've passed -1 because DrawText() is smart enough that it will figure out how long the text is itself. In the 4th parameter we pass in prc, the pointer to the client RECT. DrawText() will draw inside this rectangle based on the other flags that you give it. In the first call, we specify DT_WORDBREAK, which defaults to aligned to the top left, and will wrap the text it draws automatically at the edge of the rectangle... very useful. For the second call, we're only printing a single line without wrapping, and we want it to be centered horizontally as well as vertically (which DrawText() will do only when drawing a single line).
Client Redraw
Just a note about the example program... when the WNDCLASS is registered I have set the CS_VREDRAW and CS_HREDRAW class styles. This causes the entire client area to be redrawn if the window is resized, whereas the default is to only redraw the parts that have changed. That looks really bad since the centered text moves around when you resize and it doesn't update like you'd expect.
Choosing Fonts
In general, any program that deals with fonts will want to let the user choose their own font, as well as the colour and (3 of 6) [7/8/2003 4:34:52 PM]
Text and Fonts
style attribute to use when displaying it. Like the common dialogs for getting open and save file names, there is a common dialog for choosing a font. This is, oddly enough, called ChooseFont() and it works with the CHOOSEFONT structure for you to set the defaults it should start with as well as returning the final result of the users selection. HFONT g_hfFont = GetStockObject(DEFAULT_GUI_FONT); COLORREF g_rgbText = RGB(0, 0, 0); void DoSelectFont(HWND hwnd) { CHOOSEFONT cf = {sizeof(CHOOSEFONT)}; LOGFONT lf; GetObject(g_hfFont, sizeof(LOGFONT), &lf); cf.Flags = CF_EFFECTS | CF_INITTOLOGFONTSTRUCT | CF_SCREENFONTS; cf.hwndOwner = hwnd; cf.lpLogFont = &lf; cf.rgbColors = g_rgbText; if(ChooseFont(&cf)) { HFONT hf = CreateFontIndirect(&lf); if(hf) { g_hfFont = hf; } else { MessageBox(hwnd, "Font creation failed!", "Error", MB_OK | MB_ICONEXCLAMATION); } g_rgbText = cf.rgbColors; } } The hwnd in this call is simply the window you want to use as the parent for the font dialog. The easiest way to use this dialog is in conjunction with an existing LOGFONT structure, which is most likely from whichever HFONT you are currently using. We set the lpLogFont member of the structure to point to the LOGFONT that we just filled with our current information and also added the CF_INITTOLOGFONTSTRUCT flag so that ChooseFont() knows to use this member. The flag CF_EFFECTS tells ChooseFont() to allow the user to select a colour, as well as Underline and Strikeout attributes. Oddly enough, the Bold and Italics styles don't count as effects, they are considered part of the font itself and in fact some fonts only come in Bold or Italics. If you want to check or prevent the user from selecting a bold or italic font you can check the lfWeight and lfItalic members of the LOGFONT respectively, after the user has made their (4 of 6) [7/8/2003 4:34:52 PM]
Text and Fonts
selection. You can then prompt the user to make another selection or something change the members before calling CreateFontIndirect(). The colour of a font is not associated with an HFONT, and therefor must be stored seperately, the rgbColors member of the CHOOSEFONT struct is used both to pass in the initial colour and retreive the new colour afterward. CF_SCREENFONTS indicates that we want fonts designed to work on the screen, as opposed to fonts that are designed for printers. Some support both, some only one or the other. Depending on what you're going to be using the font for, this and many other flags can be found in MSDN to limit exactly which fonts you want the user to be able to select.
Choosing Colours
In order to allow the user to change just the colour of the font, or to let them pick a new colour for anything at all, there is the ChooseColor() common dialog. This is the code used to allow the user to select the background colour in the example program. COLORREF g_rgbBackground = RGB(255, 255, 255); COLORREF g_rgbCustom[16] = {0}; void DoSelectColour(HWND hwnd) { CHOOSECOLOR cc = {sizeof(CHOOSECOLOR)}; cc.Flags = CC_RGBINIT | CC_FULLOPEN | CC_ANYCOLOR; cc.hwndOwner = hwnd; cc.rgbResult = g_rgbBackground; cc.lpCustColors = g_rgbCustom; if(ChooseColor(&cc)) { g_rgbBackground = cc.rgbResult; } } This is fairly straightforward, again we're using the hwnd parameter as the parent to the dialog. The CC_RGBINIT parameter says to start off with the colour we pass in through the rgbResult member, which is also where we get the colour the user selected when the dialog closes. The g_rgbCustom array of 16 COLORREFs is required to store any values the user decides to put into the custom colour table on the dialog. You could potentially store these values somewhere like the registry, otherwise they will simply be lost when your program is closed. This parameter is not optional.
Control Fonts
Something else you might want to do at some point is change the font on the controls on your dialog or window. This is usually the case when using CreateWindow() to create controls as we've done in previous examples. Controls (5 of 6) [7/8/2003 4:34:52 PM]
Text and Fonts
like windows use System by default, so we used WM_SETFONT to set a new font handle (from GetStockObject()) for the control to use. You can use this method with fonts you create from CreateFont() as well. Simply pass the font handle as wParam and set lParam to TRUE to make the control redraw. I've done this in previous examples, but it makes sense to mention it here because it's relevant and very short: SendDlgItemMessage(hwnd, IDC_OF_YOUR_CONTROL, WM_SETFONT, (WPARAM)hfFont, TRUE); Where hfFont is of course the HFONT you want to use, and IDC_OF_YOUR_CONTROL is the ID of whichever control you want to change the font of.
Copyright © 1998-2003, Brook Miles (theForger). All rights reserved. (6 of 6) [7/8/2003 4:34:52 PM]
Win32 Tutorial - Recommended Books and References
[ contents | #winprog ]
Recommended Books. You can find more recommended books and links to buy at the #Winprog Store.. (1 of 2) [7/8/2003 4:34:52 PM]
Win32 Tutorial - Recommended Books and References FAQ and Store
Copyright © 1998-2003, Brook Miles (theForger). All rights reserved. (2 of 2) [7/8/2003 4:34:52 PM]
[ contents | #winprog ]
Free Visual C++ Command Line Tools
Getting Them
Microsoft has quietly released it's command line compiler and linker tools as part of the .NET Framework SDK. The Framework SDK comes with everything you need to for .NET development (C# compiler etc...) including the command line compiler cl.exe which,.
Using Them
Since comprehensive documentation is provided, and also accessable at MSDN online, you'll need to RTFM yourself to learn about the VC++ compiler and tools. To get you started, here are the most basic ways to build a program... To build a simple console application: (1 of 2) [7/8/2003 4:34:52 PM]
cl foo.c To build a simple windows application such as the examples on this tutorial: rc dlg_one.rc cl dlg_one.c dlg_one.res user32.lib
Copyright © 1998-2003, Brook Miles (theForger). All rights reserved. (2 of 2) [7/8/2003 4:34:52 PM]
Win32 Tutorial - Free Borland C++ Command Line Tools
[ contents | #winprog ] (1 of 4) [7/8/2003 4:34:53 PM]
Win32 Tutorial - Free Borland C++ Command Line Tools. (2 of 4) [7/8/2003 4:34:53 PM]
Win32 Tutorial - Free Borland C++ Command Line Tools
bcc32 -c -tW dlg_one.c ilink32 -aa -c -x -Gn dlg_one.obj c0w32.obj,dlg_one.exe,,import32.lib cw32.lib,,dlg_one.res Nice EXEFILE OBJFILES RESFILES LIBFILES DEFFILE = = = = = = dlg_one $(APP).exe $(APP).obj $(APP).res
.AUTODEPEND BCC32 = bcc32 ILINK32 = ilink32 BRC32 = brc32 CFLAGS LFLAGS RFLAGS STDOBJS STDLIBS = = = = = -c -tWM- -w -w-par -w-inl -W -a1 -Od -aa -V4.0 -c -x -Gn -X -R c0w32.obj import32.lib cw32.lib
$(EXEFILE) : $(OBJFILES) $(RESFILES) $(ILINK32) $(LFLAGS) $(OBJFILES) $(STDOBJS), $(EXEFILE), , \ $(LIBFILES) $(STDLIBS), $(DEFFILE), $(RESFILES) clean: del *.obj *.res *.tds *.map You only need to modify the first 6 lines with the appropriate information. (3 of 4) [7/8/2003 4:34:53 PM]
Win32 Tutorial - Free Borland C++ Command Line Tools
Copyright © 1998-2003, Brook Miles (theForger). All rights reserved. (4 of 4) [7/8/2003 4:34:53 PM]
Win32 Tutorial - Solutions to Common Errors
[ contents | #winprog ]
Solutions to Common Errors
q q q q q
Error LNK2001: unresolved external symbol _main Error C2440: cannot convert from 'void*' to 'HICON__ *' (or similar) Fatal error RC1015: cannot open include file 'afxres.h' Error LNK2001: unresolved external symbol InitCommonControls Dialog does not display when certain controls are added
Error LNK2001: unresolved external symbol _main
An unresolved external occurs when some code has a call to a function in another module and the linker can't find that function in any of the modules or libraries that you are currently linking to. In this specific case, it means one of two things. Either you are trying to write a Win32 GUI application (or nonconsole.
Fixing
If you're using VC++ re-create your project and select the Win32 Application project type (NOT "Console"). If you're using BC++ command line compiler, use -tW to specify a windows application.
Error C2440: cannot convert from 'void*' to 'HICON__ *' (or similar)
If you're compiling the code from this tutorial, it means that you are trying to compile it as C++ code. The code is written for the bcc32 and VC++ C compilers, and as such may not compile exactly the same under C++ since C++ has much stricter rules about converting types. C will just let it happen, C++ wants to you to make it explicit.. (1 of 3) [7/8/2003 4:34:53 PM]
Win32 Tutorial - Solutions to Common Errors.
Fixing
If you want to use C, simply rename your file from .cpp to .c. Otherwise, simply add a cast, all of the code in the tutorial will work without any other changes when compiled as C++. For example, in C this will work: HBITMAP hbmOldBuffer = SelectObject(hdcBuffer, hbmBuffer); But in C++ requires a cast: HBITMAP hbmOldBuffer = (HBITMAP)SelectObject(hdcBuffer, hbmBuffer);
Fatal error RC1015: cannot open include file 'afxres.h'.
Oddly enough, VC++ adds afxres.h to).
Error LNK2001: unresolved external symbol InitCommonControls
You aren't linking to comctl32.lib which this API is defined in. This library is not included by default so you will either need to add it to the libraries on your command line, or add it in your VC++ project settings on the Link tab.
Dialog does not display when certain controls are added
Controls such as the ListView, TreeView, Hotkey, Progress Bar, and others are classified as Common Controls, as they were added to windows in comctl32.dll and were not available prior to Windows 95. Controls such as BUTTON, EDIT, LISTBOX, etc... while no doubt being common, are not "Common Controls" and I generally refer to them as "Standard Controls".. (2 of 3) [7/8/2003 4:34:53 PM]
Win32 Tutorial - Solutions to Common Errors
Some people and documentation may tell you that InitCommonControls() is deprecated and you should use InitCommonControlsEx(). Feel free to do this if you want, InitCommonControls() is just simpler and there's nothing wrong with using it.
Copyright © 1998-2003, Brook Miles (theForger). All rights reserved. (3 of 3) [7/8/2003 4:34:53 PM]
[ contents | #winprog ]:
q q q q q q q q q. (1 of 3) [7/8/2003 4:34:53 PM].
So basically... (2 of 3) [7/8/2003 4:34:53 PM]
What it comes down to is that I think you should learn the API untill you feel comfortable with it, and then try out MFC. If it seems like it's making sense to you and saving you time, then by all means use it..
Copyright © 1998-2003, Brook Miles (theForger). All rights reserved. (3 of 3) [7/8/2003 4:34:53 PM]
Win32 Tutorial - Resource file notes
[ contents | #winprog ] (1 of 2) [7/8/2003 4:34:53 PM]
Win32 Tutorial - Resource file notes
each .rc file that is generated to include the following: #ifndef __BORLANDC__ #include "winres.h" #endif Which. BC++ compiler in Free Borland C++ Command Line Tools.
Copyright © 1998-2003, Brook Miles (theForger). All rights reserved. (2 of 2) [7/8/2003 4:34:53 PM]
This action might not be possible to undo. Are you sure you want to continue?
We've moved you to where you read on your other device.
Get the full title to continue reading from where you left off, or restart the preview.
|
https://www.scribd.com/doc/7541745/Forgers-Win32-Tutorial
|
CC-MAIN-2017-04
|
refinedweb
| 6,519
| 62.27
|
By now, you’ve probably heard that C# 4.0 is adding support for the dynamic keyword, which introduces some aspects of dynamic languages to C#. I had not had a chance to really try it, but recently I was reading Bertrand Le Roy’s post on the topic, and was sort of looking for a good opportunity to use it.
Today, I found a scenario which I thought it would work great for, but it turned out not to be supported out of the box!
The scenario is to call static class members using dynamic. That probably sounds crazy, so let’s look at an example. Say you have these two classes:
public class Foo1 { public static string TransformString(string s) { return s.ToLower(); } public static string MyConstant { get { return "Constant from Foo1"; } } } public class Foo2 { public static string TransformString(string s) { return s.ToUpper(); } public static string MyConstant { get { return "Constant from Foo2"; } } }
Note that they are unrelated classes, but share some members with the same signature. In a sense, you could say that they two classes share a duck type signature.
Now here is the problem we’re trying to solve: given a System.Type object of either class (or any other random class that shares those members), how can you call those members? Concretely, we’re trying to implement this method:
static void MakeTestCalls(Type type) { // Call TransformString("Hello World") on this type // Get the MyConstant property on this type }
How can we implement this method? Ok, we can do it the old fashion way using reflection, e.g.
static void MakeTestCalls(Type type) { Console.WriteLine(type.GetMethod("TransformString").Invoke(null, new object[] { "Hello World" })); Console.WriteLine(type.GetProperty("MyConstant").GetValue(null, null)); }
That works, but it’s ugly. These are the very type of things that dynamic is supposed to improve. So my first naive attempt was to do this:
static void MakeTestCalls(Type type) { dynamic fooTypeDynamic = type; Console.WriteLine(fooTypeDynamic.TransformString("Hello World")); Console.WriteLine(fooTypeDynamic.MyConstant); }
Basically, the theory was that when assigning a System.Type to a dynamic variable, it would let you call static members from it. I didn’t really expect it to work, but I at least had to try! 🙂 And sure enough, it didn’t work, blowing up with: “Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'System.RuntimeType' does not contain a definition for 'TransformString'”.
So I then posted the question on our internal C# list, and got a reply from C# guru Eric Lippert, basically saying that it was a potentially interesting idea but was just not supported in C# 4.0. Fair enough, this is only the beginning of C# dynamic, and it doesn’t do everything.
But I then went back to Bertrand’s post where he gives a great sample of how you can teach dymamic new tricks by implementing a custom DynamicObject. And it turned out to be relative simple. Here is the class I ended up with:
public class StaticMembersDynamicWrapper : DynamicObject { private Type _type; public StaticMembersDynamicWrapper(Type type) { _type = type; } // Handle static properties public override bool TryGetMember(GetMemberBinder binder, out object result) { PropertyInfo prop = _type.GetProperty(binder.Name, BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.Public); if (prop == null) { result = null; return false; } result = prop.GetValue(null, null); return true; } // Handle static methods public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { MethodInfo method = _type.GetMethod(binder.Name, BindingFlags.FlattenHierarchy | BindingFlags.Static | BindingFlags.Public); if (method == null) { result = null; return false; } result = method.Invoke(null, args); return true; } }
The idea is pretty simple: when the runtime needs to call something, it basically asks you to do it. It passes you the method (or property) name and the parameters, and you take it from there. And in this case, of course, we’re using reflection.
Once we have that, the real fun starts as we’re now able to call our static members using dynamic!
static void MakeTestCalls(Type type) { dynamic typeDynamic = new StaticMembersDynamicWrapper(type); // Call TransformString("Hello World") on this type Console.WriteLine(typeDynamic.TransformString("Hello World")); // Get the MyConstant property on this type Console.WriteLine(typeDynamic.MyConstant); }
Note how we wrap the type into our custom DynamicObject is order to have the dynamic invocations go through us.
Now you might say that the scenario above where you have two classes with identical static members doesn’t seem like something that would actually occur commonly in real apps. But once you start bringing in generics, it can actually be more common. e.g. suppose you have something like:
public class Table<T> { public static IEnumerable<T> Records { get { [return records from database table T] } } }
The idea is that the class is an abstraction for a database table. So Table<Product>.Records returns an IEnumerable<Products>, and Table<Category>.Records returns an IEnumerable<Category>. Now suppose you’re writing some table agnostic code that can work with the data from any table. You have a System.Type for some Table<T>, and you need to get its Records property. Even though it seems like it’s the same Records property coming for a base class, the reality is that it’s a completely different property for each T, and C# provides no simple way of making the call. But with the technique above, you get to access the property with a much simpler syntax than with reflection.
The zipped sample is attached to this post.
DynamicCallsToStaticMembers.zip
it seems like a ordinary case to me…
Nice idea – thank you for the sample.
But can’t the same be accomplished with delegates / interfaces ?
Besides that the dynamic binding seems to have a high runtime overhead, compared to delegates.
Andre
O.k. tried it.
No (simple) way to bind a delegate dynamically to an unknown types function without using reflections invoke – I’m still too much influenced by C++ template binding possibilites 😉
So your sample is the only way to accomplish that in C# for generic types (easily).
A cool method for generic static calls, where the overhead is negligible. Although I still would prefer static bindings over dynamic ones, to catch most of the bugs at compilation time.
Andre
@Andre: I’m with you on favoring static bindings whenever possible. But for cases where they’re not easily possible, ‘dynamic’ offers a cleaner syntax than its alternatives.
I can see this being useful when you’re "duct-taping" classes in 3rd party libraries… however, if you own the classes, I would prefer the use of interfaces (as both you and Andre already mentioned).
Interesting read, nonetheless 🙂 Thanks
Hy
Thanks for this insight. Although I’m a bit skeptic about the over usage of dynamic keyword. I also prefer the usage of a strict and strongly typed domain over the dynamic approach. In my point of view the dynamic approach should only be used in rare cases because actually during design time you have no guarantee that what your are coding is semantically correct and you get the surprises when you are executing your program.
Daniel
dynamic call, quite cool feature!
Coincidence, three days ago I posted a ‘proposal’ (nothing official here…) for static interface to resolve this kind of thing in C#.
You can read it here :
and here
Hi,
It’s like Jayson says it’s nice for "duct-taping" 3rd party libraries.
It saved my day! 🙂
@Jérémie: the idea of static interfaces is potentially interesting. One different is that in your case, you have T has a generic type param (as in IsInstanciated<T>() where T: ICountable). But how would you ‘cast’ to this interface if all you had was a System.Type, in a really late bound scenario?
Nice work, this is useful, however there are two problems with your approach:
1) no handling of overloaded methods
2) incorrect handling of optional/named parameters
I can’t post the code here (in the comments since it would look terrible), but I was able modify the code to check the Binder and get the Parameters for the methods of the type to correctly handle the two issues above.
Thanks for the headstart!
@David Kujawski: indeed, my code above is just a proof of concept and doesn’t deal with cases like method overloading. Thanks for pointing this out!
This is a nice in that it is an easy to follow example of using the DynamicObject class, but…
Even in the case where you are forced to rely on 3rd party libraries that are exposing the functionality you need as static methods, you should be able to wrap that functionality inside your own classes and then have them implement a common interface. Therefore I am skeptical about whether the above approach is actually something you would ever want to do.
Thanks for this. You can take it a step further with extension methods:
<code>
static readonly Dictionary<Type, StaticMembersDynamicWrapper> _typeLookup = new Dictionary<Type, StaticMembersDynamicWrapper>();
public static dynamic StaticMembersProxy(this Type type)
{
StaticMembersDynamicWrapper smdw;
if (!_typeLookup.TryGetValue(type, out smdw))
_typeLookup[type] = smdw = new StaticMembersDynamicWrapper(type);
return smdw;
}
</code>
@Stephen: agreed, that’s a nice little addition.
This could've been great for the various .Parse method overloads that the primitive BCL types provide (The Convert class doesn't solve everything.)
With some help, worked out a way to access the constant fields too:
stackoverflow.com/…/accessing-constants-with-a-dynamic-keyword
|
https://blogs.msdn.microsoft.com/davidebb/2009/10/23/using-c-dynamic-to-call-static-members/
|
CC-MAIN-2019-26
|
refinedweb
| 1,555
| 54.22
|
Python vs Parrot.
Example
A simple example, incrementing
a in Python:
LOAD_FAST a LOAD_CONST 1 BINARY_ADD STORE_FAST a
And in Parrot:
find_lex P1, a add P1, P1, 1
The first difference you may notice is that Python is stack
based, and Parrot is register based; but the difference I want to
focus on is the add operation itself. In Python, the
BINARY_ADD operation is generic and can handle everything from
integers to floating point to strings. For this to work, the
numeric
1 must first be converted to an object (a
process often referred to as boxing) pushed on the stack.
BINARY_ADD will then pull two objects off of the stack, unboxing as
appropriate, do the appropriate operation, box up the results, and
then push it back on the stack.
In Parrot, the boxing and unboxing is deferred... there is a separate and unique opcode for adding an integer to an object (a.k.a. PMC). This is in addition to opcodes that add floating point numbers to an object, adding an integer to an integer, an object to an object, etc. This requires more special cases to be handled, but the payoff is that with this additional development work, runtime work can be eliminated. In this case, all of the boxing and unboxing can be avoided.
In absolute terms, boxing and unboxing is not very expensive. But in relative terms (and in this case, what it is to be compared against is simple integer addition), it can be very significant.
With the way Parrot is structured, much of the development
overhead can be eliminated. Not every object class that
wishes to provide an add operator needs to implement an
add_int method. By using a common base class, a
generic
add_int method can be provided that boxes up
the int and calls a single
add method designed to work
on objects. Such a technique allows subclasses for which
add_int is a common enough operation worthy of
optimization to do so directly, without burdening all other
subclasses with the need to do so.
Goals
The first goal of a Python on Parrot implementation needs to be fidelity to CPython implementation. Otherwise, you are simply implementing a Python-like language on top of another runtime. Such a language would not be able to make use of the full range of existing Python libraries and scripts.
However, that goal, by itself, is insufficient. There already is a CPython implementation. Potential secondary goals include better performance and better integration with other languages. Both of those goals ultimately require some trade-offs to be made with respect to the first goal.
Most of the performance trade-offs can be made without compromise to functionality. Best cases are when common scenarios are made significantly faster at an marginal expense to less common scenarios.
The integration scenarios are trickier. Perl's integer divide has different semantics than Python's, particularly for negative numbers. What does dividing a Perl integer by a Python integer mean? If two Perl integers are passed to a Python function which attempts to divide them, what should be done?
The same operation that does a binary arithmetic also does string concatenation in Python.
These are admittedly edge cases. But such edge cases
abound. Python has a
dict as a fundamental data
type. Perl has a
hash. Keys of Python
dictionaries can be any immutable value. Keys of Perl5 hashes
can only be strings. More significantly is the impact of
Duck
Typing. If somebody passes a Perl hash to a Python
function, the Python function expects there to be a
fair number
of methods at its disposal. How much of this can be
papered over, and how much of this will show through is still a
research topic at the moment.
Fundamentals
To date, I've found a number of areas that are more fundamentally different between Python and Parrot than any of the examples above. The two implementations of Python on Parrot that I have looked at, namely pie-thon and pirate, approach these differently.
The first deals with the extent of the Python canonicalization mentioned above. In Parrot, instances may have properties, methods, and attributes. In Python, there are only attributes. This is possible as functions, methods, and even classes are also objects in Python, so each are possible values for a given attribute.
In the pie-thon implementation of Python on Parrot, all methods are attributes. In Pirate, all methods are properties. The implication being that from the perspective of a language like Perl, such Python objects will have no methods defined.
This can be dealt with by implementing a
find_method method in PyClass that searches first the
set of methods, and then the attributes/properties.
More troublesome is the issue of naming. In Parrot, the presumption is that all subroutines and classes are globally named. In Python, such names are lexically scoped. It is quite legal to have multiple methods in the same scope with the same name, in fact, the syntax to define a class in Python really only creates an anonymous class object and assigns it to a (lexically scoped) variable. The only names that are global in Python are module names. Modules in Python are used to address much the same types of problems that namespaces do in Parrot, but again, are fundamentally different.
Here's an example that can't be handled by pie-thon currently:
def f(x): class c: def m(SELF): return 0 if x<0: class c: def m(SELF): return -1 if x>0: class c: def m(SELF): return +1 return c() print f(7).m(), f(0).m(), f(-7).m()
But even that can be largely masked by clever compilers. Pirate addresses this with a bit of name mangling.
A difference that can't be masked at all is a difference that
isn't there. In Python there is no vocabulary for "new-ing"
up an instance of a class. Instead, the
__call__
method on the class is expected to act like a factory. Non
python libraries will either be required to mimic this behavior, or
an alternate syntax (perhaps a
Parrot module which
exports a
new function) will need to be provided.
Status and Plans
Michal Wallace has given me commit access to Pirate, and I've made a number of small fixes. But mostly, I've been holding back until I can get a new set of python specific classes implemented and committed.
Leopold Tötsch has been committing (most of) my patches to Parrot, and now I am ready to have a largish one committed. It is mostly new Python specific dynclass sources, with some small mods to the system to make it work. Once that is committed, I'll update Pirate, and both will once again pass all defined tests.
At that point, I plan to do two activities. One is to refactor as much of the existing logic in Pirate into Parrot dynclasses as possible. The other is to expand the test suite and use that to drive the addition of new functionality. Two sources of tests will be the parrotbench and the CPython unit test suite.
|
http://www.intertwingly.net/blog/2004/11/09/Python-vs-Parrot
|
CC-MAIN-2017-47
|
refinedweb
| 1,193
| 63.29
|
symlink(2) BSD System Calls Manual symlink(2)
NAME
symlink -- make symbolic link to a file
SYNOPSIS
#include <unistd.h> int symlink(const char *path1, const char *path2);
DESCRIPTION
A symbolic link path2 is created to path1 (path2 is the name of the file created, path1 is the string used in creating the symbolic link). Either name may be an arbitrary path name; the files need not be on the same file system.
RETURN VALUES
Upon successful completion, a zero value is returned. If an error occurs, the error code is stored in errno and a -1 value is returned.
ERRORS
The symbolic link succeeds unless: [EACCES] Write permission is denied in the directory where the symbolic link is being created. [EACCES] A component of the path2 path prefix denies search permission. EXIST] Path2 already exists. [EFAULT] Path1 or path2 points outside the process's allocated address space. [EIO] An I/O error occurs while making the directory entry or allocating the inode. [EIO] An I/O error occurs while making the directory entry for path2, or allocating the inode for path2, or writ- ing out the link contents of path2. [ELOOP] Too many symbolic links are encountered in translating the pathname. This is taken to be indicative of a looping symbolic link. [ENAMETOOLONG] A component of a pathname exceeds {NAME_MAX} charac- ters, or an entire path name exceeds {PATH_MAX} char- acters. [ENOENT] A component of path2 does not name an existing file or path2 is an empty string. [ENOSPC] The directory in which the entry for the new symbolic link is being placed cannot be extended because there is no space left on the file system containing the directory. [ENOSPC] The new symbolic link cannot be created because there there is no space left on the file system that will contain the symbolic link. [ENOSPC] There are no free inodes on the file system on which the symbolic link is being created. [ENOTDIR] A component of the path2 prefix is not a directory. [EROFS] The file path2 would reside on a read-only file sys- tem.
SEE ALSO
ln(1), link(2), unlink(2), symlink(7)
HISTORY
The symlink() function call appeared in 4.2BSD. 4.2 Berkeley Distribution June 4, 1993 4.2 Berkeley Distribution
Mac OS X 10.9.1 - Generated Mon Jan 6 18:31:58 CST 2014
|
http://www.manpagez.com/man/2/symlink/
|
CC-MAIN-2018-51
|
refinedweb
| 392
| 64.2
|
Retrieve the current value of the specified event property of type long long integer.
#include <screen/screen.h>
int screen_get_event_property_llv(screen_event_t ev, int pname, long long *param)
The handle of the event whose property is being queried.
The name of the property whose value is being queried. The properties available for query are of type Screen property types.
The buffer where the retrieved value(s) will be stored. This buffer must be of long long integer.
Function Type: Immediate Execution
This function stores the current value of an event property in a user-provided buffer.
0 if a query was successful and the value(s) of the property are stored in param, or -1 if an error occurred (errno is set; refer to /usr/include/errno.h for more details).
|
http://www.qnx.com/developers/docs/6.6.0.update/com.qnx.doc.screen/topic/screen_get_event_property_llv.html
|
CC-MAIN-2018-47
|
refinedweb
| 130
| 66.33
|
custom-error-page-spring-mvc
Custom Error Pages with Spring MVC
1. Overview
For instance, suppose you’re running a vanilla Spring MVC app on top of Tomcat. A user enters an invalid URL in his browser and is shown a not so user-friendly blue and white stack trace – not ideal.
In this tutorial we’ll set up customized error pages for a few HTTP error codes.
The working assumption is that the reader is fairly comfortable working with Spring MVC; if not, this is a great way to start.
2. The Simple Steps
Specify a single URL /errors in web.xml that maps to a method that would handle the error whenever an error is generated
Create a Controller called ErrorController with a mapping /errors
Figure out the HTTP error code at runtime and display a message according to the HTTP error code. For instance, if a 404 error is generated, then the user should see a message like ‘Resource not found’ , whereas for a 500 error, the user should see something on the lines of ‘Sorry! An Internal Server Error was generated at our end’
3. The web.xml
<error-page> <location>/errors</location> </error-page>
Note that this feature is only available in Servlet versions greater than 3.0.
Any error generated within an app is associated with a HTTP error code. For example, suppose that a user enters a URL /invalidUrl into the browser, but no such RequestMapping has been defined inside of Spring. Then, a HTTP code of 404 generated by the underlying web server. The lines that we have just added to our web.xml tells Spring to execute the logic written in the method that is mapped to the URL _/errors.
_
A quick side-note here – the corresponding Java Servlet configuration doesn’t unfortunately have an API for setting the error page – so in this case, we actually need the web.xml.
4. The Controller
Moving on, we now create our ErrorController. We create a single unifying method that intercepts the error and displays an error page:
@Controller public class ErrorController { @RequestMapping(value = "errors", method = RequestMethod.GET) public ModelAndView renderErrorPage(HttpServletRequest httpRequest) { ModelAndView errorPage = new ModelAndView("errorPage"); String errorMsg = ""; int httpErrorCode = getErrorCode(httpRequest); switch (httpErrorCode) { case 400: { errorMsg = "Http Error Code: 400. Bad Request"; break; } case 401: { errorMsg = "Http Error Code: 401. Unauthorized"; break; } case 404: { errorMsg = "Http Error Code: 404. Resource not found"; break; } case 500: { errorMsg = "Http Error Code: 500. Internal Server Error"; break; } } errorPage.addObject("errorMsg", errorMsg); return errorPage; } private int getErrorCode(HttpServletRequest httpRequest) { return (Integer) httpRequest .getAttribute("javax.servlet.error.status_code"); } }
5. The Front-End
For demonstration purposes, we will be keeping our error page very simple and compact. This page will only contain a message displayed on a white screen. Create a jsp file called errorPage.jsp :
<%@ taglib uri="" prefix="c"%> <%@ page session="false"%> <html> <head> <title>Home</title> </head> <body> <h1>${errorMsg}</h1> </body> </html>
6. Testing
We will simulate two of the most common errors that occur within any application: the HTTP 404 error, and HTTP 500 error.
Run the server and head on over to localhost:8080/spring-mvc-xml/invalidUrl.Since this URL doesn’t exist, we expect to see our error page with the message ‘Http Error Code : 404. Resource not found’.
Let’s see what happens when one of handler methods throws a NullPointerException. We add the following method to ErrorController:
@RequestMapping(value = "500Error", method = RequestMethod.GET) public void throwRuntimeException() { throw new NullPointerException("Throwing a null pointer exception"); }
Go over to localhost:8080/spring-mvc-xml/500Error. You should see a white screen with the message ‘Http Error Code : 500. Internal Server Error’.
|
https://getdocs.org/custom-error-page-spring-mvc/
|
CC-MAIN-2020-34
|
refinedweb
| 614
| 56.15
|
Using Perl in PostgreSQL
Pages: 1, 2
Writing Triggers in PL/Perl
Up until PostgreSQL version 8.0, functions like the one above were just about all you could do with PL/Perl. They're useful, but not world-shattering. Version 8.0 gave PL/Perl a major shot in the arm, and more good stuff is coming in version 8.1. From version 8.0, you can do these cool new things:
- Create event handlers (a.k.a. triggers).
- Call back to the database from within PL/Perl, either to fetch rows or perform some action.
- Return a set of values, rather than just one value.
- Return composite types, not just simple types.
- Persist data between function calls and share that data with other functions within the same session.
Triggers can be extremely useful. Users of PostgreSQL and commercial high-end database systems have long used them to solve all sorts of problems that otherwise the client might have to handle (and often unreliably). One common use is for auditing changes. The audit.sql file accompanying this article contains an example of an account transaction table with an attached trigger that logs every change to the table. The output from the script looks like this:
mod | user_id | ts | new_txn | old_txn --------+---------+-------------------------------+---------------------------------------------+--------------------------------------------- INSERT | 10 | 2005-07-17 18:50:28.991595-04 | (1,1,1000.00,"initial 'deposit'") | UPDATE | 10 | 2005-07-17 18:50:29.051915-04 | (1,1,1000.00,"modified: initial 'deposit'") | (1,1,1000.00,"initial 'deposit'") DELETE | 10 | 2005-07-17 18:50:29.05932-04 | | (1,1,1000.00,"modified: initial 'deposit'") (3 rows)
Although there are no transactions in the transactions table, this contains a complete record, or audit trail, of everything that has been done to the table. In particular, it logs what happened, who did it, and when they did it. It doesn't matter what SQL they used; whatever they did to change the transactions table in any way is in the log. This is the sort of accountability that auditors and lawyers love, and it is very easy to achieve with triggers.
There is quite a lot to notice in this very simple example, especially if you usually use a database that doesn't provide all of these features. First, notice that everything goes into a schema called
accts. A SQL schema is a namespace, and names of objects only have to be unique within a schema. Moreover, dropping a schema with cascading drops everything inside of the schema, so cleaning up is easy.
Next, notice that the declaration of the function
current_sysid() is
VOLATILE rather than
IMMUTABLE. This is because its value does not depend only on its arguments, and furthermore, its value could potentially change within a single table scan via
SECURITY DEFINER (a sort of
setuid mechanism).
There is nothing very remarkable about the
txn table, but the
txn_audit table looks very odd--the new and old fields are of
type accts.txn! This uses a new feature in PostgreSQL version 8.0 that allows tables to contain fields of opposite types. Because the name of a table is also the name of a corresponding composite type, you can use a table name as the type of a field, and that field will take exactly the same type of record as the table. This neat arrangement means that no matter how complex the base table, the audit table needs only these five fields. Without this facility, the schema would have to duplicate all of the fields in the base table twice!
No matter what the language, the trigger must be a function that takes no arguments and returns the special type
trigger. Trigger functions in PL/Perl receive a special object called
$_TD that contains lots of useful information about what caused it to be called. Of particular interest in this function are the event type that causes the trigger to fire and the values of the old and new data. Other interesting values in other circumstances include the table being modified, whether the trigger is called before or after the update, and any arguments passed to it by the trigger setup. The documentation contains a full list. Most of the work of the function consists of constructing an SQL statement to populate the audit table. It takes special care to escape the details fields, both to avoid upsetting the SQL parser and to avoid SQL injection attacks. Ideally, the trigger could use a prepared query instead of much of this, but that feature likely won't arrive until PostgreSQL 8.2.
After constructing the SQL query, the code uses another feature that is new in version 8.0--the ability to call back to the database to perform some action.
spi_exec_query() does the work and returns a hash with some information, including a status field. If this is the expected
SPI_INSERT_OK value, great! If not, the code returns the value
SKIP to Postgres, telling it not to perform the modification to the
txn table at all. If the transaction cannot be logged, the table modification should not happen. Another option is to modify the values in
$_TD->{new} and return
MODIFY. This would have caused PostgreSQL to use the modified value in the insert or update, rather than the value it originally intended to use. Instead of doing either of these things, the code returns
undef, which tells PostgreSQL that it can simply proceed with modifying the table, having logged the modification.
Finally, the code calls
CREATE TRIGGER to tie the newly created function to all of the events on the
txn table.
Conclusion
Triggers are an immensely powerful and useful database tool, and I have only scratched the surface here. Being able to write them in Perl means that if you already know Perl, you don't have to learn a new language just so you can use them. So you get productive in much less time, and with greater comfort.
Part two of this series will look at the other new features of PL/Perl that are available in version 8.0 of PostgreSQL, and part three will look at what is coming in version 8.1 and beyond.
Andrew Dunstan works for a small consulting and software company in the Triangle area of North Carolina, and contributes to PostgreSQL as an enthusiastic hobbyist as well as a sometime professional user.
Return to the Databases DevCenter
|
http://archive.oreilly.com/pub/a/databases/2005/11/10/using-perl-in-postgresql.html?page=2
|
CC-MAIN-2015-18
|
refinedweb
| 1,072
| 62.88
|
CHI::Stats(3pm) User Contributed Perl Documentation CHI::Stats(3pm) NAME
CHI::Stats - Record and report per-namespace cache statistics VERSION
version 0.54 SYNOPSIS
# Turn on statistics collection CHI->stats->enable(); # Perform cache operations # Flush statistics to logs CHI->stats->flush(); ... # Parse logged statistics my $results = CHI->stats->parse_stats_logs($file1, ...); DESCRIPTION. STATISTICS
The following statistics are tracked: METHODS
enable disable enabled flush} parse_stats_logs (log1, log2, ...) Parses logs output by "CHI::Stats" and returns a listref of stats totals by root class, cache label, and namespace. e.g. [ { root_class => 'CHI', label => 'File', namespace => 'Foo', absent_misses => 100, expired_misses => 200, ... }, {. SEE ALSO
CHI AUTHOR
Jonathan Swartz <swartz@pobox.com> COPYRIGHT AND LICENSE
This software is copyright (c) 2011 by Jonathan Swartz. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. perl v5.14.2 2012-05-30 CHI::Stats(3pm)
|
https://www.unix.com/what-is-on-your-mind-/284213-community-stats.html?s=1f3b507fc284371ee8dddadfe6b67a20
|
CC-MAIN-2022-05
|
refinedweb
| 153
| 50.02
|
?'"
Re:Boycott? (Score:5, Funny)
How does one go about boycotting this?
There's a 'how to' video on boycotting this, but it's not available online. You have to provide two forms of picture ID to order the physical media, register your IP address, sit hrough an FBI warning and promise that only you - and you alone - will watch it. Sharing it with others, making copies, posting it online or selling it as used is strictly forbidden. A 'how to ' video about acquiring their videos is being prepared by their lawyers in conjunction with the US government and Interpol.
Welcome to the future (Score:5, Insightful)
Where "independent" and "objective" simply means "giving the bad as much airtime and consideration as the good."
Re:Welcome to the future (Score:5, Insightful)
Where "independent" and "objective" simply means "giving the bad as much airtime and consideration as the good."
Reminds me of the news when they parrot statements made by government officials.
Even when the statements are easily shown to be false, internally inconsistent, misleading, etc., they just quote the statement verbatim like a sales-oriented press release. There is no criticism of the statements made. They're simply quoted. Easily researched facts that contradict such official statements are not mentioned. I guess that would be too much like real objectivity for their tastes? I mean the way the media and government works is very simple: if you are a reporter and you ask powerful people hard questions, you stop getting invited to the next press events. You lose access as punishment. Only those with the preferred dispositions are invited. It works as long as everybody doesn't want to ask hard questions, that way those who do can be singled out.
Anyway, maybe they are treating this Beringer guy like a lawyer: the "best" (most effective) oens are like attack dogs. They sic whomever their master points at. Maybe they're hoping that having him on their side will be an asset provided they can keep this dog on a short leash.
Personally, I think by hiring people with reputations and affiliations like this, they just destroyed their own goodwill and credibility supposing they had any. That's not in the least because he was the MPAA "Technology Policy Officer" and he's a pretty shitty one if he doesn't tell them to adapt to the Information Age as they have clearly failed to do.
Re:Welcome to the future (Score:5, Informative)
ISOC is an international body, with five large directories and hundreds of local chapters. ISOC America credibility has been outright destroyed by this move among the other ISOCs, and it is clear that it happened through the lobby in Washington DC. The New York chapter spoke strongly against it, but I very much doubt that anything short of a massive show of force by the non-American directories of ISOC and the non-corrupt american chapters of ISOC by outright and publicly expelling Paul Beringer and the entire DC chapter on the grounds of breach of the ISOC code of conduct and ethics will be enough to restore the ISOC good name.
For those that think ISOC doesn't matter, ISOC *funds* the IETF, and the IETF is one of the most important engineering bodies behind the Internet (and the least problematic of them all).
The ISOC code of ethics can be found here: and it is NOT optional. You have to abide to it to be an ISOC member.
Re:Welcome to the future (Score:5, Insightful)
Great. Now they have an *AA pet lapdog as part of the process. Anybody taking bets on how the engineers behind the scenes will now be pressured into 'fixing' things to make the internet into Cable TV 2.0?
Re:Welcome to the future (Score:4, Informative)
Simple. ISOC will direct IETF to reject all RFCs unless they include support for DRM
Re: (Score:2)
Re: (Score:2)
For those that think ISOC doesn't matter, ISOC *funds* the IETF, and the IETF is one of the most important engineering bodies behind the Internet (and the least problematic of them all).
If need be, the IETF could seek other funding sources through the community.
Re:Welcome to the future (Score:5, Insightful)
Re: (Score:2)
I want to hear the news. The editorializing can appear on the editorial page. Most of the MSM want to gag me with their special polemic of the day and twist and bend the facts to suit their agenda. It doesn't matter which corporate news organization, pick one, it's tainted and flawed.
We're getting a little better with independents and I can get my propaganda direct from the gov't without interference by the MSM. I'm currently harassing the mayor I voted for to quit sucking up to the MSM and put relevant ne
Re: (Score:3)
Re: (Score:3)
Re: (Score:2)
So there is no such thing as a real good or bad, right? It's all just a matter of opinion, including the consequences.
Pretty much. As a concept, sure, most people have a similar set of inate 'morals', same as a wolf pack or pride of lions does. Knowing this doesn't change what I feel when I see something I consider good or bad anymore than knowing how my sense of smell works changes the scent of a rose. But these are all "gut feelings", which are by their very nature subjective. If you want to be trully objective then the very first thing you should do is question your own "gut feelings" about the subject at hand.
Re: (Score:3)
no (Score:1)
Does this mean... (Score:5, Insightful)
Re: (Score:1)
No. They already took over the hen house, ate all the chickens, and just wait for us to put more chicks in the house for their dining pleasure...
Re:Does this mean... (Score:5, Insightful)
No.... an international hen house franchise owner just appointed the Fox as chief landlord over all the henhouses in North America.
The hen houses have some autonomy, and there is a remote possibility they could band together and reject the Fox as their landlord
Re: (Score:2)
Re: (Score:1)
so, um, yeah - how'd that beard-trimming go?
Is that a euphemism for cunnilingus?
Re: (Score:1)
You'd still be a better choice than this MPAA shill.
RIAA and MPAA are ruining everything. (Score:3, Insightful)
:-|
Re:RIAA and MPAA are ruining everything. (Score:5, Interesting)
They're not my favorites either, but let's not become too pessimistic. All is not lost. The most important thing is that the free world remain so and that we retain the ability to resist all efforts to introduce censorship of any type.
We refer to this era we live in as the information age because the Internet is so amazingly effective at making it possible for people all over the world to freely exchange information. This has been great for most people, but since it has also had the effect of decommoditizing information in general, it has been bad news for the various publishing industries and their centuries-old business model, so don't be surprised if they continue to put up a fight.
They see censorship as the best way to once again make information scarce and thereby raise the value of their products, so our task is to raise public (and ultimately political) awareness that such an artificial measure can only be counterproductive at best. It will be much better for society in general if the publishing industries learned to develop new business models, rather than if our governments effectively allow them to dictate rules that will lead to the implementation of tools more befitting of a police state. If we allow that to happen, then we may wake up one day to find that the clock has indeed been turned back... to 1984.
Re: (Score:3)
You're cute when you are naive. When the DMCA passed its implications for free speech were clear, and since that time have been used to control what appears on YouTube and many other sites. Corporations now control speech. When the PATRIOT act passed it was almost unanimous. Now you get to be virtually stripped naked every time you fly; a gross invasion of privacy. The NDAA sweeps away the last vestiges of any of your rights to a trial. Corporations now assign their cronies into critical Government roles at
He is supposed to be "one of the good guys" (Score:5, Interesting)
He was only at the MPAA for a year, and from what I hear, that was no accident. I know people who know him, and they say that he understands the Internet and didn't agree with what the MPAA was doing, and was described to me as "one of the good guys." We shall see, but he won't last long at ISOC if he isn't.
Re: (Score:1, Troll)
Re: (Score:3)
That's about on a par with saying 'Hey, Hitler wasn't all bad. After all, he did kill Hitler!'
No. Actually it's nothing like that.
As a general rule, when you use Hitler in a comparison, that comparison is probably flawed.
Re: (Score:2)
Re:He is supposed to be "one of the good guys" (Score:4, Funny)
Congratulations, you're the first commenter in this story to demonstrate Godwin's law [wikipedia.org]. Enjoy the results.
Re: (Score:2)
Re: (Score:2)
That doesn't really mean much, since there have been many more Godwins than decent threads when it comes to slashdot
Re: (Score:3)
Re: (Score:2)
He was only at the MPAA for a year,
.... didn't agree with what the MPAA was doing
and he didn't know what the mpaa was doing before he joined them? yeah right
...
Re: (Score:2)
He was only at the MPAA for a year,
.... didn't agree with what the MPAA was doing
and he didn't know what the mpaa was doing before he joined them? yeah right
...
Don't know. Maybe he was told he could change things, and found out different.
Re: (Score:2)
It's quite possible to join an organisation believing that you have a mandate for change,only to discover... You don't
Re:He is supposed to be "one of the good guys" (Score:5, Insightful).
Re:He is supposed to be "one of the good guys" (Score:5, Insightful)
He was CTPO of the MPAA. You don't work for a group that evil and get to claim that you are a person working for the common good. You cant be fair minded and take the MPAA's money. At best he is a Puyi, and someone that politically naive does not belong belong in this position.
Even if he was trying to change it from the inside the only change that needs to happen at the MPAA is for it to disband and for everyone involved who ever aided in the bribery of politicians to be locked up. Your friend is complicit in the corruption of the United States political system and belongs in a cell, not heading up a North American chapter of ISOC.
Re: (Score:2)
Thanks for this. I'd mod you up if I could, but you're at +5 and I've already posted here.
Re: (Score:1)
Does it matter what a third party like you say he is?
It's an established fact that he worked for Satan and had no remorse taking their money.
Cut the PR, actions speaks for themselves.
Re:He is supposed to be "one of the good guys" (Score:4, Insightful)
Then again, it's not that hard to find quotes with him claiming copying threatens american jobs and that PIPA is a vehicle to deal with that, or the opposition to net neutrality from his stint at Verizon.
Unfortunately I think one gets tainted beyond redemption by even associating with the MPAA not to mention having gotten a paycheck from them. Perhaps he's just saying what his employers want him to, but in that case there would be more appropriate hires with a bit more spine for the ISOC to employ.
Re: (Score:2)
I was assuming this was some sort of "know your enemy" move.
Gaining knowledge from the inside of the MPAA command chain should come in handy.
Paul Brigner. (Score:4, Informative)
Not Beringer, Brigner.
Re: (Score:2)
Re: (Score:2)
He wanted to review wine.
why are people assuming the worst?? (Score.
Re: (Score.
Elop?
Re:why are people assuming the worst?? (Score:5, Insightful)
When you hire someone, you don't magically become a shill of that person's past employer.
While true. fact that you were a chief executive of an organization such as the MPAA says something about you. And what it says is largely inconsistent with the values of the internet society.
You choose executives whose personal views are consistent with the values of the organization, or who at least are not widely known as having opposite views; such as the scope and capabilities of the internet should be heavily restricted in order to protect media companies.
Re: (Score:1)
The rare albeit slight possibility you're missing here is: He might've been someone coming in to try and rock the boat. Not everyone going into organizations you dislike is out to follow the 'company line', although I will agree that it seems like most of them conform once they get there regardless. But as someone else said, since he left/got the boot after only a year it is not impossible to imagine he might actually have sane ideas for balancing technical rights versus intellectual property rights. Hell,
Re:why are people assuming the worst?? (Score:4, Interesting) RIAA would likely benefit from having a former pirate party member at its helm, because that person would understand piracy in a way the organization currently doesn't and could drive sane policy changes.
What you're promoting seems to be ideological purity at the cost of maybe not expanding or improving policy. It's an innately defensive posture, used by people who are playing to not lose rather than to win. Maybe such a posture is better in this case, but I wouldn't say that that's always the case.
Re: (Score:3)
Re: (Score:3).
CEOs are not just people with insight, they are also leaders. Leaders are figureheads as well, models, people to set an example for others. People can ma
Re: (Score:1)
In all your examples, the previous job of each subject influences their decision in the next job. Using the obvious conclusion to your little experiment, why the FUCK would we want more RIAA in our Internet?
Re: (Score:2)
Popes aren't appointed, they're elected.
Re: (Score:1)
The process isn't magical so much as it is organic and predictable.
So ISOC will be owned by Hollywood now? (Score:2)
Awesome. Michael Bay will literally own you.
Anyone else read that as INGSOC? (Score:2)
n/t
Gambling? (Score:1)
Brigner, not "Beringer" (Score:1)
You got the name wrong.
I have known Paul Brigner since the 1990s and he is one of the most ethical, intelligent, and fair minded people I know. I expect he brought some of that to the MPAA - although I do not actually know what his impact there was. I do know that he is deserving of the benefit of the doubt, and I anticipate that he will be thoughtful, progressive, and fair-minded in his new position at ISOC. And I say this as someone who strongly supports Internet freedom and openness.
Re: (Score:2) [shinkuro.com] [mpaa.org]
So, yeah.
Re: (Score:2)
Re: (Score:2)
Remember though that people often have to represent the viewpoints of the organizations that they work for.
That may be the case for representative positions like spokesperson or similar, but as "Senior Vice President and Chief Technology Policy Officer at MPAA"? Isn't that a position which defines these viewpoints and policies?
Re: (Score:2)
Insightful. I was wondering if you would point that out.
I do not know how the MPAA operates, but I would expect that a policy group would be an advisory group that provides analysis and options to the board or executive leadership, but that final policy choices would be made by the leadership and board, and that it would be up to the policy group to draft appropriate language to reflect those policy choices. But again, I don't have any insight at all into how the MPAA operates.
Ultimately, the people who set
Re: (Score:2)
Apparently there's also a lively discussion on one of ISOC's mailing-list: [isoc.org]
Why is anyone surprised at this? (Score:4, Insightful)
Anybody who has seen both Sean Doran's brilliant screed "It Seeks Overall Control" and watched the IAHC committee where ISOC made the deal with the devil for control of the DNS which it then presented to the USG as the final solution, can not be surprised at this.
After the US government threatened to make Jon Postel "go away" for his ideas about expanding the DNS to make NSI "one of many" registires (instead of the current plan to have 10,000 sales agents for
.com) per the original NSF cooperative agreement with NSI/General Atomics/ATT, the USG (really Commerce) made their own version of IANA run by intellectual property lawyers, starting at the top with WIPO from Geneva being involved in the earliest secret (!) meetings about the DNS delivered on a platter by ISOC; this was initiated when Don Heath (ISOC) ran into Albert Tramposch (WIPO) and Bob Shaw (ITU) at an OECD workshop in Ottawa at about the time Jon was trying to expand the DNS namespace around the time the Vint Cerf's FNCAC advised the NSF to instruct NSI to began charging for domains.
ISOC, and really any of these organizations that start with an "I" are really a "you scratch my back I'll scratch yours" old boys club - look at their salaries on their organizations tax forms, they're 2 to 5 times for equivalent government work and lets face it if you saw FCC staffers in kayaks at a five star hotel Costa Rica claiming it was "bottom up multistakeholder consensus making" - one of four junkets a year - heads would roll and never mind the FCC has stated the multistakeholder model is rubbish.
But how else can they let the intellectual property crowd and speculators have as much as a say as all those people that actually own and operate nameservers?
Does it challenge it! (Score:2)
Does this challenge the notion that ISOC is a 'trusted, independent source of Internet leadership?'
Is what now?
|
http://tech.slashdot.org/story/12/03/23/2324224/isoc-hires-mpaa-executive-paul-beringer?sdsrc=prevbtmprev
|
CC-MAIN-2014-49
|
refinedweb
| 3,171
| 68.7
|
Pointers. Part 5. Memory allocation for the pointer. Arrays of pointers to basic types, functions, structures, classes
Content
- What programming errors can occur when allocating memory for a pointer?
- What are the ways to allocate memory for the unmanaged pointer (*)? Example
- In which cases is it advisable to use an array of pointers?
- What is the general form of describing a one-dimensional array of unmanaged pointers (*)?
- Array of pointers to int type. Example
- An array of pointers to type double. Example of definition. Example of dynamic allocation of memory for array elements
- Array of pointers to char. Example
- Example of sorting an array of strings using an unmanaged pointer
- How to define an array of unmanaged pointers (*) to a function? Example
- Array of unmanaged pointers (*) to the structure
- An array of unmanaged pointers (*) to the class. Example of definition and using
1. What programming errors can occur when allocating memory for a pointer?
While describing a pointer to a certain type, you must always take care that the pointer points to a variable (object) for which memory should be previously allocated. If this is not done, a critical situation will arise. The example demonstrates an attempt to use two pointers, for one of which is not allocated memory.
Example. Demonstration of allocation of memory for the pointer.
// pointer to int int * p; // the value of pointer p is still indefinite int *p2; // The value of p2 is undefined int x; // Variable for which memory is allocated x = 240; p = &x; // pointer p points to the element for which the memory is allocated *p = 100; // it works, because p points to x, so x = 100 //*p2 = 100; // Error because p2 points to unknown value
Let’s explain some fragments of the above example. The example declares two pointers to int
int * p; int *p2;
After such declaration the pointer value is indefinite. And this means that pointers point to arbitrary parts of memory. If you try to write some constant value into these pointers, for example
*p = 25; *p2 = 100;
then there will be a critical situation and the system will behave unpredictably. This is explained by the fact that an attempt is made to change the value by a pointer that points to an arbitrary memory location (for example, the pointer points to the program code).
After assignment
p = &x;
The pointer p points to the variable x, for which memory is already allocated. Therefore, the string
*p = 100;
is executed correctly. But a line of code
*p2 = 100;
is an error, since the pointer p2 is not defined.
2. What are the ways to allocate memory for the unmanaged pointer (*)? Example
There are 2 ways to allocate memory for the unmanaged pointer:
- assign the pointer the address of variable for which the memory is already statically allocated;
- allocate memory dynamically using the new operator;
- allocate memory dynamically using a special function from the C++ library, for example, malloc().
Example. Methods for allocating memory for a pointer to a double.
double x; double *p; // Method 1. Assigning an address to a variable for which memory is already allocated x = 2.86; p = &x; // p points to x *p = -0.85; // x = -0.85 // Method 2. Use the new operator p = new double; *p = 9.36; // Method 3. Use the malloc() function p = (double *)malloc(sizeof(double)); *p = -90.3;
In the above example, in method 3, to use the malloc() function, you must first connect the <malloc.h> module to the program’s text:
#include <malloc.h>
3. In which cases is it advisable to use an array of pointers?
The use of arrays of pointers is effective in cases when it is necessary to compactly place in memory “extended” data objects, which can be:
- text strings;
- structural variables;
- objects of classes.
An array of pointers helps to save memory and increase performance in the case of variable-length strings.
4. What is the general form of describing a one-dimensional array of unmanaged pointers (*)?
General form of defining a one-dimensional array of pointers:
type * name_of_array[size]
where
- name_of_array – directly the name of the array of pointers;
- type – type to which the pointers points in the array;
- size – the size of the array of pointers. In this case, the compiler reserves space for pointers, the number of which is specified in the value of the size. The size is reserved for the pointers themselves and not for the objects (data) to which they point.
5. Array of pointers to int type. Example
For each pointer in the array of pointers to the int type can be pre-allocated memory (see p.1).
Example. An array with 10 pointers to int.
// array of pointers to int int * p[10]; // array of 10 pointers to int int x; // Variable to which memory is allocated x = 240; p[0] = &x; // this works, the pointer points to the element for which the memory is allocated *p[0] = 100; // works because p[0] points to x, so x = 100 //*p[1] = 100; // error, since p[1] points an unknown value
6. An array of pointers to type double. Example of definition. Example of dynamic allocation of memory for array elements
An array of pointers to real types is declared exactly the same as an integer type (see p.2).
Example. Array of 20 pointers to double type
// array of pointers to double double *p[20]; // the value of the pointers is undefined // Memory is allocated dynamically in a loop for (int i=0; i<20; i++) { p[i] = new double; // dynamic allocation of memory for the pointer *p[i] = i+0.5; }
7. Array of pointers to char. Example
Example. Definition array to a char* with simultaneous initialization.
// array of pointers to char char * ap[] = { "C/C++", "Java", "C#", "Object Pascal", "Python" }; // displaying an array of pointers to char in the listBox1 component String str; // additional variable listBox1->Items->Clear(); for (int i=0; i<5; i++) { str = gcnew String(ap[i]); listBox1->Items->Add(str); }
In the above example, pointers get an initial value that is equal to the memory address of the corresponding lowercase literal.
8. Example of sorting an array of strings using an unmanaged pointer
Using pointers has its advantages if you want to sort arrays of strings. Sorting using pointers is faster because you do not need to copy strings when changing their positions in a string array. In fact, only the most pointers change positions. And this happens faster than rearranging the strings.
Example. Sorting strings by bubble method. A method is proposed without using the function strcmp() from the module <string.h>. Instead, the Compare() function of the System.String class is used. It also demonstrates the display of the rows pointed to by the array of pointers in the listBox1 control (ListBox type).
// array of pointers to char char * ap[] = { "C/C++", "Java", "C#", "Object Pascal", "Python" }; int n = 5; // Number of strings in ap[] // sorting strings by byble method for (int i=0; i<n-1; i++) for (int j=i; j>=0; j--) { // additional variables String s1 = gcnew String(ap[j]); // converting from char* to String String s2 = gcnew String(ap[j+1]); // use the method Compare() from class System.String int res; // additional variable res = s1->Compare(s1,s2); if (res==1) // s1>s2 { // swap the pointers char * tp; tp = ap[j]; ap[j] = ap[j+1]; ap[j+1] = tp; } } // displaying an array of pointers to char in the listBox1 component String str; // additional variable listBox1->Items->Clear(); for (int i=0; i<5; i++) { str = gcnew String(ap[i]); listBox1->Items->Add(str); }
In the above example, in fact, the pointers are sorted according to the values to which they point.
9. How to define an array of unmanaged pointers (*) to a function? Example
An array of unmanaged pointers (*) to a function can be defined only for console applications. If the program is developed using the Windows Forms template in the CLR environment, then you can not use the array of unmanaged pointers (*) to a function.
Let there be given 4 functions that receive two operands of type int and perform the following operations on them:
- addition, function Add();
- subtraction, function Sub();
- multiplications, function Mul();
- division, function Div().
The implementation of functions is as follows:
// function Add, returns x+y int Add(int x, int y) { return x+y; } // function Sub, returns x-y int Sub(int x, int y) { return x-y; } // function Mul, returns x*y int Mul(int x, int y) { return x*y; } // function Div, returns x/y int Div(int x, int y) { return (int)(x/y); }
Demonstration of the function calling through an array of pointers:
// Only for the console application // array o pointers to a function int (*p[4])(int, int); int res_add, res_sub, res_mul, res_div; p[0] = Add; // p[0] points to Add res_add = (*p[0])(7, 5); // res = 7+5 = 12 p[1] = Sub; // p[1] points to Sub res_sub = (*p[1])(7, 5); // res = 7-5 = 2 p[2] = Mul; // p[2] points to Mul res_mul = (*p[2])(7, 5); // res = 7*5 = 35 p[3] = Div; // p[3] points to Div res_div = (*p[3])(7, 5); // res = 7/5 = 1
10. Array of unmanaged pointers (*) to the structure
In Visual C++, an array of pointers to a structure can be described for both unmanaged pointers (*) and for managed pointers (^). In this example, an array of unmanaged pointers (*) is considered.
More information about the types of pointers in C++ is described here.
Example. Given a structure that defines a point (pixel) on the screen. In the MS Visual Studio environment, if the project is created using the Windows Forms Application template, then the structure should be described outside the main form class of the Form1 program.
// the structure that describes the pixel on the monitor screen struct MyPoint { int x; int y; int color; // color };
If the structure is described in another module, for example “MyStruct.h”, then at the beginning of the file of the main form module, you need to add line
#include "MyStruct.h"
Using an array of pointers to the MyPoint structure:
// unmanaged array of pointers to the structure MyPoint *p[3]; // allocating memory for an array of structured variables for (int i=0; i<3; i++) { p[i] = new MyPoint; } // filling the values of the fields of structures for (int i=0; i<3; i++) { p[i]->x = i+5; // random values of x, y, color p[i]->y = 2*i+14; p[i]->color = i; }
11. An array of unmanaged pointers (*) to the class. Example of definition and using
An array of pointers to a class is defined exactly as an array of pointers to the structure.
Example. Let there be given a class that describes the point on the monitor screen (pixel).
The class is defined in two modules:
- the module “MyPixelClass.h” defines the declaration of the class, its methods (functions) and fields (internal variables);
- the module “MyPixelClass.cpp” defines the implementation of the methods (functions) declared in the class (in the module “MyPixelClass.h”).
The text of the module “MyPixelClass.h” (class declaration):
#pragma once // class is declared without the keyword ref class MyPixelClass { int x; int y; int color; public: MyPixelClass(void); int GetX(void); int GetY(void); int GetColor(void); void SetXYColor(int nx, int ny, int nc); };
The text of the module “MyPixelClass.cpp” (implementation of class):
#include "StdAfx.h" #include "MyPixelClass.h" // implementation of methods of class MyPixelClass MyPixelClass::MyPixelClass(void) { x = y = color = 0; } int MyPixelClass::GetX(void) { return x; } int MyPixelClass::GetY(void) { return y; } int MyPixelClass::GetColor(void) { return color; } void MyPixelClass::SetXYColor(int nx, int ny, int nc) { x = nx; y = ny; color = nc; }
Demonstration of using an array of pointers to the MyPixelClass class from another program code (for example, the event handler for a click event on a button):
// array of unmanaged pointers to a class MyPixelClass *mp[5]; // Allocating memory for class objects, // to which pointers will point for (int i=0; i<5; i++) mp[i] = new MyPixelClass; // Filling objects of a class with arbitrary values // demonstration of calling SetXYColor() method for (int i=0; i<5; i++) mp[i]->SetXYColor(i+5, 2*i+8, i); // demonstration of other class methods int d; d = mp[1]->GetX(); // d = 6 d = mp[2]->GetColor(); // d = 2 d = mp[3]->GetY(); // d = 2*3+8 = 14
Related topics
- Pointers. Part 1. General concepts. Pointer types. Managed and unmanaged pointers. Pointers to a function. Examples of the use of pointers
- 6. Composite managed and native data types. Managed pointers (^) in CLR. Memory allocation. The ref and value qualifiers. Managed pointers to structures and classes
- Arrays. Part 1. Array definition. One-dimensional arrays. Initializing array
- Structures. Part 1. Composite data types. The template of structure. Structural variable. Structures in the CLR. Declaring and initializing a structured variable
|
http://www.bestprog.net/en/2017/04/30/pointers-part-5-memory-allocation-for-the-pointer-arrays-of-pointers-to-basic-types-functions-structures-classes/
|
CC-MAIN-2017-39
|
refinedweb
| 2,155
| 51.89
|
This site uses strictly necessary cookies. More Information
Hi. I just got over looking a particle systems in Unity and I need help figuring something out.
I'm currently using the Shuriken particle system in Unity 4. I'd like to sync a button press to trigger not only an increase of speed in my particle system, but trigger the particle burst feature. I've looked through the documentation on Unity's website but it's rather incomplete when it comes to Particle Systems. I've tried to code a few things and it's become rather hit or miss as to whether Unity will accept the code for things, though I will admit I'm not the best programmer.
I've been taking a few small steps trying to learn how to program the particle system. So far, the most progress I've had is:
using UnityEngine;
using System.Collections;
public class particleOnOff : MonoBehaviour {
// Use this for initialization
void Start () {
gameObject.particleSystem.enableEmission = false;
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.JoystickButton0)) {
gameObject.particleSystem.enableEmission = true;
}
/*if (gameObject.particleSystem.enableEmission = true && Input.GetKeyDown(KeyCode.JoystickButton0)) {
gameObject.particleSystem.enableEmission = false;
}*/
}
}
Now I'm using a unique gamepad for this project, the Nintendo DK Bongos, which is why it's reading joystick buttons, though I've also tested this with regular buttons. It works, but it only turns the particles on only. The commented out part is because I wanted to make the bongos turn emission on and off. Problem is that adding that commented part into the code makes it so the particle system won't work at all. Adding a normal if or else statement after the first if statement doesn't seem to work either. I consider this the first step to understanding the particle system, but I'm getting frustrated at getting these bursts to work. Can anyone help me?
Answer by Chronos-L
·
Mar 24, 2013 at 01:42 AM
Have you took a look at ParticleSystem.Emit( count:int )?
If you need a quick burst of 10 particles when you click
public class ParticleController : MonoBehaviour {
void Start () {
// You can use particleSystem instead of
// gameObject.particleSystem.
// They are the same, if I may say so
particleSystem.emissionRate = 0;
}
void Update () {
if( Input.GetKeyDown( KeyCode.A ) ) {
particleSystem.Emit(10);
}
}
}
if you need X number of particles per second while touching:
if (Input.GetKey(KeyCode.A)) {
particleSystem.Emit( (int) (particlePerSecond * Time.deltaTime) );
}
I have, but when I was fooling around with that parameter, it just refused to work and I moved on to the enableEmission function. If you don't mind. Could you post an example?
enableEmission is more suitable for something like turn on the fire, start falling leaves etc
enableEmission
You are looking for burst, so you should use emissionRate=0 with Emit(count).
emissionRate=0
Emit(count)
I edited my answer, take a look at it. I use the A key to burst particles.
Holy crap! It works awesomely! Thank you so much! You've saved me so much time and frustration! :D
One thing though:
if (Input.Get$$anonymous$$ey($$anonymous$$eyCode.A)) {
particleSystem.Emit( (int) (particlePerSecond * Time.deltaTime) );
}
I tried editing the int and particlePerSecond parameter with numbers, but I get a series of errors. How exactly particlePerSecond parameter work?
It is a parameter from you script.
public int particlePerSecond = 75;
...
if (Input.Get$$anonymous$$ey($$anonymous$$eyCode.A)) {
particleSystem.Emit( (int) (particlePerSecond * Time.deltaTime) );
}
By using particlePerSecond * Time.deltaTime, you will get a rough estimation on how many particles should be emitted on that particular Update() so it will fit particlePerSecond.
particlePerSecond * Time.deltaTime
Update()
particlePerSecond
What errors are you getting?
Oh, I didn't have a particlePerSecond variable. I added it, but I'm still getting errors.
Assets/Standard Assets/Scripts/particleOnOff.cs(17,30): error CS0119: Expression denotes a value', where a method group' was expected
value', where a
Assets/Standard Assets/Scripts/particleOnOff.cs(17,20): error CS1502: The best overloaded method match for UnityEngine.ParticleSystem.Emit(int)' has some invalid arguments Assets/Standard Assets/Scripts/particleOnOff.cs(17,20): error CS1503: Argument #1' cannot convert object' expression to type int'
UnityEngine.ParticleSystem.Emit(int)' has some invalid arguments Assets/Standard Assets/Scripts/particleOnOff.cs(17,20): error CS1503: Argument
object' expression to.
Shuriken particle System - change velocity by trigger
0
Answers
how to change the size of a particle
0
Answers
ParticleAnimator doesn't change color of particles in ParticleSystem(Shuriken)
0
Answers
How to make particles react to movement of particle system
4
Answers
How to destroy / hide a single particle?
2
Answers
EnterpriseSocial Q&A
|
https://answers.unity.com/questions/423398/particle-burst-on-button-press.html
|
CC-MAIN-2021-49
|
refinedweb
| 774
| 50.63
|
9965/how-do-we-convert-json-to-map-in-java
Which is the best way to convert a JSON code as this:
{
"data" :
{
"field1" : "value1",
"field2" : "value2"
}
}
in a Java Map in which one the keys are (field1, field2) and the values for those fields are (value1, value2).
Any ideas? Should I use Json-lib for that?
For a simple mapping, most tools from (section java) would work.
HashMap<String,Object> results = new ObjectMapper().readValue(JSON_SOURCE, HashMap.class);
(where JSON_SOURCE is a File, input stream, reader, or json content String)
When you don't know structure of json. You can use
JsonElement root = new JsonParser().parse(jsonString);
and then you can work with json. e.g. how to get "value1" from your gson:
String value1 = root.getAsJsonObject().get("data").getAsJsonObject().get("field1").getAsString();
Hi @Daisy
You can use Google gson
for more ...READ MORE
It's easy to convert a java.util.Date object ...READ MORE
The following code will perform your desired ...READ MORE
Hey, @Pooja,
Before starting with anything you should ...READ MORE
You could probably check out Google's Gson: ...READ MORE
You can use:
new JSONObject(map);
READ MORE
Here are two ways illustrating this:
Integer x ...READ MORE
We can do this in 2 ways:
String ...READ MORE
import org.json.*;
JSONObject obj = new JSONObject(" .... ...READ MORE
In Java 8 or later:
String listString = ...READ MORE
OR
Already have an account? Sign in.
|
https://www.edureka.co/community/9965/how-do-we-convert-json-to-map-in-java
|
CC-MAIN-2021-10
|
refinedweb
| 238
| 77.43
|
Injecting into JSF Phase Listeners with JSF 2.2Eric Parkerson May 13, 2016 4:39 PM
I am having trouble with an application I wrote that injects an @EJB reference into a JSF phase listener. My application was originally developed and tested using a Glassfish4 server but we have decided to attempt migration to Wildfly 10. Everything works well, except for this JSF phase listener injection.
I simplified things by writing a simple JSF application that has one web page (that amounts to "Hello World"), one EJB (BasicEJB with one function, callMe(), that does nothing), and one JSF phase listener class. Here is the code for the Phase Listener.
public class TestPhaseListener implements PhaseListener {
@EJB
BasicEJB bjb;
@Override
public void afterPhase(PhaseEvent arg0) {
bjb.callMe(); // comment me out, and I'll run just fine. Leave me here and I'll crash on a NullPointerException.
}
@Override
public void beforePhase(PhaseEvent arg0) { }
@Override
public PhaseId getPhaseId() {
return PhaseId.RESTORE_VIEW;
}
}
As the comment in the code says, if I try to call the EJB's method, I get a NullPointerException. Without it, it happily does the nothing that it was designed to do.
I understand that in JSF 2.1 and before, JSF PhaseListeners do not get anything injected into them. That changed in JSF 2.2, as I understand it, and Wildfly 10 is JSF 2.2 compliant. (The JSF module file is jboss-jsf-api_2.2_spec-2.2.12.jar).
I've also tried running this test on Wildfly 8.2, who's JSF module file is jboss-jsf-api_2.2_spec-2.2.8.jar, and I get the same issue. However, this simple test project runs perfectly on GlassFish4.
My question is, do I have something misconfigured on my Wildfly server, or is this a bug? I'm at a loss of how to proceed here. I know I can use the JNDI lookup to get a reference to my object, but I'd prefer to be able to inject my EJB. Thoughts?
1. Re: Injecting into JSF Phase Listeners with JSF 2.2Tomas Remes May 16, 2016 2:04 AM (in response to Eric Parkerson)
Hi Eric,
Yes I think this should work (when reading table "TABLE 5-3 JSF Artifacts Eligible for Injection" in JSF specification). Do you have some reproducer please? Did you try to inject with CDI by using @Inject?
2. Re: Injecting into JSF Phase Listeners with JSF 2.2Nicklas Karlsson May 16, 2016 2:39 AM (in response to Eric Parkerson)
And the instantiation is normal (done by the JSF implementation)? One would think deployment would fail if the injection fails but since it's working on GF, it sounds a bit strange. And you have checked all imports that they are the normal java/javax ones for all the usual suspects?
3. Re: Injecting into JSF Phase Listeners with JSF 2.2Tomas Remes May 17, 2016 3:01 AM (in response to Nicklas Karlsson)
I created [WFLY-6617] Cannot inject session bean with @EJB to JSF PhaseListener - JBoss Issue Tracker Note that CDI inejction with @Inject works in this case.
4. Re: Injecting into JSF Phase Listeners with JSF 2.2Eric Parkerson May 17, 2016 11:53 AM (in response to Eric Parkerson)
Tomas,
I was able to run my project with the @Inject annotation, thank you! Just for further information, while I was trying to discover the root cause of this issue, I ran my test code on Wildfly 9.0.2.Final as well as Wildfly 8.2.1.Final and had the same issues with the @EJB annotation in the JSF listener.
Nicklas,
Correct, the servers I used were downloaded and unzipped exactly as they come from the wildfly.org/downloads page. The test project to isolate this issue was created in Eclipse Neon for Java EE Developers. It was a basic Dynamic Web Project targeted to run a basic Facelets app that really does nothing but invoke the JSF PhaseListener and try to inject a dummy EJB into it. No new Jars were introducted, all the standard Java EE 7 jars are available.
|
https://developer.jboss.org/thread/269770
|
CC-MAIN-2017-47
|
refinedweb
| 684
| 65.01
|
shogi 0.0.1
shogi #
A simple shogi engine for Dart and Flutter. This engine can be combined with flutter_shogi_board to render static game board positions, tsume problems or shogi castles.
Presently the package is very basic in which it can determine the static board position for a given game. In future versions, dynamic games will be considered
Getting Started #
Import the package #
To import this package, simply add
shogi as a dependency in
pubspec.yaml
dependencies: flutter: sdk: flutter shogi:
Note that this package requires dart >= 2.3.0.
Example #
import 'package:flutter/material.dart'; import 'package:shogi/shogi.dart'; void main() { final boardPieces = ShogiUtils.initialBoard; boardPieces.forEach((p) => print(p)); } #
The packages
shogi and
flutter_shogi_board grew out of my desired to visualize shogi castles in Flutter, and with no game board widget or even a shogi engine available, I decided to roll my own.
Presently the package contains the business logic components from
flutter_shogi_board. For the future I would like to utilize these packages not just for displaying static game boards, but also for tsume problems, thus user interaction may be considered.
As the game board is static, the notation
G:K-51 is currently utilized to import game boards, however
KIF may be more suitable for future versions:
1 7六歩(77) 2 3四歩(33) 3 7五歩(76)
Raising Issues and Contributing #
Please report bugs and issues, and raise feature requests on GitHub.
To contribute, submit a PR with a detailed description and tests, if applicable.
[0.0.1] - 13/10/2019
- Initial release of shogi package, based on business logic components from flutter_shogi_board.
Use this package as a library
1. Depend on it
Add this to your package's pubspec.yaml file:
dependencies: shogi: :shogi/shogi.dart';
We analyzed this package on Jan 16, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:
- Dart: 2.7.0
- pana: 0.13.4
- Flutter: 1.12.13+hotfix.5
Health suggestions
Format
lib/src/models/board_piece.dart.
Run
flutter format to format
lib/src/models/board_piece.dart.
Format
lib/src/utils/package_utils.dart.
Run
flutter format to format
lib/src/utils/package_utils.dart.
Format
lib/src/utils/shogi_utils.dart.
Run
flutter format to format
lib/src/utils/shogi_utils.dart.
Maintenance suggestions
Maintain an example. (-10 points)
Create a short demo in the
example/ directory to show how to use this package.
Common filename patterns include
main.dart,
example.dart, and
shogi.
|
https://pub.dev/packages/shogi
|
CC-MAIN-2020-05
|
refinedweb
| 409
| 50.84
|
I am building a multiple series vertical bar graph with arcpy.Graph in ArcMap 10.6.1. The short version is:
import arcpy TESTDIR = <some dir> arcpy.env.workspace = TESTDIR arcpy.env.scratchWorkspace = TESTDIR arcpy.env.overwriteOutput = True arcpy.env.qualifiedFieldNames = False outGraphName = "VerticalBarGraph" outGraphJpeg = "VerticalBarGraph.jpg" inputTemplate = "SeriesComparison1.grf" graph = arcpy.Graph() inFieldNames = [f.name for f in arcpy.ListFields("OUT.dbf") if f.name != 'OID'] for i in range(1, len(inFieldNames)): graph.addSeriesBarVertical("OUT.dbf", inFieldNames[i], "LABEL") arcpy.MakeGraph_management(inputTemplate, graph, outGraphName) arcpy.SaveGraph_management(outGraphName, outGraphJpeg, "MAINTAIN_ASPECT_RATIO", 1000)
The output is just what I am after except that for three input fields it produces a legend with entries:
Vertical Bar
Vertical Bar 2
Vertical Bar 3
These can be changed interactively in ArcMap (see below) and I have done this to generate the template graph. I want to use Python to change these defaults, depending on user input, to the names of the input fields but I have had no success. I have been reduced to trying to reverse engineer what's going on in the interactive view:
by adding a couple of lines to the for loop above:
for i in range(1, len(inFieldNames)): graph.addSeriesBarVertical("OUT.dbf", inFieldNames[i], "LABEL") graph.graphSeries[i - 1].Custom = True graph.graphSeries[i - 1].Text = inFieldNames[i]
These instructions are accepted and I can print out their values but they have no effect on the graph output.
Is what I am trying to do possible with arcpy? Perhaps I am looking in the wrong place. I would be grateful for any advice.
Ian
Solved! Go to Solution.
As near as I can establish, it can't be done. I have used matplotlib ( ) instead.
As near as I can establish, it can't be done. I have used matplotlib ( ) instead.
|
https://community.esri.com/t5/python-questions/arcpy-modify-graph-legend-default-text/td-p/101393
|
CC-MAIN-2022-21
|
refinedweb
| 302
| 53.98
|
The main content for this post is taken from an article published by Patrick Smacchia (author of Practical .NET 2 and C# 2) which was posted here (on CodeProject.com).
Introduction
C# allows an object to offer events. The concept of event encompasses:
- Subscribers to the event. These are warned each time the event is triggered. They have the possibility of subscribing or unsubscribing themselves dynamically (i.e. during the execution of the program). In C#, a subscriber is represented by a method.
- The event itself, which can be triggered at any time by the object. Internally, the event is aware of its subscribers. The responsibility of the event is to notify its subscribers when it is triggered. The event has the possibility of supplying information to its subscribers when it is triggered, using the argument object to the event. In C#, events are similar to a delegate field which is a member of a class with the exception that it is declared using the
eventkeyword.
The concept of event/subscriber is not new and is well known in Java. The same behavior can be obtained using the Observer design pattern (Gof).
Events are very useful in an application with a graphical interface (Windows Forms and ASP.NET). In fact, each possible action on an interface (a button click, text typing, combo box selection…) triggers the call of the adequate method. During a mouse click, the argument of the event can, for example, be the position of the mouse on the screen. In the .NET platform, inheritance combined with events is at the base of all graphical controls.
The C# syntax
Let’s suppose that we have created an event in a class called
EventName. The names of the entities which are concerned by the event are functions of the
EventName name. An event argument is an object of a class derived from
System.EventArgs. You thus have the possibility of creating your own event arguments by creating your own classes derived from
System.EventArgs.
To improve code readability, it is recommended that the argument class for the
EventName be called
EventNameEventArgs.
Subscribers to the event are materialized using methods (static or not). The action of notifying subscribers translates itself by a call to each of these methods. These methods generally have the following signature:
- A return type of
void.
- The first argument is of type
object. When the method is called, this argument references the object which contains the event.
- The second argument is of type
System.EventArgs. When a method is called, this argument references the argument to the event.
An event is a member of a class, declared using the
event keyword. An event is an instance of the
EventNameEventHandler delegate class. An event has the possibility of being static or not. Visibility levels apply themselves to events. Since an event is a member of a class, the declaration can be preceded with one of the following keywords:
new public protected internal private static
virtual sealed override abstract extern
An event contains:
- A delegate object which contains the references to the subscribed methods. The delegate has the same signature as the subscribed methods and must be called
EventNameEventHandler.
- An
addaccessor which is invoked when a method subscribes to the event.
- A
removeaccessor which is invoked when a method unsubscribes to the event.
These three entities are automatically defined by the C# compiler as soon as the event is declared. You can however define your own bodies for the accessors. If you change the body of an accessor, you must also code the body of the other. In the body of an accessor, the
value keyword designates the delegate to add or remove. For example, the following two definitions of an event are acceptable:
// without accessor
public event ClickButtonEventHandler ClickButton;
// with accessors
private event ClickButtonEventHandler m_ClickButton;
public event ClickButtonEventHandler ClickButton{
add { m_ClickButton += value; }
remove { m_ClickButton -= value; }
}
Note that it is rare to have to modify the
add and
remove accessors. However, this feature can be useful in order to restrict the visibility level of an event. Understand that the possibility of using polymorphism on an event (i.e. the fact of being able to use the
virtual,
new,
override, and
abstract keywords in the declaration of an event) only applies itself to the
add and
remove accessors.
In C#, the event is triggered by a call to its delegate. This is not the case in other .NET languages. For example, VB.NET triggers an event through the use of the
RaiseEvent keyword which does not exist in C#. The compiler imposes that the call to the delegate must be done within the class that declares the event. Also, the class has the possibility of presenting a public method named
OnEventName() which allows the event to be triggered from outside the class.
...
public void OnClickButton(System.EventArgs Arg){
if(ClickButton != null )
// Trigger the event.
ClickButton(this,Arg);
}
...
A practical example
Here is an example where an object instance of the
NewsBoard class publishes press releases throughout the USA and the world. The publication is done through the
WorldNews and
USANews events. The argument of a press release event (an instance of the
InfoEventArgs class) contains the description of the press release. Finally, the instances of the
Subscriber class have the possibility of receiving press releases by subscribing to their
OnReceivingInfo() methods.
using System;
class Subscriber{
private string m_Name;
public Subscriber( string name ) { m_Name = name; }
// Method to call when an event is triggered
// (i.e when a news report is published).
public void OnReceivingInfo(object sender, EventArgs e){
NewsEventArgs info = e as NewsEventArgs;
if( info != null ){
Console.WriteLine( m_Name + " receives the news: " +
((NewsEventArgs)e).GetBulletinInfo() );
}
}
}
// An instance of this class represents a news report.
class NewsEventArgs: EventArgs{
private string m_Report;
public string GetBulletinInfo() { return m_Report; }
public NewsEventArgs (string report) { m_Report = report ; }
}
// The delegate class. Its instances reference subscriber methods.
public delegate void NewsEventHandler(object sender, EventArgs e);
// The class which publishes news reports by triggering events.
class NewsBoard {
// Events used to publish news.
public event NewsEventHandler USANews;
public event NewsEventHandler WorldNews;
// Methods used to trigger news publishing from outside NewsBoard.
public void OnUSANews(NewsEventArgs newsReport) {
if( USANews != null )
USANews( this , newsReport );
}
public void OnWorldNews(NewsEventArgs newsReport) {
if( WorldNews != null )
WorldNews( this , newsReport );
}
}
class Program {
public static void Main(){
// Create the news board.
NewsBoard newsBoard = new NewsBoard ();
// Create subscribers.
Subscriber bob = new Subscriber("Bob");
Subscriber joe = new Subscriber("Joe");
Subscriber max = new Subscriber("Max");
// Link subscribers and the news board.
newsBoard.USANews += bob.OnReceivingInfo;
newsBoard.USANews += joe.OnReceivingInfo;
newsBoard.WorldNews += joe.OnReceivingInfo;
newsBoard.WorldNews += max.OnReceivingInfo;
// Publish news reports by triggering events.
newsBoard.OnUSANews(new NewsEventArgs("Oil price increases."));
newsBoard.OnWorldNews(new NewsEventArgs("New election in France."));
// Unsubscribe Joe.
newsBoard.USANews -= new NewsEventHandler(joe.OnReceivingInfo );
// Publish another news report.
newsBoard.OnUSANews(new NewsEventArgs("Hurricane alert."));
}
}
The program displays:
Bob receives the news: Oil price increases.
Joe receives the news: Oil price increases.
Joe receives the news: New election in France.
Max receives the news: New election in France.
Bob receives the news: Hurricane alert.
In this example, nothing changes if you remove the two occurrences of the
event keyword (i.e. nothing changes if we use two delegate fields instead of two events). There are two reasons for this. The first one is that we do not use the event accessors. The second is that we do not trigger this event from outside the
NewsBoard class. In fact, one of the advantages of the
event keyword is to prevent the event from being triggered from outside its class. The triggering of an event is also forbidden from classes deriving from the class which defines the event, even if the event is
virtual. This means that the C# compiler will generate an error if we wrote the following in the body of the
Main() method in the previous example:
...
public static void Main(){
...
newsBoard.USANews(newsBoard,
new NewsEventArgs("Oil price increases."));
...
}
In C#, the notion of event is relatively close to the one of a delegate. The mechanism mostly allows supplying a standard framework for the management of events. Note that the VB.NET language presents several dedicated keywords for the management of events (
RaiseEvent,
WithEvents…).
Asynchronous event handling
When an event is triggered, you must be aware that the methods which are subscribed to the event are executed by the thread which triggers the event.
A potential problem is that certain subscribed methods may take too long to execute. Another problem is that a subscribed method may raise an exception. This exception will prevent other subscribers which have not yet been notified from being executed and will go back to the method which triggered the event. It is clear that this poses a problem as the method which triggers an event should be decoupled from the methods subscribed to the event.
To deal with these problems, it would be practical that the subscribed method be executed in an asynchronous way. Also, it would be interesting that different threads execute the subscribed methods. Hence, a subscribed method which takes a long time to execute, or that raises an exception, does not affect the method which has triggered the event nor the execution of the other subscribed methods. The thread pool of the CLR is specially adapted to these two constraints.
Those who understand the syntax of asynchronous calls may be tempted to directly use the
BeginInvoke() function on the event itself. The problem with this solution is that only a single subscribed method will be executed. The proper solution, illustrated in the following example which is based on our first example, requires the explicit traversal of the subscriber method list:
...
//;
subscriber.BeginInvoke(this, newsReport, null, null);
}
// Wait a bit to allow asynchronous threads to execute
// their tasks. Indeed, they are thread pool threads and thus,
// they are background threads. If we don’t wait,
// threadpool threads wouldn’t have the time to begin
// their tasks.
System.Threading.Thread.Sleep(100);
}
}
...
Finally, take note that there is no need to call the
EndInvoke() method since the subscribed methods are not supposed to return any results to the method which triggered the event.
Protecting your code from exceptions raised by subscriber methods in a synchronous scenario
Invoking the methods subscribed to an event in an asynchronous way is an efficient technique to protect the code which triggered the event from exceptions raised by the subscribing methods. It is, however, possible to have the same level of protection when invoking subscribed methods in a synchronous way. For this, you have to invoke them one by one as shown in the following example:
...
//;
try{
subscriber(this,newsReport);
}
catch(Exception){ /* treat the exception */ }
}
}
}
...
With my recent work in Multithreading I noticed the
article about events and how they operate in…
[tool] Remove source control bindings from a VS.NET 2003
Solution or Project [Via: Jon Galloway ] …
PingBack from
PingBack from
PingBack from
|
https://blogs.msdn.microsoft.com/sebby1234/2006/04/07/practical-net2-and-c2-event-programming-with-c/
|
CC-MAIN-2018-43
|
refinedweb
| 1,815
| 56.86
|
KEYCTL_REVOKE(3) Linux Key Management Calls KEYCTL_REVOKE(3)
keyctl_revoke - revoke a key
#include <keyutils.h> long keyctl_revoke(key_serial_t key);
keyctl_revoke() marks a key as being revoked. After this operation has been performed on a key, attempts to access it will meet with error EKEYREVOKED. The caller must have write permission on a key to be able revoke it.
On success keyctl_revoke() returns 0. On error, the value -1 will be returned and errno will have been set to an appropriate error.
ENOKEY The specified key does not exist. EKEYREVOKED The key has already been revoked. EACCES The named key exists, but is not writ_REVOKE(3)
Pages that refer to this page: keyctl(2), keyctl(3)
|
http://man7.org/linux/man-pages/man3/keyctl_revoke.3.html
|
CC-MAIN-2019-22
|
refinedweb
| 115
| 67.76
|
The other day, over our ritual lunch of beans, tortillas and coffee, in
the highland town of Acteal, Chiapas, Don Mariano
spontaneously asked: "So, is it that there are two kinds of money? One that we call dinero and the other economia? What is the economy?" he asked. What a question, I thought. My friend hesitantly attempted an answer. If money is the coins and bills we use, the economy is like
invisible money. The larger it is, the more invisible money it has acquired. It's like the coffee market. For example, you harvest and sell coffee beans to the "coyotes" (their name for middlemen) for approximately $1 per kilo, and they in turn sell them for three times that to a distributor abroad, until they end up in foreign supermarkets or restaurants where people pay $1 per cup. Don Mariano nodded knowingly, making me wonder whether this was a rhetorical question. Of anyone, he knows best the meaning of the economy. He understands it from
the ground up. It lives through him. Literally.
In this southernmost Mexican state, Mariano's relationship to coffee is not simply described by market relations and monetary value. But there is another aspect of invisibility proscribed by the economy: the lives, like Mariano's, that are narrated by the same coffee we abundantly drink.
In Chiapas, this has a very particular meaning. Today, 70,000 troops
or one third of the Mexican army occupies the state of
Chiapas. Low intensity war has been the government's response to an indigenous rebellion led by the Zapatistas-which came to the fore in
1994-and the increasing organization of peasant communities in opposition to the government and their neoliberal economic interests. In Chiapas is the evidence of the coercive nature of the PRI (the ruling party that has been in power for over 70 years) and its desperation to maintain their political and economic reign-forcefully. As part of its strategy to annihilate the opposition, covert organized armies or pro-government paramilitaries proliferate-recruited, trained and funded by the Mexican military.
Coffee is the second largest
import of the United States, next to oil; it is also the sole source of
income for Acteal. Mariano and I were
chatting one day outside his store, while he anxiously waited for his wife and children to return from his field, and he explained to me that in a normal year, a family can grow enough corn on the typical hectare of land to feed themselves for three months. The rest of the year their food supply is mostly purchased, during which time they are reliant on the little income they can make from coffee. Actually, coffee is more like the sole source of subsistence for Acteal.
Today, coffee is a central target of the government's low intensity war
strategy. Last month the Fray Bartolome de las Casas Human Rights
Center in San Cristobal, Chiapas reported that in the region of Las Margaritas,
boxes containing rats, snakes, insects, or mere
chemicals, had been found falling out of the sky into the coffee fields of peasants, killing the crops and eventually the animals. This is exemplary of a tactic whose aim is to slowly deplete a population by attacking their sole source of income instead of their immediate food
supply. I saw the implications of this coffee centered strategy on the face of a young man in Acteal. He spent an entire afternoon and evening
sitting motionless on a rock in a tranquilized, somber state, outside the room where I was staying. I was told that he had just discovered that
morning, upon returning to his coffee field, that paramilitaries from the neighboring village had cut down the trees that provided shade for his
coffee crops. Without this shade, he would lose his crops as they burnt from the penetration of the sun.
Increasingly his story is the repetition of others. Like many families
in Acteal, he has recently been displaced from his original
town, due to the growing organization of pro-government paramilitary troops in their communities. For these families in particular, coffee
harbors the story of being forced from their homes and estranged from their land simply because they refuse to support the government and take up arms. Today, displaced people in Acteal cannot return to their abandoned homes and coffee fields without the accompaniment of human rights observers for fear of confrontation, terrorization and kidnapping by the paramilitaries. Many people that have returned have found their homes and/or crops burned, their land poisoned, or the trees that gave shade to their coffee plants cut down. In fact, peasants often find that, in their absence, their coffee has been harvested and sold by the paramilitaries-one of many strategies to acquire the funds to buy their weapons.
Acteal is one of 32 communities in Chiapas that are members of the civil
society association, Las Abejas, or The Bees. They
are a pacifist, devoutly Catholic group that was founded in 1992 after 5 innocent men were imprisoned following a violent family dispute over a woman's right to inherit a portion of her family's land. Mariano explained to me that their name is a metaphor for the way they are
organized. Like a colony of bees, their Queen Bee is Dios todo poderoso, the all mighty God, and the Sun, Toltik, the Maya Tzotzil God.
When a delegation of aids to U.S. congressmen and women recently visited
Acteal, Agustin, a community representative, explained
that Las Abejas, since its inception, has been struggling against an unjust government. Furthermore, "we have been struggling against the North American Free Trade Agreement (NAFTA)," he said, "the agreement that President Carlos Salinas de Gortari signed with your country, the United States, and with Canada. But how do we benefit from this agreement?" he asked these future politicians. "The agreement enables more oil and coffee to be taken from our land in Chiapas and sent to the north. How do we benefit from this oil?" he asked. "We don't use it, we cook with firewood. But that's our land they take the oil from." He continued to explain that the government refuses to grant them the permits to export their coffee directly, meaning that only the 'coyotes' or the middlemen are capable of selling it abroad. "They control the market" he says, and stated that, although they are the ones who harvest, pick, shell, rinse, dry, and grind the coffee, the coyotes pay them between 7 and 11 pesos per kilo (the equivalent of about $1), and then sell it for 3 or 4 times that.
What mostly draws foreign delegations like this one, or human rights observers
like myself to this community, is that in Acteal
on December 22, 1997, 45 men, women and children were massacred in an onslaught by paramilitary troops that lasted approximately 8 hours. State police stationed only a few kilometers away, were advised ahead of time of the planned attack, but did nothing. The massacre was the culmination of months of terrorization by paramilitaries in the municipality of Chenalho, leading to large numbers of displacements from communities in which these armed groups were operating-hence the recent immigrants to Acteal. In fact, in Chenalho alone, it is estimated that about 8,000 people have been displaced due to paramilitary activities since 1994. In Acteal, truckloads of armed paramilitaries from neighboring communities spent the months before the fatal event, daily shooting up the highway that passes through the community. Indeed, Agustin explains to the young politicians, they wore the same uniforms as the Mexican army and carried the same weapons. "They're paid 1400 pesos a month," he said, about $130, "to carry a gun, to be organized in this covert arm of the Mexican military and to be made enemy of their neighbors, friends and family members." Poor and often landless young men, without any religious or civil society organizational affiliation, becoming a paramilitary not only means money, it means land too. After they scare off their neighbors, they can take over their fields and harvest their crops, most likely their coffee.
Becoming a paramilitary also provides a sort of social organization with
which to belong. "Viva Chenalho!" the paramilitaries
screamed after their successful slaughter. Mariano had sat in the middle of it, frozen in the spot where he and the rest of the community prayed when the armed men attacked from behind. Paralyzed and eyes a glaze as body upon body fell upon him, he recounted the clarity with which he saw the eyes and faces of every one of their assassins through their ski-masks and bandanas, the faces of neighbors and family members. "Viva Chiapas!" they shouted. "Viva Mexico!" For who, I wonder? For those who can be bought off by a manipulative government, desperate to maintain the upper hand in a state that bears the fruit of NAFTA and (someone else's) economic prosperity.
So this is the cost of coffee, I think-both theirs and ours. Our cost is also the expense of these lives, the unnecessary poverty, the struggle for a democratic country, where indigenous peasants are respected as people not fodder for their neoliberal economics. Mariano reminds me that we pay approximately $1 for our morning cups, while he is paid $1 per kilo of coffee he sells. In a good year, most families can make 200 dollars from a year's harvest, that is, without being displaced or suffering the threats and destruction by the military or paramilitary. Imagine a yearly salary of 200 dollars for a family of 10.
Recent efforts to enable coffee profits to directly benefit indigenous
peasant communities in Chiapas have been organized by
such U.S. fair-trade organizations such as Equal Exchange and The Human Bean Company. Due to the inability of Chiapan communities and coffee cooperatives to acquire the permits from the state government, that would allow them to export directly, these organizations have stepped in to enable this distribution and the majority of the profits to go to the farmers themselves. But the persecution on this side of the economy is relentless. A month ago, Kerry Appel, the founder of The Human Bean Company, was expelled from Mexico with the restriction that he may not return for 3 years. This marks the second time he has been expelled; the first time he was forced to leave was in 1996. It's no coincidence that this was the year he started his company working with Chiapan coffee cooperatives. He was the first foreigner to be expelled unconstitutionally for his activities in Chiapas, initiating a campaign the government has since waged against foreign human rights observers to curtail the number of foreign eyes that witness the activities of the Mexican military in Chiapan communities. Clearly, Appel's case illustrates the pervasiveness of this strategy. He, too, has been isolated as a threat to a specific kind of economy-a specific kind of
politics, a specific kind of war.
I asked Mariano at lunch about the flavor of coffees. Every element of its growth and production affects its taste, he explained. There's the coffee grown in tropical climates or tierra caliente, the coffee grown in the mountains or tierra fria, and the coffee grown under shade. It's that which is grown in the "coffee belt"-a region like the equator that wraps around the planet-that is the best kind, he says. I start to think of the other countries included in this "coffee belt": Colombia, Indonesia, Guatemala... I am struck by another element that Mariano didn't explicitly mention. Coffee's bitter savor is also the product of what remains an invisible economy, an unrecognized reality. Call it the taste of poverty, war and struggle; the taste of blood and dirt. Or call it the flavor of lives lived by, determined by, its demand. "The coffee we grow," Mariano says with pride, "is without doubt the best coffee in the world."
Back to Instigator Home Page
Back to CSSN Home Page
|
http://www.columbia.edu/cu/cssn/inst/chiapas.html
|
CC-MAIN-2014-52
|
refinedweb
| 2,015
| 58.32
|
Post your Comment
Welcome! to the News letter archive
News Letter Archive
In this page we are listing down the email news...;
News Letter Archive
Date
Subject
ajax news
Ajax news
Welcome! to the News letter archive
Welcome! to the News letter archive
News Letter
Archive
Date
Subject
how to archive cllocation value
how to archive cllocation value hi,
Am working with location based application, need to store cllocation value in array, for that i need to arhive... to archive cllocation i.e how do i encode and decode it...
please help.
regards
VoIP News
VoIP News
VoIP
News Net
VoIP News and Analysis, VoIP.... The news that T-Mobile has been doing trials of services using the wireless... information about the UMA trial.
Latest
News
how to delete a letter in a word?
how to delete a letter in a word? how to delete a letter in a word?
for example
if i enter= roseindia,
i want to delete 's',
then output= roeindia
frequency of a letter in a string
frequency of a letter in a string Could someone answer in netbeans please
Write a program that takes in a string and a letter from the user and displays the number of
appearances of the entered letter in the entered string
Jigsaw Archive
Jigsaw Archive
JIGSAW Archive increases the performance and stability of
your...
and preventing the proliferation of personal archives.
Archive email
Automatic Capital letter
Automatic Capital letter Morning sir,
Can you help me, i want to make a automatic capital letter.
I have a jTextfield1, if i type aaaaaa ,it will be automatic AAAAAA. can you help me give a source code.
Thank you very much
POI Word document (Letter Template)
POI Word document (Letter Template) Dear Team,
i need code for generating word document(letter format).
i am unable to get the code for
formats, font settings, letter type
settings.
please help me for the same.
Thanks
Vertical news slider using jquery
Vertical news slider using jquery how to creatw vertical news slider using jquery
Sorry for wrong category but i cant get my jquery category
letter count problem - Java Beginners
letter count problem i have a problem in my java coding to count two characters of a string.
eg to count the letter "ou" in the string "How do you feel today?". The answer should be 5. but i still have error compiling
Check for character is letter or not.
Description:
This tutorial demonstrate the use of Character.isLetter() method which checks
whether the value stored in char data-type variable is letter or not.
Code:
public class CheckLetter
Check for character is letter or digit.
Description
.style1 {
background-color: #FFFFCC;
}
Description:
This tutorial demonstrate how to check a character variable value is a digit
or letter using isLetterOrDigit() method.
Code
News Writing Services
News Writing Services
Being first with the news is a mantra across media and there is nothing wrong with it. A news story should always be new as when it becomes older it ceases to be news; it becomes follow up. At Roseindia we
Stay Informed with a News Feed Mobile Application
Stay Informed with a News Feed Mobile Application
Anyone who wants to be updated about all of the news going on in the world can do it with a proper news... be very easy to take advantage of a proper application like this.
A news feed
Java 9 Tutorial, news and examples
News, articles and example of the Java 9 Programming Language
After... of the Java 9 programming Language. Here we will be discussing
about the news... the Java Community process.
Here is the News of Java 9:
First
In this section we will see what is email archive and how it is useful in
securely storing your email communications. These days almost all the internet
users and companies are using email as communication means
Java News
Java News
Browse the following java news.
Open Source Java (14-Nov-2006)
Sun is also planning to provide dual license for its
project Glassfish that is already
display a list of names(when we press first letter)
display a list of names(when we press first letter) If i gave...("Enter letter: ");
String letter=input.next().substring(0,1...++){
if(countries[i].startsWith(letter)){
System.out.println(countries
iPhone News
iPhone News and Updates
... simple, straightforward answers to all the iPhone questions.
Herein, iPhone News... demands. The news review of latest iPhone Application provides an opportunity
Display set of names in array when we press the first letter
click the starting letter (like in gmail if we press the letter it will show...("Enter letter: ");
String letter=input.next().substring(0,1...++){
if(countries[i].startsWith(letter)){
System.out.println
Post your Comment
|
http://www.roseindia.net/discussion/6293-Welcome!-to-the-News-letter-archive.html
|
CC-MAIN-2014-52
|
refinedweb
| 792
| 63.59
|
I remember rightly, you can return OK from an 80386 or later INT 0 ISR, but 80286 or earlier had CS:IP pointing to the instruction that causes the exception. Because the ISR is a software exception and not therefore thrown by the PIC, there is no need to send an EOI to the PIC.
You'll need to experiment, and I'll defer to any other DOS dinosaurs out there :-)
Try this:
--------8<--------
/* Avoid the call to the default handler - i.e. comment it out.
I think you ought to disable interrupts during this ISR too,
by putting a call to enable() at the beginning and disable()
at the end. */
void interrupt divide0()
{
puts("Error: Divide by Zero\n");
/* (*oldhandle)(); */
}
--------8<--------
This time, when I put zero into the program, my error handler is called, so Error: Divide by Zero is printed, and the default error handle is not called.
However, the program seems to continually call the error handler, as it sits in a loop printing Error: Divide by Zero.
Is there something I have to do to tell the system that I have handled the interrupt, and it can be cleared?
If you are using TurboC from the Borland Museum, you'll need to get your hands on tasm.exe to do some assembler work. You want to increment the value of the CS:IP pushed on the stack to get it to return to the next instruction after the IDIV to prevent it repeatedly calling IDIV. I recommend compiling with the -S switch to see the assembly (.asm code) so that you can find the address of the CS:IP, which you need to increment to get your IRET to go to the right place. You'll find that your ISR pushes all of the registers. I debugger would be a fine thing for this so you can step through your ISR and see that it increments the right bit of the stack.
Experts Exchange Solution brought to you by
Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.Start your 7-day free trial
--------8<--------
#include <stdio.h>
#include <dos.h>
void interrupt (*oldhandler)();
void interrupt myhandler();
void myexit();
int main()
{
int x = 10,y = 0;
puts("Testing INT0 handler\n");
oldhandler = getvect(0x0); /* Divide by zero default handler */
setvect(0x00,myhandler); /* Install replacement handler */
atexit(myexit);
printf("%d/%d is %d\n"
,x,y
,x/y /* This assembles to IDIV DI */
);
puts("Program terminated normally\n");
}
void interrupt myhandler()
{
puts("My divide by zero handler: Caught exception!\n");
asm mov si,sp;
/* Make the return address skip past the opcodes for IDIV DI. We are messing with the IP pushed on the stack */
asm add word ptr [si+18],2; /* Skip the IDIV DI instruction */
/* The result of the division is in AX (and remainder in DX). These were pushed on the stack by TurboC, because we are in an ISR */
asm mov word ptr [si+16],0ffffh; /* AX = -1 */
asm mov word ptr [si+10],0ffffh; /* DX = -1 */
}
void myexit()
{
setvect(0x00,oldhandler);
puts("Old handler restored\n");
}
--------8<--------
You can see that it increments past the two opcodes generated for the division (IDIV DI) and pokes the value -1 into AX, taking an arbitrary application decision that you want a return value of -1 when you div by zero.
I hope this helps.
It makes you appreciate that life was much easier implementing the divide0 handler for 8086. A 80286+ handler requires that you take the address of the opcodes from the stack and interpret the opcodes to find out how many are used in the instruction so that you can progress to the next instruction. Presumably this is something which Intel reckoned was a good thing to have to do in divide by zero handler, because your handler gets access to the actual registers and operand, which caused the divide by zero. Over in the EE Assembler TA they'd probably make easy work of this sort of thing!
|
https://www.experts-exchange.com/questions/20784118/Setting-a-handler-for-interrupts-to-over-ride-the-existing-one-Turbo-C-DOS.html
|
CC-MAIN-2018-30
|
refinedweb
| 683
| 65.96
|
I managed to simplify the error:
var o = {g : false};
function f(){
console.log(o.g());
}
If I call it from Chrome and form console, than I will not get any line
number.
If the database you are using is some version of Microsoft SQL Server
Compact Edition (which the error message would suggest) the error stems
from the fact that particular database doesn't support thechar/varchardata
types as it's purely unicode based. What you need to do is to use the
corresponding unicode data typesnchar/nvarcharlike this:
Create table Employee (
Employee_ID nchar(5) Primary key,
First_Name nchar(20) NOT NULL,
Last_Name nchar(20) NOT NULL,
Phone_Number nvarchar(20) NULL
);
For reference: Data Types Supported in SQL Server CE
you can try this:
find /i "ERROR" pdm_webstat.txt >nul 2>&1 && (
echo "ERROR" found
REM run your Java program here
) || (
echo "ERROR" not found
REM command if "ERROR" not found
)
I don't know what causes the error, but I had the same problem. If I were
you, I would try this, because it worked for me.
Add the following line to the xml code of your button:
android:onClick="startNewActivity"
Then the xml of your button should look approximately like this:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your Text"
android:
Use the Java code:
public void startNewActivity(View view) {
Intent intent = new Intent(this, Letters.class);
startActivity(intent);
}
You have to add the following lines to the import section:
import android.view.View;
android.content.Intent;
Edit: Oh, and I am not sure if you need to do this, but I would add this
line in the
You should be using data-required-message instead of data-error-message for
the "Port is required" message.
Also, you may want digits instead of number if this is for a port-number
field.
Solution :- I have added focusInvalid: false, suggested by @Barmar in
$("form").validate() function.
$(document).ready(function(){
$("form").validate({
focusInvalid: false,
messages: {
name: "Please specify your name.",
required: "We need your email address to contact you.",
name@domain.com."
},
url: "A valid URL, please.",
comment: "Please enter your comment."
},
showErrors: function(errorMap, errorList) {
if(errorList.length) {
$("span").html(errorList[0].message);
}
}
});
});
Your code is wide-open to SQL injection attacks and that is partly the
cause of your problem: you're not verifying (let alone sanitizing) your
input that you use to formulate queries.
See this QA before continuing: What is SQL injection?
We can't tell you how to properly solve it without knowing what DBMS you're
using, but a quick workaround is this:
Dim invoiceNum
invoiceNum = CInt( Request.QueryString("num") )
Dim name
name = Request.QueryString("nam")
name = Replace( name, "'", "''" )
Dim sql
sql = "SELECT name FROM finals WHERE invoice_num = " & invoiceNum &
" AND name LIKE '&" & name & "%'"
There
You're right, parsing multi-line error messages for quickfix is difficult.
I'm not even sure it's possible to parse the errors in such a block as
individual errors.
A workaround that I've employed for unwieldy error output is to append a
transformation step (typically using sed) to 'makeprg' which converts the
multi-line errors into traditional, one-line-per-error messages; something
like
Error: /somefile/something/something.c:12:123 SOME MESSAGE
Error: /somefile/something/something.c:12:123 ANOTHER HELPFUL MESSAGE
Error: /somefile/something/something.c:12:123 ANOTHER MESSAGE
in your case.
I figured out what the issue was:
Instead of:
$e = $_.Exception
$line = $_.Exception.InvocationInfo.ScriptLineNumber
$msg = $e.Message
Write-Host -ForegroundColor Red "caught exception: $e at $line"
It needs to be:
$e = $_.Exception
$line = $_.InvocationInfo.ScriptLineNumber
$msg = $e.Message
Write-Host -ForegroundColor Red "caught exception: $e at $line".
The way I have my configurations, I see everything. Here is how:
TamperMonkey Dashboard |> Settings Tab |> General |> Config mode: |> Select
Advanced
Debug scripts: |> Checked
Logging level: |> Select Error (dealer's choice here, I chose this but you
can decide)
Your custom error function can capture the file and line as arguments:
function customError($errno, $errstr, $errfile, $errline) {
$e=$errno . ",". $errstr . "," . $errfile . "," . $errline;
...
}
From the Manual:
A callback with the following siganture. NULL may be passed instead, to
reset this handler to its default state.
bool handler ( int $errno , string $errstr [, string $errfile [, int
$errline [, array $errcontext ]]] )
Your call is incorrect:
$.fn.jqDialogConfirm([snipped], "$.fn.MenuItemRemove", null, null);
okFunction needs to be a function, but you're passing a string. You should
be passing:
$.fn.jqDialogConfirm([snipped], $.fn.MenuItemRemove, null, null);
On a side note, it's not really recommended to place application logic in
the jQuery namespace. I would personally put MenuItemRemove in
MyApp.MenuItemRemove or something.
Not sure if this is by design, but for now, raise TypeError() from within
Python causes a javascript exception to be raised and displayed (along with
line and column numbers). Great success!
I believe that source attribute of the TemplateSyntaxError is what you are
looking for. Django code implies that the mentioned numbers are line
numbers between which an error occured, see.
As for TemplateDoesNotExist, it seems to be ignored, when it occurs as a
result of the template tag, see.
So you're new to Python--as I suggested in a comment, you need to figure
out which values cause the error when the function is called. Try this:
try:
win32api.SetCursorPos((int(x1 + var_x + i*(float(dis_x)/n)),
int(y1 + var_y + i*(float(dis_y)/n))))
except:
print "error in SetCursorPos() with x1", x1, "y1", y1, "var_x", var_x,
"var_y", var_y, "dis_x", dis_x, "dis_y", dis_y, "n", n
raise
The idea is to briefly intercept the exception, print all the arguments
which caused it, then let it propagate as it did before (possibly
terminating the program). Hopefully this will help you understand which
arguments lead to errors.
You need to escape any ampersands and angle brackets in your XML content.
So & should become, &, < should become < and >
should become >.
The easiest way to do that is probably with str_replace call like this:
$string = str_replace(
array('&', '<', '>'),
array('&', '<', '>'),
$string);
I was having the same problem. I got it working eventually; I had a few
things wrong.
I went to the Google Cloud Console and regenerated and downloaded my key
file. Go to APIs & auth->Registered Apps.
The ONLY properties I put in the provider object are .ServiceAccountId and
.Scope.
I had to replace Scope with the actual scope and not use the enum value
(This is only a problem because I am using VB). I'm working in Fusion
Tables and the scope was rendering as just "Fusiontables" because VB.NET
does not use the GetStringValue() enum function. Now I'm using
"". Go here for a list of
valid scopes.
For the ServiceAccountId, I used the service account "Email address:" with
the "@" in it. (12345@developer.gserviceaccount.com), and not the on
If you open the link to the current version of the script, you will see
that this section of the code is commented out. Also on lines 38 and 39 it
is specified that:
* Returns a color map you can use to map original pixels to the reduced
* palette. Still a work in progress.
Therefore, I wouldn't expect it to work, perhaps there are some missing
libraries. I suggest you update your code with the latest version at.
Also, you can keep your page clean and separate the module. For example
create a subdirectory assets, put the quantize.js in there and in your page
include:
<script src="/assets/quantize.js"
type="text/javascript"></script>.
This may have been solved by now; however, try setting the PACKAGE argument
for the .C call in SolarSpectrum.PAR to "SolarSpectrum" (this may involve
altering the package source files for SolarSpectrum.PAR). That may get R to
look in the correct namespace (I haven't actually tried this, but it worked
for a different package with the same error).
The problem stems from splitting the dataframe on the wrong variable. You
should use group, not subregion (see end of post), however, rather than by
how about trying sapply instead? I think it gives nicer formatted and more
easily useable output:
t( sapply( unique(df$group) , function(x)
Polygon(df[df$group==x,c("long","lat")])@labpt ) )
# [,1] [,2]
# [1,] -92.40716 30.29909
# [2,] -92.82364 30.65532
# [3,] -90.91371 30.20234
# [4,] -91.06610 29.90319
# [5,] -92.00565 31.08009
# [6,] -93.34896 30.65511
# ..........
edit
the problem was more simple than I imagined! You were splitting on the
wrong group variable, should be group NOT subregion. However, my solution
gives nicer more useable output for placing labels than the funny
formatting of by (IMHumbleO)
centroids <-
Here are couple of things you could try
Go to "", find the
corresponding cluster that got started (based on timestamp), click on
"Debug", you should find logs about each step.
Or start an EMR cluster from AWS Console, login into the Master node, run
the Pig script to check if its working.
Taken from the question:
I figured it out.
Go to your website in Azure
Go to the configure page
Roll down to a heading called site diagnostics
Turn on detailed error message then click save at the bottom of the
page.
Your detailed errors will be logged in the diagnostics FTP site.
Don't know why it took me so long to find it.
I was hoping I can cleanup some redundant stuff and create more space
You couldn't reduce significantly the size of an upstream repo from a
downstream location.
That upstream repo is likely a bare repo, and even deleting a branch
wouldn't change much (a branch is just a pointer, and the reflog of that
repo would still have the reference of the commits for that branch.
All the commands mentioned in "Reduce git repository size" are local
commands.
So even without increasing the disk space, you would still need an admin to
go on that server an clean that repo for you.
It's not clear if you are using the iOS Twitter functionality, or another
framework (but the oAuth makes me think it's another framework). The
Twitter V1 API has been deprecated and retired. You should now use the 1.1
version:
This means the URI should have 1.1 in it, as opposed to just "1".
I would try updating the framework you are using, or perhaps switching to
the built in Twitter functionality, which streamlines the authentication
process if the user has a Twitter account on their phone.
you cant make network calls on your UI thread you need to move your login
method to a new thread by either using the Async Class or by just starting
a new thread and doing the login on there.
You need to call AddToTasks from a separate Subroutine. (Right now you are
trying to call it from inside itself.) So, create a separate Subroutine
something like this:
Sub CallAddToTasksFunction
If AddToTasks("12/31/2008", "Something to remember", 30) = True Then
Debug.Print "Task Added"
Else
Debug.Print "Failed"
End If
End Sub
AddToTasks returns True or False depending on if it succeeded. You can see
where that happens in a couple of spots in the function where the code is
like:
AddToTasks = False (or True)
and you can see that things like dates that aren't really dates will cause
it to fail.
What should this "return" do? Anyway it's wrong here and is your error at
line 77.
$res1 = return($mythisql);
Solution:
$res1 = $mythisql;
or
$res1 = mysql_query($thisql);
It might be
echo $users->pack_info($uinfo['package']['max_attack_time']);
instead of
echo $users->pack_info($uinfo; ['package'] )['max_attack_time']
edit
assuming you are trying to do function array dereferencing (which requires
php>=5.4) it might be
echo $users->pack_info($uinfo['package'])['max_attack_time'];
Your query selects SUM(s.SaleValue) into a variable saleValue defined as
Sales.SaleValue%type.
Normally using the %type syntax is good practice, but only when it matches
the assigned value. If Sales.SaleValue is defined with scale and precision
it is quite likely that a SUM() of that column will blow the bounds of that
definition. As appears to be the case here.
You might want to check BindingErrorProcessor used by WebDataBinder. There
you can implement your own custom logic for translating exceptions to
validation errors.
Notes:
You should implement your own exception (to be able to distinguish it from
IllegalArgumentException thorwn by other components).
You can initialize WebDataBinder with your custom BindingErrorProcessor
within your @InitBinder method (or set specific WebBindingInitializer to
your handler adapter).
A couple things to check:
Where does ip come from? You might need to use htonl.
How is the socket created? Perhaps your particular socket can't deal with
IPv4 addresses (e.g. it's an IPv6 socket).
Also, make sure GetQueuedCompletionStatus returns FALSE before calling
GetLastError. GetQueuedCompletionStatus has three possible outcomes:
Return value of TRUE:
Completion packet dequeued successfully, and the I/O finished successfully.
Return value of FALSE, with the OVERLAPPED set to NULL:
GetQueuedCompletionStatus itself failed to dequeue a completion (e.g. timed
out).
Return value of FALSE, with the OVERLAPPED not NULL:
Completion packet dequeued, but the I/O it represents failed.
The best solution would be to add more robust error handling so that if the
class is used incorrectly it lets you know. Of course, this implies that
you know the extent of exceptions you'll need to handle. Implementing a
better error handler is a start. You can trace back up the call stack by
using debug_backtrace().
The first element of the backtrace is always the current function/method,
followed by the caller of that function/method, and so on up the chain.
Inside an error handler the first element is the error handler function.
With that in mind and based on your sample code you could do the following:
function customError($errno, $errstr, $errFile, $errLine){
$backtrace = debug_backtrace();
$error = "- [".date("Y-m-d, H:i:s")."] Error on page
".$_SERVER["SCRIPT_NAME"]." fro
You have a bad placeholder token first off: orderNbr=: orderNbr needs to be
orderNbr=:orderNbr; Note the whitspace. Secondly, even if that was correct
i dont see you binding :orderNbr anywhere.
I would think though that the order number should be an autoincrement
integer field, and if that is the case you should not include it in your
insert.
The "Project SDK" is probably missing.
Check under File > Project Structure > Project
If it says <No SDK>, click New... and navigate to your new JDK home
directory.
|
http://www.w3hello.com/questions/Intellij-not-going-to-line-number-of-error-when-I-click-on-the-error-message
|
CC-MAIN-2018-17
|
refinedweb
| 2,406
| 64.41
|
Overview
Here you will learn what are the different ways to design urls in django. Here I'm using version 2.2 for this tutorial.
We will make use of path and re_path.
# From where to import from django.urls import path, re_path
Let's Start with an example
urlpatterns = [ path('articles/2003/', views.special_case_2003), #1 path('articles/<int:year>/', views.year_archive),#2 path('articles/<int:year>/<int:month>/', views.month_archive), #3 path('articles/<int:year>/<int:month>/<slug:slug>/', views.article_detail),#4 ]
Explaination
#1 - It is a simple url pattern to match the exact string 'articles/2003/'
#2 - In this a parameter year of type int is passed to the view, which can be accessed like
def myview(request,year=2000): print(year) ...
#3 - In this case, year and month of type int are passed to the view.
#4 - In this, year, month of type int and slug of type slug is passed to the view.
Note: int and slug are called path converters.
Default Path converters available are:.
Creating a custom path converter:
ValueErroris interpreted as no match and as a consequence a 404 response is sent to the user.
- A
to_url(self, value)method, which handles converting the Python type into a string to be used in the URL.
Example
Create a file converters.py inside your app and paste the.
Some of the common useful url patterns using re_path are
# Primary Key AutoField re_path(r'^questions/(?P<pk>\d+)/$', views.question_details, name='question_details'), # Slug Fields re_path(r'^posts/(?P<slug>[-\w]+)/$', views.post, name='post'), # Slug with Primary Key re_path(r'^blog/(?P<slug>[-\w]+)-(?P<pk>\d+)/$', views.blog_post, name='blog_post'), # Usernames re_path(r'^profile/(?P<username>[\w.@+-]+)/$', views.user_profile), # Dates re_path(r'^articles/(?P<year>[0-9]{4})/$', views.year_archive) # Year / Month re_path(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$', views.month_archive), # Year / Month / Day re_path(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<day>[0-9]{2})/$', views.article_detail)
Wanna share some useful URL pattern you use? Leave a comment below and I will update the post!
|
https://raturi.in/blog/designing-django-urls-best-practices/
|
CC-MAIN-2021-43
|
refinedweb
| 354
| 62.04
|
React Native Tutorial & Example [2019]
Receive new React tutorials.
Throughout this tutorial, you’ll learn to create your first React Native example app step by step by emphasizing basic theory and practice.
We’ll make use of React Native v0.6 (released in 2019), which is the latest version at the time of writing this tutorial.
What we'll be building in this React Native tutorial?
We'll be building a simple news app example that allows you to read and save news in the local storage for reading them later.
We’ll be using the news API from NewsAPI.org, register for an account and you’ll recieve an API key, note it and let’s continue.
What we'll be learning in this React Native tutorial?
In this React Native tutorial, we will teach you about the following topics:
- How to scaffold a React Native project,
- How to create a view in React Native by composing predefined UI components and Flexbox layout,
- How to implement navigation in your React Native app,
- How to style the UI,
- How to fetch data from REST API servers,
- How to get user input in React Native,
- How to respond to touch events in React Native,
- How to display images in React Native, etc.
What're the Prerequisites of this React Native tutorial?
In order to follow this React Native tutorial, you will need to have some prerequisites:
Familiarity with modern JavaScript/ES6 features: React Native is based on React which is a JavaScript library for building UIs, so you will need to be familiar with JavaScript and the latest ES6 features such as imports, exports and arrow functions.
React basics: You will need to be familiar with
- Components,
- State and properties,
- React Hooks,
- JSX: JSX is a powerful syntax extension that allows you to write your UI code with XML-like syntax and JavaScript., etc.
Node.js and NPM: We’ll be using React Native CLI for generating and working with our project which is built on to of Node.js, so you will need to have Node.js 8.3+ and NPM installed on your system. You can refer to the official docs for how to install Node.js using a package manager.
JDK 8+ and Android Studio installed on your system for Android development.
The
ANDROID_HOMEenvironment variable set to the path of your Android SDK.
On Ubuntu, you can add Android SDK to your
PATH by adding the following lines to the
~/.bash_profile or
~/.bashrc configuration files:
export ANDROID_HOME=$HOME/Android/Sdk export PATH=$PATH:$ANDROID_HOME/emulator export PATH=$PATH:$ANDROID_HOME/tools export PATH=$PATH:$ANDROID_HOME/tools/bin export PATH=$PATH:$ANDROID_HOME/platform-tools
We also added the
tools/bin and
platform-tools folder to the
PATH variable to be able to run various utilities like
adb from any folder. Next, run the following command:
$ source ~/.bashrc
How to run an Android Emulator
You can test your React Native app in a real device or better yet an emulator. Make sure you have created an Android Virtual Device in your system. Next, check the names of the installed AVDs using the following command in your terminal:
$ emulator -list-avds
For example, I have the following virtual device installl:
Pixel_2_XL_API_28
Next, you need to run the following command to start your emulator with a chosen AVD:
$ emulator -avd Pixel_2_XL_API_28
Editing the code with Visual Studio Code
This is not a requirement and you can use your prefered IDE but in this React Native tutorial we’ll be use Visual Studio Code. It has great support for JavaScript and you can easily install it from the official website.
For iOS development
You can also built your React Native app for iOS provided that you are using a macOS, you only need to get a free iOS developer account.
Note: To deploy the app to the iOS App Store, you will need to get a license with $99/year.
For development, you will need to install Xcode from the official Xcode website.
Note: Xcode includes the Xcode IDE, the iOS simulators, and the iOS SDK. ****
Generate your React Native project
If you have the previous prerequisites, let’s get started by generating a new React Native project using React Native CLI.
Head over to a new terminal and run the following command to run the React Native CLI using the
npx command:
$ npx react-native init firstapp
Note: Thanks to the npx tool, you don’t need to install React Native CLI. You can run directly from npm.
We used the
init command of React Native CLI to create a project called firstapp.
Next, you need to navigate inside your React Native project and run the Metro Bundler using the following commands:
$ cd firstapp $ react-native start
Metro is a bundler for JavaScript and React Native created by Facebook for compiling the React Native code.
Next, let’s leave Metro running and open a new terminal where you need to run the following commands to build and start your React Native application in the Android emulator you started earlier:
$ cd firstapp $ react-native run-android
The
run-android command will build and run the app in the Android virtual device.
Note: For iOS, you will need to use the
react-native run-ioscommand to build and run your app.
If your React Native app is successfully built, you’ll see a BUILD SUCCESSFUL message in your terminal and your app will be started in the Android emulator:
This is a screenshot of our app running inside an Android emulator:
Congratulations, you have started your first React Native app in your Android emulator. Now, let’s start writing the code.
If you have VS Code installed, head back to your previous terminal and run the following code from your project’s folder to open your it in VS Code:
$ code .
If you do any changes in your code, they will be live reloaded in your Android emulator so you don’t need to restart your app again.
Understanding the structure of your React Native project
After running our React Native app and opening the project in our IDE, let’s understand the structure of our project.
The project has the typical folders and configuration files for a Node.js project like the
package.json and
package-lock.json files and the
node_modules folder. We also have these files and folders:
babel.config.js: The configuration file for Babel (A compiler and transpiler for JavaScript)
metro.config.js: The configuration file for Metro, a JavaScript bundler for React Native,
app.json: configures parts of our app that don’t belong in code. See this article.
watchman.config: The configuration file for Watchman, a file watch service,
.flowconfig: The configuration file for Flow, a static type checker for JavaScript,
.eslintrc.js: The configuration file for ESLint, a JavaScript and JSX linter (a tool for code quality),
.buckconfig: The configuration file for Buck, a build system created by Facebook,
.gitignoreand
.gitattributes: ignores all files in version control that should be unique to each development machine,
android: The folder for the Android project,
ios: The folder for the iOS project,
__tests__: The folder for tests,
App.js: The main component in our React Native app,
index.js: The main file of our application where the components are registered.
That’s it. We have seen the most important files and folders of our React Native project generated using the official CLI.
Create a React Native screen
After understanding the basic structure of our project, let’s now see how we can use the prebuilt React Native UI components to create a view.
We already have an
App.js file which contains the code of the root React component in our app. So go ahead and open the
App.js file in your code IDE, and remove the existing code then add the following code instead:
import React from 'react'; import { View, Text, } from 'react-native'; const App = () => { return ( <View style=> <Text>Hello, world!</Text> </View> ); }; export default App;
We first import
React from
react, next we import the View and Text components from
react-native.
Next, we create a functional React component called
App using the ES6 arrow syntax. This function returns the JSX code that describes the UI of our screen.
The
View and
Text components are basic UI components that can be considered as the equivalents to the
<div> or
<span> and
<p> elements in HTML.
Finally, we export the App function so it can be imported from the other files.
After saving the file, go to your Android emulator and press R twice in your keyboard to reload your app. You should get the following UI:
The previous JSX code created an empty screen with a Hello, world! text at the center.
JSX is an extension for JavaScript that allows you to write HTML-like markup in JavaScript.
Note: You can think of JSX as a template language with JavaScript syntax.
You can also include JavaScript code inside JSX using curly braces
{ }.
The React Native
View Component
In our
App component, we used the
View component to create a container for our text
View is a fundamental React Native component for creating a UI. It’s simply a container which is equivalent to a native view such as
UIView in iOS, or
android.view in Android.
You can nest View components to create complex layouts and add zero or multiple children inside a View.
View supports the Flexbox layout by default, can have styles and can listen for touch events.
The React Native
Text Component
Inside the
View container, we used a Text component which wraps our Hello World text.
In React Native, you have to use a Text component if you want to display text in the UI. It supports nesting, styling, and touch handling.
For example, we could write our previous component without the
<View> component and it will still work:
const App = () => { return ( <Text>Hello, world!</Text> ); };
But we can’t add text without the
<Text> component. For example, if you write the following code:
const App = () => { return ( <View style={ { flex: 1, justifyContent: "center", alignItems: "center" } }> Hello, world! </View> ); };
You will get an Invariant Violation error with the Text strings must be rendered within a
<Text> component message:
Styling the UI in React Native
At this point of our React Native tutorial, we have seen how to create a basic screen using the View and Text components. Let's now see how to style our simple UIs using CSS written in JavaScript. The CSS properties are defined using the camelCase instead of hyphens. For example, you need to use
backgroundColor instead of
background-color.
All the React Native components like View and Text can have a
style prop in which you can provide styles for the component using an inline JavaScript object or a reference to a JavaScript variable that contains the styles.
You can also provide an array of styles with the last style has precedence which can be used for emuating style inheritance which doesn't exist in React Native.
In our previous example, we supplied some inline styles using the
style prop which allowed us to center the text in our view:
<View style={ { flex: 1, justifyContent: "center", alignItems: "center" } }></View>
Adding styles in React Native with
StyleSheet
React Native provides a
StyleSheet API that allows you to define and manage multiple styles in seprate places of files instead of adding them in your JSX code.
You simply need to call the
StyleSheet.create() method for defining reusable styles in one place/fie and reference them from your JSX code.
Note: In React Native, styles don’t cascade, but you can emulate cascading by re-using the same style object in the parent and chidren components.
At this point of our React Native tutorial, we have added some inline styles to our View component to center our Hello World text which is fine for our simple example but for the sake of learning best practices, let's take the inline styles from the JSX and define them in their own object using the
StyleSheet.create() method.
Head over to your code IDE, locate the
App.js file and start by importing
StyleSheet as follows:
import { StyleSheet, } from 'react-native';
Next, in the same file, add a
styles variable and add your styles using the
StyleSheet.create() method as follows:
const styles = StyleSheet.create({ container: { flex: 1, justifyContent: "center", alignItems: "center" } });
We can now use the
container reference to apply our styles to any React Native component.
Next, apply the styles to
View component as follows:
const App = () => { return ( <View style={styles.container}> <Text> Hello, world! </Text> </View> ); };
You can also pass an array instead of one object to the
style prop:
const App = () => { return ( <View style={ [styles.container] }> <Text> Hello, world! </Text> </View> ); };
Note: Fo bigger apps, you can also add styles in separate files and import them using the
importstatement so you can reuse them in multiple views.
Again for the sake of learning the best practices, let’s define styles in a separate file in our simple tutorial example.
First, let's start by creating a new
styles.js file. Head back to your terminal and run the following command from your project's folder:
$ touch styles.js
Next, add the following code in the
styles.js file:
import { StyleSheet, } from 'react-native'; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: "center", alignItems: "center" } }); export default styles;
We import
StyleSheet from
react-native and we call the
create() method to create a bunch of styles referenced by
container. We also need to export the
styles object so we can import it from the other JS files.
Next, you need to import the
styles object in your
App.js file as follows:
import styles from './styles'; const App = () => { return ( <View style={ [styles.container] }> <Text> Hello, world! </Text> </View> ); };
Building layouts in React Native with Flexbox
Ath this point of our React Native tutorial, we have created a basic screen using some fundamental UI components such as View and Text and we have seen how to define styles and apply them using the
style prop. We have also seen how to build a basic layout using Flexbox, let's now see more details about Flexbox.
Flexbox is the default layout for buiding UIs in React native. It's quite similar how it works in CSS except that the
flexDirection defaults to
column instead of
row, and the
flex parameter supports only a single number (a proportion of the available space).
In Flexbox, items are laid out horizontally or vertically (default) depending on the value of the
flexDirection property (
row |
column |
row-reverse |
column-reverse ).
Flex
The
flex property is designed to specify a proportion of the available space (vertical or horizontal depending on
flexDirection) to a child element.
Note: You don’t need to add
display: flexto a container to make it a flex container. Elements are by default flex containers.
You can also use properties like
justifyContent and
alignItems to align items either on the X-axis or the Y-axis.
Justifying Content
You can use the
[justifyContent]() property to define how to align items in the main axis of a container. The main axis can be either the X-axis or the Y-axis depending on the value of
flexDirection which means:
- When
flexDirectionis set to
column,
justifyContentwill align items vertically,
- When
flexDirectionis set to
row,
justifyContentwill align items horizontally,
You can align items in many ways:
flex-start(default): Align the items to the start of the container,
flex-end: Align the items to the end of the container,
center: Align the items in the center of the container,
space-between: Align the items across the main axis of the container with equal space between them.
space-around: Align the items across the main axis of the container, the remaining space will distributed around all items i.e to the beginning of the first child and end of the last child.
Aligning Items
You can use the
[*alignItems*]() property to specify how to align items along the cross axis of the container.
Align items is similar to
justifyContent but it aligns items according to the cross axis.
It takes the following values:
stretch(default):.
Note: You can use this playground to visually play with Flexbox.
Equipped with this basic information about Flexbox, let’s understand our previous snippet and improve it:
container: { flex: 1, justifyContent: "center", alignItems: "center" }
This is the style object applied to the
<View> component.
We used the
flex property to assign the available space to the container
<View>. This means it will span all the viewport since we only have one
<View> component.
We used the
justifyContent property with a
center value to center the children of the
<View> component vertically and the
alignItems property set to
center to center the children of the
<View> horizontally.
This makes the Hello, world! text (wrapped within the
<Text> component) vertically and horizontally centered in our application:
Adding images in React Native
Images are important in most apps, let's see how to add a background image in our React Native tutorial.
Let’s add a background image to our previous screen.
Since the previous screen is the only screen in our example app, let's make it the welcome/splash screen of our app that shows an image with the name of our app.
Head over to your IDE, change the
App component to show the name and description of our app.
In your
App.js file, import
<ImageBackground> as follows:
import { View, Text, Button, ImageBackground, } from 'react-native';
Next, change the
App component as follows:
const App = (props) => { return ( <View style = { styles.container } > <ImageBackground style= { styles.backgroundImage } source= > <View style= { styles.logoContainer }> <Text style = { styles.logoText }> Newzzz </Text> <Text style = { styles.logoDescription }> Get your doze of daily news! </Text> </View> </ImageBackground> </View> ); }
Let's also add some styles for the new elements. Go to the
styles.js file and add the following styles:
const styles = StyleSheet.create({ container: { flex: 1, justifyContent: "center", alignItems: "center", backgroundColor: "orange" }, logoContainer:{ alignItems: "center", }, logoText: { fontSize: 24, fontWeight: '600', color: 'white' }, logoDescription:{ fontSize: 15, fontWeight: '600', color: 'white' }, backgroundImage:{ flex: 1, width: '100%', height: '100%', justifyContent: "center", alignItems: "center", opacity: 0.7 } });
This is the screenshot of our view:
Creating multiple React Native screens
At this point of our React Native tutorial, we have created a basic splash screen with some text and a background image that can be considered as a welcome screen of our app. Let’s create another screen that will be used to render the news headlines from the news REST API.
In the same
App.js file, define a
HomeScreen() function as follows:
const HomeScreen = () => { return ( <View> <Text> Here, will be rendered our news. </Text> </View> ); }
Before tacking React Native navigation, let's see how we can use conditional rendering to create and change between multiple views in simple example apps.
First, change the name of the original
App component to
SplashScreen. Now we have two components:
SplashScreen and
HomeScreen.
Next, define a new
App() function as follows:
const App = () => { const [loading, setLoading ] = useState(true); setTimeout(() =>{ setLoading(false); } , 1000); if (loading){ return <SplashScreen /> } else { return <HomeScreen /> } };
We used the
useState hook to define a
useState() method:
import React, { useState } from 'react';
The laoding variable has an initial value of
true which means the
<SplashScreen /> component will be rendered. After one second, the value of loading will be
false which will cause the
<SplashScreen /> to disappair and
<HomeScreen /> will be rendered instead.
This is just for the sake of showing how conditional rendering can be used to create multiple views. We'll see later in this React Native tutorial how we can use a real navigation system to implement mutiple views with more control and features.
Fetching data in React Native
Instead of switching between the two views based on time, let’s see how we can fetch data from a remote REST API before displaying the home screen. This is a more realistic use case!
In React Native, you can use the Fetch API for calling REST APIs or getting data from web servers.
In a functional React components, we don't have life-cycle methods so we need to use the
useEffect hook for performing side effects.
In the
App.js file, import the
useEffect() method as follows:
import React, { useState, useEffect } from 'react';
Next, define the
API_KEY and
URL constants as follows:
const App = () => { const API_KEY = "<YOUR_API_KEY_HERE>"; const URL = `{API_KEY}`;
Note: You need to replace
<YOUR_API_KEY_HERE>with your API key from the News API.
Next, define the
articles variable for storing the articles and initialize it with an empty array:
const [articles, setArticles] = useState([]);
Next, call the
fetch() API in the
useEffect() method to get data from the news API:
useEffect(()=>{ fetch(URL) .then((response) => response.json()) .then((responseJson) => { return responseJson.articles; }) .then( articles => { setArticles(articles); setLoading(false); }) .catch( error => { console.error(error); }); } , []);
Also, finally we need to pass the
articles variable to the
<HomeScreen> component using a custom
articles property as follows:
if (loading){ return <SplashScreen /> } else { return <HomeScreen articles = { articles }/> }
As you can guess, the HomeScreen component doesn't actually know about any prop called
articles so we need to modify our component to render the items passed via the
articles prop:
const HomeScreen = (props) => { return ( <View> { props.articles.map((article, index)=>{ return <Text key = {index}> { article.title } </Text> }) } </View> ); }
We simpy render each news article using a
Text component.
This not the most efficient method of rendering lists. In the next section of our React Native tutorial, we’ll learn how to use the
FlatList component to render lists.
Rendering lists in React Native
In React Native, you can use FlatList or SectionList for rendering lists.
Let's change our previous code to use a flast list. In the
App.js file, start by importing
the
FlatList component as follows:
import { FlatList } from 'react-native';
Next, update the
HomeScreen component as follows:
const HomeScreen = (props) => { return ( <View> <FlatList keyExtractor={(item, index) => index.toString() data={ props.articles } renderItem={({item}) => <Text> {item.title}</Text>} /> </View> ); }
We use the data prop to pass the articles to the list and the renderItem to tell React Native how to render each item of our data. In our example, we simply render the title of each item using the
Text component:
We can also render complex components as the list item. Let's first create a custom component that dispays the title and description of a news article.
In the
App.js file, define the
ArticleItem component as follows:
const ArticleItem = ({article}) => { const { description, title } = article; return ( <View> <Text> { title } </Text> <Text> { description } </Text> </View> ) }
The component accept an
article prop and render the title and description of the article with Text components.
Using buttons in React Native
React Native provides a button component and a set of "Touchable" components for implmenting custom buttons if the default one is not enough.
We need to be able to open a news article or save it for reading later in our app so let's change our
ArticleItem component as follows:
const ArticleItem = ({article}) => { const { description, url, urlToImage } = article; return ( <View> <Image source= /> <Text> { title } </Text> <Text> { description } </Text> <Button onPress = { () => { console.log("Button pressed!")} } <Button onPress = { () => { console.log("Button pressed!") } } </View> ) }
For now, when your press the buttons you will only see Button pressed! message in the terminal if you are listenning for logs. We’ll learn how to implement the actual features using the
Linking and
AsyncStorage modules in our React Native tutorial in the next sections.
We also added an
<Image> component to display the image of the article.
Next, let's wire the
ArticleItem component to the
FlatList component in
HomeScreen function as follows:
const HomeScreen = (props) => { return ( <View> <FlatList data={ props.articles } renderItem={({item}) => <ArticleItem article = { item }/>} /> </View> ); }
This is our UI at this point:
Unlike what's expected the images of the articles don’t appear!
To solve this issue, we need to add a height to the Image component. Head over to the
styles.js file and add the following styles:
const styles = StyleSheet.create({ /* [...] */ articleContainer:{ borderWidth: 0, width: '100%', padding: 5 }, articleImage: { height: 200 }, articleTitle:{ textAlign: "center", padding: 20, fontSize: 17, color: 'black', backgroundColor: 'white', }, articleDescription:{ fontSize: 17, padding: 10, color: 'black', backgroundColor: 'white', }, articleBtns:{ flexDirection: 'row', backgroundColor: 'white', }, });
Next, you need to apply the styles to their components:
const ArticleItem = ({article}) => { const { title, description, url, urlToImage } = article; return ( <View style = { styles.articleContainer }> <Image style={ styles.articleImage } source= /> <Text style= { styles.articleTitle }> { title } </Text> <Text style = { styles.articleDescription }> { description } </Text> <View style = { styles.articleBtns}> <Button onPress = { () => { console.log("Button pressed!")} } <Button onPress = { () => { console.log("Button pressed!") } } </View> </View> ) }
Now, we have a much better UI:
Tutorial wrap-up
Throughout this React Native tutorial for the latest v0.6 released in 2019, we have created a simple example mobile app for Android and iOS using the fundamental concepts_11<<
_13<<
|
https://www.techiediaries.com/react-native-tutorial-example/
|
CC-MAIN-2020-05
|
refinedweb
| 4,169
| 61.06
|
Intel:
First, companies bought into the false premise that they exist to maximize shareholder value — which said “keep the stock price high.”
As a consequence, corporations used metrics like return on net assets (RONA), return on capital deployed, and internal rate of return (IRR) to measure efficiency.
These metrics make it difficult for a company that wants to invest in long-term innovation. It’s a lot easier to get these numbers to look great by outsourcing everything, getting assets off the balance sheet and only investing in things that pay off fast.
To do that, companies jettisoned internal R&D labs, outsourced manufacturing and cut long-term investment. These resulting business models made them look incredibly profitable.
Second, the leaders of these companies tended to be those who excelled at finance, supply chain or production. They knew how to execute the current business model.
Intel under their last two CEOs delivered more revenue and profit than any ever before. They could point to record investment in R&D for more expensive chip fabs yet today the writing is on the wall that Intel’s leading days are over. Why?
Over the last decade, Intel missed two important disruptive trends. First, the shift away from desktop computers to mobile devices meant that Intel’s power-hungry x86 processors weren’t suitable. ARM, a competitor, not only had a better, much lower power processor, but a better business model.
They licensed their architecture to other companies that designed their own products. Intel attempted to compete, (and actually owned an ARM license) but fell victim to a classic failure of ignoring a low-end disruptor and hobbling their own chances by deciding not cannibalize their own very profitable x86 business.
All of Intel’s resources — fabs, manufacturing strategies, and most importantly executive mindset — were geared towards large, expensive x86 processors, not low-cost mobile cores of someone else’s design.
The result, Intel laid off 12,000 people,.
Third, the reason why companies find it hard to innovate is the explosive shifts in technology, platforms and markets that have occurred in the last 15 years–personal computers moving to mobile devices.
We have life science breakthroughs in therapeutics, diagnostics, devices and digital health; and new markets like China emerging as consumers and suppliers.
Fourth,.
Startups are unencumbered by the status quo.
They re-envision how an industry can operate and grow, and they focus on better value propositions. On the low-end, they undercut cost structures, resulting in customer migration. At the high-end they create products and services that never existed before..
Corporations can foster innovation from the outside by promoting open innovation and buying startup-driven innovation. Google has bought close to 160 companies in the last decade. Its acquisition of Android may have been the biggest bargain in corporate history.)
|
https://medium.com/startup-grind/intel-disrupted-why-large-companies-find-it-difficult-to-innovate-and-what-they-can-do-about-it-1851e643431b
|
CC-MAIN-2017-30
|
refinedweb
| 471
| 53.81
|
RSpec has come a long way since I last used it in anger. Today, I'm starting through a worked example on test-driving a Ruby on Rails controller with RSpec, Capybara feature specs, and plenty of mocking. Along the way, we'll see some neat new features of RSpec in action. To my mind, Ruby on Rails controllers are a simple beast in the Model-View-Controller (MVC) pattern. They simply: take an HTTP action (GET, POST, PUT or DELETE) for a particular resource. The mapping between the HTTP verb, the resource, and the corresponding action is handled above the controller, at the routing layer. By the time it gets down to the controller, we already know what the desired action is, and we have an identifier for the resource, where applicable. communicate the intent of the action to the underlying model. return an appropriate response, whether that’s rendering a template with particular information, or sending back an HTTP redirect. There are two possibilities when it comes to communicating the intent of the action to the underlying model: It can query the model for some information, usually to render it as an HTML page, or emit some JSON representation of the model; or it can send a command to the model, and return an indication of the success or failure of the command. That’s it. The controller is merely an orchestration layer for translating between the language and idioms of HTTP, and the underlying model. I should probably note at this point that the underlying model isn’t necessarily just a bunch of ActiveRecord::Base-inherited models, it can be composed of service layers, aggregate roots, etc. The point is that the controllers are “just” about communicating between two other parts of the system (at least that’s how I always interpreted Jamis Buck’s famous Skinny Controller, Fat Model post). That’s handy, because it makes them nice and easy to test. I’ve been brushing up on RSpec over the past couple of weeks, learning all about the new syntax and features, and applying them to a couple of demo projects. I thought I’d share what I’d learned about rspec in the form of a worked example. Get indepth Ruby On Rails Training here We’ve got a requirement to keep track of Widgets. Widgets are pretty simple things: they have a name, and they have a size in millimetres (you wouldn’t want to get different sized widgets mixed up!). Our client, who manufactures these widgets, is looking for a simple web app where she can: list all widgets; create a new widget; and delete an existing widget. We’ve been developing their in-house stock management system for a while, so we’ve got an established Ruby on Rails project in which to hang the new functionality. It’s just going to be a case of extending it with a new model, controller, and a couple of actions. And we’re all set up with rspec, of course. Better still, we’re set up with Guard, too, so our tests run automatically whenever we make a change. You can find the starting point of the project on the initial setup branch. Listing all the widgets Let’s start with an integration test. I like the outside-in flow of testing that BDD encourages (in particular, the flow discussed in The RSpec Book), where we start with an integration test that roughly outlines the next feature we want to build, then start fleshing out the functionality with unit tests. So, our first scenario, in spec/features/widgets_spec.rb: RSpec.feature 'Managing widgets' do # All our subsequent scenarios will be inside this feature block. scenario 'Finding the list of widgets' do visit '/' click_on 'List Widgets' expect(current_path).to be('/widgets') end end I always like to start simple, and from the user’s perspective. If I’m going to manage a set of widgets, I need to be able to find the page from another location. In this scenario, we’re checking that there’s a ‘List Widgets’ link somewhere on the home page. It saves that embarrassing conversation with the client where you’ve implemented a new feature, but she can’t find it. The first thing to note is that, by default, rspec now no longer creates global methods, so Capybara’s feature DSL method (and RSpec’s describe, which we’ll see in a minute) are both defined on the RSpec namespace. Perhaps the other thing to note is that I’m just using RSpec feature specs – with Capybara for a nice DSL – instead of Cucumber, which I’ve advocated in the past? Why? It turned out that people rarely read my Cucumber stories, and those that did could cope with reading code, too. RSpec features are more succinct, consistent with the unit tests, and have fewer unwieldy overheads. You and your team’s mileage may, of course, vary! Finally, there’s rspec’s new expect syntax. Instead of adding methods to a global namespace (essentially, defining the should and should_not methods on Object), you have to explicitly wrap your objects. So, where in rspec 2.x and older, we’d have written: current_path.should eq('/widgets') (which relies on a method called should being defined on your object) instead we now wrap the object under test with expect: expect(current_path).to eq('/widgets') It still reads well (“expect current path to equal /widgets” as opposed to the older version, “current path should equal /widgets”). Combined with the allow decorator method, it also gives us a consistent language for mocking, which we’ll see shortly. To my mind, it also makes it slightly clearer exactly what the object under test really is, since it’s (necessarily) wrapped in parentheses. I like the new syntax. Let’s just assume we’ve implemented this particular scenario, by inserting the following into app/views/layouts/application.html.erb: <li><%= link_to 'List widgets', widgets_path %></li> It does bring up the issue of routes, though: how to we specify that the list of widgets is located at /widgets? Let’s write a couple of quick specs to verify the routes. I swither between testing routes being overkill or not. If there is client side JavaScript relying on the contract that the routes provide, I err on the side of specifying them. It’s not too hard, anyway. So, in spec/routing/widgets_controller_routing_spec.rb (what a mouthful, but it’s what rubocop recommends): RSpec.describe 'WidgetsController' do it 'routes GET /widgets to widgets#index' do expect(get: '/widgets').to route_to('widgets#index') end it 'generates /widgets from widgets_path' do expect(widgets_path).to eq('/widgets') end end In order to make these specs pass, add the following inside the routes block in config/routes.rb: resources :widgets, only: [:index] But one of our specs is still failing, complaining about the missing controller. Let’s create an empty controller to keep it happy. Add the following to app/controllers/widgets_controller.rb: class WidgetsController < ApplicationController end We’ve still got a failing scenario, though – because it’s missing the index action that results from clicking on the link to list widgets. Let’s start to test-drive the development of that controller action. This is what I describe as a “query”-style action, in that the user is querying something about the model and having the results displayed to them. In these query-style actions, there are four things that typically happen: the controller asks the model for some data; it responds with an HTTP status of '200 OK’; it specifies a particular template to be rendered; and it passes one or more objects to that template. Let’s specify the middle two for now. I’ve a feeling that will be enough to make our first scenario pass. In spec/controllers/widgets_controller_spec.rb, describe the desired behaviour: RSpec.describe WidgetsController do describe 'GET index' do def do_get get :index end it 'responds with http success' do do_get expect(response).to have_http_status(:success) end it 'renders the index template' do do_get expect(response).to render_template('widgets/index') end end end Defining a method to perform the action is just one of my habits. It doesn’t really add much here – it’s just replacing get :index with do_get – but it helps to remove repetition from testing other actions, and doing it here too gives me consistency amongst tests. Now define an empty index action in WidgetsController: def index end and create an empty template in app/views/widgets/index.html.erb. That’s enough to make the tests pass. Time to commit the code, and go grab a fresh coffee. Next up, let’s specify a real scenario for listing some widgets: scenario 'Listing widgets' do Widget.create! name: 'Frooble', size: 20 Widget.create! name: 'Barble', size: 42 visit '/widgets' expect(page).to have_content('Frooble (20mm)') expect(page).to have_content('Barble (42mm)') end Another failing scenario. Time to write some code. This time it’s complaining that the widgets we’re trying to create don’t have a model. Let’s sort that out: rails g model Widget name:string size:integer We’ll tweak the migration so neither of those columns are nullable (in our domain model it isn’t valid to have a widget without a name and a size) class CreateWidgets < ActiveRecord::Migration def change create_table :widgets do |t| t.string :name, null: false t.integer :size, null: false t.timestamps null: false end end end Run rake db:migrate and we’re good to go again. Our scenario is now failing where we’d expect it to – the list of widgets are not appearing on the page. Let’s think a bit about what we actually want here. Having discussed it with the client, we’re just looking for a list of all the Widgets in the system – no need to think about complex things like ordering, or pagination. So we’re going to ask the model for a list of all the widgets, and we’re going to pass that to the template to be rendered. Let’s write a controller spec for that behaviour, inside our existing describe block: let(:widget_class) { class_spy('Widget').as_stubbed_const } let(:widgets) { [instance_spy('Widget')] } before(:each) do allow(widget_class).to receive(:all) { widgets } end it 'fetches a list of widgets from the model' do do_get expect(widget_class).to have_received(:all) end it 'passes the list of widgets to the template' do do_get expect(assigns(:widgets)).to eq(widgets) end There are a few interesting new aspects to rspec going on here, mostly around the test doubles (the general name for mocks, stubs, and spies). Firstly, you’ll see that stubbed methods, and expectations of methods being called, use the new expect/allow syntax for consistency with the rest of your expectations. Next up is the ability to replace constants during the test run. You’ll see that we’re defining a test double for the Widget class. Calling as_stubbed_const on that class defines, for the duration of each test, the constant Widget as the test double. In the olden days of rspec 2, we’d have to either use dependency injection to supply an alternative widget implementation (something that’s tricky with implicitly instantiated controllers in Rails), or we’d have to define a partial test double, where we supply stubbed implementations for particular methods. This would be something along the lines of: before(:each) do allow(Widget).to receive(:all) { widgets } end While this works, it is only stubbing out the single method we’ve specified; the rest of the class methods on Widget are the real, live, implementations, so it’s more difficult to tell if the code under test is really calling what we expect it to. But the most interesting thing (to my mind) is that, in addition to the normal mocks and stubs, we also have test spies. Spies are like normal test doubles, except that they record how their users interact with them. This allows us, the test authors, to have a consistent pattern for our tests: Given some prerequisite; When I perform this action; Then I have these expectations. Prior to test spies, you had to set up the expectations prior to performing the action. So, when checking that the controller asks the model for the right thing, we’d have had to write: it 'fetches a list of widgets from the model' do expect(widget_class).to receive(:all) do_get end It seems like such a little thing, but it was always jarring to have some specs where the expectations had to precede the action. Spies make it all more consistent, which is a win. We’re back to having a failing test, so let’s write the controller implementation. In the index action of WidgetsController, it’s as simple as: @widget = Widget.all and finish off the implementation with the view template, in app/views/widgets/index.html.erb: <h1>All Widgets</h1> <ul> <%= render @widgets %> </ul> and, finally, app/views/widgets/widget.html.erb: <%= content_tag_for :li, widget do %> <%= widget.name %> (<%= widget.size %>mm) <% end %>
on 2017-02-06 12:32
|
https://www.ruby-forum.com/topic/6879261
|
CC-MAIN-2018-09
|
refinedweb
| 2,200
| 62.27
|
Does anyone know where I can find a website with a whole layout on how to program a file transfer program using sockets (Winsock) in C? Strictly C, so no C++ nor C#. I want to test out transferring files over from my desktop to my laptop.
You should check out Beej's Guide to Network Programming, that's where I learned how to use socketing in C. It's mainly Linux-based but it does include information on how to use it with Windows. You simply have to
#include <winsock.h> and call
WSAStartup.
There are also a lot of comprehensive guides on the internet, along with simple client-server examples you can implement.
|
https://codedump.io/share/8MN9Lsx2ILfo/1/winsock-file-transfer-in-c
|
CC-MAIN-2018-22
|
refinedweb
| 115
| 74.59
|
INTRODUCTION TO ADVANCED MACROECONOMICS Preliminary Exam with answers September 2014
- Ross Farmer
- 3 years ago
- Views:
Transcription
1 Duration: 120 min INTRODUCTION TO ADVANCED MACROECONOMICS Preliminary Exam with answers September 2014 Format of the mock examination Section A. Multiple Choice Questions (20 % of the total marks) Section B. True/False? Briefly explain Questions (20 % of the total marks) Section C. Problem set (40 % of the total marks) Section D. Open-end question (20 % of the total marks) Section A comprises 10 questions from which all 10 must be answered (accounting for 20% of the total marks). Each opening statement has four possible answers (a-d). There is only one correct answer to each question. Please clearly mark with X sign the correct answer in the table belw. There will be no penalty for the wrong answer though guessing is strongly discouraged. a b c d A.1 A.2 A.3 A.4 A.5 A.6 A.7 A.8 A.9 A.10 Section B True or false? Briefly explain your answer comprises 5 questions from which 4 must be answered (accounting for 20% of the total marks). You are expected not only to provide an answer but also briefly to justify it on the basis of the relevant theory. Full formal derivation of the relevant model is not expected, and often a graphic or descriptive (non-analytical) answer is sufficient. On average, only nine minutes should be allocated to any individual short question. There will be TWO long questions (problems) in Section C that are subdivided into at least three parts. There is a mixture of essay-based questions and questions requiring a more analytical model-based approach. In this section you are to be as precise as possible in your answers, and often formally to derive the relevant models, possibly in addition to a graphical or descriptive approach. Section D in an open-end essay-based question (accounting for 20% of the total marks). You are advised to limit your answer by 10 sentences. Ensure you can provide argumentation using both everyday AND professional language in order to be easily understood by non-economists. 1
2 Section A 1. Economy A with proportional taxes is closed and the government adjusts its spending to the level of taxes raised. Economy B is open and has lump-sum tax system. Comparing the balanced budget multipliers of the two economies one can conclude that: (a) Mult A < Mult B; (b) Mult A = Mult B; (c) Mult A > Mult B; (d) The multipliers can not be compared due to insufficient information. 2. A project yields 1500 every year for 2 years. What is the maximum disbursement you will agree to invest in the project had the interest rate been 5%: (a) 2929; (b) 2927; (c) 2788; (d) An unplanned decrease in stocks means: (a) The economy is in equilibrium in the goods market; (b) There is excess supply in the goods market; (c) There is excess demand in the goods market; (d) We cannot infer anything from this information. 4. Easy monetary policy brings about: (a) An excess supply of bonds and their price will fall; (b) An excess supply of bonds and the interest rate will fall; (c) An excess demand for bonds and their price will increase; (d) An excess demand for bonds and the interest rate will rise. 5. In a closed economy with fully flexible prices and wages, a balanced budget fiscal expansion will lead to: (a) A crowding out of investment by exactly the amount of additional government expenditure; (b) No changes in output and savings due to complete crowding out effect; (c) An increase in output and a decline in investment due to partial crowding out effect; (d) None of the above. 6. An increase in the economy wide marginal propensity to spend: (a) Will make the IS flatter and therefore, the AD will be steeper; (b) Will make the IS flatter and therefore, the AD will be flatter; (c) Will make the IS steeper and therefore, the AD will be flatter; (d) Will make the IS steeper and therefore, the AD will be steeper. 7. In an open economy with perfect capital mobility and a fixed but adjustable exchange rate, devaluation policy will: (a) Have no effect on the economy; (b) Lead to an increase in output and an increase in the supply of liquid assets; (c) Lead to an increase in output and a fall in the supply of liquid assets; (d) Lead to a fall in output and a decrease in the supply of liquid assets. 8. In an open economy with perfect capital mobility and a flexible exchange rate an increase in international interest rates will lead to: (a) No changes in trade deficit; (b) An increase in net exports; (c) A decrease in net exports; (d) An increase in domestic interest rates by monetary contraction. 9. In an open economy with no capital mobility and flexible exchange rate an increase in government spending will: 2
3 Section B (a) Have no real effect; (b) Lead to an increase in output; (c) Lead to a recession; (d) Lead to monetary contraction. 10. An increase labour supply would cause: (a) a decrease in nominal wages; (b) no change in nominal wages; (c) an increase in nominal wages; (d) uncertain effect on nominal wages. B1. If all prices and wages are fully flexible in the short run then the aggregate supply (AS) curve is vertical. It is possible to argue that this statement could be either TRUE or FALSE. With flexible wages and prices, the labour market will adjust to a point where labour demand is equal to labour supply (there is an equilibrium real wage w = W/P). In the case where all agents have perfect information and do not suffer from money illusion, the equilibrium real wage and employment level will be independent of the price level P. With employment independent of P, the supply of output is also independent of P. This means the aggregate supply function is vertical. When the information available to agents is imperfect, the aggregate supply function will be upward sloping even if wages and prices are fully flexible. For example, suppose workers do not observe the price level P, but firms do. In this case, workers must infer the real value of their nominal wage. This means the position of the labour supply curve depends on how the actual price level differs from workers expectations (labour demand is unaffected if firms have full information). Given expectations, the price level changes equilibrium employment and hence output. B2. An increase in a central bank s discount rate will reduce the monetary base. The statement is TRUE. The discount rate is the interest rate charged by the central bank for loans of reserves. A higher discount rate discourages banks from borrowing reserves from the central bank through the discount window (because the amount they must repay has increased), thus fewer reserves will be created this way. Since reserves form part of the monetary base, the monetary base will be lower. A good answer to this question would start by giving a definition of the monetary base (reserves plus cash) and then explain the basics of the discount window (discount facility) offered by central banks. Candidates are encouraged to keep their answers to short questions as relevant and concise as possible. In particular, in this question, it is not necessary to mention or discuss other means of controlling the money supply such as open-market operations. B3. An increase in the level of money wages implies the aggregate supply (AS) curve shifts to the right. The statement is FALSE. For a given price level P, an increase in money wages W raises the real wage w = W/P. Firms incentives to hire labour are thus reduced, and employment is lower, moving down the labour demand curve (workers are assumed not to be on their labour supply curve because wages are sticky, so the labour market does not clear). Lower employment leads to lower output. Output is therefore reduced for each and every price level, so the short-run aggregate supply curve (SRAS) shifts to the left, not to the right. 3
4 A full answer to this question requires an explanation of how the direction of the shift of the AS curve is determined. While it is not necessary to give a full derivation of the SRAS curve, it is helpful to have the labour-market diagram in the answer to provide a clear analysis. B4. According to uncovered interest parity (UIP), a higher domestic nominal interest rate is associated with an expected depreciation of the domestic currency. The statement is TRUE. Uncovered interest parity states that investors must receive the same expected return (adjusting for currency movements) whether they hold domestic or foreign bonds (because they are assumed to be risk neutral). The domestic-currency return on domestic bonds is i, while the foreign-currency return on foreign bonds is i*. Any appreciation of the domestic exchange rate e e (as a percentage) decreases the domestic-currency return on foreign bonds, which is therefore i e e. Mathematically, the UIP equation is i = i e e. An expected depreciation is a negative value of e e, which increases the domestic interest rate i. The best approach to answering this question clearly and quickly is to write down the UIP equation and briefly explain what the equation represents. When writing down any equation, it is strongly advised that candidates define notation where there is a danger of ambiguity or misunderstanding. In particular, it should be made clear whether the exchange rate is the domestic price of foreign currency (as in the explanation above) or the foreign price of domestic currency. B5. A minimum wage law can be a cause of classical unemployment. The statement is TRUE. A minimum wage that is binding pushes up the real wage above its market-clearing level. This means that more individuals would like to work than the number of jobs firms have an incentive to create. In other words, at the minimum wage, desired labour supply exceeds labour demand. Without the minimum wage or other rigidities, the real wage would fall to bring demand and supply into line. But the minimum wage prevents this adjustment, so the excess of desired labour supply above labour demand is classical unemployment. A good answer to this question would provide a clear definition of classical unemployment that distinguishes it from other types of unemployment. The most efficient way of explaining the effects of the minimum wage is to use a standard labour-market diagram, comparing the outcome with a market-clearing real wage to the outcome with the minimum wage. 4
5 Section C Problem C.1. Consider a closed economy with fixed prices and wages. (a) Suppose the demand for money is given by M d /P = m 0 + ky hr, where M d is nominal money demand, P is the price level, Y is real income, and r is the interest rate. Assume the price level is fixed at P = 1. Suppose that the central bank fixes the money supply M s = M. Show that the slope of the LM curve (representing money-market equilibrium) is dr/dy = k/h Which values of the parameters k and h represent the case of money demand that is inelastic with respect to income? Using the equation above, deduce that the LM curve is horizontal in this case. (7 marks) Money-market equilibrium (represented by the LM curve) is found using the equation M d = M S with P = 1: This equation can be rearranged as follows: M = m 0 + ky hr. r = m 0 M + ky. h Differentiating with respect to Y shows that the slope of the LM curve is k/h. Money demand being inelastic with respect to income requires a zero response, hence k = 0. It follows that k/h = 0, so the LM curve has slope equal to zero, in other words, it is flat. (b) Goods market equilibrium is where output is equal to the sum of consumption, investment, and government spending: Y = C + I + G. The consumption function is C = C 0 + c 1 (Y T) and the investment function is: I = I 0 br. Government spending G = G 0 and taxes T = T 0 are exogenous. Consider an economy where the LM curve is horizontal, as in part (a). Suppose that households increase their desire to save, which can be interpreted as a fall in autonomous consumption C 0. What are the effects on output Y and national saving S N? (Recall that national saving is defined as S N = (Y T C) + (T G).) Explain your answer intuitively. (7 marks) With a horizontal LM curve, the interest rate r must be the same no matter what is the level of output Y. Goodsmarket equilibrium (represented by the IS curve) is found using the following equation, which can be solved for output Y: Y = C + I + G = C 0 + c 1 (Y T 0 ) + I 0 br + G o = c 1 Y + (C 0 + I 0 + G o c 1 T 0 br). Collecting all terms in Y on the left-hand side of the equation: and therefore equilibrium output is: (1 c 1 )Y = C 0 + I 0 + G o c 1 T 0 br Y = C 0 + I 0 + G o c 1 T 0 br. 1 c 1 From this equation, a fall in C 0 is seen to reduce Y. Alternatively, this part of the answer can be explained using an IS/LM or expenditure/income diagram. Note that a greater desire to save implies a reduction in the autonomous component of consumption demand. Lower consumption demand means lower expenditure, hence the IS curve shifts to the left. Output is therefore lower. 5
6 Now consider national saving, defined as S N = Y C G. The equilibrium level of national saving can be found using the consumption function: S N = Y C 0 + c 1 (Y T 0 ) G o = (1 c 1 )Y C 0 G o + c 1 T 0. Substituting in the expression for (1 - c)y derived earlier: S N = (C 0 + I 0 + G o c 1 T 0 br) C 0 G o + c 1 T 0 = I 0 br. Therefore, national saving is not affected by the increase in desired saving (the interest rate is constant because the LM curve is flat). Alternatively, a simpler way of reaching this conclusion is to note S N = (C + I + G) - C - G = I. Since I = I 0 br and as the interest rate is constant because of the horizontal LM curve, there is no change in investment, hence no change in national saving. Intuitively, although households would like to save more, they do this by spending less, which reduces demand. Since interest rates cannot fall, investment cannot rise to compensate, thus demand is lower. With sticky prices, demand determines incomes, which then fall. With lower incomes, even if consumption is lower, actual saving can remain unchanged. (c) Repeat the analysis of part (b) when investment depends positively on output, as implied by the equation I = I 0 + ay br Explain the intuition for the differences you find compared with your answers to part (b). (6 marks) In this case, following the same steps as in part (b), the expression for equilibrium output is: Y = C 0 + I 0 + G o c 1 T 0 br. 1 c 1 a Since 1 (1 c 1 a) > 1 (1 c 1 ), the fall in C 0 leads to a larger reduction in output than in part (b). Alternatively, the result can be explained using the expenditure/income diagram. When investment depends on income, the expenditure line is steeper. Thus, a given reduction in demand (shifting the expenditure line down by a given amount) now leads to a larger fall in output in equilibrium. This means that the IS curve shifts further to the left. The intuition is that there is now an additional multiplier effect working through investment as well as consumption (lower demand reduces output, which further reduces demand for investment). National saving is still equal to investment, and since Y falls while r remains constant, investment must fall. This means that national saving actually falls now. 6
7 7
8 Problem C.2. Consider the Solow model of economic growth. Assume the production function is Y = K 1/2 L 1/2 where Y is output, K is the capital stock, and L is the labour force. The labour force (assumed equal to the population) grows at a constant rate n. The capital stock depreciates at a constant rate δ. There is no exogenous technological progress (g = 0). The saving rate is s. (a) Let y = Y/L and k = K/L denote output per person and capital per person. Show that the production function implies: y = f (k) = k 1/2 The dynamics of the capital stock per person are described by the equation k = s f (k) (δ + n)k (you are not required to derive this equation). Show how the steady-state stock of capital per person is found using a diagram and explain why the economy will converge to this point in the long run. Using the diagram, find the effects of a rise in the saving rate s on steady-state capital and output per person. Sketch a graph showing the path of capital and output per person over time during convergence to the new steady state. (7 marks) Divide the expression for output Y given by the production function by population L to obtain output per person: y = Y L = K1 2 L 1 2 L = K1 2 L 1 2 L 1 2 L 1 2 = K 1 2 L = k. The steady state is the intersection between the upward-sloping and concave saving line s f (k) and the straight depreciation line (δ + n)k. To the left of the intersection point, the saving line is above the depreciation line, so using the equation for Dk, the capital stock will increase, and similarly, capital will fall to the right of the intersection point. Therefore, the economy will converge to the intersection point in the long run. An increase in the saving rate s shifts the saving line upwards. The intersection point with the depreciation line is now to the right, so steady-state capital per person will be higher. Moving up the unchanged production function y = f (k), output per person will also be higher. 8
9 Convergence to the new steady state takes place gradually over time. There is no initial jump in either capital or output since the capital stock is predetermined (the existing capital stock is derived from past investment). Putting all these findings together and plotting the evolution of capital and output per person over time: (b) Let c = C/L denote consumption per person. Given the saving rate s, consumption per person is determined by the equation: c = (1 s) f (k) The Golden-rule level of the capital stock k * is the level that maximizes steady-state consumption per person. Using your diagram or using algebra, explain why the Golden-rule capital stock is the solution of the equation: f '(k * ) = δ + n Assume that the capital stock is initially below the Golden-rule level. The saving rate is now increased to allow the economy to reach the Golden rule. Sketch a graph showing the path of consumption over time following this change in the saving rate. (7 marks) The steady-state capital stock is such that the savings and depreciation lines have the same height, which can be written algebraically as the equation s f (k) = (δ + n)k. This equation can be used to derive an expression for consumption in the steady state: c = (1 s)f(k) = f(k) sf(k) = f(k) (δ + n)k. The Golden-rule capital stock is the capital stock that maximises steady-state consumption. Differentiating with respect to k and setting the derivative equal to zero gives the first-order condition for the maximum: c k = f (k) (δ + n) = 0. This equation implies that the Golden-rule capital stock must have a marginal product of capital f (k) equal to the sum of the depreciation and population growth rates. 9
10 The alternative graphical argument notes that steady-state consumption is the vertical distance between the production function and the depreciation line (because the saving line has the same height as the depreciation line in any steady state). Geometrically, this is at its greatest where the tangent to the production function (with slope f (k)) has the same slope as that of the depreciation line (i.e. δ + n). It is important to note that the question explicitly calls for one of these arguments justifying the Golden-rule condition. A good answer therefore requires an explanation of why the Golden-rule capital stock satisfies the equation f (k) = (δ + n), not simply a description of what the Golden rule means. When the saving rate is increased, this immediately reduces consumption (since c = (1 s)f(k) and the capital stock k does not adjust immediately). In the long run, the economy will converge to the Golden-rule capital stock, so consumption will be higher than it was in the initial steady state (this follows from the definition of the Golden rule as the capital stock that maximises steady-state consumption). The results from part (a) show that capital and output will rise during the transition to the long run, so consumption, which is proportional to output (c = (1 s)y) will be rising while convergence is taking place. This means that consumption will be below its initial value for some time. The best answers were able to explain all the movements in consumption depicted in the diagram above. A significant number of candidates failed to account for there being two effects on consumption: a direct effect from changing the saving rate, and an indirect effect caused by the changes in output following the change to the saving rate (which affects capital accumulation). The key to understanding the dynamics of consumption is that once the saving rate has changed (which has an immediate effect on consumption), the subsequent movements in consumption will follow the movements in output. (c) Suppose the saving rate is s = 0.2, population growth is n = 0.01, and the depreciation rate is δ = Calculate whether the economy described by these parameters requires a higher or a lower saving rate to reach the Golden-rule level of capital. (6 marks) Substituting the parameters from the question into the equation sf(k) = (δ + n)k for the steady-state capital stock: By dividing both sides by 0.1 k, this equation implies 0.2 k = ( )k. k = = 2 and therefore k = 4. The marginal product of capital f (k) can be obtained by differentiating the production function f(k) with respect to capital k: f (k) = k k = 1 2 k. 10
11 Evaluating this at k = 4 yields f (k) = 1/4 = With the parameters in the question, δ + n = 0.1, so f (k) > δ + n. Since the marginal product of capital increases when the capital stock is lower (diminishing marginal returns to capital), this shows that the economy has too little capital, so the saving rate should be increased to reach the Golden rule. A common mistake when answering this part of the question was not understanding that f (k) increases when k is lower. The diminishing marginal product of capital is one of the most important assumptions of the Solow growth model. Section D The December 14, 2010 issue of the Wall Street Journal ran an article entitled Official Relieves Pressure on BOJ. The article states: The chief spokesman for Japan's government said additional monetary easing, including setting an inflation target, won't help Japan conquer deflation. He also suggests Tokyo won't press the Bank of Japan for more steps to prop up the economy anytime soon. Yoshito Sengoku said in an interview Japan has experienced continued price declines despite years of aggressive easing policies from both the monetary and fiscal sides, a phenomenon that convinces him that deflation is caused by the nation's proximity to lower-cost economies like China and the nations in South East Asia. Some people seem to believe the BOJ can generate an adequate level of inflation by just printing money. But I don't think that's the case, said Mr. Sengoku, who serves as chief of staff to Prime Minister Naoto Kan." a) Suppose one takes Mr. Sengoku s conjecture that lower-cost economies like China are causing deflation in Japan as operating through a reduction in P* in our model. In this case, does Mr. Sengoku s conjecture match with the long-run predictions of the small open economy flexible exchange rate model developed in class? (10 marks) A fall in P* does nothing to the full employment level of output, the BB curve, or the LM curve. It shifts the IS curve back as demand is shifted away from domestic goods and towards foreign goods. To restore long-run equilibrium, the exchange rate must depreciate and shift IS back. The price of domestic goods cannot fall to push IS back because a change in domestic prices would shift LM, and that can t move. In other words, Mr. Sengoku s prediction is not consistent with the model. b) Use the relevant model to evaluate Mr. Sengoku s claim that additional monetary easing won t help Japan conquer deflation. In particular, compare the long-run effect on the price of domestically produced goods of a permanent increase in the money supply in a closed economy and a small open economy with flexible exchange rates. (10 marks) In either case P rises in equal percentage. Since changes in money supply have no long run effect on interest rates (with expected inflation held fixed) or output, prices must adjust to re-equilibrate the money market following an increase in supply, and that means an equal percentage increase in prices and money supply. This change in price will not spill over and affect a small open economy in the goods market because the exchange rate will offset any movement in prices.
CHAPTER 7: AGGREGATE DEMAND AND AGGREGATE SUPPLY
CHAPTER 7: AGGREGATE DEMAND AND AGGREGATE SUPPLY Learning goals of this chapter: What forces bring persistent and rapid expansion of real GDP? What causes inflation? Why do we have business cycles? How
QUESTION 1: SHORT VERSUS MEDIUM RUN. 30 points
QUESTION 1: SHORT VERSUS MEDIUM RUN. 30 points Consider an economy that fits the AS-AD model. The labor market equilibrium is given by the AS curve. The equilibrium in the goods market is given by the
Practiced Questions. Chapter 20
Practiced Questions Chapter 20 1. The model of aggregate demand and aggregate supply a. is different from the model of supply and demand for a particular market, in that we cannot focus on the substitution. Key Concepts
Chapter 11 FISCAL POLICY* Key Concepts The Federal Budget The federal budget is an annual statement of the government s expenditures and tax revenues. Using the federal budget to achieve macroeconomic
Business Conditions Analysis Prof. Yamin Ahmad ECON 736
Business Conditions Analysis Prof. Yamin Ahmad ECON 736 Sample Final Exam Name Id # Instructions: There are two parts to this midterm. Part A consists of multiple choice questions. Please mark the answers:
MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.
Econ 111 Summer 2007 Final Exam Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) The classical dichotomy allows us to explore economic growth 102 Aggregate Supply and Demand
Econ 102 ggregate Supply and Demand 1. s on previous homework assignments, turn in a news article together with your summary and explanation of why it is relevant to this week s topic, ggregate Supply
Chapter 13. Aggregate Demand and Aggregate Supply Analysis
Chapter 13. Aggregate Demand and Aggregate Supply Analysis Instructor: JINKOOK LEE Department of Economics / Texas A&M University ECON 203 502 Principles of Macroeconomics In the short run, real GDP and
Use the following to answer question 9: Exhibit: Keynesian Cross
1. Leading economic indicators are: A) the most popular economic statistics. B) data that are used to construct the consumer price index and the unemployment rate. C) variables that tend to fluctuate
0 100 200 300 Real income (Y)
Lecture 11-1 6.1 The open economy, the multiplier, and the IS curve Assume that the economy is either closed (no foreign trade) or open. Assume that the exchange rates are either fixed or flexible. Assume
I d ( r; MPK f, τ) Y < C d +I d +G
1. Use the IS-LM model to determine the effects of each of the following on the general equilibrium values of the real wage, employment, output, the real interest rate, consumption, investment, and
Problem Set #4: Aggregate Supply and Aggregate Demand Econ 100B: Intermediate Macroeconomics
roblem Set #4: Aggregate Supply and Aggregate Demand Econ 100B: Intermediate Macroeconomics 1) Explain the differences between demand-pull inflation and cost-push inflation. Demand-pull inflation results
AGGREGATE DEMAND AND AGGREGATE SUPPLY The Influence of Monetary and Fiscal Policy on Aggregate Demand
AGGREGATE DEMAND AND AGGREGATE SUPPLY The Influence of Monetary and Fiscal Policy on Aggregate Demand Suppose that the economy is undergoing a recession because of a fall in aggregate demand. a. Using
Refer to Figure 17-1
Chapter 17 1. Inflation can be measured by the a. change in the consumer price index. b. percentage change in the consumer price index. c. percentage change in the price of a specific commodity. d. change
Answers to Text Questions and Problems. Chapter 22. Answers to Review Questions
Answers to Text Questions and Problems Chapter 22 Answers to Review Questions 3. In general, producers of durable goods are affected most by recessions while producers of nondurables (like food) and services
MONEY, INTEREST, REAL GDP, AND THE PRICE LEVEL*
Chapter 11 MONEY, INTEREST, REAL GDP, AND THE PRICE LEVEL* The Demand for Topic: Influences on Holding 1) The quantity of money that people choose to hold depends on which of the following? I. The price
The Aggregate Demand- Aggregate Supply (AD-AS) Model
The AD-AS Model The Aggregate Demand- Aggregate Supply (AD-AS) Model Chapter 9 The AD-AS Model addresses two deficiencies of the AE Model: No explicit modeling of aggregate supply. Fixed price level.
Problem Set for Chapter 20(Multiple choices)
Problem Set for hapter 20(Multiple choices) 1. According to the theory of liquidity preference, a. if the interest rate is below the equilibrium level, then the quantity of money people want to hold is
7 AGGREGATE SUPPLY AND AGGREGATE DEMAND* Chapter. Key Concepts
Chapter 7 AGGREGATE SUPPLY AND AGGREGATE DEMAND* Key Concepts Aggregate Supply The aggregate production function shows that the quantity of real GDP (Y ) supplied depends on the quantity of labor
Economics 152 Solution to Sample Midterm 2
Economics 152 Solution to Sample Midterm 2 N. Das PART 1 (84 POINTS): Answer the following 28 multiple choice questions on the scan sheet. Each question is worth 3 points. 1. If Congress passes legislation
The Circular Flow of Income and Expenditure
The Circular Flow of Income and Expenditure Imports HOUSEHOLDS Savings Taxation Govt Exp OTHER ECONOMIES GOVERNMENT FINANCIAL INSTITUTIONS Factor Incomes Taxation Govt Exp Consumer Exp Exports FIRMS Capital
ECO209 MACROECONOMIC THEORY. Chapter 11
Prof. Gustavo Indart Department of Economics University of Toronto ECO209 MACROECONOMIC THEORY Chapter 11 MONEY, INTEREST, AND INCOME Discussion Questions: 1. The model in Chapter 9 assumed that both the
Chapter Outline. Chapter 13. Exchange Rates. Exchange Rates
Chapter 13, Business Cycles, and Macroeconomic Policy in the Open Economy Chapter Outline How Are Determined: A Supply-and-Demand Analysis The IS-LM Model for an Open Economy Macroeconomic Policy in an
Econ 336 - Spring 2007 Homework 5
Econ 336 - Spring 2007 Homework 5 Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) The real exchange rate, q, is defined as A) E times P
Econ 202 Section 4 Final Exam
Douglas, Fall 2009 December 15, 2009 A: Special Code 00004 PLEDGE: I have neither given nor received unauthorized help on this exam. SIGNED: PRINT NAME: Econ 202 Section 4 Final Exam 1. Oceania buys $40 OPEN AGGREGATE DEMAND AGGREGATE SUPPLY MODEL.
THE OPEN AGGREGATE DEMAND AGGREGATE SUPPLY MODEL. Introduction. This model represents the workings of the economy as the interaction between two curves: - The AD curve, showing the relationship between
CHAPTER 7 Economic Growth I
CHAPTER 7 Economic Growth I Questions for Review 1. In the Solow growth model, a high saving rate leads to a large steady-state capital stock and a high level of steady-state output. A low saving rate 9 Building the Aggregate Expenditures Model
CHAPTER 9 Building the Aggregate Expenditures Model Topic Question numbers 1. Consumption function/apc/mpc 1-42 2. Saving function/aps/mps 43-56 3. Shifts in consumption and saving functions 57-72 4 Graphs/tables:
MONETARY AND FISCAL POLICY IN THE VERY SHORT RUN
C H A P T E R12 MONETARY AND FISCAL POLICY IN THE VERY SHORT RUN LEARNING OBJECTIVES After reading and studying this chapter, you should be able to: Understand that both fiscal and monetary policy can Unemployment and Inflation
Chapter 12 Unemployment and Inflation Multiple Choice Questions 1. The origin of the idea of a trade-off between inflation and unemployment was a 1958 article by (a) A.W. Phillips. (b) Edmund Phelps.
Answer: C Learning Objective: Money supply Level of Learning: Knowledge Type: Word Problem Source: Unique
1.The aggregate demand curve shows the relationship between inflation and: A) the nominal interest rate. D) the exchange rate. B) the real interest rate. E) short-run equilibrium output. C) the unemployment
S.Y.B.COM. (SEM-III) ECONOMICS
Fill in the Blanks. Module 1 S.Y.B.COM. (SEM-III) ECONOMICS 1. The continuous flow of money and goods and services between firms and households is called the Circular Flow. 2. Saving constitute a leakage
8. Simultaneous Equilibrium in the Commodity and Money Markets
Lecture 8-1 8. Simultaneous Equilibrium in the Commodity and Money Markets We now combine the IS (commodity-market equilibrium) and LM (money-market equilibrium) schedules to establish a general equilibrium
Chapters 7 and 8 Solow Growth Model Basics
Chapters 7 and 8 Solow Growth Model Basics The Solow growth model breaks the growth of economies down into basics. It starts with our production function Y = F (K, L) and puts in per-worker terms. Y L
6. Budget Deficits and Fiscal Policy
Prof. Dr. Thomas Steger Advanced Macroeconomics II Lecture SS 2012 6. Budget Deficits and Fiscal Policy Introduction Ricardian equivalence Distorting taxes Debt crises Introduction (1) Ricardian equivalence
ECON 4423: INTERNATIONAL FINANCE
University of Colorado at Boulder Department of Economics ECON 4423: INTERNATIONAL FINANCE Final Examination Fall 2005 Name: Answer Key Student ID: Instructions: This test is 1 1/2 hours in length. You
BUSINESS ECONOMICS CEC2 532-751 & 761
BUSINESS ECONOMICS CEC2 532-751 & 761 PRACTICE MACROECONOMICS MULTIPLE CHOICE QUESTIONS Warning: These questions have been posted to give you an opportunity to practice with the multiple choice format
1 Multiple Choice - 50 Points
Econ 201 Final Winter 2008 SOLUTIONS 1 Multiple Choice - 50 Points (In this section each question is worth 1 point) 1. Suppose a waiter deposits his cash tips into his savings account. As a result of only
Answers to Text Questions and Problems in Chapter 8
Answers to Text Questions and Problems in Chapter 8 Answers to Review Questions 1. The key assumption is that, in the short run, firms meet demand at pre-set prices. The fact that firms produce to meet
ANSWERS TO END-OF-CHAPTER QUESTIONS
ANSWERS TO END-OF-CHAPTER QUESTIONS 9-1 Explain what relationships are shown by (a) the consumption schedule, (b) the saving schedule, (c) the investment-demand curve, and (d) the investment schedule.
Homework #6 - Answers. Uses of Macro Policy Due April 20
Page 1 of 8 Uses of Macro Policy ue April 20 Answer all questions on these sheets, adding extra sheets where necessary. 1. Suppose that the government were to increase its purchases of goods and services
Examination II. Fixed income valuation and analysis. Economics
Examination II Fixed income valuation and analysis Economics Questions Foundation examination March 2008 FIRST PART: Multiple Choice Questions (48 points) Hereafter you must answer all 12 multiple choice
CH 10 - REVIEW QUESTIONS
CH 10 - REVIEW QUESTIONS 1. The short-run aggregate supply curve is horizontal at: A) a level of output determined by aggregate demand. B) the natural level of output. C) the level of output at which the.
Econ 202 Section 2 Final Exam
Douglas, Fall 2009 December 17, 2009 A: Special Code 0000 PLEDGE: I have neither given nor received unauthorized help on this exam. SIGNED: PRINT NAME: Econ 202 Section 2 Final Exam 1. The present value
The
|
http://docplayer.net/21067864-Introduction-to-advanced-macroeconomics-preliminary-exam-with-answers-september-2014.html
|
CC-MAIN-2019-35
|
refinedweb
| 6,222
| 51.38
|
hey I got to create an oval class for my java class.
Create an Oval class given the following design:
YourLastNameOval
variables: width, length
methods:
setWidth - changes the width. Requires one parameter for width.
setLength - changes the length. Requires one parameter for length.
getWidth - returns the oval width.
getLength - returns the oval length.
area - returns the area of the oval ((l*w)*0.8) given the current width and length
Write appropriate client code to test the class. Call the client class simply YourLastName
This is what I have so far.
public class McIntoshOval {
public double length, width;
public Oval(){
public int width = 5;
public int length = 10;
}
public Oval(double l, double w){
length = l;
width = w;
}
public void setLength(){
length = l;
}
public double getLength(){
return(length);
}
public void setWidth(){
width = w;
}
public double getWidth(){
return(width);
}
public double area (){
return((l*w)*0.8) ;
}
public static void main(String[] args) {
}
}
Can anyone give me some help, perhaps stir me in the right direction and let me know of things I am missing Id really appreciate it. Thanks.
And client code?? What is that?
the client class simply has a main method, creates one or more Oval objects and tests them.
Regarding help: what specific questions do you have?
If you provide methods to set the length or the width, you need to allow the desired values to be passed into them.
Computers are good at following instructions, but not at reading your mind...
D. Knuth
Please use [CODE]...your code here...[/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.
View Tag Cloud
Forum Rules
|
http://forums.codeguru.com/showthread.php?469928-Creating-a-Oval-class
|
CC-MAIN-2016-44
|
refinedweb
| 279
| 76.62
|
Subject: [Boost-build] How to execute a command after succesful buildx
From: Kim Tang (kuentang_at_[hidden])
Date: 2016-05-08 16:50:01
Hi all,
Is it possible to execute a shell command once the build was successful?
I would like to do something like this:
# Declare an executable called pik that embeds Python
lib pik : pik.cpp /python//python q ;
import testing ;
# Declare a test of the pik application
# I just want to run something like
# q test_pik.q
# q is a shell program
testing.run pik pik.cpp
: # any
ordinary arguments
: # any
arguments that should be treated as relative paths
: #
requirements
: test_pik ; #
name of test
Many thanks for any suggestions or help.
-- Kim Tang
Boost-Build list run by bdawes at acm.org, david.abrahams at rcn.com, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
|
https://lists.boost.org/boost-build/2016/05/28636.php
|
CC-MAIN-2019-22
|
refinedweb
| 144
| 68.47
|
You.
You must always put a mock method definition (MOCK_METHOD*) in a public: section of the mock class, regardless of the method being mocked being public, protected, or private in the base class. This allows ON_CALL and EXPECT_CALL to reference the mock function from outside of the mock class. (Yes, C++ allows a subclass to change the access level of a virtual function in the base class.) Example:
class Foo {
public:
...
virtual bool Transform(Gadget* g) = 0;
protected:
virtual void Resume();
private:
virtual int GetTimeOut();
};
class MockFoo : public Foo {
public:
...
MOCK_METHOD1(Transform, bool(Gadget* g));
// The following must be in the public section, even though the
// methods are protected or private in the base class.
MOCK_METHOD0(Resume, void());
MOCK_METHOD0(GetTimeOut, int());
};
You can mock overloaded functions as usual. No special attention is required:
class Foo {
...
// Must be virtual as we'll inherit from Foo.
virtual ~Foo();
// Overloaded on the types and/or numbers of arguments.
virtual int Add(Element x);
virtual int Add(int times, Element x);
// Overloaded on the const-ness of this object.
virtual Bar& GetBar();
virtual const Bar& GetBar() const;
};
class MockFoo : public Foo {
...
MOCK_METHOD1(Add, int(Element x));
MOCK_METHOD2(Add, int(int times, Element x);
MOCK_METHOD0(GetBar, Bar&());
MOCK_CONST_METHOD0(GetBar, const Bar&());
};
Note: if you don't mock all versions of the overloaded method, the compiler will give you a warning about some methods in the base class being hidden. To fix that, use using to bring them in scope:
class MockFoo : public Foo {
...
using Foo::Add;
MOCK_METHOD1(Add, int(Element x));
// We don't want to mock int Add(int times, Element x);
...
};
To mock a class template, append _T to the MOCK_* macros:
template <typename Elem>
class StackInterface {
...
// Must be virtual as we'll inherit from StackInterface.
virtual ~StackInterface();
virtual int GetSize() const = 0;
virtual void Push(const Elem& x) = 0;
};
template <typename Elem>
class MockStack : public StackInterface<Elem> {
...
MOCK_CONST_METHOD0_T(GetSize, int());
MOCK_METHOD1_T(Push, void(const Elem& x));
};
Google Mock can mock non-virtual functions to be used in what we call hi-perf dependency injection.
In this case, instead of sharing a common base class with the real class, your mock class will be unrelated to the real class, but contain methods with the same signatures. The syntax for mocking non-virtual methods is the same as mocking virtual methods:
// A simple packet stream class. None of its members is virtual.
class ConcretePacketStream {
public:
void AppendPacket(Packet* new_packet);
const Packet* GetPacket(size_t packet_number) const;
size_t NumberOfPackets() const;
...
};
// A mock packet stream class. It inherits from no other, but defines
// GetPacket() and NumberOfPackets().
class MockPacketStream {
public:
MOCK_CONST_METHOD1(GetPacket, const Packet*(size_t packet_number));
MOCK_CONST_METHOD0(NumberOfPackets, size_t());
...
};
Note that the mock class doesn't define AppendPacket(), unlike the real class. That's fine as long as the test doesn't need to call it.
Next, you need a way to say that you want to use ConcretePacketStream in production code, and use MockPacketStream in tests. Since the functions are not virtual and the two classes are unrelated, you must specify your choice at compile time (as opposed to run time).
One way to do it is to templatize your code that needs to use a packet stream. More specifically, you will give your code a template type argument for the type of the packet stream. In production, you will instantiate your template with ConcretePacketStream as the type argument. In tests, you will instantiate the same template with MockPacketStream. For example, you may write:
template <class PacketStream>
void CreateConnection(PacketStream* stream) { ... }
template <class PacketStream>
class PacketReader {
public:
void ReadPackets(PacketStream* stream, size_t packet_num);
};
Then you can use CreateConnection<ConcretePacketStream>() and PacketReader<ConcretePacketStream> in production code, and use CreateConnection<MockPacketStream>() and PacketReader<MockPacketStream> in tests.
MockPacketStream mock_stream;
EXPECT_CALL(mock_stream, ...)...;
.. set more expectations on mock_stream ...
PacketReader<MockPacketStream> reader(&mock_stream);
... exercise reader ...
It's possible to use Google Mock to mock a free function (i.e. a C-style function or a static method). You just need to rewrite your code to use an interface (abstract class).
Instead of calling a free function (say, OpenFile) directly, introduce an interface for it and have a concrete subclass that calls the free function:
class FileInterface {
public:
...
virtual bool Open(const char* path, const char* mode) = 0;
};
class File : public FileInterface {
public:
...
virtual bool Open(const char* path, const char* mode) {
return OpenFile(path, mode);
}
};
Your code should talk to FileInterface to open a file. Now it's easy to mock out the function.
This may seem much hassle, but in practice you often have multiple related functions that you can put in the same interface, so the per-function syntactic overhead will be much lower.
If you are concerned about the performance overhead incurred by virtual functions, and profiling confirms your concern, you can combine this with the recipe for mocking non-virtual methods.
If a mock method has no EXPECT_CALL spec but is called, Google Mock will print a warning about the "uninteresting call". The rationale is:
However, sometimes you may want to suppress all "uninteresting call" warnings, while sometimes you may want the opposite, i.e. to treat all of them as errors. Google Mock lets you make the decision on a per-mock-object basis.
Suppose your test uses a mock class MockFoo:
TEST(...) {
MockFoo mock_foo;
EXPECT_CALL(mock_foo, DoThis());
... code that uses mock_foo ...
}
If a method of mock_foo other than DoThis() is called, it will be reported by Google Mock as a warning. However, if you rewrite your test to use NiceMock<MockFoo> instead, the warning will be gone, resulting in a cleaner test output:
using ::testing::NiceMock;
TEST(...) {
NiceMock<MockFoo> mock_foo;
EXPECT_CALL(mock_foo, DoThis());
... code that uses mock_foo ...
}
NiceMock<MockFoo> is a subclass of MockFoo, so it can be used wherever MockFoo is accepted.
It also works if MockFoo's constructor takes some arguments, as NiceMock<MockFoo> "inherits" MockFoo's constructors:
using ::testing::NiceMock;
TEST(...) {
NiceMock<MockFoo> mock_foo(5, "hi"); // Calls MockFoo(5, "hi").
EXPECT_CALL(mock_foo, DoThis());
... code that uses mock_foo ...
}
The usage of StrictMock is similar, except that it makes all uninteresting calls failures:
using ::testing::StrictMock;
TEST(...) {
StrictMock<MockFoo> mock_foo;
EXPECT_CALL(mock_foo, DoThis());
... code that uses mock_foo ...
// The test will fail if a method of mock_foo other than DoThis()
// is called.
}
There are some caveats though (I don't like them just as much as the next guy, but sadly they are side effects of C++'s limitations):
Finally, you should be very cautious when using this feature, as the decision you make applies to all future changes to the mock class. If an important change is made in the interface you are mocking (and thus in the mock class), it could break your tests (if you use StrictMock) or let bugs pass through without a warning (if you use NiceMock). Therefore, try to specify the mock's behavior using explicit EXPECT_CALL first, and only turn to NiceMock or StrictMock as the last resort.
Sometimes a method has a long list of arguments that is mostly uninteresting. For example,
class LogSink {
public:
...
virtual void send(LogSeverity severity, const char* full_filename,
const char* base_filename, int line,
const struct tm* tm_time,
const char* message, size_t message_len) = 0;
};
This method's argument list is lengthy and hard to work with (let's say that the message argument is not even 0-terminated). If we mock it as is, using the mock will be awkward. If, however, we try to simplify this interface, we'll need to fix all clients depending on it, which is often infeasible.
The trick is to re-dispatch the method in the mock class:
class ScopedMockLog : public LogSink {
public:
...
virtual void send(LogSeverity severity, const char* full_filename,
const char* base_filename, int line, const tm* tm_time,
const char* message, size_t message_len) {
// We are only interested in the log severity, full file name, and
// log message.
Log(severity, full_filename, std::string(message, message_len));
}
// Implements the mock method:
//
// void Log(LogSeverity severity,
// const string& file_path,
// const string& message);
MOCK_METHOD3(Log, void(LogSeverity severity, const string& file_path,
const string& message));
};
By defining a new mock method with a trimmed argument list, we make the mock class much more user-friendly.
Often you may find yourself using classes that don't implement interfaces. In order to test your code that uses such a class (let's call it Concrete), you may be tempted to make the methods of Concrete virtual and then mock it.
Try not to do that.
Making a non-virtual function virtual is a big decision. It creates an extension point where subclasses can tweak your class' behavior. This weakens your control on the class because now it's harder to maintain the class' invariants. You should make a function virtual only when there is a valid reason for a subclass to override it.
Mocking concrete classes directly is problematic as it creates a tight coupling between the class and the tests - any small change in the class may invalidate your tests and make test maintenance a pain.
To avoid such problems, many programmers have been practicing "coding to interfaces": instead of talking to the Concrete class, your code would define an interface and talk to it. Then you implement that interface as an adaptor on top of Concrete. In tests, you can easily mock that interface to observe how your code is doing.
This technique incurs some overhead:
However, it can also bring significant benefits in addition to better testability:
Some people worry that if everyone is practicing this technique, they will end up writing lots of redundant code. This concern is totally understandable. However, there are two reasons why it may not be the case:
You need to weigh the pros and cons carefully for your particular problem, but I'd like to assure you that the Java community has been practicing this for a long time and it's a proven effective technique applicable in a wide variety of situations. :-)
Some times you have a non-trivial fake implementation of an interface. For example:
class Foo {
public:
virtual ~Foo() {}
virtual char DoThis(int n) = 0;
virtual void DoThat(const char* s, int* p) = 0;
};
class FakeFoo : public Foo {
public:
virtual char DoThis(int n) {
return (n > 0) ? '+' :
(n < 0) ? '-' : '0';
}
virtual void DoThat(const char* s, int* p) {
*p = strlen(s);
}
};
Now you want to mock this interface such that you can set expectations on it. However, you also want to use FakeFoo for the default behavior, as duplicating it in the mock object is, well, a lot of work.
When you define the mock class using Google Mock, you can have it delegate its default action to a fake class you already have, using this pattern:
using ::testing::_;
using ::testing::Invoke;
class MockFoo : public Foo {
public:
// Normal mock method definitions using Google Mock.
MOCK_METHOD1(DoThis, char(int n));
MOCK_METHOD2(DoThat, void(const char* s, int* p));
// Delegates the default actions of the methods to a FakeFoo object.
// This must be called *before* the custom ON_CALL() statements.
void DelegateToFake() {
ON_CALL(*this, DoThis(_))
.WillByDefault(Invoke(&fake_, &FakeFoo::DoThis));
ON_CALL(*this, DoThat(_, _))
.WillByDefault(Invoke(&fake_, &FakeFoo::DoThat));
}
private:
FakeFoo fake_; // Keeps an instance of the fake in the mock.
};
With that, you can use MockFoo in your tests as usual. Just remember that if you don't explicitly set an action in an ON_CALL() or EXPECT_CALL(), the fake will be called upon to do it:
using ::testing::_;
TEST(AbcTest, Xyz) {
MockFoo foo;
foo.DelegateToFake(); // Enables the fake for delegation.
// Put your ON_CALL(foo, ...)s here, if any.
// No action specified, meaning to use the default action.
EXPECT_CALL(foo, DoThis(5));
EXPECT_CALL(foo, DoThat(_, _));
int n = 0;
EXPECT_EQ('+', foo.DoThis(5)); // FakeFoo::DoThis() is invoked.
foo.DoThat("Hi", &n); // FakeFoo::DoThat() is invoked.
EXPECT_EQ(2, n);
}
Some tips:
Regarding the tip on mixing a mock and a fake, here's an example on why it may be a bad sign: Suppose you have a class System for low-level system operations. In particular, it does file and I/O operations. And suppose you want to test how your code uses System to do I/O, and you just want the file operations to work normally. If you mock out the entire System class, you'll have to provide a fake implementation for the file operation part, which suggests that System is taking on too many roles.
Instead, you can define a FileOps interface and an IOOps interface and split System's functionalities into the two. Then you can mock IOOps without mocking FileOps.
When using testing doubles (mocks, fakes, stubs, and etc), sometimes their behaviors will differ from those of the real objects. This difference could be either intentional (as in simulating an error such that you can test the error handling code) or unintentional. If your mocks have different behaviors than the real objects by mistake, you could end up with code that passes the tests but fails in production.
You can use the delegating-to-real technique to ensure that your mock has the same behavior as the real object while retaining the ability to validate calls. This technique is very similar to the delegating-to-fake technique, the difference being that we use a real object instead of a fake. Here's an example:
using ::testing::_;
using ::testing::AtLeast;
using ::testing::Invoke;
class MockFoo : public Foo {
public:
MockFoo() {
// By default, all calls are delegated to the real object.
ON_CALL(*this, DoThis())
.WillByDefault(Invoke(&real_, &Foo::DoThis));
ON_CALL(*this, DoThat(_))
.WillByDefault(Invoke(&real_, &Foo::DoThat));
...
}
MOCK_METHOD0(DoThis, ...);
MOCK_METHOD1(DoThat, ...);
...
private:
Foo real_;
};
...
MockFoo mock;
EXPECT_CALL(mock, DoThis())
.Times(3);
EXPECT_CALL(mock, DoThat("Hi"))
.Times(AtLeast(1));
... use mock in test ...
With this, Google Mock will verify that your code made the right calls (with the right arguments, in the right order, called the right number of times, etc), and a real object will answer the calls (so the behavior will be the same as in production). This gives you the best of both worlds.
Ideally, you should code to interfaces, whose methods are all pure virtual. In reality, sometimes you do need to mock a virtual method that is not pure (i.e, it already has an implementation). For example:
class Foo {
public:
virtual ~Foo();
virtual void Pure(int n) = 0;
virtual int Concrete(const char* str) { ... }
};
class MockFoo : public Foo {
public:
// Mocking a pure method.
MOCK_METHOD1(Pure, void(int n));
// Mocking a concrete method. Foo::Concrete() is shadowed.
MOCK_METHOD1(Concrete, int(const char* str));
};
Sometimes you may want to call Foo::Concrete() instead of MockFoo::Concrete(). Perhaps you want to do it as part of a stub action, or perhaps your test doesn't need to mock Concrete() at all (but it would be oh-so painful to have to define a new mock class whenever you don't need to mock one of its methods).
The trick is to leave a back door in your mock class for accessing the real methods in the base class:
class MockFoo : public Foo {
public:
// Mocking a pure method.
MOCK_METHOD1(Pure, void(int n));
// Mocking a concrete method. Foo::Concrete() is shadowed.
MOCK_METHOD1(Concrete, int(const char* str));
// Use this to call Concrete() defined in Foo.
int FooConcrete(const char* str) { return Foo::Concrete(str); }
};
Now, you can call Foo::Concrete() inside an action by:
using ::testing::_;
using ::testing::Invoke;
...
EXPECT_CALL(foo, Concrete(_))
.WillOnce(Invoke(&foo, &MockFoo::FooConcrete));
or tell the mock object that you don't want to mock Concrete():
using ::testing::Invoke;
...
ON_CALL(foo, Concrete(_))
.WillByDefault(Invoke(&foo, &MockFoo::FooConcrete));
(Why don't we just write Invoke(&foo, &Foo::Concrete)? If you do that, MockFoo::Concrete() will be called (and cause an infinite recursion) since Foo::Concrete() is virtual. That's just how C++ works.)
You can specify exactly which arguments a mock method is expecting:
using ::testing::Return;
...
EXPECT_CALL(foo, DoThis(5))
.WillOnce(Return('a'));
EXPECT_CALL(foo, DoThat("Hello", bar));
You can use matchers to match arguments that have a certain property:
using ::testing::Ge;
using ::testing::NotNull;
using ::testing::Return;
...
EXPECT_CALL(foo, DoThis(Ge(5))) // The argument must be >= 5.
.WillOnce(Return('a'));
EXPECT_CALL(foo, DoThat("Hello", NotNull()));
// The second argument must not be NULL.
A frequently used matcher is _, which matches anything:
using ::testing::_;
using ::testing::NotNull;
...
EXPECT_CALL(foo, DoThat(_, NotNull()));
You can build complex matchers from existing ones using AllOf(), AnyOf(), and Not():
using ::testing::AllOf;
using ::testing::Gt;
using ::testing::HasSubstr;
using ::testing::Ne;
using ::testing::Not;
...
// The argument must be > 5 and != 10.
EXPECT_CALL(foo, DoThis(AllOf(Gt(5),
Ne(10))));
// The first argument must not contain sub-string "blah".
EXPECT_CALL(foo, DoThat(Not(HasSubstr("blah")),
NULL));
Google Mock matchers are statically typed, meaning that the compiler can catch your mistake if you use a matcher of the wrong type (for example, if you use Eq(5) to match a string argument). Good for you!
Sometimes, however, you know what you're doing and want the compiler to give you some slack. One example is that you have a matcher for long and the argument you want to match is int. While the two types aren't exactly the same, there is nothing really wrong with using a Matcher<long> to match an int - after all, we can first convert the int argument to a long before giving it to the matcher.
To support this need, Google Mock gives you the SafeMatcherCast<T>(m) function. It casts a matcher m to type Matcher<T>. To ensure safety, Google Mock checks that (let U be the type m accepts):
The code won't compile if any of these conditions isn't met.
Here's one example:
using ::testing::SafeMatcherCast;
// A base class and a child class.
class Base { ... };
class Derived : public Base { ... };
class MockFoo : public Foo {
public:
MOCK_METHOD1(DoThis, void(Derived* derived));
};
...
MockFoo foo;
// m is a Matcher<Base*> we got from somewhere.
EXPECT_CALL(foo, DoThis(SafeMatcherCast<Derived*>(m)));
If you find SafeMatcherCast<T>(m) too limiting, you can use a similar function MatcherCast<T>(m). The difference is that MatcherCast works as long as you can static_cast type T to type U.
MatcherCast essentially lets you bypass C++'s type system (static_cast isn't always safe as it could throw away information, for example), so be careful not to misuse/abuse it.
If you expect an overloaded function to be called, the compiler may need some help on which overloaded version it is.
To disambiguate functions overloaded on the const-ness of this object, use the Const() argument wrapper.
using ::testing::ReturnRef;
class MockFoo : public Foo {
...
MOCK_METHOD0(GetBar, Bar&());
MOCK_CONST_METHOD0(GetBar, const Bar&());
};
...
MockFoo foo;
Bar bar1, bar2;
EXPECT_CALL(foo, GetBar()) // The non-const GetBar().
.WillOnce(ReturnRef(bar1));
EXPECT_CALL(Const(foo), GetBar()) // The const GetBar().
.WillOnce(ReturnRef(bar2));
(Const() is defined by Google Mock and returns a const reference to its argument.)
To disambiguate overloaded functions with the same number of arguments but different argument types, you may need to specify the exact type of a matcher, either by wrapping your matcher in Matcher<type>(), or using a matcher whose type is fixed (TypedEq<type>, An<type>(), etc):
using ::testing::An;
using ::testing::Lt;
using ::testing::Matcher;
using ::testing::TypedEq;
class MockPrinter : public Printer {
public:
MOCK_METHOD1(Print, void(int n));
MOCK_METHOD1(Print, void(char c));
};
TEST(PrinterTest, Print) {
MockPrinter printer;
EXPECT_CALL(printer, Print(An<int>())); // void Print(int);
EXPECT_CALL(printer, Print(Matcher<int>(Lt(5)))); // void Print(int);
EXPECT_CALL(printer, Print(TypedEq<char>('a'))); // void Print(char);
printer.Print(3);
printer.Print(6);
printer.Print('a');
}
When a mock method is called, the last matching expectation that's still active will be selected (think "newer overrides older"). So, you can make a method do different things depending on its argument values like this:
using ::testing::_;
using ::testing::Lt;
using ::testing::Return;
...
// The default case.
EXPECT_CALL(foo, DoThis(_))
.WillRepeatedly(Return('b'));
// The more specific case.
EXPECT_CALL(foo, DoThis(Lt(5)))
.WillRepeatedly(Return('a'));
Now, if foo.DoThis() is called with a value less than 5, 'a' will be returned; otherwise 'b' will be returned.
Sometimes it's not enough to match the arguments individually. For example, we may want to say that the first argument must be less than the second argument. The With() clause allows us to match all arguments of a mock function as a whole. For example,
using ::testing::_;
using ::testing::Lt;
using ::testing::Ne;
...
EXPECT_CALL(foo, InRange(Ne(0), _))
.With(Lt());
says that the first argument of InRange() must not be 0, and must be less than the second argument.
The expression inside With() must be a matcher of type Matcher<tr1::tuple<A1, ..., An> >, where A1, ..., An are the types of the function arguments.
You can also write AllArgs(m) instead of m inside .With(). The two forms are equivalent, but .With(AllArgs(Lt())) is more readable than .With(Lt()).
You can use Args<k1, ..., kn>(m) to match the n selected arguments (as a tuple) against m. For example,
using ::testing::_;
using ::testing::AllOf;
using ::testing::Args;
using ::testing::Lt;
...
EXPECT_CALL(foo, Blah(_, _, _))
.With(AllOf(Args<0, 1>(Lt()), Args<1, 2>(Lt())));
says that Blah() will be called with arguments x, y, and z where x < y < z.
As a convenience and example, Google Mock provides some matchers for 2-tuples, including the Lt() matcher above. See the CheatSheet for the complete list.
Note that if you want to pass the arguments to a predicate of your own (e.g. .With(Args<0, 1>(Truly(&MyPredicate)))), that predicate MUST be written to take a tr1::tuple as its argument; Google Mock will pass the n selected arguments as one single tuple to the predicate.
Have you noticed that a matcher is just a fancy predicate that also knows how to describe itself? Many existing algorithms take predicates as arguments (e.g. those defined in STL's <algorithm> header), and it would be a shame if Google Mock matchers are not allowed to participate.
Luckily, you can use a matcher where a unary predicate functor is expected by wrapping it inside the Matches() function. For example,
#include <algorithm>
#include <vector>
std::vector<int> v;
...
// How many elements in v are >= 10?
const int count = count_if(v.begin(), v.end(), Matches(Ge(10)));
Since you can build complex matchers from simpler ones easily using Google Mock, this gives you a way to conveniently construct composite predicates (doing the same using STL's <functional> header is just painful). For example, here's a predicate that's satisfied by any number that is >= 0, <= 100, and != 50:
Matches(AllOf(Ge(0), Le(100), Ne(50)))
Since matchers are basically predicates that also know how to describe themselves, there is a way to take advantage of them in Google Test assertions. It's called ASSERT_THAT and EXPECT_THAT:
ASSERT_THAT(value, matcher); // Asserts that value matches matcher.
EXPECT_THAT(value, matcher); // The non-fatal version.
For example, in a Google Test test you can write:
#include "gmock/gmock.h"
using ::testing::AllOf;
using ::testing::Ge;
using ::testing::Le;
using ::testing::MatchesRegex;
using ::testing::StartsWith;
...
EXPECT_THAT(Foo(), StartsWith("Hello"));
EXPECT_THAT(Bar(), MatchesRegex("Line \\d+"));
ASSERT_THAT(Baz(), AllOf(Ge(5), Le(10)));
which (as you can probably guess) executes Foo(), Bar(), and Baz(), and verifies that:
The nice thing about these macros is that they read like English. They generate informative messages too. For example, if the first EXPECT_THAT() above fails, the message will be something like:
Value of: Foo()
Actual: "Hi, world!"
Expected: starts with "Hello"
Credit: The idea of (ASSERT|EXPECT)_THAT was stolen from the Hamcrest project, which adds assertThat() to JUnit.
Google Mock provides a built-in set of matchers. In case you find them lacking, you can use an arbitray unary predicate function or functor as a matcher - as long as the predicate accepts a value of the type you want. You do this by wrapping the predicate inside the Truly() function, for example:
using ::testing::Truly;
int IsEven(int n) { return (n % 2) == 0 ? 1 : 0; }
...
// Bar() must be called with an even number.
EXPECT_CALL(foo, Bar(Truly(IsEven)));
Note that the predicate function / functor doesn't have to return bool. It works as long as the return value can be used as the condition in statement if (condition) ....
When you do an EXPECT_CALL(mock_obj, Foo(bar)), Google Mock saves away a copy of bar. When Foo() is called later, Google Mock compares the argument to Foo() with the saved copy of bar. This way, you don't need to worry about bar being modified or destroyed after the EXPECT_CALL() is executed. The same is true when you use matchers like Eq(bar), Le(bar), and so on.
But what if bar cannot be copied (i.e. has no copy constructor)? You could define your own matcher function and use it with Truly(), as the previous couple of recipes have shown. Or, you may be able to get away from it if you can guarantee that bar won't be changed after the EXPECT_CALL() is executed. Just tell Google Mock that it should save a reference to bar, instead of a copy of it. Here's how:
using ::testing::Eq;
using ::testing::ByRef;
using ::testing::Lt;
...
// Expects that Foo()'s argument == bar.
EXPECT_CALL(mock_obj, Foo(Eq(ByRef(bar))));
// Expects that Foo()'s argument < bar.
EXPECT_CALL(mock_obj, Foo(Lt(ByRef(bar))));
Remember: if you do this, don't change bar after the EXPECT_CALL(), or the result is undefined.
Often a mock function takes a reference to object as an argument. When matching the argument, you may not want to compare the entire object against a fixed object, as that may be over-specification. Instead, you may need to validate a certain member variable or the result of a certain getter method of the object. You can do this with Field() and Property(). More specifically,
Field(&Foo::bar, m)
is a matcher that matches a Foo object whose bar member variable satisfies matcher m.
Property(&Foo::baz, m)
is a matcher that matches a Foo object whose baz() method returns a value that satisfies matcher m.
For example:
Field(&Foo::number, Ge(3)) Matches x where x.number >= 3.
Property(&Foo::name, StartsWith("John ")) Matches x where x.name() starts with "John ".
Note that in Property(&Foo::baz, ...), method baz() must take no argument and be declared as const.
BTW, Field() and Property() can also match plain pointers to objects. For instance,
Field(&Foo::number, Ge(3))
matches a plain pointer p where p->number >= 3. If p is NULL, the match will always fail regardless of the inner matcher.
What if you want to validate more than one members at the same time? Remember that there is AllOf().
C++ functions often take pointers as arguments. You can use matchers like IsNull(), NotNull(), and other comparison matchers to match a pointer, but what if you want to make sure the value pointed to by the pointer, instead of the pointer itself, has a certain property? Well, you can use the Pointee(m) matcher.
Pointee(m) matches a pointer iff m matches the value the pointer points to. For example:
using ::testing::Ge;
using ::testing::Pointee;
...
EXPECT_CALL(foo, Bar(Pointee(Ge(3))));
expects foo.Bar() to be called with a pointer that points to a value greater than or equal to 3.
One nice thing about Pointee() is that it treats a NULL pointer as a match failure, so you can write Pointee(m) instead of
AllOf(NotNull(), Pointee(m))
without worrying that a NULL pointer will crash your test.
Also, did we tell you that Pointee() works with both raw pointers and smart pointers (linked_ptr, shared_ptr, scoped_ptr, and etc)?
What if you have a pointer to pointer? You guessed it - you can use nested Pointee() to probe deeper inside the value. For example, Pointee(Pointee(Lt(3))) matches a pointer that points to a pointer that points to a number less than 3 (what a mouthful...).
Sometimes you want to specify that an object argument has a certain property, but there is no existing matcher that does this. If you want good error messages, you should define a matcher. If you want to do it quick and dirty, you could get away with writing an ordinary function.
Let's say you have a mock function that takes an object of type Foo, which has an int bar() method and an int baz() method, and you want to constrain that the argument's bar() value plus its baz() value is a given number. Here's how you can define a matcher to do it:
using ::testing::MatcherInterface;
using ::testing::MatchResultListener;
class BarPlusBazEqMatcher : public MatcherInterface<const Foo&> {
public:
explicit BarPlusBazEqMatcher(int expected_sum)
: expected_sum_(expected_sum) {}
virtual bool MatchAndExplain(const Foo& foo,
MatchResultListener* listener) const {
return (foo.bar() + foo.baz()) == expected_sum_;
}
virtual void DescribeTo(::std::ostream* os) const {
*os << "bar() + baz() equals " << expected_sum_;
}
virtual void DescribeNegationTo(::std::ostream* os) const {
*os << "bar() + baz() does not equal " << expected_sum_;
}
private:
const int expected_sum_;
};
inline Matcher<const Foo&> BarPlusBazEq(int expected_sum) {
return MakeMatcher(new BarPlusBazEqMatcher(expected_sum));
}
...
EXPECT_CALL(..., DoThis(BarPlusBazEq(5)))...;
Sometimes an STL container (e.g. list, vector, map, ...) is passed to a mock function and you may want to validate it. Since most STL containers support the == operator, you can write Eq(expected_container) or simply expected_container to match a container exactly.
Sometimes, though, you may want to be more flexible (for example, the first element must be an exact match, but the second element can be any positive number, and so on). Also, containers used in tests often have a small number of elements, and having to define the expected container out-of-line is a bit of a hassle.
You can use the ElementsAre() matcher in such cases:
using ::testing::_;
using ::testing::ElementsAre;
using ::testing::Gt;
...
MOCK_METHOD1(Foo, void(const vector<int>& numbers));
...
EXPECT_CALL(mock, Foo(ElementsAre(1, Gt(0), _, 5)));
The above matcher says that the container must have 4 elements, which must be 1, greater than 0, anything, and 5 respectively.
ElementsAre() is overloaded to take 0 to 10 arguments. If more are needed, you can place them in a C-style array and use ElementsAreArray() instead:
using ::testing::ElementsAreArray;
...
// ElementsAreArray accepts an array of element values.
const int expected_vector1[] = { 1, 5, 2, 4, ... };
EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector1)));
// Or, an array of element matchers.
Matcher<int> expected_vector2 = { 1, Gt(2), _, 3, ... };
EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector2)));
In case the array needs to be dynamically created (and therefore the array size cannot be inferred by the compiler), you can give ElementsAreArray() an additional argument to specify the array size:
using ::testing::ElementsAreArray;
...
int* const expected_vector3 = new int[count];
... fill expected_vector3 with values ...
EXPECT_CALL(mock, Foo(ElementsAreArray(expected_vector3, count)));
Tips:
Under the hood, a Google Mock matcher object consists of a pointer to a ref-counted implementation object. Copying matchers is allowed and very efficient, as only the pointer is copied. When the last matcher that references the implementation object dies, the implementation object will be deleted.
Therefore, if you have some complex matcher that you want to use again and again, there is no need to build it everytime. Just assign it to a matcher variable and use that variable repeatedly! For example,
Matcher<int> in_range = AllOf(Gt(5), Le(10));
... use in_range as a matcher in multiple EXPECT_CALLs ...
If you are not interested in how a mock method is called, just don't say anything about it. In this case, if the method is ever called, Google Mock will perform its default action to allow the test program to continue. If you are not happy with the default action taken by Google Mock, you can override it using DefaultValue<T>::Set() (described later in this document) or ON_CALL().
Please note that once you expressed interest in a particular mock method (via EXPECT_CALL()), all invocations to it must match some expectation. If this function is called but the arguments don't match any EXPECT_CALL() statement, it will be an error.
If a mock method shouldn't be called at all, explicitly say so:
using ::testing::_;
...
EXPECT_CALL(foo, Bar(_))
.Times(0);
If some calls to the method are allowed, but the rest are not, just list all the expected calls:
using ::testing::AnyNumber;
using ::testing::Gt;
...
EXPECT_CALL(foo, Bar(5));
EXPECT_CALL(foo, Bar(Gt(10)))
.Times(AnyNumber());
A call to foo.Bar() that doesn't match any of the EXPECT_CALL() statements will be an error.
Although an EXPECT_CALL() statement defined earlier takes precedence when Google Mock tries to match a function call with an expectation, by default calls don't have to happen in the order EXPECT_CALL() statements are written. For example, if the arguments match the matchers in the third EXPECT_CALL(), but not those in the first two, then the third expectation will be used.
If you would rather have all calls occur in the order of the expectations, put the EXPECT_CALL() statements in a block where you define a variable of type InSequence:
using ::testing::_;
using ::testing::InSequence;
{
InSequence s;
EXPECT_CALL(foo, DoThis(5));
EXPECT_CALL(bar, DoThat(_))
.Times(2);
EXPECT_CALL(foo, DoThis(6));
}
In this example, we expect a call to foo.DoThis(5), followed by two calls to bar.DoThat() where the argument can be anything, which are in turn followed by a call to foo.DoThis(6). If a call occurred out-of-order, Google Mock will report an error.
Sometimes requiring everything to occur in a predetermined order can lead to brittle tests. For example, we may care about A occurring before both B and C, but aren't interested in the relative order of B and C. In this case, the test should reflect our real intent, instead of being overly constraining.
Google Mock allows you to impose an arbitrary DAG (directed acyclic graph) on the calls. One way to express the DAG is to use the After clause of EXPECT_CALL.
Another way is via the InSequence() clause (not the same as the InSequence class), which we borrowed from jMock 2. It's less flexible than After(), but more convenient when you have long chains of sequential calls, as it doesn't require you to come up with different names for the expectations in the chains. Here's how it works:
If we view EXPECT_CALL() statements as nodes in a graph, and add an edge from node A to node B wherever A must occur before B, we can get a DAG. We use the term "sequence" to mean a directed path in this DAG. Now, if we decompose the DAG into sequences, we just need to know which sequences each EXPECT_CALL() belongs to in order to be able to reconstruct the orginal DAG.
So, to specify the partial order on the expectations we need to do two things: first to define some Sequence objects, and then for each EXPECT_CALL() say which Sequence objects it is part of. Expectations in the same sequence must occur in the order they are written. For example,
using ::testing::Sequence;
Sequence s1, s2;
EXPECT_CALL(foo, A())
.InSequence(s1, s2);
EXPECT_CALL(bar, B())
.InSequence(s1);
EXPECT_CALL(bar, C())
.InSequence(s2);
EXPECT_CALL(foo, D())
.InSequence(s2);
specifies the following DAG (where s1 is A -> B, and s2 is `A -> C -> D`):
+---> B
|
A ---|
|
+---> C ---> D
This means that A must occur before B and C, and C must occur before D. There's no restriction about the order other than these.
When a mock method is called, Google Mock only consider expectations that are still active. An expectation is active when created, and becomes inactive (aka retires) when a call that has to occur later has occurred. For example, in
using ::testing::_;
using ::testing::Sequence;
Sequence s1, s2;
EXPECT_CALL(log, Log(WARNING, _, "File too large.")) // #1
.Times(AnyNumber())
.InSequence(s1, s2);
EXPECT_CALL(log, Log(WARNING, _, "Data set is empty.")) // #2
.InSequence(s1);
EXPECT_CALL(log, Log(WARNING, _, "User not found.")) // #3
.InSequence(s2);
as soon as either #2 or #3 is matched, #1 will retire. If a warning "File too large." is logged after this, it will be an error.
Note that an expectation doesn't retire automatically when it's saturated. For example,
using ::testing::_;
...
EXPECT_CALL(log, Log(WARNING, _, _)); // #1
EXPECT_CALL(log, Log(WARNING, _, "File too large.")); // #2
says that there will be exactly one warning with the message `"File too large."`. If the second warning contains this message too, #2 will match again and result in an upper-bound-violated error.
If this is not what you want, you can ask an expectation to retire as soon as it becomes saturated:
using ::testing::_;
...
EXPECT_CALL(log, Log(WARNING, _, _)); // #1
EXPECT_CALL(log, Log(WARNING, _, "File too large.")) // #2
.RetiresOnSaturation();
Here #2 can be used only once, so if you have two warnings with the message "File too large.", the first will match #2 and the second will match #1 - there will be no error.
If a mock function's return type is a reference, you need to use ReturnRef() instead of Return() to return a result:
using ::testing::ReturnRef;
class MockFoo : public Foo {
public:
MOCK_METHOD0(GetBar, Bar&());
};
...
MockFoo foo;
Bar bar;
EXPECT_CALL(foo, GetBar())
.WillOnce(ReturnRef(bar));
The Return(x) action saves a copy of x when the action is created, and always returns the same value whenever it's executed. Sometimes you may want to instead return the live value of x (i.e. its value at the time when the action is executed.).
If the mock function's return type is a reference, you can do it using ReturnRef(x), as shown in the previous recipe ("Returning References from Mock Methods"). However, Google Mock doesn't let you use ReturnRef() in a mock function whose return type is not a reference, as doing that usually indicates a user error. So, what shall you do?
You may be tempted to try ByRef():
using testing::ByRef;
using testing::Return;
class MockFoo : public Foo {
public:
MOCK_METHOD0(GetValue, int());
};
...
int x = 0;
MockFoo foo;
EXPECT_CALL(foo, GetValue())
.WillRepeatedly(Return(ByRef(x)));
x = 42;
EXPECT_EQ(42, foo.GetValue());
Unfortunately, it doesn't work here. The above code will fail with error:
Value of: foo.GetValue()
Actual: 0
Expected: 42
The reason is that Return(value) converts value to the actual return type of the mock function at the time when the action is created, not when it is executed. (This behavior was chosen for the action to be safe when value is a proxy object that references some temporary objects.) As a result, ByRef(x) is converted to an int value (instead of a const int&) when the expectation is set, and Return(ByRef(x)) will always return 0.
ReturnPointee(pointer) was provided to solve this problem specifically. It returns the value pointed to by pointer at the time the action is executed:
using testing::ReturnPointee;
...
int x = 0;
MockFoo foo;
EXPECT_CALL(foo, GetValue())
.WillRepeatedly(ReturnPointee(&x)); // Note the & here.
x = 42;
EXPECT_EQ(42, foo.GetValue()); // This will succeed now.
Want to do more than one thing when a function is called? That's fine. DoAll() allow you to do sequence of actions every time. Only the return value of the last action in the sequence will be used.
using ::testing::DoAll;
class MockFoo : public Foo {
public:
MOCK_METHOD1(Bar, bool(int n));
};
...
EXPECT_CALL(foo, Bar(_))
.WillOnce(DoAll(action_1,
action_2,
...
action_n));
Sometimes a method exhibits its effect not via returning a value but via side effects. For example, it may change some global state or modify an output argument. To mock side effects, in general you can define your own action by implementing ::testing::ActionInterface.
If all you need to do is to change an output argument, the built-in SetArgPointee() action is convenient:
using ::testing::SetArgPointee;
class MockMutator : public Mutator {
public:
MOCK_METHOD2(Mutate, void(bool mutate, int* value));
...
};
...
MockMutator mutator;
EXPECT_CALL(mutator, Mutate(true, _))
.WillOnce(SetArgPointee<1>(5));
In this example, when mutator.Mutate() is called, we will assign 5 to the int variable pointed to by argument #1 (0-based).
SetArgPointee() conveniently makes an internal copy of the value you pass to it, removing the need to keep the value in scope and alive. The implication however is that the value must have a copy constructor and assignment operator.
If the mock method also needs to return a value as well, you can chain SetArgPointee() with Return() using DoAll():
using ::testing::_;
using ::testing::Return;
using ::testing::SetArgPointee;
class MockMutator : public Mutator {
public:
...
MOCK_METHOD1(MutateInt, bool(int* value));
};
...
MockMutator mutator;
EXPECT_CALL(mutator, MutateInt(_))
.WillOnce(DoAll(SetArgPointee<0>(5),
Return(true)));
If the output argument is an array, use the SetArrayArgument<N>(first, last) action instead. It copies the elements in source range [first, last) to the array pointed to by the N-th (0-based) argument:
using ::testing::NotNull;
using ::testing::SetArrayArgument;
class MockArrayMutator : public ArrayMutator {
public:
MOCK_METHOD2(Mutate, void(int* values, int num_values));
...
};
...
MockArrayMutator mutator;
int values[5] = { 1, 2, 3, 4, 5 };
EXPECT_CALL(mutator, Mutate(NotNull(), 5))
.WillOnce(SetArrayArgument<0>(values, values + 5));
This also works when the argument is an output iterator:
using ::testing::_;
using ::testing::SeArrayArgument;
class MockRolodex : public Rolodex {
public:
MOCK_METHOD1(GetNames, void(std::back_insert_iterator<vector<string> >));
...
};
...
MockRolodex rolodex;
vector<string> names;
names.push_back("George");
names.push_back("John");
names.push_back("Thomas");
EXPECT_CALL(rolodex, GetNames(_))
.WillOnce(SetArrayArgument<0>(names.begin(), names.end()));
If you expect a call to change the behavior of a mock object, you can use ::testing::InSequence to specify different behaviors before and after the call:
using ::testing::InSequence;
using ::testing::Return;
...
{
InSequence seq;
EXPECT_CALL(my_mock, IsDirty())
.WillRepeatedly(Return(true));
EXPECT_CALL(my_mock, Flush());
EXPECT_CALL(my_mock, IsDirty())
.WillRepeatedly(Return(false));
}
my_mock.FlushIfDirty();
This makes my_mock.IsDirty() return true before my_mock.Flush() is called and return false afterwards.
If the behavior change is more complex, you can store the effects in a variable and make a mock method get its return value from that variable:
using ::testing::_;
using ::testing::SaveArg;
using ::testing::Return;
ACTION_P(ReturnPointee, p) { return *p; }
...
int previous_value = 0;
EXPECT_CALL(my_mock, GetPrevValue())
.WillRepeatedly(ReturnPointee(&previous_value));
EXPECT_CALL(my_mock, UpdateValue(_))
.WillRepeatedly(SaveArg<0>(&previous_value));
my_mock.DoSomethingToUpdateValue();
Here my_mock.GetPrevValue() will always return the argument of the last UpdateValue() call.
If a mock method's return type is a built-in C++ type or pointer, by default it will return 0 when invoked. You only need to specify an action if this default value doesn't work for you.
Sometimes, you may want to change this default value, or you may want to specify a default value for types Google Mock doesn't know about. You can do this using the ::testing::DefaultValue class template:
class MockFoo : public Foo {
public:
MOCK_METHOD0(CalculateBar, Bar());
};
...
Bar default_bar;
// Sets the default return value for type Bar.
DefaultValue<Bar>::Set(default_bar);
MockFoo foo;
// We don't need to specify an action here, as the default
// return value works for us.
EXPECT_CALL(foo, CalculateBar());
foo.CalculateBar(); // This should return default_bar.
// Unsets the default return value.
DefaultValue<Bar>::Clear();
Please note that changing the default value for a type can make you tests hard to understand. We recommend you to use this feature judiciously. For example, you may want to make sure the Set() and Clear() calls are right next to the code that uses your mock.
You've learned how to change the default value of a given type. However, this may be too coarse for your purpose: perhaps you have two mock methods with the same return type and you want them to have different behaviors. The ON_CALL() macro allows you to customize your mock's behavior at the method level:
using ::testing::_;
using ::testing::AnyNumber;
using ::testing::Gt;
using ::testing::Return;
...
ON_CALL(foo, Sign(_))
.WillByDefault(Return(-1));
ON_CALL(foo, Sign(0))
.WillByDefault(Return(0));
ON_CALL(foo, Sign(Gt(0)))
.WillByDefault(Return(1));
EXPECT_CALL(foo, Sign(_))
.Times(AnyNumber());
foo.Sign(5); // This should return 1.
foo.Sign(-9); // This should return -1.
foo.Sign(0); // This should return 0.
As you may have guessed, when there are more than one ON_CALL() statements, the news order take precedence over the older ones. In other words, the last one that matches the function arguments will be used. This matching order allows you to set up the common behavior in a mock object's constructor or the test fixture's set-up phase and specialize the mock's behavior later.
If the built-in actions don't suit you, you can easily use an existing function, method, or functor as an action:
using ::testing::_;
using ::testing::Invoke;
class MockFoo : public Foo {
public:
MOCK_METHOD2(Sum, int(int x, int y));
MOCK_METHOD1(ComplexJob, bool(int x));
};
int CalculateSum(int x, int y) { return x + y; }
class Helper {
public:
bool ComplexJob(int x);
};
...
MockFoo foo;
Helper helper;
EXPECT_CALL(foo, Sum(_, _))
.WillOnce(Invoke(CalculateSum));
EXPECT_CALL(foo, ComplexJob(_))
.WillOnce(Invoke(&helper, &Helper::ComplexJob));
foo.Sum(5, 6); // Invokes CalculateSum(5, 6).
foo.ComplexJob(10); // Invokes helper.ComplexJob(10);
The only requirement is that the type of the function, etc must be compatible with the signature of the mock function, meaning that the latter's arguments can be implicitly converted to the corresponding arguments of the former, and the former's return type can be implicitly converted to that of the latter. So, you can invoke something whose type is not exactly the same as the mock function, as long as it's safe to do so - nice, huh?
Invoke() is very useful for doing actions that are more complex. It passes the mock function's arguments to the function or functor being invoked such that the callee has the full context of the call to work with. If the invoked function is not interested in some or all of the arguments, it can simply ignore them.
Yet, a common pattern is that a test author wants to invoke a function without the arguments of the mock function. Invoke() allows her to do that using a wrapper function that throws away the arguments before invoking an underlining nullary function. Needless to say, this can be tedious and obscures the intent of the test.
InvokeWithoutArgs() solves this problem. It's like Invoke() except that it doesn't pass the mock function's arguments to the callee. Here's an example:
using ::testing::_;
using ::testing::InvokeWithoutArgs;
class MockFoo : public Foo {
public:
MOCK_METHOD1(ComplexJob, bool(int n));
};
bool Job1() { ... }
...
MockFoo foo;
EXPECT_CALL(foo, ComplexJob(_))
.WillOnce(InvokeWithoutArgs(Job1));
foo.ComplexJob(10); // Invokes Job1().
Sometimes a mock function will receive a function pointer or a functor (in other words, a "callable") as an argument, e.g.
class MockFoo : public Foo {
public:
MOCK_METHOD2(DoThis, bool(int n, bool (*fp)(int)));
};
and you may want to invoke this callable argument:
using ::testing::_;
...
MockFoo foo;
EXPECT_CALL(foo, DoThis(_, _))
.WillOnce(...);
// Will execute (*fp)(5), where fp is the
// second argument DoThis() receives.
Arghh, you need to refer to a mock function argument but C++ has no lambda (yet), so you have to define your own action. :-( Or do you really?
Well, Google Mock has an action to solve exactly this problem:
InvokeArgument<N>(arg_1, arg_2, ..., arg_m)
will invoke the N-th (0-based) argument the mock function receives, with arg_1, arg_2, ..., and arg_m. No matter if the argument is a function pointer or a functor, Google Mock handles them both.
With that, you could write:
using ::testing::_;
using ::testing::InvokeArgument;
...
EXPECT_CALL(foo, DoThis(_, _))
.WillOnce(InvokeArgument<1>(5));
// Will execute (*fp)(5), where fp is the
// second argument DoThis() receives.
What if the callable takes an argument by reference? No problem - just wrap it inside ByRef():
...
MOCK_METHOD1(Bar, bool(bool (*fp)(int, const Helper&)));
...
using ::testing::_;
using ::testing::ByRef;
using ::testing::InvokeArgument;
...
MockFoo foo;
Helper helper;
...
EXPECT_CALL(foo, Bar(_))
.WillOnce(InvokeArgument<0>(5, ByRef(helper)));
// ByRef(helper) guarantees that a reference to helper, not a copy of it,
// will be passed to the callable.
What if the callable takes an argument by reference and we do not wrap the argument in ByRef()? Then InvokeArgument() will make a copy of the argument, and pass a reference to the copy, instead of a reference to the original value, to the callable. This is especially handy when the argument is a temporary value:
...
MOCK_METHOD1(DoThat, bool(bool (*f)(const double& x, const string& s)));
...
using ::testing::_;
using ::testing::InvokeArgument;
...
MockFoo foo;
...
EXPECT_CALL(foo, DoThat(_))
.WillOnce(InvokeArgument<0>(5.0, string("Hi")));
// Will execute (*f)(5.0, string("Hi")), where f is the function pointer
// DoThat() receives. Note that the values 5.0 and string("Hi") are
// temporary and dead once the EXPECT_CALL() statement finishes. Yet
// it's fine to perform this action later, since a copy of the values
// are kept inside the InvokeArgument action.
Sometimes you have an action that returns something, but you need an action that returns void (perhaps you want to use it in a mock function that returns void, or perhaps it needs to be used in DoAll() and it's not the last in the list). IgnoreResult() lets you do that. For example:
using ::testing::_;
using ::testing::Invoke;
using ::testing::Return;
int Process(const MyData& data);
string DoSomething();
class MockFoo : public Foo {
public:
MOCK_METHOD1(Abc, void(const MyData& data));
MOCK_METHOD0(Xyz, bool());
};
...
MockFoo foo;
EXPECT_CALL(foo, Abc(_))
// .WillOnce(Invoke(Process));
// The above line won't compile as Process() returns int but Abc() needs
// to return void.
.WillOnce(IgnoreResult(Invoke(Process)));
EXPECT_CALL(foo, Xyz())
.WillOnce(DoAll(IgnoreResult(Invoke(DoSomething)),
// Ignores the string DoSomething() returns.
Return(true)));
Note that you cannot use IgnoreResult() on an action that already returns void. Doing so will lead to ugly compiler errors.
Say you have a mock function Foo() that takes seven arguments, and you have a custom action that you want to invoke when Foo() is called. Trouble is, the custom action only wants three arguments:
using ::testing::_;
using ::testing::Invoke;
...
MOCK_METHOD7(Foo, bool(bool visible, const string& name, int x, int y,
const map<pair<int, int>, double>& weight,
double min_weight, double max_wight));
...
bool IsVisibleInQuadrant1(bool visible, int x, int y) {
return visible && x >= 0 && y >= 0;
}
...
EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _))
.WillOnce(Invoke(IsVisibleInQuadrant1)); // Uh, won't compile. :-(
To please the compiler God, you can to define an "adaptor" that has the same signature as Foo() and calls the custom action with the right arguments:
using ::testing::_;
using ::testing::Invoke;
bool MyIsVisibleInQuadrant1(bool visible, const string& name, int x, int y,
const map<pair<int, int>, double>& weight,
double min_weight, double max_wight) {
return IsVisibleInQuadrant1(visible, x, y);
}
...
EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _))
.WillOnce(Invoke(MyIsVisibleInQuadrant1)); // Now it works.
But isn't this awkward?
Google Mock provides a generic action adaptor, so you can spend your time minding more important business than writing your own adaptors. Here's the syntax:
WithArgs<N1, N2, ..., Nk>(action)
creates an action that passes the arguments of the mock function at the given indices (0-based) to the inner action and performs it. Using WithArgs, our original example can be written as:
using ::testing::_;
using ::testing::Invoke;
using ::testing::WithArgs;
...
EXPECT_CALL(mock, Foo(_, _, _, _, _, _, _))
.WillOnce(WithArgs<0, 2, 3>(Invoke(IsVisibleInQuadrant1)));
// No need to define your own adaptor.
For better readability, Google Mock also gives you:
As you may have realized, InvokeWithoutArgs(...) is just syntactic sugar for WithoutArgs(Inovke(...)).
Here are more tips:
The selecting-an-action's-arguments recipe showed us one way to make a mock function and an action with incompatible argument lists fit together. The downside is that wrapping the action in WithArgs<...>() can get tedious for people writing the tests.
If you are defining a function, method, or functor to be used with Invoke*(), and you are not interested in some of its arguments, an alternative to WithArgs is to declare the uninteresting arguments as Unused. This makes the definition less cluttered and less fragile in case the types of the uninteresting arguments change. It could also increase the chance the action function can be reused. For example, given
MOCK_METHOD3(Foo, double(const string& label, double x, double y));
MOCK_METHOD3(Bar, double(int index, double x, double y));
instead of
using ::testing::_;
using ::testing::Invoke;
double DistanceToOriginWithLabel(const string& label, double x, double y) {
return sqrt(x*x + y*y);
}
double DistanceToOriginWithIndex(int index, double x, double y) {
return sqrt(x*x + y*y);
}
...
EXEPCT_CALL(mock, Foo("abc", _, _))
.WillOnce(Invoke(DistanceToOriginWithLabel));
EXEPCT_CALL(mock, Bar(5, _, _))
.WillOnce(Invoke(DistanceToOriginWithIndex));
you could write
using ::testing::_;
using ::testing::Invoke;
using ::testing::Unused;
double DistanceToOrigin(Unused, double x, double y) {
return sqrt(x*x + y*y);
}
...
EXEPCT_CALL(mock, Foo("abc", _, _))
.WillOnce(Invoke(DistanceToOrigin));
EXEPCT_CALL(mock, Bar(5, _, _))
.WillOnce(Invoke(DistanceToOrigin));
Just like matchers, a Google Mock action object consists of a pointer to a ref-counted implementation object. Therefore copying actions is also allowed and very efficient. When the last action that references the implementation object dies, the implementation object will be deleted.
If you have some complex action that you want to use again and again, you may not have to build it from scratch everytime. If the action doesn't have an internal state (i.e. if it always does the same thing no matter how many times it has been called), you can assign it to an action variable and use that variable repeatedly. For example:
Action<bool(int*)> set_flag = DoAll(SetArgPointee<0>(5),
Return(true));
... use set_flag in .WillOnce() and .WillRepeatedly() ...
However, if the action has its own state, you may be surprised if you share the action object. Suppose you have an action factory IncrementCounter(init) which creates an action that increments and returns a counter whose initial value is init, using two actions created from the same expression and using a shared action will exihibit different behaviors. Example:
EXPECT_CALL(foo, DoThis())
.WillRepeatedly(IncrementCounter(0));
EXPECT_CALL(foo, DoThat())
.WillRepeatedly(IncrementCounter(0));
foo.DoThis(); // Returns 1.
foo.DoThis(); // Returns 2.
foo.DoThat(); // Returns 1 - Blah() uses a different
// counter than Bar()'s.
versus
Action<int()> increment = IncrementCounter(0);
EXPECT_CALL(foo, DoThis())
.WillRepeatedly(increment);
EXPECT_CALL(foo, DoThat())
.WillRepeatedly(increment);
foo.DoThis(); // Returns 1.
foo.DoThis(); // Returns 2.
foo.DoThat(); // Returns 3 - the counter is shared.
Believe it or not, the vast majority of the time spent on compiling a mock class is in generating its constructor and destructor, as they perform non-trivial tasks (e.g. verification of the expectations). What's more, mock methods with different signatures have different types and thus their constructors/destructors need to be generated by the compiler separately. As a result, if you mock many different types of methods, compiling your mock class can get really slow.
If you are experiencing slow compilation, you can move the definition of your mock class' constructor and destructor out of the class body and into a .cpp file. This way, even if you #include your mock class in N files, the compiler only needs to generate its constructor and destructor once, resulting in a much faster compilation.
Let's illustrate the idea using an example. Here's the definition of a mock class before applying this recipe:
// File mock_foo.h.
...
class MockFoo : public Foo {
public:
// Since we don't declare the constructor or the destructor,
// the compiler will generate them in every translation unit
// where this mock class is used.
MOCK_METHOD0(DoThis, int());
MOCK_METHOD1(DoThat, bool(const char* str));
... more mock methods ...
};
After the change, it would look like:
// File mock_foo.h.
...
class MockFoo : public Foo {
public:
// The constructor and destructor are declared, but not defined, here.
MockFoo();
virtual ~MockFoo();
MOCK_METHOD0(DoThis, int());
MOCK_METHOD1(DoThat, bool(const char* str));
... more mock methods ...
};
and
// File mock_foo.cpp.
#include "path/to/mock_foo.h"
// The definitions may appear trivial, but the functions actually do a
// lot of things through the constructors/destructors of the member
// variables used to implement the mock methods.
MockFoo::MockFoo() {}
MockFoo::~MockFoo() {}
When it's being destoyed, your friendly mock object will automatically verify that all expectations on it have been satisfied, and will generate Google Test failures if not. This is convenient as it leaves you with one less thing to worry about. That is, unless you are not sure if your mock object will be destoyed.
How could it be that your mock object won't eventually be destroyed? Well, it might be created on the heap and owned by the code you are testing. Suppose there's a bug in that code and it doesn't delete the mock object properly - you could end up with a passing test when there's actually a bug.
Using a heap checker is a good idea and can alleviate the concern, but its implementation may not be 100% reliable. So, sometimes you do want to force Google Mock to verify a mock object before it is (hopefully) destructed. You can do this with Mock::VerifyAndClearExpectations(&mock_object):
TEST(MyServerTest, ProcessesRequest) {
using ::testing::Mock;
MockFoo* const foo = new MockFoo;
EXPECT_CALL(*foo, ...)...;
// ... other expectations ...
// server now owns foo.
MyServer server(foo);
server.ProcessRequest(...);
// In case that server's destructor will forget to delete foo,
// this will verify the expectations anyway.
Mock::VerifyAndClearExpectations(foo);
} // server is destroyed when it goes out of scope here.
Tip: The Mock::VerifyAndClearExpectations() function returns a bool to indicate whether the verification was successful (true for yes), so you can wrap that function call inside a ASSERT_TRUE() if there is no point going further when the verification has failed.
Sometimes you may want to "reset" a mock object at various check points in your test: at each check point, you verify that all existing expectations on the mock object have been satisfied, and then you set some new expectations on it as if it's newly created. This allows you to work with a mock object in "phases" whose sizes are each manageable.
One such scenario is that in your test's SetUp() function, you may want to put the object you are testing into a certain state, with the help from a mock object. Once in the desired state, you want to clear all expectations on the mock, such that in the TEST_F body you can set fresh expectations on it.
As you may have figured out, the Mock::VerifyAndClearExpectations() function we saw in the previous recipe can help you here. Or, if you are using ON_CALL() to set default actions on the mock object and want to clear the default actions as well, use Mock::VerifyAndClear(&mock_object) instead. This function does what Mock::VerifyAndClearExpectations(&mock_object) does and returns the same bool, plus it clears the ON_CALL() statements on mock_object too.
Another trick you can use to achieve the same effect is to put the expectations in sequences and insert calls to a dummy "check-point" function at specific places. Then you can verify that the mock function calls do happen at the right time. For example, if you are exercising code:
Foo(1);
Foo(2);
Foo(3);
and want to verify that Foo(1) and Foo(3) both invoke mock.Bar("a"), but Foo(2) doesn't invoke anything. You can write:
using ::testing::MockFunction;
TEST(FooTest, InvokesBarCorrectly) {
MyMock mock;
// Class MockFunction<F> has exactly one mock method. It is named
// Call() and has type F.
MockFunction<void(string check_point_name)> check;
{
InSequence s;
EXPECT_CALL(mock, Bar("a"));
EXPECT_CALL(check, Call("1"));
EXPECT_CALL(check, Call("2"));
EXPECT_CALL(mock, Bar("a"));
}
Foo(1);
check.Call("1");
Foo(2);
check.Call("2");
Foo(3);
}
The expectation spec says that the first Bar("a") must happen before check point "1", the second Bar("a") must happen after check point "2", and nothing should happen between the two check points. The explicit check points make it easy to tell which Bar("a") is called by which call to Foo().
Sometimes you want to make sure a mock object is destructed at the right time, e.g. after bar->A() is called but before bar->B() is called. We already know that you can specify constraints on the order of mock function calls, so all we need to do is to mock the destructor of the mock function.
This sounds simple, except for one problem: a destructor is a special function with special syntax and special semantics, and the MOCK_METHOD0 macro doesn't work for it:
MOCK_METHOD0(~MockFoo, void()); // Won't compile!
The good news is that you can use a simple pattern to achieve the same effect. First, add a mock function Die() to your mock class and call it in the destructor, like this:
class MockFoo : public Foo {
...
// Add the following two lines to the mock class.
MOCK_METHOD0(Die, void());
virtual ~MockFoo() { Die(); }
};
(If the name Die() clashes with an existing symbol, choose another name.) Now, we have translated the problem of testing when a MockFoo object dies to testing when its Die() method is called:
MockFoo* foo = new MockFoo;
MockBar* bar = new MockBar;
...
{
InSequence s;
// Expects *foo to die after bar->A() and before bar->B().
EXPECT_CALL(*bar, A());
EXPECT_CALL(*foo, Die());
EXPECT_CALL(*bar, B());
}
And that's that.
IMPORTANT NOTE: What we describe in this recipe is ONLY true on platforms where Google Mock is thread-safe. Currently these are only platforms that support the pthreads library (this includes Linux and Mac). To make it thread-safe on other platforms we only need to implement some synchronization operations in "gtest/internal/gtest-port.h".
In a unit test, it's best if you could isolate and test a piece of code in a single-threaded context. That avoids race conditions and dead locks, and makes debugging your test much easier.
Yet many programs are multi-threaded, and sometimes to test something we need to pound on it from more than one thread. Google Mock works for this purpose too.
Remember the steps for using a mock:
If you follow the following simple rules, your mocks and threads can live happily togeter:
If you violate the rules (for example, if you set expectations on a mock while another thread is calling its methods), you get undefined behavior. That's not fun, so don't do it.
Google Mock guarantees that the action for a mock function is done in the same thread that called the mock function. For example, in
EXPECT_CALL(mock, Foo(1))
.WillOnce(action1);
EXPECT_CALL(mock, Foo(2))
.WillOnce(action2);
if Foo(1) is called in thread 1 and Foo(2) is called in thread 2, Google Mock will execute action1 in thread 1 and action2 in thread 2.
Google Mock does not impose a sequence on actions performed in different threads (doing so may create deadlocks as the actions may need to cooperate). This means that the execution of action1 and action2 in the above example may interleave. If this is a problem, you should add proper synchronization logic to action1 and action2 to make the test thread-safe.
Also, remember that DefaultValue<T> is a global resource that potentially affects all living mock objects in your program. Naturally, you won't want to mess with it from multiple threads or when there still are mocks in action.
When Google Mock sees something that has the potential of being an error (e.g. a mock function with no expectation is called, a.k.a. an uninteresting call, which is allowed but perhaps you forgot to explicitly ban the call), it prints some warning messages, including the arguments of the function and the return value. Hopefully this will remind you to take a look and see if there is indeed a problem.
Sometimes you are confident that your tests are correct and may not appreciate such friendly messages. Some other times, you are debugging your tests or learning about the behavior of the code you are testing, and wish you could observe every mock call that happens (including argument values and the return value). Clearly, one size doesn't fit all.
You can control how much Google Mock tells you using the --gmock_verbose=LEVEL command-line flag, where LEVEL is a string with three possible values:
Alternatively, you can adjust the value of that flag from within your tests like so:
::testing::FLAGS_gmock_verbose = "error";
Now, judiciously use the right flag to enable Google Mock serve you better!
If you build and run your tests in Emacs, the source file locations of Google Mock and Google Test errors will be highlighted. Just press <Enter> on one of them and you'll be taken to the offending line. Or, you can just type C-x ` to jump to the next error.
To make it even easier, you can add the following lines to your ~/.emacs file:
(global-set-key "\M-m" 'compile) ; m is for make
(global-set-key [M-down] 'next-error)
(global-set-key [M-up] '(lambda () (interactive) (next-error -1)))
Then you can type M-m to start a build, or M-up/M-down to move back and forth between errors.
Google Mock's implementation consists of dozens of files (excluding its own tests). Sometimes you may want them to be packaged up in fewer files instead, such that you can easily copy them to a new machine and start hacking there. For this we provide an experimental Python script fuse_gmock_files.py in the scripts/ directory (starting with release 1.2.0). Assuming you have Python 2.4 or above installed on your machine, just go to that directory and run
python fuse_gmock_files.py OUTPUT_DIR
and you should see an OUTPUT_DIR directory being created with files gtest/gtest.h, gmock/gmock.h, and gmock-gtest-all.cc in it. These three files contain everything you need to use Google Mock (and Google Test). Just copy them to anywhere you want and you are ready to write tests and use mocks. You can use the scrpts/test/Makefile file as an example on how to compile your tests against them.
The MATCHER* family of macros can be used to define custom matchers easily. The syntax:
MATCHER(name, description_string_expression) { statements; }
will define a matcher with the given name that executes the statements, which must return a bool to indicate if the match succeeds. Inside the statements, you can refer to the value being matched by arg, and refer to its type by arg_type.
The description string is a string-typed expression that documents what the matcher does, and is used to generate the failure message when the match fails. It can (and should) reference the special bool variable negation, and should evaluate to the description of the matcher when negation is false, or that of the matcher's negation when negation is true.
For convenience, we allow the description string to be empty (""), in which case Google Mock will use the sequence of words in the matcher name as the description.
MATCHER(IsDivisibleBy7, "") { return (arg % 7) == 0; }
allows you to write
// Expects mock_foo.Bar(n) to be called where n is divisible by 7.
EXPECT_CALL(mock_foo, Bar(IsDivisibleBy7()));
or,
using ::testing::Not;
...
EXPECT_THAT(some_expression, IsDivisibleBy7());
EXPECT_THAT(some_other_expression, Not(IsDivisibleBy7()));
If the above assertions fail, they will print something like:
Value of: some_expression
Expected: is divisible by 7
Actual: 27
...
Value of: some_other_expression
Expected: not (is divisible by 7)
Actual: 21
where the descriptions "is divisible by 7" and `"not (is divisible by 7)"` are automatically calculated from the matcher name IsDivisibleBy7.
As you may have noticed, the auto-generated descriptions (especially those for the negation) may not be so great. You can always override them with a string expression of your own:
MATCHER(IsDivisibleBy7, std::string(negation ? "isn't" : "is") +
" divisible by 7") {
return (arg % 7) == 0;
}
Optionally, you can stream additional information to a hidden argument named result_listener to explain the match result. For example, a better definition of IsDivisibleBy7 is:
MATCHER(IsDivisibleBy7, "") {
if ((arg % 7) == 0)
return true;
*result_listener << "the remainder is " << (arg % 7);
return false;
}
With this definition, the above assertion will give a better message:
Value of: some_expression
Expected: is divisible by 7
Actual: 27 (the remainder is 6)
You should let MatchAndExplain() print any additional information that can help a user understand the match result. Note that it should explain why the match succeeds in case of a success (unless it's obvious) - this is useful when the matcher is used inside Not(). There is no need to print the argument value itself, as Google Mock already prints it for you.
Notes:
Sometimes you'll want to define a matcher that has parameters. For that you can use the macro:
MATCHER_P(name, param_name, description_string) { statements; }
where the description string can be either "" or a string expression that references negation and param_name.
MATCHER_P(HasAbsoluteValue, value, "") { return abs(arg) == value; }
will allow you to write:
EXPECT_THAT(Blah("a"), HasAbsoluteValue(n));
which may lead to this message (assuming n is 10):
Value of: Blah("a")
Expected: has absolute value 10
Actual: -9
Note that both the matcher description and its parameter are printed, making the message human-friendly.
In the matcher definition body, you can write foo_type to reference the type of a parameter named foo. For example, in the body of MATCHER_P(HasAbsoluteValue, value) above, you can write value_type to refer to the type of value.
Google Mock also provides MATCHER_P2, MATCHER_P3, ..., up to MATCHER_P10 to support multi-parameter matchers:
MATCHER_Pk(name, param_1, ..., param_k, description_string) { statements; }
Please note that the custom description string is for a particular instance of the matcher, where the parameters have been bound to actual values. Therefore usually you'll want the parameter values to be part of the description. Google Mock lets you do that by referencing the matcher parameters in the description string expression.
For example,
using ::testing::PrintToString;
MATCHER_P2(InClosedRange, low, hi,
std::string(negation ? "isn't" : "is") + " in range [" +
PrintToString(low) + ", " + PrintToString(hi) + "]") {
return low <= arg && arg <= hi;
}
...
EXPECT_THAT(3, InClosedRange(4, 6));
would generate a failure that contains the message:
Expected: is in range [4, 6]
If you specify "" as the description, the failure message will contain the sequence of words in the matcher name followed by the parameter values printed as a tuple. For example,
MATCHER_P2(InClosedRange, low, hi, "") { ... }
...
EXPECT_THAT(3, InClosedRange(4, 6));
would generate a failure that contains the text:
Expected: in closed range (4, 6)
For the purpose of typing, you can view
MATCHER_Pk(Foo, p1, ..., pk, description_string) { ... }
as shorthand for
template <typename p1_type, ..., typename pk_type>
FooMatcherPk<p1_type, ..., pk_type>
Foo(p1_type p1, ..., pk_type pk) { ... }
When you write Foo(v1, ..., vk), the compiler infers the types of the parameters v1, ..., and vk for you. If you are not happy with the result of the type inference, you can specify the types by explicitly instantiating the template, as in Foo<long, bool>(5, false). As said earlier, you don't get to (or need to) specify arg_type as that's determined by the context in which the matcher is used.
You can assign the result of expression Foo(p1, ..., pk) to a variable of type FooMatcherPk<p1_type, ..., pk_type>. This can be useful when composing matchers. Matchers that don't have a parameter or have only one parameter have special types: you can assign Foo() to a FooMatcher-typed variable, and assign Foo(p) to a FooMatcherP<p_type>-typed variable.
While you can instantiate a matcher template with reference types, passing the parameters by pointer usually makes your code more readable. If, however, you still want to pass a parameter by reference, be aware that in the failure message generated by the matcher you will see the value of the referenced object but not its address.
You can overload matchers with different numbers of parameters:
MATCHER_P(Blah, a, description_string_1) { ... }
MATCHER_P2(Blah, a, b, description_string_2) { ... }
While it's tempting to always use the MATCHER* macros when defining a new matcher, you should also consider implementing MatcherInterface or using MakePolymorphicMatcher() instead (see the recipes that follow), especially if you need to use the matcher a lot. While these approaches require more work, they give you more control on the types of the value being matched and the matcher parameters, which in general leads to better compiler error messages that pay off in the long run. They also allow overloading matchers based on parameter types (as opposed to just based on the number of parameters).
A matcher of argument type T implements ::testing::MatcherInterface<T> and does two things: it tests whether a value of type T matches the matcher, and can describe what kind of values it matches. The latter ability is used for generating readable error messages when expectations are violated.
The interface looks like this:
class MatchResultListener {
public:
...
// Streams x to the underlying ostream; does nothing if the ostream
// is NULL.
template <typename T>
MatchResultListener& operator<<(const T& x);
// Returns the underlying ostream.
::std::ostream* stream();
};
template <typename T>
class MatcherInterface {
public:
virtual ~MatcherInterface();
// Returns true iff the matcher matches x; also explains the match
// result to 'listener'.
virtual bool MatchAndExplain(T x, MatchResultListener* listener) const = 0;
// Describes this matcher to an ostream.
virtual void DescribeTo(::std::ostream* os) const = 0;
// Describes the negation of this matcher to an ostream.
virtual void DescribeNegationTo(::std::ostream* os) const;
};
If you need a custom matcher but Truly() is not a good option (for example, you may not be happy with the way Truly(predicate) describes itself, or you may want your matcher to be polymorphic as Eq(value) is), you can define a matcher to do whatever you want in two steps: first implement the matcher interface, and then define a factory function to create a matcher instance. The second step is not strictly needed but it makes the syntax of using the matcher nicer.
For example, you can define a matcher to test whether an int is divisible by 7 and then use it like this:
using ::testing::MakeMatcher;
using ::testing::Matcher;
using ::testing::MatcherInterface;
using ::testing::MatchResultListener;
class DivisibleBy7Matcher : public MatcherInterface<int> {
public:
virtual bool MatchAndExplain(int n, MatchResultListener* listener) const {
return (n % 7) == 0;
}
virtual void DescribeTo(::std::ostream* os) const {
*os << "is divisible by 7";
}
virtual void DescribeNegationTo(::std::ostream* os) const {
*os << "is not divisible by 7";
}
};
inline Matcher<int> DivisibleBy7() {
return MakeMatcher(new DivisibleBy7Matcher);
}
...
EXPECT_CALL(foo, Bar(DivisibleBy7()));
You may improve the matcher message by streaming additional information to the listener argument in MatchAndExplain():
class DivisibleBy7Matcher : public MatcherInterface<int> {
public:
virtual bool MatchAndExplain(int n,
MatchResultListener* listener) const {
const int remainder = n % 7;
if (remainder != 0) {
*listener << "the remainder is " << remainder;
}
return remainder == 0;
}
...
};
Then, EXPECT_THAT(x, DivisibleBy7()); may general a message like this:
Value of: x
Expected: is divisible by 7
Actual: 23 (the remainder is 2)
You've learned how to write your own matchers in the previous recipe. Just one problem: a matcher created using MakeMatcher() only works for one particular type of arguments. If you want a polymorphic matcher that works with arguments of several types (for instance, Eq(x) can be used to match a value as long as value == x compiles -- value and x don't have to share the same type), you can learn the trick from "gmock/gmock-matchers.h" but it's a bit involved.
Fortunately, most of the time you can define a polymorphic matcher easily with the help of MakePolymorphicMatcher(). Here's how you can define NotNull() as an example:
using ::testing::MakePolymorphicMatcher;
using ::testing::MatchResultListener;
using ::testing::NotNull;
using ::testing::PolymorphicMatcher;
class NotNullMatcher {
public:
// To implement a polymorphic matcher, first define a COPYABLE class
// that has three members MatchAndExplain(), DescribeTo(), and
// DescribeNegationTo(), like the following.
// In this example, we want to use NotNull() with any pointer, so
// MatchAndExplain() accepts a pointer of any type as its first argument.
// In general, you can define MatchAndExplain() as an ordinary method or
// a method template, or even overload it.
template <typename T>
bool MatchAndExplain(T* p,
MatchResultListener* /* listener */) const {
return p != NULL;
}
// Describes the property of a value matching this matcher.
void DescribeTo(::std::ostream* os) const { *os << "is not NULL"; }
// Describes the property of a value NOT matching this matcher.
void DescribeNegationTo(::std::ostream* os) const { *os << "is NULL"; }
};
// To construct a polymorphic matcher, pass an instance of the class
// to MakePolymorphicMatcher(). Note the return type.
inline PolymorphicMatcher<NotNullMatcher> NotNull() {
return MakePolymorphicMatcher(NotNullMatcher());
}
...
EXPECT_CALL(foo, Bar(NotNull())); // The argument must be a non-NULL pointer.
Note: Your polymorphic matcher class does not need to inherit from MatcherInterface or any other class, and its methods do not need to be virtual.
Like in a monomorphic matcher, you may explain the match result by streaming additional information to the listener argument in MatchAndExplain().
A cardinality is used in Times() to tell Google Mock how many times you expect a call to occur. It doesn't have to be exact. For example, you can say AtLeast(5) or Between(2, 4).
If the built-in set of cardinalities doesn't suit you, you are free to define your own by implementing the following interface (in namespace testing):
class CardinalityInterface {
public:
virtual ~CardinalityInterface();
// Returns true iff call_count calls will satisfy this cardinality.
virtual bool IsSatisfiedByCallCount(int call_count) const = 0;
// Returns true iff call_count calls will saturate this cardinality.
virtual bool IsSaturatedByCallCount(int call_count) const = 0;
// Describes self to an ostream.
virtual void DescribeTo(::std::ostream* os) const = 0;
};
For example, to specify that a call must occur even number of times, you can write
using ::testing::Cardinality;
using ::testing::CardinalityInterface;
using ::testing::MakeCardinality;
class EvenNumberCardinality : public CardinalityInterface {
public:
virtual bool IsSatisfiedByCallCount(int call_count) const {
return (call_count % 2) == 0;
}
virtual bool IsSaturatedByCallCount(int call_count) const {
return false;
}
virtual void DescribeTo(::std::ostream* os) const {
*os << "called even number of times";
}
};
Cardinality EvenNumber() {
return MakeCardinality(new EvenNumberCardinality);
}
...
EXPECT_CALL(foo, Bar(3))
.Times(EvenNumber());
If the built-in actions don't work for you, and you find it inconvenient to use Invoke(), you can use a macro from the ACTION* family to quickly define a new action that can be used in your code as if it's a built-in action.
By writing
ACTION(name) { statements; }
in a namespace scope (i.e. not inside a class or function), you will define an action with the given name that executes the statements. The value returned by statements will be used as the return value of the action. Inside the statements, you can refer to the K-th (0-based) argument of the mock function as argK. For example:
ACTION(IncrementArg1) { return ++(*arg1); }
... WillOnce(IncrementArg1());
Note that you don't need to specify the types of the mock function arguments. Rest assured that your code is type-safe though: you'll get a compiler error if *arg1 doesn't support the ++ operator, or if the type of ++(*arg1) isn't compatible with the mock function's return type.
Another example:
ACTION(Foo) {
(*arg2)(5);
Blah();
*arg1 = 0;
return arg0;
}
defines an action Foo() that invokes argument #2 (a function pointer) with 5, calls function Blah(), sets the value pointed to by argument #1 to 0, and returns argument #0.
For more convenience and flexibility, you can also use the following pre-defined symbols in the body of ACTION:
For example, when using an ACTION as a stub action for mock function:
int DoSomething(bool flag, int* ptr);
we have:
Sometimes you'll want to parameterize an action you define. For that we have another macro
ACTION_P(name, param) { statements; }
ACTION_P(Add, n) { return arg0 + n; }
will allow you to write
// Returns argument #0 + 5.
... WillOnce(Add(5));
For convenience, we use the term arguments for the values used to invoke the mock function, and the term parameters for the values used to instantiate an action.
Note that you don't need to provide the type of the parameter either. Suppose the parameter is named param, you can also use the Google-Mock-defined symbol param_type to refer to the type of the parameter as inferred by the compiler. For example, in the body of ACTION_P(Add, n) above, you can write n_type for the type of n.
Google Mock also provides ACTION_P2, ACTION_P3, and etc to support multi-parameter actions. For example,
ACTION_P2(ReturnDistanceTo, x, y) {
double dx = arg0 - x;
double dy = arg1 - y;
return sqrt(dx*dx + dy*dy);
}
lets you write
... WillOnce(ReturnDistanceTo(5.0, 26.5));
You can view ACTION as a degenerated parameterized action where the number of parameters is 0.
You can also easily define actions overloaded on the number of parameters:
ACTION_P(Plus, a) { ... }
ACTION_P2(Plus, a, b) { ... }
For maximum brevity and reusability, the ACTION* macros don't ask you to provide the types of the mock function arguments and the action parameters. Instead, we let the compiler infer the types for us.
Sometimes, however, we may want to be more explicit about the types. There are several tricks to do that. For example:
ACTION(Foo) {
// Makes sure arg0 can be converted to int.
int n = arg0;
... use n instead of arg0 here ...
}
ACTION_P(Bar, param) {
// Makes sure the type of arg1 is const char*.
::testing::StaticAssertTypeEq<const char*, arg1_type>();
// Makes sure param can be converted to bool.
bool flag = param;
}
where StaticAssertTypeEq is a compile-time assertion in Google Test that verifies two types are the same.
Sometimes you want to give an action explicit template parameters that cannot be inferred from its value parameters. ACTION_TEMPLATE() supports that and can be viewed as an extension to ACTION() and ACTION_P*().
The syntax:
ACTION_TEMPLATE(ActionName,
HAS_m_TEMPLATE_PARAMS(kind1, name1, ..., kind_m, name_m),
AND_n_VALUE_PARAMS(p1, ..., p_n)) { statements; }
defines an action template that takes m explicit template parameters and n value parameters, where m is between 1 and 10, and n is between 0 and 10. name_i is the name of the i-th template parameter, and kind_i specifies whether it's a typename, an integral constant, or a template. p_i is the name of the i-th value parameter.
Example:
// DuplicateArg<k, T>(output) converts the k-th argument of the mock
// function to type T and copies it to *output.
ACTION_TEMPLATE(DuplicateArg,
// Note the comma between int and k:
HAS_2_TEMPLATE_PARAMS(int, k, typename, T),
AND_1_VALUE_PARAMS(output)) {
*output = T(std::tr1::get<k>(args));
}
To create an instance of an action template, write:
ActionName<t1, ..., t_m>(v1, ..., v_n)
where the ts are the template arguments and the vs are the value arguments. The value argument types are inferred by the compiler. For example:
using ::testing::_;
...
int n;
EXPECT_CALL(mock, Foo(_, _))
.WillOnce(DuplicateArg<1, unsigned char>(&n));
If you want to explicitly specify the value argument types, you can provide additional template arguments:
ActionName<t1, ..., t_m, u1, ..., u_k>(v1, ..., v_n)
where u_i is the desired type of v_i.
ACTION_TEMPLATE and ACTION/ACTION_P* can be overloaded on the number of value parameters, but not on the number of template parameters. Without the restriction, the meaning of the following is unclear:
OverloadedAction<int, bool>(x);
Are we using a single-template-parameter action where bool refers to the type of x, or a two-template-parameter action where the compiler is asked to infer the type of x?
If you are writing a function that returns an ACTION object, you'll need to know its type. The type depends on the macro used to define the action and the parameter types. The rule is relatively simple:
Note that we have to pick different suffixes (Action, ActionP, ActionP2, and etc) for actions with different numbers of value parameters, or the action definitions cannot be overloaded on the number of them.
While the ACTION* macros are very convenient, sometimes they are inappropriate. For example, despite the tricks shown in the previous recipes, they don't let you directly specify the types of the mock function arguments and the action parameters, which in general leads to unoptimized compiler error messages that can baffle unfamiliar users. They also don't allow overloading actions based on parameter types without jumping through some hoops.
An alternative to the ACTION* macros is to implement ::testing::ActionInterface<F>, where F is the type of the mock function in which the action will be used. For example:
template <typename F>class ActionInterface {
public:
virtual ~ActionInterface();
// Performs the action. Result is the return type of function type
// F, and ArgumentTuple is the tuple of arguments of F.
//
// For example, if F is int(bool, const string&), then Result would
// be int, and ArgumentTuple would be tr1::tuple<bool, const string&>.
virtual Result Perform(const ArgumentTuple& args) = 0;
};
using ::testing::_;
using ::testing::Action;
using ::testing::ActionInterface;
using ::testing::MakeAction;
typedef int IncrementMethod(int*);
class IncrementArgumentAction : public ActionInterface<IncrementMethod> {
public:
virtual int Perform(const tr1::tuple<int*>& args) {
int* p = tr1::get<0>(args); // Grabs the first argument.
return *p++;
}
};
Action<IncrementMethod> IncrementArgument() {
return MakeAction(new IncrementArgumentAction);
}
...
EXPECT_CALL(foo, Baz(_))
.WillOnce(IncrementArgument());
int n = 5;
foo.Baz(&n); // Should return 5 and change n to 6.
The previous recipe showed you how to define your own action. This is all good, except that you need to know the type of the function in which the action will be used. Sometimes that can be a problem. For example, if you want to use the action in functions with different types (e.g. like Return() and SetArgPointee()).
If an action can be used in several types of mock functions, we say it's polymorphic. The MakePolymorphicAction() function template makes it easy to define such an action:
namespace testing {
template <typename Impl>
PolymorphicAction<Impl> MakePolymorphicAction(const Impl& impl);
} // namespace testing
As an example, let's define an action that returns the second argument in the mock function's argument list. The first step is to define an implementation class:
class ReturnSecondArgumentAction {
public:
template <typename Result, typename ArgumentTuple>
Result Perform(const ArgumentTuple& args) const {
// To get the i-th (0-based) argument, use tr1::get<i>(args).
return tr1::get<1>(args);
}
};
This implementation class does not need to inherit from any particular class. What matters is that it must have a Perform() method template. This method template takes the mock function's arguments as a tuple in a single argument, and returns the result of the action. It can be either const or not, but must be invokable with exactly one template argument, which is the result type. In other words, you must be able to call Perform<R>(args) where R is the mock function's return type and args is its arguments in a tuple.
Next, we use MakePolymorphicAction() to turn an instance of the implementation class into the polymorphic action we need. It will be convenient to have a wrapper for this:
using ::testing::MakePolymorphicAction;
using ::testing::PolymorphicAction;
PolymorphicAction<ReturnSecondArgumentAction> ReturnSecondArgument() {
return MakePolymorphicAction(ReturnSecondArgumentAction());
}
Now, you can use this polymorphic action the same way you use the built-in ones:
using ::testing::_;
class MockFoo : public Foo {
public:
MOCK_METHOD2(DoThis, int(bool flag, int n));
MOCK_METHOD3(DoThat, string(int x, const char* str1, const char* str2));
};
...
MockFoo foo;
EXPECT_CALL(foo, DoThis(_, _))
.WillOnce(ReturnSecondArgument());
EXPECT_CALL(foo, DoThat(_, _, _))
.WillOnce(ReturnSecondArgument());
...
foo.DoThis(true, 5); // Will return 5.
foo.DoThat(1, "Hi", "Bye"); // Will return "Hi".
When an uninteresting or unexpected call occurs, Google Mock prints the argument values and the stack trace to help you debug. Assertion macros like EXPECT_THAT and EXPECT_EQ also print the values in question when the assertion fails. Google Mock and Google Test do this using Google Test's user-extensible value printer.
This printer knows how to print built-in C++ types, native arrays, STL containers, and any type that supports the << operator. For other types, it prints the raw bytes in the value and hopes that you the user can figure it out. Google Test's advanced guide explains how to extend the printer to do a better job at printing your particular type than to dump the bytes.
|
http://code.google.com/p/googlemock/wiki/CookBook#Writing_New_Matchers_Quickly
|
crawl-003
|
refinedweb
| 14,628
| 55.03
|
I have a module B which gets mixed in to a module I, like this: module B BC = 4711 def g puts 'works' end end module I extend self extend B def f g puts B::BC end end If I invoke I.f I get the output works 4711 as expected. From I::f, I can invoke g directly, as if it had been defined inside I, because I included B using extend B. For accessing the constant BC, I have to qualify it explicitly, B::BC. Is there a way I can access the constants in B from within I without qualification with the module name?
on 2016-12-13 09:41
on 2016-12-14 01:24
I believe you need to both include & extend B for this to work. Here is an example: =========================== module B BC = 4711 def g puts 'works' end def self.extended(base) base.send(:include, self) end end module I extend self extend B def f g puts BC end end I.f =========================== Explanation: When you use 'extend' everything is dumped into I's singleton class, and the singleton class is not part of the constant lookup path. Notice that this will add an extra 'g' instance method to I's public interface. If that's a problem you could try separating the constants & the methods like this: =========================== module B module Constants BC = 4711 end include Constants def g puts 'works' end def self.extended(base) base.send(:include, Constants) end end =========================== I hope that helps :) - Jesus Castello, blackbytes.info
on 2016-12-14 12:32
I never had considered doing include AND extend together. The complexity of the solution makes me wonder, whether what I want to achieve is really still in "Ruby spirit". Maybe my thinking was influenced too much by other languages (C++ namespaces for instance). Am I the (nearly) only one who wants to use modules in this way? In any case: Thanks a lot! Your suggestions helps indeed.
|
https://www.ruby-forum.com/topic/6879175
|
CC-MAIN-2017-34
|
refinedweb
| 331
| 71.24
|
Learn how to build a web server to control the ESP32 or ESP8266 outputs using MicroPython framework. As an example we’ll build a web server with ON and OFF buttons to control the on-board LED of the ESP32/ESP8266. We’ll use sockets and the Python socket API.
>
If this is your first time dealing with MicroPython you may find these next tutorials useful:
- Getting Started with MicroPython on ESP32 and ESP8266
- MicroPython Programming Basics with ESP32 and ESP8266
- MicroPython with ESP32 and ESP8266: Interacting with GPIOs
Parts required
For this tutorial you need an ESP32 or ESP8266 board:
- ESP32 DEVKIT DOIT board – read ESP32 Development Boards Review and Comparison
- ESP8266-12E NodeMCU Kit – read Best ESP8266 Wi-Fi Development Board
You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!
Preparing the Files
Connect the ESP32 or ESP8266 board to your computer. Open uPyCraft IDE, and go to Tools > Serial and select the serial port.
You should see the files on the ESP32/ESP8266 board on the device folder. By default, when you burn MicroPython firmware, a boot.py file is created.
For this project you’ll need a boot.py file and a main.py file. The boot.py file has the code that only needs to run once on boot. This includes importing libraries, network credentials, instantiating pins, connecting to your network, and other configurations.
The main.py file will contain the code that runs the web server to serve files and perform tasks based on the requests received by the client.
Creating the main.py file on your board
- Press.
boot.py
Copy the following code to the ESP32/ESP8266 boot.py file.
# Complete project details at try: import usocket as socket except: import socket from machine import Pin import network import esp esp.osdebug(None) import gc gc.collect() ssid = 'REPLACE_WITH_YOUR_SSID' password = 'REPLACE_WITH_YOUR_PASSWORD' station = network.WLAN(network.STA_IF) station.active(True) station.connect(ssid, password) while station.isconnected() == False: pass print('Connection successful') print(station.ifconfig()) led = Pin(2, Pin.OUT)
As mentioned previously, we create our web server using sockets and the Python socket API. The official documentation imports the socket library as follows:
try: import usocket as socket except: import socket
We need to import the Pin class from the machine module to be able to interact with the GPIOs.
from machine import Pin
After importing the socket library, we need to import the network library. The network library allows us to connect the ESP32 or ESP8266 to a Wi-Fi network.
import network
The following lines turn off vendor OS debugging messages:
import esp esp.osdebug(None)
Then, we run a garbage collector:
import gc gc.collect()
A garbage collector is a form of automatic memory management. This is a way to reclaim memory occupied by objects that are no longer in used by the program. This is useful to save space in the flash memory.
The following variables hold your network credentials:
ssid = 'REPLACE_WITH_YOUR_SSID' password = 'replace_with_your_password'
You should replace the words highlighted in red with your network SSID and password, so that the ESP is able to connect to your router.
Then, set the ESP32 or ESP8266 as a Wi-Fi station:
station = network.WLAN(network.STA_IF)
After that, activate the station:
station.active(True)
Finally, the ESP32/ESP8266 connects to your router using the SSID and password defined earlier:
station.connect(ssid, password)
The following statement ensures that the code doesn’t proceed while the ESP is not connected to your network.
while station.isconnected() == False: pass
After a successful connection, print network interface parameters like the ESP32/ESP8266 IP address – use the ifconfig() method on the station object.
print('Connection successful') print(station.ifconfig())
Create a Pin object called led that is an output, that refers to the ESP32/ESP8266 GPIO2:
led = Pin(2, Pin.OUT)
main.py
Copy the following code to the ESP32/ESP8266 main.py file.
# Complete project details at def web_page(): if led.value() == 1:""" return html s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind(('', 80)) s.listen(5) while True: conn, addr = s.accept() print('Got a connection from %s' % str(addr)) request = conn.recv(1024) request = str(request) print('Content = %s' % request) led_on = request.find('/?led=on') led_off = request.find('/?led=off') if led_on == 6: print('LED ON') led.value(1) if led_off == 6: print('LED OFF') led.value(0) response = web_page() conn.send('HTTP/1.1 200 OK\n') conn.send('Content-Type: text/html\n') conn.send('Connection: close\n\n') conn.sendall(response) conn.close()
The script starts by creating a function called web_page(). This function returns a variable called html that contains the HTML text to build the web page.
def web_page():
The web page displays the current GPIO state. So, before generating the HTML text, we need to check the LED state. We save its state on the gpio_state variable:
if led.value() == 1: gpio_state="ON" else: gpio_state="OFF"
After that, the gpio_state variable is incorporated into the HTML text using “+” signs to concatenate strings.>"""
Creating a socket server
After creating the HTML to build the web page, we need to create a listening socket to listen for incoming requests and send the HTML text in response. For a better understanding, the following figure shows a diagram on how to create sockets for server-client interaction:
Create a socket using socket.socket(), and specify the socket type. We create a new socket object called s with the given address family, and socket type. This is a STREAM TCP socket:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Next, bind the socket to an address (network interface and port number) using the bind() method. The bind() method accepts a tupple variable with the ip address, and port number:
s.bind(('', 80))
In our example, we are passing an empty string ‘ ‘ as an IP address and port 80. In this case, the empty string refers to the localhost IP address (this means the ESP32 or ESP8266 IP address).
The next line enables the server to accept connections; it makes a “listening” socket. The argument specifies the maximum number of queued connections. The maximum is 5.
s.listen(5)
In the while loop is where we listen for requests and send responses. When a client connects, the server calls the accept() method to accept the connection. When a client connects, it saves a new socket object to accept and send data on the conn variable, and saves the client address to connect to the server on the addr variable.
conn, addr = s.accept()
Then, print the address of the client saved on the addr variable.
print('Got a connection from %s' % str(addr))
The data is exchanged between the client and server using the send() and recv() methods.
The following line gets the request received on the newly created socket and saves it in the request variable.
request = conn.recv(1024)
The recv() method receives the data from the client socket (remember that we’ve created a new socket object on the conn variable). The argument of the recv() method specifies the maximum data that can be received at once.
The next line simply prints the content of the request:
print('Content = %s' % str(request))
Then, create a variable called response that contains the HTML text returned by the web_page() function:
response = web_page()
Finally, send the response to the socket client using the send() and sendall() methods:
conn.send('HTTP/1.1 200 OK\n') conn.send('Content-Type: text/html\n') conn.send('Connection: close\n\n') conn.sendall(response)
In the end, close the created socket.
conn.close()
Testing the Web Server
Upload the main.py and boot.py files to the ESP32/ESP8266. Your device folder should contain two files: boot.py and main.py.
After uploading the files, press the ESP EN/RST on-board button.
After a few seconds, it should establish a connection with your router and print the IP address on the Shell.
Open your browser, and type your ESP IP address you’ve just found. You should see the web server page as shown below.
When you press the ON button, you make a request on the ESP IP address followed by /?led=on. The ESP32/ESP8266 on-board LED turns on, and the GPIO state is updated on the page.
Note: some ESP8266 on-board LEDs turn on the LED with an OFF command, and turn off the LED with the ON command.
When you press the OFF button, you make a request on the ESP IP address followed by /?led=off. The LED turns off, and the GPIO state is updated.
Note: to keep this tutorial simple, we’re controlling the on-board LED that corresponds to GPIO 2. You can control any other GPIO with any other output (a relay, for example) using the same method. Also, you can modify the code to control multiple GPIOs or change the HTML text to create a different web page.
Wrapping Up
This tutorial showed you how to build a simple web server with MicroPython firmware to control the ESP32/ESP8266 GPIOs using sockets and the Python socket library. If you’re looking for a web server tutorial with Arduino IDE, you can check the following resources:
If you’re looking for more projects with the ESP32 and ESP8266 boards, you can take a look at the following:
We hope you’ve found this article about how to build a web server with MicroPython useful. To learn more about MicroPython, take a look at our eBook: MicroPython Programming with ESP32 and ESP8266.
66 thoughts on “ESP32/ESP8266 MicroPython Web Server – Control Outputs”
Thanks very much for this article. This was exactly what I was looking for.
Would also appreciate an article about sending e-mail with micro python from an esp8266.
Great Rui, I stay tuned , bye Domenico
Great! Keep going on!
Hello Sara,
this explanation is pretty detailed. IMHO it is a good compromise between explaining it all from scratch and “drop a short textline”
I want to make some suggestions how to improve the explanation.
Add “ESP32” to word “server” and the words “your smartphone, tablet or PC” to the word “client” at the grafic which shows the steps what server and client are doing.
The result a webpage that can be clicked to switch on/off a LED is impressing. To achieve this a lot of code-technologies have to be used. I don’t want to suggest explain all
– server-client,
– TCP/IP,
– sockets,
– HTML
all from scratch. That would inflate the explanation much too much.
But there are a few places where a small effort gives pretty much more insight into using all these coding-technologies.
I mean find a way that the parts of the html-code that defines the buttons and the text on the buttons is very easy to find and easy to modify.
Another way could be using some kind of a website-editor, if there exists one that is easy to use. By “easy to use” I mean a software that is very very similar to an office-software or at least very very intuitive to use.
So that one hour of learning is enough to create a website-variation of your demo that has three buttons and a slider.
Then showing how the html-code-output of this software is implemented into the python-code by copy and paste.
best regards
Stefan
Hi Stefan.
Thank you for your suggestions. We’ll take those into account when writing new posts about this subject.
Also, I’ll try to improve this article when I have the chance.
Thank you.
Regards,
Sara 🙂
Thanks
Great
Philippe
Thanks 🙂
Hi Rui,
I have Linux Mint 19 based on ubuntu … uPyCraft IDE doesn’t work … Is there another way or an improvement pf uPyCraft IDE ?
Thank you
Hi Bernard.
uPyCraft should work on your system if you compile it yourself: github.com/DFRobot/uPyCraft_src
If you compile it, it should work.
Note: you don’t need to use uPycraft IDE, you can program program the board with a serial connection using REPL or webREPL.
Regards,
Sara 🙂
Use Thonny, is much easier.
Dear, I’have a lot of problem to use this app with Safari or Google Chrome for iPhone. If I use Google Chrome for mac I don’t have any problem, but when I use Safari I can’t open the page. I see the serial, and I can read the connection by computer to ESP32, but the browser don’t open the contents. Also on Android and Google Chrome all works.
Hi Giovanni.
I’m sorry to hear that.
I actually didn’t test the web server on Safari or iPhone. I’ll try to figure out what happens.
Meanwhile, if you find what causes the problem, just let us know.
Regards,
Sara 🙂
good article as usual 🙂
My question though is why or when would you use python instead of the Arduino ide? What are the benefits etc.
Also I agree with Stefan on the editor HTML thing might be helpful.
Hi Bob.
I think both are good ways to program the ESP32.
MicroPython is much simpler to program, it supports a REPL (Read-Evaluate-Print Loop). The REPL allows you to connect to a board and execute code quickly without the need to compile or upload code.
It also gives you a better overview of the files stored on the ESP32. Uploading code to the ESP32 is much faster with MicroPython.
In terms of libraries for sensors and modules, at the moment there is more support for Arduino IDE.
Regards,
Sara 🙂
Works perfect on my old laptop ( Ubuntu ) using Chromium or Firefox . Doesn’t work on my IPhone 5S ( tried Safari and Chromium ) . EFM ( electronics F…… magic) ..
Thanks anyway , great tutorial , step by step explained , Great Job !
Bob
I made a printscreen with the result of “request = conn.recv(1024)” . First logon is the laptop , 2nd one is the Phone . I can mail it if you want it . Thanks again , keep up the good job !
Bob
Hi Bob.
Thank you.
You can send your results using our contact form:
Regards,
Sara
Hi Sara , thx for the quick reply ! How can I submit a .png file ( printscreen from a Linux screen session )?
Thx , many greetings from Belgium ,
Bob
Hi Bob.
You can upload the image using and then paste the link.
Regards,
Sara
Did Some research and tried different browsers on my. IPhone .
Puffin browser replied : Error 102
(net:: ERR_CONNECTION_REFUSED) when loading URL
Hope this is a clue ….
Thanks a lot and keep up the good job !
Bob
I think I followed the steps correctly but when I try to run it I get error messages:
main.py:4: undefined name ‘led’
main.py:18: undefined name ‘socket’
main.py:18: undefined name ‘socket’
main.py:18: undefined name ‘socket’
main.py:32: undefined name ‘led’
main.py:35: undefined name ‘led’
Any suggestions what I’m doing wrong?
Thank you.
Hi Michael.
I think you’re getting those error because you haven’t uploaded the boot.py file to the ESP32.
I hope this helps.
Regards,
Sara 🙂
I am getting the same problem even after using code in your book, I bought last week, and at github.
I am not sure how esp_web_server_main.py gets socket and led from esp_web_server_boot.py?
uPyCraft shows both these files only under device.
Hi Dave.
If you’re having problems with our course, I recommend that you post a question in our forum – that’s where we give support to our costumers.
The files should have the following names: main.py, and boot.py (it will not work if they are called esp_web_server_main.py or esp_web_server_boot.py using uPycraft IDE).
Can you post your doubts, problems and questions here:
Thank you
Regards,
Sara
Found a working script for the IPhone , out of the box from the official micropython site :
I modified boot.py a little ( removed double imports ) , works perfect 🙂
these lines ( “arduino style”) make the difference I think …
line = cl_file.readline()
if not line or line == b’\r\n’:
Anyway , thanks a lot for helping people to become decent programmers 🙂
Love you guys , lots of greetings from Belgium ,
Bob
Hi Bob.
That’s great!
Thank you so much for sharing and for supporting our work.
Regards,
Sara 🙂
Hi Rui,
I’m a complete beginner and I’m not sure why the code appears
if led_on == 6:
Why is there number 6?
Hi Jaroslav.
In the while loop, after receiving a request, we need to check if the request contains the ‘/?led=on’ or ‘/?led=on’ expressions. For that, we can apply the find() method on the request variable. the find() method returns the lowest index of the substring we are looking for.
Because the substrings we are looking for are always on index 6, we can add an if statement to detect the content of the request. If the led_on variable is equal to 6, we know we’ve received a request on the /?led=on URL and we turn the LED on.
If the led_off variable is equal to 6, we’ve received a request on the /?led=off URL and we turn the LED off.
I hope my explanation is clear.
Regards,
Sara 🙂
Hi
Many thanks for your work
Following this article works fine. But there is tow questions
The program stops at “conn, addr = s.accept()” waiting for a request, and it can wait for ever.
Is it possible just to check if there is one and if there is not continue the loop and the check again the next loop. If this is possible you can use the micro controller for other task in between the requests as in the Arduino env
When connecting with Chrome, on PC or phone, the connection are busy for ever if you do not close the browser
The server hangs printing Got a connection from (‘192.168.1.193’, 54536) and you can not use any other computer or browser untill it is closed, not just the tab but the whole browser.
Connecting the a Raspberry pi works fine.
As it works on RPi it seems to be the PC/phone or Chrome that is the problem. Is there something to do about this. It happen that you forget to close the window and then is it impossible to aces the serve from an other place
Hi Hans.
You are right.
But I don’t think it is something to do with the code. Because when we first implemented this, it worked fine supporting several clients at the same time.
It seems that google Chrome opens two connections, leaving the second one opened. So we are not able to listen requests from other clients while that connection is opened.
I don’t know why this is happening, but we’re working to find a solution.
If you know a workaround for this, please share with us.
Thank you for your comment.
Regards,
Sara
As usual, this was a great tutorial. Took me a couple of times to get it to come together. I have a Heltec wifi 32 with oled and wanted the oled to tell me what ip I was connected to. Has anyone else complained that the Upycraft ide crashes windows 10?
Hi Joseph.
If you have frequent crashes with upycraft IDE, I suggest you experiment Thonny IDE.
You can follow our tutorial and see if you like this IDE better:
Regards,
Sara
Tried it, but like the Upycraft because you can see the files in the espxxxx. Also Thonny has updated since your tutorial and the commands under the ‘device’ are not there. It’s a lot more awkward to use for me. Been trying Rshell on a Pi to program the modules. Not too bad except I don’t have much space to set it up.
Hi Sara! Thanks for this great tutorial. Is there a way that this functionality could be extended so that the ESP32 could listen for requests on a non-local address, i.e. a post request to ?
|
https://randomnerdtutorials.com/esp32-esp8266-micropython-web-server/?replytocom=360533
|
CC-MAIN-2021-25
|
refinedweb
| 3,374
| 74.79
|
Red Hat Bugzilla – Bug 461419
Improve behavior of "pydoc -k" in the face of broken modules
Last modified: 2010-11-04 11:07:14 EDT
Description of problem:
Upon using pydoc -k 'different strings' i get what is below:
$ pydoc -k string
docstrings - Module documentation
StringIO - File-like objects that read from or write to a string buffer.
UserString - A user-defined wrapper around string objects
distutils.versionpredicate - Module for parsing and testing package version predicate strings.
doctest - Module doctest -- a framework for running examples in docstrings.
encodings.string_escape - Python 'escape' Codec
string - A collection of string operations (most are no longer used).
stringold - Common string manipulations.
stringprep - Library that exposes various tables found in the StringPrep RFC 3454.
cStringIO
OpenGL.GL.GREMEDY.string_marker
Traceback (most recent call last):
File "/usr/bin/pydoc", line 5, in <module>
pydoc.cli()
File "/usr/lib/python2.5/pydoc.py", line 2189, in cli
apropos(val)
File "/usr/lib/python2.5/pydoc.py", line 1887, in apropos
ModuleScanner().run(callback, key)
File "/usr/lib/python2.5/pydoc.py", line 1852, 110, in walk_packages
__import__(name)
File "/usr/lib/python2.5/site-packages/OpenGL/WGL/__init__.py", line 3, in <module>
wglUseFontBitmaps = wglUseFontBitmapsW
NameError: name 'wglUseFontBitmapsW' is not defined
Version-Release number of selected component (if applicable):
Python 2.5.1
How reproducible:
Easily, everytime i do use pydoc -k 'anything' results in the same thing
Steps to Reproduce:
1.pydoc -k 'anything'
2.
3.
Actual results:
The above explains it well enough I think. this because pydoc still doesn't gracefully handle offensive modules, i.e. those that insist on doing stuff when imported, which fails in some situations:
--- 8< ----------
nils@gibraltar:~> rpm -q python
python-2.6.2-2.fc12.x86_64
nils@gibraltar:~> pydoc -k string
StringIO - File-like objects that read from or write to a string buffer.
UserString - A user-defined wrapper around string objects
[...]
dm.c: 1640: not running as root returning empty list
[...]
(process:6997): Gdk-CRITICAL **: gdk_keymap_get_for_display: assertion `GDK_IS_DISPLAY (display)' failed
(process:6997): Gdk-CRITICAL **: gdk_screen_get_root_window: assertion `GDK_IS_SCREEN (screen)' failed
** (process:6997): CRITICAL **: egg_keymap_resolve_virtual_modifiers: assertion `GDK_IS_KEYMAP (keymap)' failed
[...]
gtcache.gettext: not initialized for string "Ok"
gtcache.gettext: not initialized for string "Close"
gtcache.gettext: not initialized for string "Cancel"
[...]
Traceback (most recent call last):
File "/usr/bin/pydoc", line 5, in <module>
pydoc.cli()
File "/usr/lib64/python2.6/pydoc.py", line 2264, in cli
apropos(val)
File "/usr/lib64/python2.6/pydoc.py", line 1962, in apropos
ModuleScanner().run(callback, key)
File "/usr/lib64/python2.6/pydoc.py", line 1927, in run
for importer, modname, ispkg in pkgutil.walk_packages(onerror=onerror):
File "/usr/lib64/python2.6/pkgutil.py", line 110, in walk_packages
__import__(name)
File "/usr/lib64/python2.6/site-packages/parted/__init__.py", line 28, in <module>
from _ped import AlignmentException
RuntimeError: pyparted requires root access
-- >8 ----------
Running "pydoc -k" should catch all exceptions while importing modules, and display failed modules _after_ all positive keyword matches (not in between). It also should redirect stdout/stderr while importing so error message e.a. don't clutter up the list of hits.
Renaming from:
"pydoc -k" yields "NameError: name 'wglUseFontBitmapsW' is not
defined"
so that this bug can be a more general bug about improving the robustness of "pydoc -k" in the face of broken modules.
I've filed this issue in the upstream tracker here:
with a first pass at a patch.
*** Bug 447779 has been marked as a duplicate of this bug. ***
*** Bug 561419 has been marked as a duplicate of this bug. ***
*** Bug 594686 has been marked as a duplicate of this bug. ***
*** Bug 596370 has been marked as a duplicate of this bug. ***
Adding my workaround; building into rawhide as python-2.6.5-12.fc14
I'm confused. The upstream bug tracker comments seemed positive. Is this not going in upstream?
(In reply to comment #11)
> I'm confused. The upstream bug tracker comments seemed positive. Is this not
> going in upstream?
Upstream patch review can take a while, alas. Given that the patch is trivial and that this issue is continuing to affect people and generate bug reports, I feel applying the patch downstream is appropriate.
*** Bug 639125 has been marked as a duplicate of this bug. ***
*** Bug 649707 has been marked as a duplicate of this bug. ***
|
https://bugzilla.redhat.com/show_bug.cgi?id=461419
|
CC-MAIN-2018-05
|
refinedweb
| 716
| 60.21
|
dcecp(1m) dcecp(1m) NAME dcecp - Administrative interface for DCE management tasks SYNOPSIS dcecp [-s] [-local] [script_name | -c command ] OPTIONS A list containing one or more valid dcecp commands. For a description of the dcecp command format, see Administration Objects. Turns off inheritance of the login context. The default is to inherit the cur‐ rent login context of the principal that invokes dcecp. The -local option specifies that the dcecp session should operate on the local dced object while the dced process is in a partial-service state. ARGUMENTS Filename of a user-defined script containing dcecp commands. DESCRIPTION The DCE control program, dcecp, is the primary DCE administration interface, providing local and remote access to routine DCE administra‐ tive fea‐ tures, providing a set of commands for manipulating specific DCE objects. The control program also includes task scripts to help admin‐ istrators The DCE control program allows you to invoke dcecp commands in the fol‐ lowing modes: Interactive mode Command-line mode> Activate command-line mode from the system prompt by using one of the following methods: Enter the dcecp command with a filename of a script containing dcecp commands, other valid Tcl commands, or both, as fol‐ lows: % When you invoke dcecp, the following script files are executed in the order shown: Contains the standard Tcl initialization scripts with def‐ initions for the unknown command and the auto_load facility. Contains the initialization scripts implementing the dcecp commands and tasks. The implementation sets the Tcl variable dcecp_library to dce‐ shared/dcecp by default. Contains user customizations. Administration Objects A dcecp command has the following syntax: object operation [argument] [-option [opt_arg]] ... where: Specifies the name of a dcecp administration object. Examples of administration objects are Cell Directory Service (CDS) directories, access control lists (ACLs), Distributed Time Service (DTS) servers, server control objects, and so on. Each administration object is briefly described below. Specifies the name of an action, such as cre‐ ate, show, or remove, that is to be performed on an administration object. For complete descriptions of operations supported by each dcecp object, refer to individual object reference pages. Common oper‐ ations are briefly described below. Specifies the name of one or more specific objects to operate on. Most, but not all, dcecp objects take an argument. Refer to the individual reference pages for descriptions of the arguments supported by various objects. Specifies a qualifier that controls the precise behavior of a dcecp command. Most, but not all, dcecp commands take options. Specify options by preceding the option name with a dash, as in -replica. Some options take an argu‐ ment,. Manages an account in the DCE Security Service registry. Manages DCE ACLs. Manipulates attribute lists in scripts. Manages the audit daemon on any DCE host. Displays the audit event classes on any DCE host. Manages audit event filters on any DCE host. Displays audit trail files on the local host. Manages the CDS server daemon on any DCE host. Manages cell names known to CDS. Manages the CDS clerk cache on any DCE host. Manages the CDS client daemon on any DCE host. Performs cellwide tasks. Per‐ forms cell aliasing and connection tasks. Manages CDS clearinghouses on the local host. Manages the clock on any DCE host. Manages direc‐ tory entries in the CDS namespace. Manages DTS on any host. Displays remote endpoints, manages local endpoints. Manages DCE groups in the security service. Performs tasks involving a host in a DCE cell. Man‐ ages host-specific information on any DCE host. Manages host-specific variables on the local DCE host. Manages server key tables on any DCE host. Manages softlinks in CDS. Manages routing for DCE serviceabil‐ ity messages. Manages CDS name translation. Manages object entries in CDS. Manages DCE organizations in the Security Service. Manages DCE principals in the Security Service. Manages DCE security replicas and registry wide information. Manages a server entry in CDS. Manages a group entry in CDS. Manages a profile entry in CDS. Manages the secu‐ rity validation service on any DCE host. Manages DCE servers on any DCE host. Performs tasks involving individual user information. Manipulates Universal Time Coordinated (UTC) timestamps. Manipulates (generates or compares) Universal Unique Identifiers (UUIDs). Manages schemas for extended registry attributes (ERAs). Common Operations This section describes operations common to more than one object. Some operations presented here are implemented in all objects, some in only a few, and some only for specific types of objects such as containers (for instance, CDS directories).. Returns the names of all instances of an object. It usually takes no argument. In some cases, though, an argument specifying a scope, such as a cell name, is optional. For example, the principal catalog com‐ mand returns a list of all principals in the registry. By default, full names are returned. Some objects support a -simplename option, which returns names in a shorter form (either relative or not fully qualified). The order of the returned list depends on the. Destroys an instance of the object. It takes one argument, a list of names of instances to be deleted. This operation returns an empty string on success. If the object does not exist, an error is returned. Returns help information on the object as described in the Help section. It takes an argument, which may be an operation supported by the object or the -verbose option to return more information. Returns a list of the names of all the members of a container. This operation returns names only and not any other information about the members. It is imple‐ mented on all objects that represent containers. The argument is a list of names of containers for which to return members. The order of the returned list depends on the object. If more than one container name is given, all member names are returned in one list. This opera‐ tion is used to modify attributes, policies, counters, or any other information in an object. Therefore, all attributes, policies, coun‐ ters,. Used to add an attribute to an object or merely to add values to an existing attribute. The value of this option is an attribute list. Used to remove an entire attribute or merely some values from an attribute. The value of this option is an attribute list. Used to change one attribute value to another. The value of this option is an attribute list. Returns a list of the operations supported by the object. It takes no arguments, and always returns a Tcl list suitable for use in a foreach statement. The operations in the list are in alphabetical order with the exception of help and operations, which are listed last. To return the elements fully sorted, use the following command: lsort [object operations] Removes an object from a container. It is imple‐ mented com‐ mand are both lists, then each listed member is removed from each spec‐ ified container. If the members do not exist an error is returned. This operation returns an empty string on success.. Pairwise synchronization is not supported. This operation returns an empty string on success. Miscellaneous Commands The DCE control program includes a set of commands for miscellaneous operations. Initializes a base Tcl interpreter with all the dcecp com‐ mands. Displays the supplied string as output. Takes a DCE status code as an argument and returns the text of the associated message as found in the message catalogs. The argument can be in decimal, octal (leading 0), or hexadecimal (leading 0x) notation. ref‐ erence page. Login contexts are stacked. Takes an account name as an argument. The password is prompted for and not echoed to the screen. Also takes the -password option to enter a password.. Exits from dcecp. A synonym of the Tcl built-in command exit. Takes a partial string binding and returns a fully bound string binding. Takes a required -interface option and an optional -object option with an interface identifier as an argument to provide enough information for the mapping to occur. returned upon completion. Always returns an empty string, though an error exception is generated if the shell exits abnormally. Command Processing exe‐ cutes the command. If the command exists as an executable UNIX pro‐ gram, them‐ selves. This mechanism allows the operation name to be abbreviated to the shortest unique operation string supported by the object, and the option names to be abbreviated to the shortest unique string represent‐ ing an option supported by an object and operation. For example, consider the following directory create command: directory create /.:/admin/printers/ascii -replica -clearinghouse /.:/SFO_ch In the abbreviated form, the same command can be entered as follows: dir cre /.:/admin/printers/ascii -r -c /.:/SFO_ch Although abbreviating commands and options is a good way to save key‐ strokes when typing interactive commands, abbreviations are not recom‐ mended for use in scripts. New procedures in scripts can cause abbre‐ viations to become ambiguous. Furthermore, abbreviations are not always portable. When scripts move to other machines, some definitions may be left behind so scripts may not work correctly. Always spell out complete names in scripts. Syntax The dcecp commands have a default word order, which is object opera‐ tion. opera‐ tion order. You can load the script for all users on a host by includ‐ ing the following line in the system's init.dcecp file: source verb- object.dcecp You can configure operation object for individual users by including the line in that user's .dcecprc file. Attribute Lists: principal create smith -attribute {{quota 5} {uid 123}} principal create melman -quota 5 -uid 123 Lists of Lists‐ man} {user salamone}} Lists of one value that do not contain spaces do not require braces. The string syntax of an ACL entry allows the type and key to be sepa‐ rated. Convenience variables behave just like other variables in dcecp. Thus, you can trigger variable substitution by prepending a $ (dollar sign) before the name of the variable. Alternatively, you can trigger sub‐ stitution by using set. The convenience variables can be set only by using dcecp. The following variables are defined by dcecp:. Holds the cell name of the current princi‐ pal. The login command sets the cell name (_c) and principal name (_u) convenience variables at login (see the login command). This variable cannot be set by the user. This variable alters the behavior of most commands that operate on a CDS object. It indicates the confidence you have in the local CDS daemon to fulfill requests. The legal values are low, medium, and high. The default is medium. Holds the last DCE error code encountered. This variable has meaning only if dcecp is able to determine what the error code is. The value -l (negative one) is used when an actual error code is unavailable. This variable cannot be set by the user. Holds the hostname the current user is operating on. This variable cannot be set by the user. Holds a flag that indi‐ cates the mode in which the dcecp session is operating. This variable is set to true if the dcecp session was started with the -local option. This variable cannot be set by the user. Holds a list of the names entered in the last command. These names are the names that the com‐ mand operated on, typically entered as the third argument. This vari‐ able cannot be set by the user. For example, the following command lists the simplenames of the entries in the /.: directory: dcecp> directory list /.: -simplename hosts sub‐ sys> Holds the object used in the last operation. For example, if the last command was dir show /.:, then _o is directory. This variable cannot be set by the user. par‐ ents of /.:/gumby and /.:/pokey: dcecp> directory create {/.:/gumby /.:/pokey} dcecp> dcecp> echo $_n /.:/gumby /.:/pokey dcecp> dcecp> echo $_p /.: /.: dcecp> Holds the return value of the last exe‐ cuted command. This variable cannot be set by the user. Holds the name of the server to bind to by the next command. This variable is actually a Tcl array where the indexes are used to identify the ser‐ vice. reg‐ istry vari‐ able. Holds the current principal name. The login command sets the cell name (_c) and principal name (_u) convenience variables at login (see the login command). This variable cannot be set by the user. Error Handling com‐ mands return one line error messages by default. If the variable dcecp_verbose_errors is set to 1, then a stack trace as it would appear in errorInfo is output as well. When a dcecp command argument is a list of objects, the command oper‐ ates on multiple objects. These operations are usually performed iter‐ atively. If an error occurs, the command ceases at the time of error, producing an exception. Some operations will have finished and others will not have. These operations are always performed in the order listed, and the error message should make it clear on which object the command failed. Help oper‐ ation is supported by an object can use this command to find the answer. The output is a dcecp list that can be used by other dcecp commands. To see other information about an object, use an object's help opera‐ tion.> View brief information about the options an operation supports by using help with the name of the opera‐ tion The file opt/dcelocal/dcecp/utility.dcp contains Tcl functions useful for DCE administration. The functions, which can vary from release to release, are fully commented to document their use. Reference Pages Command-Line Editing You can edit a line before it is sent to dcecp by typing certain con‐ trol case-sensitive; con‐ trol: Action Performed Move to the beginning of the line Move left (backward) [n] Delete the next character [n] Move to the end of the line Move right (forward) [n] Ring the bell Delete the character before the cur‐ sor [n] Complete the filename (<Tab>) Done with the line (<Return>) Kill to the end of the line (or column [n]) Redisplay the line Done with the line (alternate <Return>) Get the next line from history [n] Get the previous line from history [n] Search backward (or forward if [n]) through history for the text; start the line if the text begins with an up arrow Transpose the characters Insert the next character even if it is an edit command Wipe to the mark Exchange the current location and mark Yank back the last killed test Start an escape sequence (<Escape>) Move forward to the next character c Delete the character before the cursor [n] Action Performed Delete the previous word (<Backspace>) [n] Delete the previous word (<Delete>) [n] Set the mark (<Space>); refer to the <Ctrl-X><Ctrl-X> and <Ctrl-Y> control characters Get the last (or [n]th) word from the previous line Show the possible completions Move to the start of history Move to the end of history Move backward one word [n] Delete the word under the cursor [n] Move forward one word [n] Make the word lowercase [n] Make the word uppercase [n] Yank back the last killed text Make area up to mark yankable Set repeat count to the number nn The DCE control program also supports filename completion. For exam‐ ple, file‐ name for you. Command History and Command-Line Recall The DCE control program includes a history facility that stores previ‐ ously fol‐ lows: dcecp> !dir [execution of last event beginning with dir] dcecp> Invocations The following examples show some ways to issue dcecp commands: Invoke dcecp for interactive use: % dcecp dcecp> Invoke dcecp for a single command: % dcecp -c clock show 1994-04-21-19:12:42.203+00:00I----- % Invoke dcecp and run a script: % dcecp get_users.Tcl % Simple Object Commands dcecp> acl show /.: -ic {unauthenticated r--t---} {group sub‐ sys dcecp> foreach i [group list temps] { > account modify $i -description "temps research" -expdate 1997-01-22-11} dcecp> RELATED INFORMATION Commands: cds_intro(1m), dce_intro(1m), dts_intro(1m), sec_intro(1m). dcecp(1m)[top]
|
http://www.polarhome.com/service/man/?qf=dcecp&tf=2&of=HP-UX&sf=1m
|
CC-MAIN-2020-40
|
refinedweb
| 2,663
| 58.18
|
Jim Miller
Joined
Activity
In case someone stumbles across this and needs an answer. Modify message_list_controller:
app/javascript/controllers/message_list_controller.js
_cableReceived(data) { this.messagesTarget.innerHTML += data.message; }
Hi,
I'm having some issues with Stimulus and I was hoping that someone could review this code and see if they see anything that I missed.
The Rails part is working and saving to the db. I'm sure that I have a typo somewhere...
Here is what I have:
app/channels/message_channel.rb
class MessageChannel < ApplicationCable::Channel def subscribed stream_from 'message_channel' end def unsubscribed stop_all_streams end end
app/javascript/controllers/message_list_controller.js
import { Controller } from "stimulus"; import consumer from "../channels/consumer"; export default class extends Controller { static targets = ["input", "messages"]; connect() { this.channel = consumer.subscriptions.create("MessageChannel", { connected: this._cableConnected.bind(this), disconnected: this._cableDisconnected.bind(this), received: this._cableReceived.bind(this), }); } clearInput() { this.inputTarget.value = ""; } _cableConnected() {} _cableDisconnected() {} _cableReceived() { this.messagesTarget.innerHTML += data.message; } }
app/controllers/messages_controller.rb
class MessagesController < ApplicationController before_action :set_message, only: [:show, :edit, :update, :destroy] def index @messages = Message.all end def create @message = Message.new(params.require(:message).permit(:content)) @message.save! ActionCable.server.broadcast('message_channel', message: (render @message)) head :ok end private def set_message @message = Message.find(params[:id]) end def message_params params.require(:message).permit(:content) end end
app/views/messages/index.html.erb
<p id="notice"><%= notice %></p> <h1>Messages</h1> <div data- <div data- <%= render @messages %> </div> <%= form_with(model: Message.new, data: { action: 'ajax:success->message-list#clearInput' }) do |form| %> <%= form.text_area :content, data: { target: 'message-list.input' }, rows: 1, autofocus: true %> <%= form.submit class: "btn btn-default" %> <% end %> </div>
Thanks!
Updated my controller but still no go:
def create message = @hangout.messages.new(message_params) message.user = current_user respond_to do |format| if message.save format.html { redirect_to @hangout, notice: 'Success' } format.js else format.html { render action: 'new' } end end
BTW, I am working on this Lesson:
Group Chat with ActionCable: Part 3
I am using Rails 6. I have a form that I need to pass
remote: true so I get POST to process as JS:
LOG: MessagesController#create as JS
Here is what I have tried:
<%= form_for [@hangout, Message.new] do |f| %>
The result is a good save to the DB but processes as HTML:
LOG: MessagesController#create as HTML
So I tried:
<%= form_for [@hangout, Message.new], remote: true do |f| %>
I learned that this would give an InvalidAuthenticityToken error:
LOG: ActionController::InvalidAuthenticityToken - ActionController::InvalidAuthenticityToken:
Tried this:
<%= form_for [@hangout, Message.new], authenticity_token: true do |f| %>
It passes as HTML, not JS
I read that for Rails 6, the best way to do this was with form_with because it passes
remote:true:
<%= form_with(model: [@hangout, Message.new]) do |f| %>
Unfortunately, this never reaches the controller so I get no response. I know that my model and controller are set up properly since the first try with form_for works, so it has to be with the way I am writing my form_with, right?
Does anyone have any advice?
Thanks!
#model class Message < ApplicationRecord belongs_to :hangout belongs_to :user end #controller class MessagesController < ApplicationController before_action :authenticate_user! before_action :set_hangout def create message = @hangout.messages.new(message_params) message.user = current_user message.save redirect_to @hangout end private def set_hangout @hangout = Hangout.find(params[:hangout_id]) end def message_params params.require(:message).permit(:body) end end #routes require 'sidekiq/web' Rails.application.routes.draw do resources :hangouts do resource :hangout_users resources :messages end resources :notes authenticate :user, lambda { |u| u.admin? } do mount Sidekiq::Web => '/sidekiq' end devise_for :users, controllers: { registrations: 'users/registrations' } get 'mine', to: 'notes#mine' root to: 'application#root' mount Shrine.presign_endpoint(:cache) => '/images/upload' end
Posted in Help with Debugging
Hi all,
I am trying to help out an open source project that I use. I found an issue and the developer has asked me to help debug the javascript but I'm a javascript hack and not sure how to do it.
Background:
- The project is coc-tailwindcss
- The plugin works in one project but not the other. Here's the issue:
- The developer says the LSP init fail, debug the error at line:
- The developer asked me "Use console.log to print info to output channel or follow"
I have at least 2 questions:
- The developer wants the console.log() on 7134. Exactly where in the code should I put it and what variable should I use?
- I'm assuming that the output would be in :CocCommand workspace.showOutput but I'm not sure. Am I right? Is there another spot to output?
I appreciate any help!!
Jim
Posted in How to Set Up a Stripe Scheduled Subscription with an option for Deposit but with only X months to Pay the Balance?
";)
Posted in How to Set Up a Stripe Scheduled Subscription with an option for Deposit but with only X months to Pay the Balance?
Its only "Very cool" if it works! LOL
So you are basically saying that I control everything in Rails and just use Stripe as the final payment method, right?
So like this:
- The deposit would be one payment thru Stripe, say $200 out of $400 (I'm assuming that I can use the same JavaScript as I have been with your tutorial?)
- Thru Rails I would set that as "deposit". Maybe using Enums? enum status: [:paid_in_full, :deposit]
- Set up Cron to send an email to all depositors every month as a reminder
- The rest of the payment would be a seperate payment thru Stripe
- If full payment is made, update status: :paid_in_full
- If status: :paid_in_full, then show advertisement on WordPress site
I plan on pulling json generated from the users controller to populate the WordPress site. I'm sure I will post questions when I get to that stage!
Thanks for the help, Chris!
Hi Kasper,
The first thing that I notice is that you don't have any actions defined in your controller. Rails is trying to process UserprofilesController#update but the action empty. So that would be a start, define your actions and see what happens.
A couple of things that you should try after you resolve the first one:
- Your UsersController should inherit from Devise. See Devise github page:
- Make sure that you sanitize any additonal attribute from the Devise standard:
My personal opinion is to not overly complicate your Rails code to make the UI better for the user. You can order attributes into groups on the front-end to make it easier for the user to focus, you could make tabs to seperate the groups. What I would do is use something like the Wicked gem. It helps you create a wizard type of experience for your user. Breaks the profile creation into bit-sized pieces. Richard Schneeman is the maintainer. Check out his screen cast, I think that its what you are looking for:
I hope that my comments are helpful! Good luck!
Posted in How to Set Up a Stripe Scheduled Subscription with an option for Deposit but with only X months to Pay the Balance?
Its for a Tattoo Convention. These are artists putting a deposit down for a booth or multiple booths. The deposit is "no refund". Which is the industry accepted practice.
The system I am creating will:
- have the artist register with the normal contact info plus other info like tattoing style, Instagram and/or Facebook urls and their picture which will be in their profile/account info in Devise.
- Then they can pay full price for a booth(s) or they can put a deposit down.
- The deposit holds a booth for them until the determined due date. If the date passes, they loose the spot for the booth and deposit.
- Once the artist pays in full, their info and picture will be posted on the site, not before. This is for advertisement on the Convention site so its incentive for them to pay in full so they get there advertisement on the site. So I need to record when they complete payment so then I will have the advertisment posted dynamically to the Convention site, which is a Wordpress site.
I also found that you can set the Stripe API to send the invoice to the customer by email, which is cool:
Kasper, can you tell us why you want to split the user profile into 3 different pages?
Kasper, does your log files give you any indication as to what is going on?
Posted in How to Set Up a Stripe Scheduled Subscription with an option for Deposit but with only X months to Pay the Balance?
I am creating a Stripe product that gives the buyer an option to put a deposit down then they are given x amount of months to pay. Or they can pay in full. I'm sure that I would use scheduled subscriptions to do that. How would I set up that Subscription so that the customer only has x months to pay and requires the balance paid at the end?
Thanks!
Jim
Hi all,
I am getting an error "uncaught syntaxerror unexpected token ' var'" . I'm using this JQuery plugin:
The error is showing up on "var updateTime.
Here is the page that I am adding it to:
Can anyone see what I am doing wrong?
Thanks ahead of time!
Jim
<script> var cl = cloudinary.Cloudinary.new({ cloud_name: 'downtown' }); cl.responsive(); //Script for CountDownTimer $("#DateCountdown").TimeCircles(); $("#CountDownTimer").TimeCircles({ time: { Days: { show: false }, Hours: { show: false } }}); $("#PageOpenTimer").TimeCircles(); ------------ var updateTime = function(){ var date = $("#date").val(); var time = $("#time").val(); var datetime = date + ' ' + time + ':00'; $("#DateCountdown").data('date', datetime).TimeCircles().start(); } $("#date").change(updateTime).keyup(updateTime); $("#time").change(updateTime).keyup(updateTime); // Start and stop are methods applied on the public TimeCircles instance $(".startTimer").click(function() { $("#CountDownTimer").TimeCircles().start(); }); $(".stopTimer").click(function() { $("#CountDownTimer").TimeCircles().stop(); }); // Fade in and fade out are examples of how chaining can be done with TimeCircles $(".fadeIn").click(function() { $("#PageOpenTimer").fadeIn(); }); $(".fadeOut").click(function() { $("#PageOpenTimer").fadeOut(); }); </script>
Posted in How do I resolve this syntax error
That's it! Thanks!
Posted in How do I resolve this syntax error
Hi guys,
I have this error and I don't understand what the error is. I'm using Rails 6
syntax error, unexpected tLABEL
stripe_id: customer.id,
~~~~~~~~~
/vagrant/Rails/stripe-test/app/controllers/subscriptions_controller.rb:34: syntax error, unexpected tLABEL, expecting '='
My code is:
options = (
stripe_id: customer.id,
stripe_subscription_id: subscription.id
)
current_user.update(options)
Thanks,
Jim
that sounds good! live and learn. luckily this is only a tutorial.
thanks Chris
lol. that sucks. I'm in Fla and my computer is in PA. I guess it defeats the purpose, but can it be reset locally so I can finish my tutorial? ":)
Hi all,
I cloned my project to my laptop but when I try to access credentials.yml.enc with rails credentials:edit, I get this error:
Couldn't decrypt config/credentials.yml.enc. Perhaps you passed the wrong key?
Can anyone give me the steps to properly reset my credentials.yml in a cloned repo?
Thanks,
Jim
Posted in Subscriptions with Stripe Discussion
Thanks Chris!
|
https://gorails.com/users/118
|
CC-MAIN-2020-50
|
refinedweb
| 1,840
| 58.38
|
Week 20
-
PROJECT DEVELOPMENT
Individual Assignment
Complete your final project, tracking your progress.
Project progress (INDIVIDUAL ASSIGNMENT)
This project is about a medical device. It will help patients with scoliosys, to correct their posture mechanically. My first ideas for actuator were rotary or linear servos, but following the Neil's feedback I read more about soft robotics. I found very nice projects that uses this kind of actuator.
(Taked from Youtube)
One of these project includes McKibben actuators, made of an cilindrical expandable globe, into a mesh. This actuator can contracts when the pressure air inside increase. The problem is the relative high pressure needed to act it.
First ideas
Corset with rotary servos.
Second idea
Softactuator, powered by pressure air..
Mockup of the project
The softactuator placed over a belt.
First actuator powered by pressure air
This actuator works, but needs a high pressure to operate.
The next prototypes that I made were soft actuators too. These were made from silicone mainly, but this time, I tried another approach (taken form this link). Inside the silicone globe, I puted an electric resistance wire, and fill all the inside of the actuator with alcohol, then sealed.
(Taked from Youtube)
So, I tarted to made prototypes
The concept
The first idea was emulate the natural way the muscles create movements on the human body.
First actuator mold
I used a marker to made a fast mold.
First actuator mold
I used a marker to made a fast mold.
First actuator mold
The hole allows introduce a core to the mold.
Core of mold
The core of the mold is a aluminum tube.
Cast silicone RTV 20
The material used to cast was platinum silicone bi-component. Hardness Shore A 20.
Some tools to cast
Some accesories were needed to make the casting..
The process of fabrication can be seen at the images.
When I tried to use this actuator, with alcohol inside, I couldnt make it work. The heat generated in the wire, was not enough to evaporate the liquid (and increase the volume) to generate the pressure inside, needed to expand the wall of silicone. So, I decide to tried with a thin wall and made a mold to achieve that.
I decide to design and 3d print a mold, but the only material available on tha Fablab at that time was ABS on a machine most used with PLA. The result was the expected. It failed. After that, I decided modify the design, to use the CNC machine, to get the mold with polyurethane resin. Unfourtunelly, there was no wax aviable and I used nylon, but the surface finish of that material was very poor (at least with my mill tool). I decided to continue with the casting of the poliurethane and get the mold.
Saddly, due to the surface porous on the mold and the thin wall of silicone, the pieces resulted porous.
After that, I decide try a simpler approach than before. I found a simple way to act an soft actuator with negative pressure. So, I decide to try with this.
(Taked from Youtube)
Looks simplier than before designs and require relative low pressures differences.So I started with a simple version, made of cardboard.
The test of this actuator was very successful.
The next step was built a 3d printed mold and cast silicone to make a soft actuator. Actually I cast a couple of silicone variants, the first one a bicomponent platinum silicone RTV 20 (white color) and a silicone with catalyzer (pink color).
After that I taked a decision (not good at all). I complete the actuator with silicone walls. To do that, I made a frame of MDF. This allows cast a layer of silicone, then I placed the actuators over there and wait to cure. The result after some hours, was 4 complete soft actuators. Was very important, made some holes on the inner walls to the actuator BEFORE the casting of the external walls.
Once the actuator was ready, I designed a support to align the servo motor and a three way valve (used with venoclysis equipments). I 3d print it and fixed together with zip ties.
Finally, to integrate all the components, I designed a "boxes" to hold the supports, valves, servo motors and the Fabduino.
The result of assemble the supports, valves and hoose is this. To be honest, I was planning a lean prototype, but the size was defined by the servos and valves. I'm pretty sure I can make it smaller than this in a next iteration (And pretiest than this :).
Meanwhile, all this works was running, I was developing the software to control de servos (and valves) through a smartphone via bluetooth, communicating an Fabduino. This Fabduino, is connected to the servos, then open and close the valves, according the smartphone orders.
This code, stablish a serial communication between a bluetooth module HC-05 and the Fabduino. I was develop this in detail in week 14 assignment. The code, receive a number from the Android App, this number is used to identify what servomotor must open (turn to 0 degress) or close (turn to 100 degress) a valve.
#include < SoftwareSerial.h> #include < Servo.h> //Bluetooth definitions #define RxD 10 #define TxD 11 #define DEBUG_ENABLED 1 SoftwareSerial blueToothSerial(RxD,TxD); int led_test = 8; //Servo definitions Servo L1; int pinL1 = 2; // byte Servo R1; int pinR1 = 3; Servo L2; int pinL2 = 4; Servo R2; int pinR2 = 5;(){ //Bluetooth setup----------- pinMode(RxD, INPUT); pinMode(TxD, OUTPUT); setupBlueToothConnection(); pinMode(led_test,OUTPUT); digitalWrite(led_test,LOW); //led for testing //Servo setup-------------- Serial.begin(9600); L1.attach(pinL1); L1.write(90); //Degrees = CLOSE R1.attach(pinR1); R1.write(90); //Degrees = CLOSE L2.attach(pinL2); L2.write(90); //Degrees = CLOSE R2.attach(pinR2); R2.write(90); //Degrees = CLOSE } void loop(){ char recived_char; char last_recived_char; while(1){ //check if there's any data sent from the remote bluetooth shield if(blueToothSerial.available()){ recived_char = blueToothSerial.read(); //Servo L1-------------- if( recived_char == '1' ){ digitalWrite(led_test,HIGH); L1.write(0);//turn 0 degrees = OPEN last_recived_char = recived_char; delay(20); } else if( recived_char == '0' ){ digitalWrite(led_test,LOW); L1.write(100);//return to 100 degrees = CLOSE last_recived_char = recived_char; delay(20); } //Servo R1-------------- if( recived_char == '2' ){ digitalWrite(led_test,HIGH); R1.write(0);//turn 0 degrees = OPEN last_recived_char = recived_char; delay(20); } else if( recived_char == '3' ){ digitalWrite(led_test,LOW); R1.write(100);//return to 100 degrees = CLOSE last_recived_char = recived_char; delay(20); } //Servo L2-------------- if( recived_char == '4' ){ digitalWrite(led_test,HIGH); L2.write(0);//turn 0 degrees = OPEN last_recived_char = recived_char; delay(20); } else if( recived_char == '5' ){ digitalWrite(led_test,LOW); L2.write(100);//return to 100 degrees = CLOSE last_recived_char = recived_char; delay(20); } //Servo R2-------------- if( recived_char == '6' ){ digitalWrite(led_test,HIGH); R2.write(0);//turn 0 degrees = OPEN last_recived_char = recived_char; delay(20); } else if( recived_char == '7' ){ digitalWrite(led_test,LOW); R2.write(100);//return to 100 degrees = CLOSE last_recived_char = recived_char; delay(20); } } } }
The mobile app that send the instruction from the user, was made with MIT App Inventor.
The process of develop an mobile app for Android, was developed on the week 16 assignment.
The app I made looks like this:
(the apk and the project to built it, can be downloaded from the link at the end of page).
Finally, after all the work (So many hours). The final test worked!
Final comments
what tasks have been completed, and what tasks remain?
I completed: the software loaded to the Fabduino, mobile Android application, 3d printed supports to servos and valves, assembly of the machine working togheter.
The tasks remain are: Improve the brace with another material (no MDF), manage the cables and hoses, Use some batteries and a portable vacuum pump.
what has worked? what hasn’t?
Worked: The software on Fabduino receive the values from the HC-05 bluetooth module, via serial communication, the mobile app send the correct values to the Fabduino. The micro servos can move the valves (slowly, but did it).
Not worked: The actuator is too rigid. ON the test, I used a thin film of plastic to enclosure, but when used silicone the actuator turns rigid and the contraction reduces. This is tha way that would be work with a thin enclosure:
what questions need to be resolved?
I think the main question is: Can I get the pressure needed from a portable vacuum pump?
This is a feature that makes the device portable. I demostrated that it work, but I would like to do this entirely portable.
what will happen when?
I will try a portable vacuum pump with LIPO batteries and improve the brace design with other materials. Basically, I will continue with the development until make it practical enough.
Once I reach that, I will need to test it with the supervision of medics, to guarantee a proper function.
What have you learned?
- I think the idea of made the entire actuator with silicone, wasn't good. The outer material must be thin and inextensible, to get a larger contraction of the actuator.
- The torque of the micro servos are barely the needed to turn the valves. I think must analyze another option to turn the valves (or use larger servos).
- Cable and hoose management must be considered carefully on a next iteration and integrated with the design.
- This prototype use an external vacuum pump. I think t must be replaced by an portable option. I will check the air pumps of the portable blood pressure monitors.
Files of this assignment:
- Robotic-Brace-v2.c (Fabduino code)
- Robotic-Brace-v2.aia (App Inventor Project)
- Robotic-Brace-v2.apk (Android App)
<<< Go to Week 6 assignment | >>> Go to Week 8 assignments
|
http://fabacademy.org/2019/labs/tecsup/students/carlos-ochoa/week-20.html
|
CC-MAIN-2020-10
|
refinedweb
| 1,602
| 65.62
|
Opened 5 years ago
Closed 3 years ago
#22510 closed enhancement (worksforme)
Enhanced package uninstallation for Sage spkgs
Description (last modified by )
Currently spkg uninstallation is handled in an ad-hoc manner. Many packages contain some rough uninstallation steps in their
spkg-install scripts (to be run, for example, when upgrading/reinstalling a package). But these are often imprecise and not thorough (though maybe still worth keeping where they already exist, as I will explain below).
implementation
- #22509 - most packages are now installed with staged installation (i.e. DESTDIR installation), which enables creating a manifest of all files installed by that package (minus files created by the package's
spkg-postinstscript). This is mostly working now for almost all packages (see #24024).
- #25139 - add an spkg-uninstall script: this would read the file manifest for a package (if it exists) and remove those files from
$SAGE_LOCAL--thus uninstalling the package thoroughly and precisely.
- #25139 - support legacy uninstallers: many existing spkgs have steps in their
spkg-installfor "uninstalling" that package--mostly just removing a few key files associated with the package (executables and libraries), but was rarely complete. However, some of these legacy uninstall steps are still necessary for properly building the package if the package has not already been uninstalled. This is an issue for the new system insofar as we want upgrades from older versions of Sage to work, so the legacy uninstallers are still needed at least for one upgrade, if uninstalling a package that doesn't have a proper file manifest. Since these steps are no longer needed in the
spkg-install(in fact ideally
spkg-installshould not modify
$SAGE_LOCALat all, we move those steps into a separate
spkg-legacy-uninstallscript which is run only when uninstalling a package that is missing its file manifest.
- #25139 - also add support for an
spkg-postrmscript that would be the complement to a
spkg-postinstscript, and may clean up files generated by a package that are not part of the package's file manifest
old design discussion
Here are a few proposals for improving package uninstallation (which is useful even for required packages, such as in the case of upgrading them):
- For all installed packages, maintain lists of the files installed by those packages. For this, something like #22509 is a prerequisite. This list could even go into the
$SAGE_LOCAL/var/lib/sage/installed/files we already have. Uninstalling a package would consist primarily of removing all files in this list. It would also remove directories that are left empty after all files are removed.
- Add support an optional
spkg-uninstallscript for any spkgs. This can be used to perform any additional uninstallation steps. For example, it is a place to remove files / data added specifically for Sage by
spkg-install(e.g. symlinks) that are not installed by the package's
make install. This would be run before the full uninstall described in the previous bullet point (in case any files from the package are necessary to determine additional uninstall steps). So this would be sort of like a pre-uninstall.
- Add support for an optional
spkg-legacy-uninstallscript. This would contain whatever commands the
spkg-installscripts currently perform for uninstall. This would only be run when the installed file list described in the first bullet point is unavailable (e.g. for backwards compatibility when upgrading to this new system for the first time). This feature could maybe be removed entirely later, but would be good to add at first and keep around for a while.
The new process for upgrading / reinstalling a package could be (especially if more progress is made toward supporting #21726 in all spkgs):
- Build
- Install to temporary directory (#22509)
- Upon successful completion of 1. and 2., uninstall old package
- Install new package by copying from temp dir into
$SAGE_LOCAL
- Run post-install scripts, if any
This means a cleaner rollback from failed upgrades.
Change History (20)
comment:1 Changed 5 years ago by
- Dependencies set to #22509
comment:2 Changed 5 years ago by
- Branch set to u/embray/build/uninstall
- Commit set to ae503162358d7251f8132b02a568a154dda882bf
comment:3 Changed 5 years ago by
There is a slight possibility for a race condition here. If two packages share a directory (other than some top level directory like
lib that almost all packages use), but say something like
share/pari, it's possible one package can be trying to install to that directory while the other is uninstalling from it and this could lead to errors.
I haven't seen it come up in practice yet and it's probably pretty rare, but I might consider a mutex around the uninstall/install sections...
comment:4 Changed 5 years ago by
- Commit changed from ae503162358d7251f8132b02a568a154dda882bf to 18530eddafc2e11f08ad01e3c6aa194edd88a5d8
Branch pushed to git repo; I updated commit sha1. New commits:
comment:5 follow-up: ↓ 6 Changed 5 years ago by
Out of curiosity I had a look to see if any packages are installing (and hence uninstalling) the same file, as I figured there might be some such cases and indeed there are. I don't have an exhaustive list, because I have not installed every optional and experimental package.
The duplicate files fall into a few different categories:
- Most are due to packages that conflict with/replace another package. Either because two packages provide the same functionality (e.g. openblas/atlas, mpir/gmp) or because one package is a stripped down version of another (e.g. boost_cropped/boost, pari_seadata_small/database_pari).
I think it might be good if we had explicit conflicts/replaces markers for some packages. If a package conflicts with an installed package, it will not be installed unless forced. If a package replaces another package, the package it replaces is explicitly uninstalled first. In effect this already happens implicitly. If I install pari_seadata_small, and then install database_pari, the latter will override the former. But I think it would be better to do this explicitly.-info.
__init__.pyin Python namespace packages (e.g. backports_ssl_match_hostname/backports_shutil_get_terminal_size). If both are installed and one clobbers the other that's fine, but if one is then uninstalled it should not remove the shared
__init__.py. I'll have to look at how Debian handles this. It might be handled contextually--these files usually contain some boilerplate like
__path__ = extend_path(__path__, __name__). But the boilerplate is not always spelled exactly the same, so it might be tricky to check for. Maybe this just needs to be handled explicitly on a case-by-case basis.
bin/2to3--just one special case of a script that is being installed by both Python 2 and Python 3. This should of course be fixed in those packages.
comment:6 in reply to: ↑ 5 Changed 5 years ago by-infof.
In retrospect, I've come back around to thinking there should be a mechanism for
post-install/pre-uninstall scripts. For common examples like
share/info/dir there can be a boilerplate that's linked to or something.
Another example I found where this would be useful, which granted is an experimental package, while be
compilerwrapper. This package conflicts with
gcc unless the step of creating the wrapper scripts is done as a post-install step (and undone, if necessary, pre-uninstall).
comment:7 Changed 5 years ago by
- Commit changed from 18530eddafc2e11f08ad01e3c6aa194edd88a5d8 to 620287c2606f30fe3ea5623c87015dbc1b73817c
Branch pushed to git repo; I updated commit sha1. This was a forced push. Last 10 new commits:
comment:8 Changed 5 years ago by
- Description modified (diff)
- Milestone changed from sage-wishlist to sage-8.1
- Status changed from new to needs_review
Rebased on latest #22509; addressed issue of properly uninstalling the widgetsnbextension. It's working pretty well now, after multiple around of install/uninstall and upgrading from old builds from before these changes.
Of course #22509 should be reviewed and merged first as it lays most of the groundwork for this. If diff'd against #22509 the changes in this ticket don't look as big.
comment:9 Changed 5 years ago by
- Status changed from needs_review to needs_work
Needs to be rebased (but maybe not right now).
comment:10 Changed 5 years ago by
comment:11 Changed 5 years ago by
- Milestone changed from sage-8.1 to sage-8.2
comment:12 Changed 4 years ago by
- Dependencies #22509 deleted
I've had this on hold pending total completion of #22509 but it's still taking some time to get all the packages updated for DESTDIR support (see #24024). However, for many packages this is already working, and the general infrastructure is in place. So there's no reason not to move forward with the uninstallation work--the only problem is that packages that aren't installed with staged installation won't be properly uninstallable...yet.
Similarly, this work can be split up into a few smaller tickets, so I will move forward on that.
comment:13 Changed 4 years ago by
- Branch u/embray/build/uninstall deleted
- Commit 620287c2606f30fe3ea5623c87015dbc1b73817c deleted
- Description modified (diff)
Some new explanation of the work planned for this ticket, so I can break it up into multiple smaller chunks.
comment:14 Changed 4 years ago by
comment:15 Changed 4 years ago by
comment:16 Changed 4 years ago by
- Milestone changed from sage-8.2 to sage-8.3
comment:17 Changed 4 years ago by
- Milestone changed from sage-8.3 to sage-8.4
I believe this issue can reasonably be addressed for Sage 8.4.
comment:18 Changed 4 years ago by
- Milestone changed from sage-8.4 to sage-8.5
comment:19 Changed 3 years ago by
- Milestone changed from sage-8.5 to sage-8.7
Retargeting some of my tickets (somewhat optimistically for now).
comment:20 Changed 3 years ago by
- Milestone changed from sage-8.7 to sage-duplicate/invalid/wontfix
- Resolution set to worksforme
- Status changed from needs_work to closed
Adding initial work on the
sage-spkg-uninstallscript.
I've already created
spkg-legacy-uninstallscripts for most standard packages, but I'm still testing this mechanism. These scripts are just created by taking any uninstall steps found in the
spkg-installand splitting it out to a separate script. Implementation of uninstall steps is of course very uneven across packages, and I'm not creating legacy-uninstall scripts for those packages that didn't already have uninstall steps--if it wasn't needed before it isn't needed now. Many of the existing uninstall steps probably aren't needed either, but are (they reference specific tickets). To be on the safe side I just took what already exists more or less at face value and didn't change any of the details.
I haven't implemented support for the separate
spkg-uninstallscript yet as it hasn't been needed. Though there are a handful of packages where it might be useful (for example maxima's
spkg-installhas a step that removes files from
$DOT_SAGE).
Last 10 new commits:
|
https://trac.sagemath.org/ticket/22510?cversion=0&cnum_hist=5
|
CC-MAIN-2022-27
|
refinedweb
| 1,823
| 61.56
|
Path scripting
Introduction
The Path workbench offers tools to import, create, manipulate and export machine toolpaths in FreeCAD. With it, the user is able to import, visualize and modify existing gcode programs, generate toolpaths from 3D shapes, and export these toolpaths to gcode.
The Path workbench is currently in early development, and does not offer all the advanced functions found in some commercial alternatives. However, the python scripting interface makes it easy to modify or develop more powerful tools.
Quickstart
FreeCAD's Path objects are made of a sequence of motion commands. A typical use is this:
>>> import Path >>> c1 = Path.Command("g1x1") >>> c2 = Path.Command("g1y4") >>> c3 = Path.Command("g1 x2 y2") # spaces end newlines are not considered >>> p = Path.Path([c1,c2,c3]) >>> o = App.ActiveDocument.addObject("Path::Feature","mypath") >>> o.Path = p >>> print p.toGCode()
FreeCAD's internal GCode format
A preliminary concept is important to grasp. Most of the implementation below relies heavily on motion commands that have the same names as GCode commands, but aren't meant to be close to a particular controller's implementation. We chose names such as 'G0' to represent 'rapid' move or 'G1' to represent 'feed' move for performance (efficient file saving) and to minimize the work needed to translate to/from other GCode formats. Since the CNC world speaks thousands of GCode dialects, we chose to stick with a very simplified subset of it. You could describe FreeCAD's GCode format as a "machine-agnostic" form of GCode.
Inside .FCStd files, Path data is saved directly into that GCode form.
All translations to/from dialects to FreeCAD GCode are done through pre and post scripts. That means that if you want to work with a machine that uses a specific LinuxCNC, Fanuc, Mitusubishi, or HAAS controller etc, you will have to use (or write if inexistant) a post processor for that particular control (see the "Importing and exporting GCode" section below).
GCode reference
The following rules and guidelines define the GCode subset used internally in FreeCAD:
- GCode data, inside FreeCAD Path objects, is separated into "Commands". A Command is defined by a command name, which must begin with G or M, and (optionally) arguments, which are in the form Letter = Float, for example X 0.02 or Y 3.5 or F 300. These are examples of typical GCode commands in FreeCAD:
G0 X2.5 Y0 (The command name is G0, the arguments are X=2.5 and Y=0)
G1 X30 (The command name is G1, the only argument is X=30)
G90 (The command name is G90, there are no arguments)
- For the numeric part of a G or M command, both "G1" or "G01" forms are supported.
- Only commands starting with G or M are supported at the moment.
- Only millimeters are accepted at the moment. G20/G21 are not considered.
- Arguments are always sorted alphabetically. This means that if you create a command with "G1 X2 Y4 F300", it will be stored as "G1 F300 X2 Y4"
- Arguments cannot be repeated inside a same command. For example, "G1 X1 Y2 X2 Y3" will not work. You will need to split it into two commands, for example: "G1 X1 Y2, G1 X2 Y3"
- X, Y, Z, A, B, C arguments are absolute or relative, depending on the current G90/G91 mode. Default (if not specified) is absolute.
- I, J, K are always relative to the last point. K can be omitted.
- X, Y, or Z (and A, B, C) can be omitted. In this case, the previous X, Y or Z coordinates are maintained.
- Gcode commands other than the ones listed in the table below are supported, that is, they are saved inside the path data (as long as they comply to the rules above, of course), but they simply won't produce any visible result on screen. For example, you could add a G81 command, it will be stored, but not displayed.
List of currently supported GCode commands
The Command object
The Command object represents a gcode command. It has three attributes: Name, Parameters and Placement, and two methods: toGCode() and setFromGCode(). Internally, it contains only a name and a dictionary of parameters. The rest (placement and gcode) is computed to/from this data.
>>> import Path >>> c=Path.Command() >>> c Command ( ) >>> c.>> c Command G1 ( ) >>> c.Parameters= {"X":1,"Y":0} >>> c Command G1 ( X:1 Y:0 ) >>> c.Parameters {'Y': 0.0, 'X': 1.0} >>> c.Parameters= {"X":1,"Y":0.5} >>> c Command G1 ( X:1 Y:0.5 ) >>> c.toGCode() 'G1X1Y0.5' >>> c2=Path.Command("G2") >>> c2 Command G2 ( ) >>> c3=Path.Command("G1",{"X":34,"Y":1.2}) >>> c3 Command G1 ( X:34 Y:1.2 ) >>> c3.Placement Placement [Pos=(34,1.2,0), Yaw-Pitch-Roll=(0,0,0)] >>> c3.toGCode() 'G1X34Y1.2' >>> c3.setFromGCode("G1X1Y0") >>> c3 Command G1 [ X:1 Y:0 ] >>> c4 = Path.Command("G1X4Y5") >>> c4 Command G1 [ X:4 Y:5 ] >>> p1 = App.Placement() >>> p1.Base = App.Vector(3,2,1) >>> p1 Placement [Pos=(3,2,1), Yaw-Pitch-Roll=(0,0,0)] >>> c5=Path.Command("g1",p1) >>> c5 Command G1 [ X:3 Y:2 Z:1 ] >>> p2=App.Placement() >>> p2.Base = App.Vector(5,0,0) >>> c5 Command G1 [ X:3 Y:2 Z:1 ] >>> c5.Placement=p2 >>> c5 Command G1 [ X:5 ] >>> c5.x 5.0 >>> c5.x=10 >>> c5 Command G1 [ X:10 ] >>> c5.y=2 >>> c5 Command G1 [ X:10 Y:2 ]
The Path object
The Path object holds a list of commands
>>> import Path >>> c1=Path.Command("g1",{"x":1,"y":0}) >>> c2=Path.Command("g1",{"x":0,"y":2}) >>> p=Path.Path([c1,c2]) >>> p Path [ size:2 length:3 ] >>> p.Commands [Command G1 [ X:1 Y:0 ], Command G1 [ X:0 Y:2 ]] >>> p.Length 3.0 >>> p.addCommands(c1) Path [ size:3 length:4 ] >>> p.toGCode() 'G1X1G1Y2G1X1' lines = """ G0X-0.5905Y-0.3937S3000M03 G0Z0.125 G1Z-0.004F3 G1X0.9842Y-0.3937F14.17 G1X0.9842Y0.433 G1X-0.5905Y0.433 G1X-0.5905Y-0.3937 G0Z0.5 """ slines = lines.split('\n') p = Path.Path() for line in slines: p.addCommands(Path.Command(line)) o = App.ActiveDocument.addObject("Path::Feature","mypath") o.Path = p # but you can also create a path directly form a piece of gcode. # The commands will be created automatically: p = Path.Path() p.setFromGCode(lines)
As a shortcut, a Path object can also be created directly from a full GCode sequence. It will be divided into a sequence of commands automatically.
>>> p = Path.Path("G0 X2 Y2 G1 X0 Y2") >>> p Path [ size:2 length:2 ]
The Path feature
The Path feature is a FreeCAD document object, that holds a path, and represents it in the 3D view.
>>> pf = App.ActiveDocument.addObject("Path::Feature","mypath") >>> pf <Document object> >>> pf.Path = p >>> pf.Path Path [ size:2 length:2 ]
The Path feature also holds a Placement property. Changing the value of that placement will change the position of the Feature in the 3D view, although the Path information itself won't be modified. The transformation is purely visual. This allows you, for example, to create a Path around a face that has a particular orientation on your model, that is not the same orientation as your cutting material will have on the CNC machine.
However, Path Compounds can make use of the Placement of their children (see below).
The Tool and Tooltable objects
The Tool object contains the definitions of a CNC tool. The Tooltable object contains an ordered list of tools. Tooltables are attached as a property to Path Project features, and can also be edited via the GUI, by double-clicking a project in the tree view, and clicking the "Edit tooltable" button in the task views that opens.
From that dialog, tooltables can be imported from FreeCAD's .xml and HeeksCad's .tooltable formats, and exported to FreeCAD's .xml format.
>>> import Path >>> t1=Path.Tool() >>> t1 Tool Default tool >>> t1.>> t1 Tool 12.7mm Drill Bit >>> t1.ToolType 'Undefined' >>> t1.>> t1.Diameter= 12.7 >>> t1.LengthOffset = 127 >>> t1.CuttingEdgeAngle = 59 >>> t1.CuttingEdgeHeight = 50.8 >>> t2 = Path.Tool("my other tool",tooltype="EndMill",diameter=10) >>> t2 Tool my other tool >>> t2.Diameter 10.0 >>> table = Path.Tooltable() >>> table Tooltable containing 0 tools >>> table.addTools(t1) Tooltable containing 1 tools >>> table.addTools(t2) Tooltable containing 2 tools >>> table.Tools {1: Tool 12.7mm Drill Bit, 2: Tool my other tool} >>>
Features
The Path Compound feature
The aim of this feature is to gather one or more toolpaths and associate it (them) with a tooltable. The Compound feature also behaves like a standard FreeCAD group, so you can add or remove objects to/from it directly from the tree view. You can also reorder items by double-clicking the Compound object in the Tree view, and reorder its elements in the Task view that opens.
>>> import Path >>> p1 = Path.Path("G1X1") >>> o1 = App.ActiveDocument.addObject("Path::Feature","path1") >>> o1.Path=p1 >>> p2 = Path.Path("G1Y1") >>> o2 = App.ActiveDocument.addObject("Path::Feature","path2") >>> o2.Path=p2 >>> o3 = App.ActiveDocument.addObject("Path::FeatureCompound","compound") >>> o3.Group=[o1,o2]
An important feature of Path Compounds is the possibility to take into account the Placement of their child paths or not, by setting their UsePlacements property to True or False. If not, the Path data of their children will simply be added sequentially. If True, each command of the child paths, if containing position information (G0, G1, etc..) will first be transformed by the Placement before being added.
Creating a compound with just one child path allows you therefore to turn the child path's Placement "real" (it affects the Path data).
The Path Project feature
The Path project is an extended kind of Compound, that has a couple of additional machine-related properties such as a tooltable. It is made mainly to be the main object type you'll want to export to gcode once your whole path setup is ready. The Project object is now coded in python, so its creation mechanism is a bit different:
>>> from PathScripts import PathProject >>> o4 = App.ActiveDocument.addObject("Path::FeatureCompoundPython","prj") >>> PathProject.ObjectPathProject(o4) >>> o4.Group = [o3] >>> o4.Tooltable Tooltable containing 0 tools
The Path module also features a GUI tooltable editor that can be called from python, giving it an object that has a ToolTable property:
>>> from PathScripts import TooltableEditor >>> TooltableEditor.edit(o4)
Getting Path from Shape
Assign the shape of wire Part to a normal Path object, using Path.fronShape() script function (or more powerful Path.fronShapes()). By giving as parameter a wire Part object, its path will be automatically calculated from the shape. Note that in this case the placement is automatically set to the first point of the wire, and the object is therefore not movable anymore by changing its placement. To move it, the underlying shape itself must be moved.
>>> import Part >>> import Path >>> v1 = FreeCAD.Vector(0,0,0) >>> v2 = FreeCAD.Vector(0,2,0) >>> v3 = FreeCAD.Vector(2,2,0) >>> v4 = FreeCAD.Vector(3,3,0) >>> wire = Part.makePolygon([v1,v2,v3,v4]) >>> o = FreeCAD.ActiveDocument.addObject("Path::Feature","myPath2") >>> o.Path = Path.fromShape(wire) >>> FreeCAD.ActiveDocument.recompute() >>> p = o.Path >>> print(p.toGCode())
Python features
Both Path::Feature and Path::FeatureShape features have a python version, respectively named Path::FeaturePython and Path::FeatureShapePython, that can be used in python code to create more advanced parametric objects derived from them.
Importing and exporting GCode
Native format
GCode files can be directly imported and exported via the GUI, by using the "open", "insert" or "export" menu items. After the file name is acquired, a dialog pops up to ask which processing script must be used. It can also be done from python:
Path information is stored into Path objects using a subset of gcode described in the "FreeCAD's internal GCode format"section above. This subset can be imported or exported "as is", or converted to/from a particular version of GCode suited for your machine.
If you have a very simple and standard GCode program, that complies to the rules described in the "FreeCAD's internal GCode format" section above, for example the boomerang from , it can be imported directly into a Path object, without translation (this is equivalent to using the "None" option of the GUI dialog):
import Path f = open("/path/to/boomerangv4.ncc") s = f.read() p = Path.Path(s) o = App.ActiveDocument.addObject("Path::Feature","boomerang") o.Path = p
In the same manner, you can obtain the path information as "agnostic" gcode, and store it manually in a file:
text = o.Path.toGCode() print text myfile = open("/path/to/newfile.ngc") myfile.write(text) myfile.close()
If you need a different output, though, you will need to convert this agnostic GCode into a format suited for your machine. That is the job of post-processing scripts.
Using pre- and post-processing scripts
If you have a gcode file written for a particular machine, which doesn't comply to the internal rules used by FreeCAD, described in the "FreeCAD's internal GCode format" section above, it might fail to import and/or render properly in the 3D view. To remedy to this, you must use a pre-processing script, which will convert from your machine-specific format to the FreeCAD format.
If you know the name of the pre-processing script to use, you can import your file using it, from the python console like this:
import example_pre example_pre.insert("/path/to/myfile.ncc","DocumentName")
In the same manner, you can output a path object to GCode, using a post_processor script like this:
import example_post example_post.export (myObjectName,"/path/to/outputFile.ncc")
Writing processing scripts
Pre- and post-processing scripts behave like other common FreeCAD imports/exporters. When choosing a pre/post processing script from the dialog, the import/export process will be redirected to the specified given script. Preprocessing scripts must contain at least the following methods open(filename) and insert(filename,docname). Postprocessing scripts need to implement export(objectslist,filename).
Scripts are placed into either the Mod/Path/PathScripts folder or the user's macro path directory. You can give them any name you like but by convention, and to be picked by the GUI dialog, pre-processing scripts names must end with "_pre", post-processing scripts with "_post" (make sure to use the underscore, not the hyphen, otherwise python cannot import it). This is an example of a very, very simple preprocessor. More complex examples are found in the Mod/Path/PathScripts folder:
def open(filename): gfile = __builtins__.open(filename) inputstring = gfile.read() # the whole gcode program will come in as one string, # for example: "G0 X1 Y1\nG1 X2 Y2" output = "" # we add a comment output += "(This is my first parsed output!)\n" # we split the input string by lines lines = inputstring.split("\n") for line in lines: output += line # we must insert the "end of line" character again # because the split removed it output += "\n" # another comment output += "(End of program)" import Path p = Path.Path(output) myPath = FreeCAD.ActiveDocument.addObject("Path::Feature","Import") myPath.Path = p FreeCAD.ActiveDocument.recompute()
Pre- and post-processors work exactly the same way. They just do the contrary: The pre scripts convert from specific GCode to FreeCAD's "agnostic" GCode, while post scripts convert from FreeCAD's "agnostic" GCode to machine-specific GCode.
Adding all faces of a ShapeString to the BaseFeature's list of a ProfileFromFaces operation
This example is based on a discussion in the german forum.
Prerequisits
- Create a solid with ShapeString as Cutout
- Create a Job using this solid as its BaseObject
- Create a ProfileFromFaces operation named "Profile_Faces" with empty BaseGeometry.
The code
The following code will then add all faces from ShapeString and create the paths:
doc = App.ActiveDocument list_of_all_element_faces = [] for i, face in enumerate(doc.ShapeString.Shape.Faces): list_of_all_element_faces.append('Face' + str(i + 1)) doc.Profile_Faces.Base = [(doc.ShapeString, tuple(list_of_all_element_faces))] doc.recompute()
|
https://www.freecadweb.org/wiki/Path%20scripting
|
CC-MAIN-2019-51
|
refinedweb
| 2,657
| 58.28
|
This is Legba7's modification of the modified, unofficial LCD4BitLibrary from Neillzero for the LCD Module TM404 TM404 from Tianma
This display has a second HD44780 for the third and fourth line with its own Enable Input.
So I wired the second Enable Input to pin 3 on the arduino and edited Jonathan's modified library
Read more on 20x4 modifications in the arduinoforum
/* LCD4Bit v0.1 16/Oct/2006 neillzero edited by lega7 05/Oct/2007 to work with tm404a tm404a has a second HD44780 controller for line 3 and line 4 with a second Enable input What is this? An arduino library for comms with HD44780-compatible LCD, in 4-bit mode (saves pins) Sources: - The original "LiquidCrystal" 8-bit library and tutorial - DEM 16216 datasheet - Massimo's suggested 4-bit code (I took initialization from here) See also: - glasspusher's code (probably more correct): Tested only with a DEM 16216 (maplin "N27AZ" -) Tested and modifier for a 20x4 lcd controller (blue background and white text) If you use this successfully, consider feeding back to the arduino wiki with a note of which LCD it worked on. Usage: see the examples folder of this library distribution. */ #include "LCD4Bit.h" extern "C" { #include <stdio.h> //not needed yet #include <string.h> //needed for strlen() #include <inttypes.h> #include "WConstants.h" //all things wiring / arduino } //command bytes for LCD #define CMD_CLR 0x01 #define CMD_RIGHT 0x1C #define CMD_LEFT 0x18 #define CMD_HOME 0x02 // --------- = 12; int RW = 11; //legba7: two HD44780; per HD44780 one Enable Input int; void LCD4Bit::WriteCGRAM(int adress, char code[]) { commandWrite(0x40+(adress<<3)); printIn(code); commandWrite(CMD_HOME); // How to return to previous position ? } //pulse the Enable pin high (for a microsecond). //This clocks whatever command or data is in DB4~7 into the LCD controller. void LCD4Bit::pulseEnablePin(){ digitalWrite(Enable,LOW); delayMicroseconds(1); // send a pulse to enable digitalWrite(Enable,HIGH); delayMicroseconds(1); digitalWrite(Enable,LOW); delay(1); // pause 1 ms. TODO: what delay, if any, is necessary here? (it seems that 1ms is a good choice) } //push a nibble of data through the the LCD's DB4~7 pins, clocking with the Enable pin. //We don't care what RS and RW are, here. void LCD4Bit::pushNibble(int value){ int val_nibble= value & 0x0F; //clean the value. (unnecessary) for (int i=DB[0]; i <= DB[3]; i++) { digitalWrite(i,val_nibble & 01); val_nibble >>= 1; } pulseEnablePin(); } //push a byte of data through the LCD's DB4~7 pins, in two steps, clocking each with the enable pin. void LCD4Bit::pushByte(int value){ int val_lower = value & 0x0F; int val_upper = value >> 4; pushNibble(val_upper); pushNibble(val_lower); } //stuff the library user might call--------------------------------- //constructor. num_lines must be 1 or 2 or 4, currently. LCD4Bit::LCD4Bit (int num_lines) { g_num_lines = num_lines; if (g_num_lines != 1 && g_num_lines != 2 && g_num_lines != 4) { g_num_lines = 1; } } void LCD4Bit::commandWriteNibble(int nibble) { digitalWrite(RS, LOW); if (USING_RW) { digitalWrite(RW, LOW); } pushNibble(nibble); } void LCD4Bit::commandWrite(int value) { digitalWrite(RS, LOW); if (USING_RW) { digitalWrite(RW, LOW); } pushByte(value); //TODO: perhaps better to add a delay after EVERY command, here. many need a delay, apparently. } //print the given character at the current cursor position. overwrites, doesn't insert. void LCD4Bit::print(int value) { //set the RS and RW pins to show we're writing data digitalWrite(RS, HIGH); if (USING_RW) { digitalWrite(RW, LOW); } //let pushByte worry about the intricacies of Enable, nibble order. pushByte(value); } //print the given string to the LCD at the current cursor position. overwrites, doesn't insert. //While I don't understand why this was named printIn (PRINT IN?) in the original LiquidCrystal library, I've preserved it here to maintain the interchangeability of the two libraries. void LCD4Bit::printIn(char msg[]) { uint8_t i; //fancy int. avoids compiler warning when comparing i with strlen()'s uint8_t for (i=0;i < strlen(msg);i++){ print(msg[i]); } } //send the clear screen command to the LCD void LCD4Bit::clear(){ commandWrite(CMD_CLR); delay(1); } // initiatize lcd after a short pause //while there are hard-coded details here of lines, cursor and blink settings, you can override these original settings after calling .init() void LCD4Bit::init () { pinMode(Enable,OUTPUT); pinMode(RS,OUTPUT); if (USING_RW) { pinMode(RW,OUTPUT); } pinMode(DB[0],OUTPUT); pinMode(DB[1],OUTPUT); pinMode(DB[2],OUTPUT); pinMode(DB[3],OUTPUT); delay(50); //The first 4 nibbles and timings are not in my DEM16217 SYH datasheet, but apparently are HD44780 standard... commandWriteNibble(0x03); delay(5); commandWriteNibble(0x03); delayMicroseconds(100); commandWriteNibble(0x03); delay(5); // needed by the LCDs controller //this being 2 sets up 4-bit mode. commandWriteNibble(0x02); commandWriteNibble(0x02); //todo: make configurable by the user of this library. //NFXX where //N = num lines (0=1 line or 1=2 lines). //F= format (number of dots (0=5x7 or 1=5x10)). //X=don't care); //The rest of the init is not specific to 4-bit mode. //NOTE: we're writing full bytes now, not nibbles. // display control: // turn display on, cursor off, no blinking commandWrite(0x0C); delayMicroseconds(60); //clear display commandWrite(0x01); delay(3); // entry mode set: 06 // increment automatically, display shift, entire shift off commandWrite(0x06); delay(1);//TODO: remove unnecessary delays } //non-core stuff -------------------------------------- //move the cursor to the given absolute position. line numbers start at 1. //if this is not a 2-line LCD4Bit instance, will always position on first line. // //legba7: second controller, with its own Enable input, for line 3 and 4 void); } //scroll whole display to left //Doesn't seems to be usefull with 4 lines displays! // void LCD4Bit::leftScroll(int num_chars, int delay_time){ for (int i=0; i<num_chars; i++) { commandWrite(CMD_LEFT); delay(delay_time); } } //Improvements ------------------------------------------------ //Remove the unnecessary delays (e.g. from the end of pulseEnablePin()). //Allow the user to pass the pins to be used by the LCD in the constructor, and store them as member variables of the class instance. //-------------------------------------------------------------
#include <LCD4Bit.h> LCD4Bit lcd = LCD4Bit(4); void setup(){ pinMode(13, OUTPUT); //we'll use the debug LED to output heartbeat lcd.init(); lcd.clear(); lcd.cursorTo(3,0); //select second displaycontroller, line 3, 4 lcd.init(); lcd.clear(); } void loop(){ digitalWrite(13, HIGH); //light the debug LED lcd.cursorTo(1,0); lcd.printIn("Line 1"); lcd.cursorTo(2,0); lcd.printIn("Line 2"); lcd.cursorTo(3,0); lcd.printIn("Line 3"); lcd.cursorTo(4,0); lcd.printIn("Line 4"); delay(1000); lcd.cursorTo(1,0); // select first two rows lcd.leftScroll(40, 80); //scroll first two rows lcd.cursorTo(3,0); //select second displaycontroller, line 3, 4 lcd.leftScroll(40, 80); //scroll third and fourth row delay(1000); digitalWrite(13, LOW); }
Edit: by bingo_
The code from above fixed with one extra line. It works now and all in one Zip!
Attach:LCD4Bit.zip
|
http://arduino.cc/playground/Code/LCD4BitLibrary-tm404a
|
crawl-003
|
refinedweb
| 1,113
| 55.24
|
Codeforces Round #452 (Div.2) Editorial
In problem D (n + (n - 1) - sum) / 2
(n + (n - 1) - sum) / 2
I think it should be (n + (n - 1) - p) / 2
(n + (n - 1) - p) / 2
Can you explain me why this formula works?
sorry, I do not understand how it works, I found this after reading other's code.
oo ok) but (n + (n - 1) - sum) / 2 100% not right... becuse it`s always 0
D. Why is there this weird result?2 => 13 => 34 => 6
How is it possible to get 6 pairs?
UPD: I did it because my last tests were not passed, for example
The question asks for the number of pairs such that they produce the maximum number of trailing nines. When n < 5, there exists no pair such that their sum is a number with a trailing nine. Therefore we should print all pairs (as all of them produce the maximum number of trailing nines, which is zero). The number of pairs is simply nC2.
got it, thank you
why not just output -1 or 0 when n<5...
Refer to Fayaz's comment above or.
Yes please. Someone explain D. or atleast how to come up with those ideas and the formulas.
The solution for D is fairly simple to come up with.
1) Observe that when n < 5, the answer is nC2.
2) Observe that when n + (n — 1) is of the form 9....9 the answer is 1.
3) In all other cases, we need to iterate through the possible (i + j)'s that produce the maximum number of nines. So, say the maximum number of nines is x. Start at 9...9 (x times) and increment this to 1(9....9) (x times) 2(9....9) (x times) until we reach n + n — 1. For each of these numbers we need to calculate how many pairs (i, j) sum up to them. Now, when the number is >= n + n — 1, we need to add (number / 2) to our answer. This is because we can have: (number / 2) + (number / 2), (number / 2 + 1) + (number / 2 — 1)...so on to sum up to the number. Otherwise if the number < n + n — 1, we need to add (n — number / 2) to our answer. This is because we can have: (number / 2) + (number / 2), ..., n + (number — n).
Here's my submission for reference
It can be solved using digit DP. Submission Link Explanation
It should be 1 + (n + (n-1) - p)/2
1 + (n + (n-1) - p)/2
Pardon me for a stupid question.
In Div2B, the 13th test case is the following:
21 30 31 30 31 31 28 31 30 31 30 31 31 30 31 30 31 31 28 31 30 31
and correct output is "YES"
Doesn't this show two consecutive leap years? year 1: 31 28 31 30 31 30 31 31 30 31 30 31, next year: 31 28 31 30 31 ... this should not be possible right?
A leap year has 29 days.
Oh god. I can't believe I made this mistake D: So stupid of me.
Thanks though!
Look at all the people who failed problem B. They all did same mistake as you. It's because of the problem statement, January, 28 or 29 days in February (depending on whether the year is leap or not) , which gives an idea that correspondly leap has 28 days and not leap has 29 days.
Yeah. :(
I solved C by just making two set and giving element to the smaller sum set in a reverse sorted order.I don't know why this works though. Can anyone help me with proving this method's correctness or tell where it could fail?
I am trying the same approach and in pretest 5 59998 its failing as i am putting 48950 twice. I am not sure why only that case failing :|
EDIT: a lot of other cases are also failing. have to do something else,
Try to do it in reverse order, so construct your sets starting with n, then n-1, and so on. This will give you a correct solution.
A set of 4 numbers can always be divided into two sets so that their differences is 0. Take n, n-1, n-2, n-3. Set1 contains n, n-3 and Set2 contains n-1, n-2. When dividing a consecutive sequence, you can always start from the last, take a group of 4 consecutive integers, and start dividing like earlier.
If you can't take a group of 4 consecutive integers, the sequences left might be: i) 1, which can be assigned to any set. ii) 1, 2 : where 1 can be assigned to one set and 2 can be assigned the other set. iii) 1, 2, 3: where 1 and 2 has to be assigned to one set and 3 has to be assigned to the other set.
Your algorithm automatically takes care of the first step. When it assigns n to one set, and n-1 to another, then n-2 becomes assigned to the set containing n-1 and n-3 becomes assigned to the set containing n.
Your algorithm also automatically takes care of the 2nd step. A quick thinking will reveal why.
Hope you understood! :)
Yeah .Thanks !
good explanation .
Can someone please explain solution to problem E. I don't understand the editorial.
Understood from others solutions :)
A much easier solution for C : My solution link... 1. Just take the sum of the numbers= N*(N+1)/2.
3.If sum is odd, then logically one group will have one more sum than other group(g2). Let G2 sum be x. Keep giving the largest numbers possible to form x
I have also done with similar approach.
I wonder why the writer didn't explain in this way. Are there any cases that this approach doesn't work properly?
I used some FOR loops and my code passed all the test cases but I haven't understood how it worked yet, and your approach seems to be the way it works. Would anyone mind suggesting or showing me a proof of correctness?
Can someone explain D? Why we are adding those numbers etc..
难得有一次cf这么适合Chinese。。。
结果差点忘记比赛..晚了几十分钟
Easier way to solve problem C . The sum of the first N numbers is N * ( N + 1 ) / 2, let's call it tot.
If you have a number X less than or equal tot, it is possible to represent it as a sum of first N numbers. ( Iterate from N to 1, and subtract when possible), call that function represent(X). This is very well known.
Now .. if tot is even, we can obtain a difference of zero which we obtain by represent(tot/2). If tot is odd, we can obtain a difference of one which we obtain by represent(tot/2).
In even case, we get the best possible answer, in the odd case it's easy to see that the best we can obtain is a difference of one, and hence the algorithm is optimal.
Another way to solve F is keeping a treap for each character. However, it is overkill in my opinion. But if you have template ready to be copied and pasted, then it should be fastest solution.
Why crash?
You are using this loop:
for(set<int>::iterator re=ya.begin(); re!=ya.end(); re++)
if((*(re)+i<48)&&(a[*(re)+i]!=j))
ya.erase(re);
As soon as you do ya.erase(re), the iterator re is invalidated (refer to the first line in heading Iterator validity), so you get unexpected behavior, i.e., you shouldn't use re anymore.
ya.erase(re)
re
Thank you so much!
My solution to 899C - Dividing the numbers is the following:
We know that for every two consecutive numbers a and b, a-b = 1 if a > b and a-b = -1 if a < b. So if we take the rightmost two consecutive numbers a, b, a > b, and put them in separate groups, we have |group1-group2| = |a-b| = 1; now if we take the next two consecutive number c, d, with c < d, and put c in group1 and d in group2, then |group1-group2| = |(a+c)-(b+d)| = |(a-b)+(c-d)| = |1-1| = 0. If we greedily continue doing this strategy, we would compute two groups that their absolute difference of sums is minimum.
To compute the minimum absolute difference we can check in O(1) if we have a pair number of pairs (it means that every number has his pair in the strategy above) or not.
Code:
In problem D we can use a binary search for counting the number of pairs with a fixed amount on a interval: 33359972
Hey anyone got the solution of E by simulating the process using stacks, as i am getting stuck somewhere in this implementation.
Hi guys! Can anybody help me with problem F ?! I tried to solve it using a Multimap and a Fenwick Tree for building the initial positions but I'm getting "Wrong answer" on test 7 :(( Maybe I omit something. Thx in advance!
I solved it by checking if some char already deleted. If yes, don't update
Thank you! I was just deleting characters multiple times. ^^
I have a doubt in Problem E.
While merging the two nodes, I can see how we are deleting the right and the left element from the second set(called segments), and then inserting the merged set. I don't understand, how can we perform the same operation in the first set(called lens) ?
we know the position of the beginning of the segment and the length of the segment. so we can just use set.find
Got it. Thanks!
got it :)
Hey guys! Here are some of my thoughts on problem E this round, using priority queue and linked list! Have a glance! Use of Linked List and Priority Queue in CF Round 452, Problem E
can you please explain how the merge section and del function is working? I am a beginner and unable to understand it directly from your code.
Yeah. The del function will be called when I need to remove a node.
For the merge function, when I remove a node, I need to consider whether the node on the left and the one on the right will merge to a longer sequence. For example, after delete [2,2,2,2] in [3,3,3,1,1,2,2,2,2,1,1], the two sequence [1,1] and [1,1] merge together and become a long sequence, that's what the merge function does.
thanks for your reply :)
In 899F, I didnt understand how would change the current l,r to positions in initial string using segment tree?
we can use binary search the prefix sum on the segment tree。
Please elaborate a bit more.
Sure。 We define a sequence a, a_i equals 0 if the ith element of the original sequence has been deleted, otherwise a_i equals 1. If we need to find the current position of the xth element in the original sequence, then it is equivalent to the smallest i that satisfies the sequence sum [i] = x. Because the sum function is incremented, we can use the binary search to find i that satisfies the condition, This i is the current position of the xth element in the original sequence. We can use the segment tree to maintain this sequence a.
Thanks again.
What does it mean for an item to be in the ith position? It means that before it there are i — 1 items before it.
Now assume for each query you have a data structure that tells you for each original index of the string, how many non deleted elements are before it.
Now to find index L, you just need to find index i such that there are l — 1 non deleted items before it.
Can be done by Binary search + fenwick tree or segment tree.
Got it. Thanks.
Hello guys, Happy Coming New Year to everyone! Can somebody help me, why do I keep getting TL7? Thanks in advance. Solution
Hey everyone The editorial for the dividing numbers question is great but have a look at my soluton its easy far.. I uses two pointer approach consider a given n = 11
1 2 3 4 5 6 7 8 9 10 11
now set i = 1 and j = n (i.e 11) now I set the condition in an loop as ::
for (i = 1,j=n; i+2 != j && i<=j; i++,j--)
for (i = 1,j=n; i+2 != j && i<=j; i++,j--) {
if(n%2==0){//100% ok
if(i%2==0&&i+1==j){
if(count2==count1)//extra condition
{
count1+=i,A[k++]=i,count2+=j;
}
else {count2+=i+j;}
}
else if(i%2==0&&i+1!=j){count2+=i+j;}
//coding is love and fun
else if(i%2!=0&&i+1==j){
if(count2==count1)
{A[k++]=i,count1+=i,count2+=j;}
else {count2+=i+j;}//extra condition
}
else if(i%2!=0&&i+1!=j){A[k++]=i,A[k++]=j,count1+=i+j;}
}
else {//for odd case
//for odd lenght both cases for even psotion and odd position
if(i%2!=0){A[k++]=i,A[k++]=j,count1+=i+j;}
else {count2+=i+j;}
}
}
Now in case when n is odd the manipulations are done till the exit condition is not founded which is i+2!=j (founded in every odd case length n) so it will stops at i = 5 and j = 7 then out of the loop I checks that in case when count1 ! =count2 then how to arrange the remaining numbers on the group 1 and group 2.
if(n%2!=0){//this thing is outside the loop
if(count2!=count1){
a=(abs((count2+j+i+1)-(count1+i)));
b=(abs((count2+i+j)-(count1+i+1))),c=(abs((count2+i+i+1)-(count1+j)));
ans=min(min(a,min(b,c)),min(b,min(a,c)));
if(ans==a){
count2=count2+j+i+1,count1+=i,A[k++]=i;}
else if(ans==b){
count2=count2+j+i,count1+=i+1,A[k++]=i+1;}
else if(ans==c){ count2=count2+i+i+1,count1+=j,A[k++]=j;}
}
else {
A[k++]=i,A[k++]=i+1,count1=count1+i+(i+1),count2+=j;
}
}
plzz have a look at the code deeply and plzz try to understand it..and finally
cout<<abs(count1-count2)<<"\n";
std::cout << k <<" ";//k denotes size of group 1
for (i = 0; i < k; i++) {
/* code */
cout<<A[i]<<" ";
}
PLZZ TELL ME WHERE I AM LAGGING IN MY SOULTION or which case i am missing you can use my code below completely to run and check which case i am being missed and even try to submit my code thnkss :_) for ur time this is the link to my code :)
Problem C
Can be solved greedily:
Start with putting N on the left pile and N - 1 on the right one. Then by placing N - 2 on the right and N - 3 on the left we got left - right == 0 and we reduce the problem to the one of the size N - 4.
N
N - 1
N - 2
N - 3
left - right == 0
N - 4
At some point we end up with one of four possible problem sizes: 0, 1, 2, 3.
0, 1, 2, 3
In the first case the difference was 0 and it's the best we can do. In the second case we get 1 which is also the best solution because in than case N = 4k + 1 and the sum = N * (N + 1) / 2 = (4k + 1)(2k) is odd. In the third case we end up with two numbers: 1 and 2, the best diff of 1 and 2 is 1 again and again it is optimal since N = 4k + 2 and sum = (2k)(4k + 3) is odd. In the last case we have numbers 1, 2, and 3, we can place them so diff will be 0 which is optimal.
0
1
N = 4k + 1
sum = N * (N + 1) / 2 = (4k + 1)(2k)
2
N = 4k + 2
sum = (2k)(4k + 3)
3
The code
import sys
n = int(sys.stdin.readline())
g = []
ls, rs = 0, 0
for i in xrange(n, 0, -1):
if ls <= rs:
g.append(i)
ls += i
else:
rs += i
print abs(ls - rs)
print '{} {}'.format(len(g), ' '.join(map(str, g)))
i have solved it through the editorial way get ACCEPTED VERDICT but i cant figure out why my solution is not working plzz have a look at that it will be very beneficial for me both u and have applied the same thing but u done in mathematical way i done it through observation plzz understand my code link is above :_)
i understand completely ur code i have done the same thing but in different way but after seeing ur algorithm i detected my mistake thnkss for ur algorithm :)
I'm glad it helps! Your welcome! :)
This tutorial is not attached to the contest (I can see only Announcement link from there).
Problem F can also be done using sqrt decomposition.
can anyone tell me why there are 11 pairs for n=15 in Div2D problem 1-8 2-7 3-6 4-5 9-10 8-11 7-12 6-13 5-14 4-15
Don't you think the editorials should be more elaborate(eg they can include one example).
Can anyone please explain why in problem D we are adding P/2 to the answer when P <= n+1 ?
Because you can take P/2 pairs to form P as sum. Take as example, P = 9 and N+1 something bigger. To form P = 9 as sum of two numbers you can take, 1-8, 2-7, 3-6, 4-5. As you can see if you continue you will take 5-4 which is similar to 4-5. So moving until the middle of P gives you all the pairs and so P/2 occurs.
thanks alot i got it now :-)
I've been stuck for ages... anyone know what test #33 was on div2E?
My answer is 1 + the correct answer. :(
Another solution for F :
Store the positions of every character in an array of Sets (like the tutorial)...
Then after each query we can find the original position which has the Kth order after the previous updates by storing original positions in a Binary Search Tree, such as Treap which I used and delete them from the tree while applying the query. Therefore you can get the range query according to the original positions then you can remove positions from the corresponding set using lower_bound like the Tutorial..
(Sorry about my bad English)
|
http://codeforces.com/blog/entry/56392
|
CC-MAIN-2018-05
|
refinedweb
| 3,158
| 80.01
|
454 members
103 members
283 members
565 members
295 members
I have just come off the colon cleanse and notice that for the past 2 mornings, I have awoken with the sense of high vibratory energy encased in my body. Last night, I dreamt this: on/off, move on,…Continue
Started this discussion. Last reply by Sara Catherine Blaise Jan 23, 2015.
In one of Sevans' broadcasts (TimeBreaker, I think), he mentions the moment in perfect balance between day and night. I have googled that query every which way and only come up with…Continue
Started this discussion. Last reply by Sara Catherine Blaise Jan 18, 2015.
Wholeness to all and good day!In 2008, I went into toxic shock (my diagnosis, since I don't seek out western medical advice). When I returned from the abyss, my system was squeaky clean. I couldn't…Continue
Started this discussion. Last reply by Sara Catherine Blaise Jan 8, 2015.
Join THE OFFICIAL RESISTANCE
Hey Sara wholeness :) hope u r having a good day. Gosh I see so many comments about diet here I relate to!! Like Jana largely vegan but must admit dark choc eggs and cheese are a think for me too!! Like many others here I am extremely conscious of the importance not only of diet but of good water - distilled then adding megahydrate and cell salts to restructure. It is high on my list of stuff and that little voice is virtually screaming at me now sort it out!! Great to have this site and so many lovely like minded individuals to chat to. I wish us all wholeness and strength on our continuing journey through the innerverse. See you inside I hope. Wouldn't it be amazing if we could all gather together in our dreams for seminars in wholeness. I actually have a vague recollection of sitting cross legged listening to seven talking about wholeness along with others. Does anyone else have any similar dreams to report. This was a while back... Sometime last year
Hello Sara :) Yes I still eat solid food but experience many days I do not feel I need it. I also have days I can soak the sun prana for food. I'm strong but rather thin. My main staple aside from supplements is a 'matrix shake' in the morning that consists of fruits, kale and other greens, sprouts, seeds, veggie protein such as hemp, pea, cranberry, brown rice, etc etc. I also eat plenty of herbs, raw greens, roots such as turmeric and ginger, all sorts of teas, etc.
I must say that I still have some creature comfort foods such as eggs, some cheese (not good), organic dark chocolate, etc. So even though I have gone through activation, etc., I still strive to improve some old habits and am grateful for those like 7 who do this consistently as it motivates me to as well.
What does your diet consist of?
Wholeness to you
last week i dealt with a situation, a person who wanted to be friends and was interested in what i spoke about and we got on and she wanted to change certain things in her life.
she ended up being totally of key.
it was not the first and it is diffently the last!
but i am glad it ended quickly, i have had situations last long time.
the colon cleanse made me deal with things easy,
yes i faced it and it worked out,
thanks
i do have access to ebay,
i just want to measure all the different waters for when i am out and about and more importantly when i am distilling and putting the Megahydrate.in.
what did your water measure at.?
before and after.?
hi hope all is well.
whats was that instrument that sevan use's do measure the water Megahydrate..?
the name and if possible the model please
i recall the email you sent but cant find it
sorry
but i differently would like to buy one ;0)
do it...........
well done
totally over looked sevan. your good at this
but i do not mine paying extra, call it the best innerverse so far to learn from and apply
arthur from herb ppl mailed back and siad the 4 day period between the colon cleanse and the internal cleanse is a must do. ( i remix the words but that what it means)
so how has your day been.?
wow sara greetings, i remembered another part of my dream, had a few last night.
This lady who was kind (like a lawyer) showed me this piece of paper and it had 7 and 2 other numbers on it either i cant remember eeerr!! and she siad it will or i will lose some money.?
so later on after remember that bit.
i remembered it fully after getting a post-note to say i owe customs tax..? i thought
wtf.? from what.? so i headed down to the post office and it was for the megahydrate.
import and customs tax.? duty
never happen before purchasing from realm lot
maybe the lady in my dream who i never seem before was informing me.
whats your view as you been keeping a log for years.?
and i am writing this after trying a tiny bit of megahydrate.in my water
and it made me feel all buzzing ;0)
hey sara how are you.?
i had the most interesting l;lucid dreams again.
how are you finding then Megahydrate.?
Mine has been ordered 3 weeks back and still in transit ;0(
l am interested in the results your getting from it..?
realms lot has had shipping issues so my salts have just ben shipped as well.
nevermind lot me no though
|
https://www.resistance2010.com/profiles/profile/show?id=SaraCatherineBlaise
|
CC-MAIN-2019-18
|
refinedweb
| 958
| 81.43
|
Re: [hreg] Please Comment on this Ethanol Article
Expand Messages
- Eco and Steve
Thanks for the comments.
Eco - what type of biodiesel car do you run? Where do you fill up on biodiesel in Houston? I've read a lot about the homebrew folks, the french fry oil guys, Bio-Willie and "The Veggie Van." All good stories. Biodiesel, unlike ethanol, is non-toxic and releases very little harmful emissions.
Steve - thanks for the Smithsonian article - not much mention of ethanol there, though. About ethanol feedstock - most of the feedstock in the U.S. comes from corn, in Brazil its from sugar cane, in Europe it is from sugar beets or from corn. Cellulosic from grass and weeds is the next big thing, since it has a higher energy content for feedstock, and takes less energy to grow. About the toxicity - it is a choice between buying foreign oil or using U.S. resources, and therefore a security issue (just like global warming). Which choice will consumers accept without the government making us pay $8 a gallon?
If anybody is interested in the Biodiesel study, or is interested in contributing, you can find a prospectus here: Im working on this one 24/7until September, when the PhD kicks in and starts kickin my butt.
Thanks
WIll
On 7/5/06, Steve Stelzer <stelman@...> wrote:
Another item I've missed is the amount of oil used to grow biodiesel feedstocks. Anyone have a handle on that?
Steve
-----Original Message-----
From: hreg@yahoogroups.com [mailto: hreg@yahoogroups.com]On Behalf Ofeco@...
Sent: Wednesday, July 05, 2006 2:08 PM
To: hreg@yahoogroups.com; hreg@yahoogroups.com
Subject: RE: [hreg] Please Comment on this Ethanol Article
Regarding "Ethanol use in gasoline, as a replacement for the toxic gasoline additive MTBE, has been mandated by the government"
MTBE became a problem due to its affinity for water, meaning it is absorbed into water table after leaking from leaking underground gas tanks and has been linked to cancer. Guess what else has been linked to cancer and also has a much stronger affinity for water than MTBE? If you guessed ethanol you are ahead of the future press reports you will be reading when this fact comes into the light of public awareness.
With the exception of abstinence (just bought a used late year model 5-speed manual 23/29 mph small SUV 'rocket' for cheap) for liquid 'bio' fuels, I prefer biodiesel. A single biodiesel refinery can accept multiple feed stocks from soybeans, sun flower seed, rapseed, palm oil, offal, sorgum, used cooking oil, and with small front end modification accept any seed or oily rosin producing weed (grass clippings?) that can be grown. A city switching by mandate to an 80/20 biodiesel blend in city buses, school buses, garbage collection, internal trucking, and marine fuel will both extended engine life on existing city owned (and taxpayer purchased) diesel vehicles due to fuel lubricity while it immediately reduces the smog/soot level in that city.
---- Original Message ----
To: <hreg@yahoogroups.com>
From: "Steve Stelzer" <stelman@...>
Date: Wed, 5 Jul 2006 13:19:37 -0500
Subject: RE: [hreg] Please Comment on this Ethanol Article
Will, one item I've missed with ethanol is how much oil we use to produce
the ethanol. See this interesting article on corn production from the
Smithsonian.
Steve Stelzer
-----Original Message-----
From: hreg@yahoogroups.com [mailto: hreg@yahoogroups.com]On Behalf Of will
thurmond
Sent: Tuesday, July 04, 2006 10:38 PM
To: hreg@yahoogroups.com
Subject: [hreg] (hreg) Please Comment on this Ethanol Article
Hreg members,
I'm working a Biodiesel study, and thinking about launching another on
Ethanol. There have been many mixed messages by the press and analysts for
and against Ethanol in the last few weeks. The following article is a
critique of some of the "upsides" of the market.
I would like to ask HREG members for their commentary on this article, and
Ethanol in general. If the Ethanol market does not progress, I may scrap my
plans for a study.
Your comments and expert opinions on this article, and viewpoints on the
future of Ethanol in the U.S. (not Brazil or Europe) would be much
appreciated.
Many Thanks
Will Thurmond
Emerging Markets Online
===================================
p.s. Please comment on this article - thanks
"Ethanol Investment: Golden Opportunity or Fool's Gold?"
By Russell Hasan, Alt Energy News Altenews.com
Introduction: The Ethanol Boom
We are strong advocates of alternative energy, and we are
happy to see the American ethanol industry growing. But we are also
advocates of informed investments and not "irrational exuberance"
manufactured by hyperactive investment bankers and a media that goes with
the flow. This report is a cautionary note for investors interested in
American companies producing ethanol from corn, pointing out various factors
and data to consider before risking losses in ethanol investments.
The investment banks who led us to the golden pastures of
dotcom before 2000 and the subsequent burst bubble are the same that are now
leading the charge for corn ethanol. Corn ethanol is projected to be a sure
bet for investors, just as dotcom was at one time. We believe that a
near-term boom and bust in corn ethanol is possible if the individual
investors are not careful. In this report we examine eight points of caution
for ethanol investors, after which is a conclusion focusing on the long-term
potential of ethanol.
1. Supply and Demand: Ethanol use in gasoline, as a
replacement for the toxic gasoline additive MTBE, has been mandated by the
government. Several states have also passed ethanol mandates or are
considering mandates. Ethanol producers are blessed with extremely generous
financial incentives, including a $0.51 of tax exemption on federal excise
tax per gallon of ethanol blended with gasoline, a $.10/gal tax credit for
"small" producers making less than 60 million gallons, and a $0.54/gal
import tariff on ethanol. We have the capacity to produce 4.7 billion
gallons annually, with capacity of 2 billion additional gallons under
construction, according to the Renewable Fuels Association. By 2012,
mandatory ethanol consumption will rise to 7.5 billion gallons per year,
required by President Bush's Energy Policy Act of 2005. If U.S. corn ethanol
capacity exceeds 7.5 billion gallons in 2012, prices may decline sharply. If
corn ethanol capacity in the near future exceeds the mandatory ethanol
consumption levels for the near future, then there will be pressure on
ethanol prices much sooner. If the current rate of capacity increase
continues, then this scenario will definitely take place.
2. Government Support: The use of ethanol for powering
vehicles is not new. Henry Ford designed and built ethanol-powered vehicles
almost a hundred years ago. But it did not catch on, and there was little
attention paid to ethanol in the middle of the 20th century, when gasoline
prices were acceptable. Following the OPEC oil crisis of the 1970s,
President Carter offered a $0.40 per gallon tax incentive and engineered the
first ethanol boom. The ethanol industry unfortunately fell apart with the
collapse of crude oil prices in 1986. It can be argued that high oil prices
are driving the recent interest in ethanol, and if oil prices go down
significantly, due to factors involving oil producers and beyond the control
of the ethanol industry, political support for mandates, tax cuts and
tariffs may dissipate. If this government support were removed it would put
a major damper on ethanol profit margins. Much of Carter's rhetoric about
the need for energy independence is similar to recent speeches by President
Bush. If the political concern for alternative energy of the Carter era
could fade away, it is conceivable for current political interest to fade as
well.
3. Competition from Gasoline: Ethanol offers the promise of domestic
energy independence, but it must be able to compete with gasoline to have
long-term profitability. It must also be mentioned that ethanol is at a
disadvantage compared to gasoline in mile-per-gallon fuel efficiency.
According to fueleconomy.gov, a car that gets 16 miles-per-gallon on gas
will get only 12 miles on E85. It was also recently reported that the
wholesale price of ethanol "was around $3 per gallon compared with about
$2.28 for gasoline (before being mixed with ethanol)." Even with GM and Ford
having made announcements about producing more flex-fuel cars capable of
running on E85, and with more gas stations offering E85, it is questionable
whether motorists will find E85 economically justifiable.
4. South American Imports: Brazil, a major player in ethanol,
now accounts for more than 50% of the 20,000 barrels/day of U.S. ethanol
imports. Brazilian production costs have been 40-50% lower than the U.S.,
according to a Congressional Research Service Report for Congress of 2005.
It may be as low as 20% now. Even with the supposedly prohibitive tariff,
which violates WTO rules, Brazilian sugarcane ethanol is competitive with
domestic corn ethanol. Brazilian exports to the U.S. are limited only by its
capacity constraints. Japan plans to invest $1.29 billion in Brazil towards
the production of sugarcane ethanol and biodiesel, which will increase
Brazilian ethanol capacity significantly before the end of the decade.
Caribbean and CAFTA countries, because of the duty free access provided by
the Caribbean Basin Initiative and CAFTA, have been long time exporters of
ethanol to the U.S. CBI and CAFTA allow Caribbean and Central American
countries to purchase ethanol from other countries such as Brazil, reprocess
it, and export to the U.S. without paying the import tariff.
It is questionable whether America can champion globalization and keep the
ethanol import tariff indefinitely. It is also a matter of time before
Brazilian ethanol finds its way to the U.S. via the Caribbean. Brazilian
sugarcane ethanol is more energy efficient than American corn ethanol and
cheaper than gasoline. By 2010, Brazil will export 2.5 billion gallons of
ethanol, which is likely to put enormous pressure on domestic ethanol. Thus,
competition from Brazil and the Caribbean may lower the price of ethanol in
America in five years.
5. Corn Supply: Corn, a perennial surplus commodity, is now in
tight supply because of ethanol. As with all agricultural commodities, corn
prices are affected by weather conditions. Ten years ago, for example, corn
prices had reached $4.70/bushel, approximately twice the price today. That
year had seen a 25% drop in the production of ethanol.
The secular long-term tightness of corn is expected to
continue for some time. China, a traditional exporter of corn, has now
become a net importer. No one knows how severely China will impact corn
prices. Of the 11.1 billion bushels produced in the U.S., the ethanol
industry consumed an estimated 1.6 billion bushels or 14% in 2005. Corn
production is estimated to be 10.5 billion bushels this year with ethanol
industry usage projected to rise above 20%. Export markets, poultry and
livestock industries will be adversely affected. Poultry prices may rise
sharply. The corn ethanol industry will be vulnerable to long-term supply of
its raw material, corn.
The near term outlook of corn supply does not appear to be
assured. USDA reported corn stocks of 3.8 billion bushels as of March 1st.
During the Dec-Feb quarter, consumption of corn did not go down as much as
was expected due to the higher prices. Worldwatch Institute cautions that
"if U.S. corn use and exports were to continue at the same rate in the
months ahead as during the December-February period, U.S. corn stocks would
be totally depleted by July 28th – roughly 2 months before the next harvest
begins." The demand for corn ethanol is inelastic at present and hence the
ethanol industry will be able to cope with likely higher prices. However,
lower margins and complaints about possible higher poultry and livestock
prices may bring the corn ethanol enthusiasts down to Earth before fall this
year. Alan Greenspan recently testified before Congress saying that he has
doubts about corn supplies being sufficient for corn ethanol to replace
gasoline. If he is right, and the above factors affect corn supplies, then
there will not be enough corn to make large-scale ethanol production viable.
Ethanol cannot be shipped by pipeline. It has to be barged and
trucked. As such, bigger producers may not have an inherent advantage over
smaller ones. Many small producers are owned by corn producers' co-ops.
During periods of tight corn supply, small co-ops may do better than larger
companies without captive corn supply. There is also a tax break that
benefits only small ethanol producers, further making smaller producers
preferable to larger ones.
6. Cellulosic Ethanol: Cellulosic ethanol, whose large-scale
commercial production is probably at least five years away, will dominate
ethanol in the future. There is a Canadian company already producing 260,000
gallons per year of cellulosic ethanol. Several companies working to perfect
enzymes for cellulosic ethanol production claim to be close to perfection.
Cellulosic ethanol can be produced from straw, switch-grass, short maturity
super trees, and biowaste. Curiously, cellulosic ethanol has been unfairly
criticized recently as requiring more energy to produce than it yields. Only
one process, acid hydrolysis, requires more energy. Current research is
concentrated on several other processes which are expected to be the least
energy consuming of all kinds of ethanol production. (Corn ethanol has also
been criticized as requiring more energy than it yields, but a majority of
studies dispute this claim.)
The Department of Energy's Energy Efficiency and Renewable Energy (EERE)
office claims that "in terms of key energy and environmental benefits, …
cornstarch ethanol clearly outpaces petroleum-based fuels, and that
tomorrow's cellulose-based ethanol would do even better." They also say that
while "corn ethanol reduces (greenhouse gas) emissions by 18% to 29%;
cellulosic ethanol offers an even greater benefit, with an 85% reduction in
GHG emissions." A Natural Resources Defense Council-commissioned paper in
"Environmental Science and Technology" claims that 1 unit of fossil fuel
energy produces 1.3 units of ethanol energy, while 1 unit of fossil fuel may
create 6 units of cellulosic ethanol energy, meaning that cellulosic ethanol
might be almost six times more efficient. Nathan Glasgow and Lena Hansen of
Rocky Mountain Institute report that "while corn-based ethanol reduces
carbon emissions by about 20 percent below gasoline, cellulosic ethanol is
predicted to be carbon-neutral, or possibly even net-carbon-negative." In
his Congressional testimony Greenspan claimed that cellulosic ethanol held
more promise than corn ethanol. It has also been claimed that the byproducts
of the process of creating cellulosic ethanol can be burned to power the
process, making it more oil-independent than corn ethanol. The previously
mentioned Canadian company is seeking loan guarantees from the Department of
Energy to help build a cellulosic ethanol production facility in the United
States, specifically in Idaho. Still, for the time being the vast majority
of American ethanol producers are making corn-based ethanol, which will not
compete favorably with cellulosic ethanol in the long term. The ability of
U.S. producers to make the switch from corn to cellulose in the future is
hard to predict.
7. The Price of Oil: The world is running out of crude oil and
this is shaping up to be the decade for alternative energy initiatives. The
transfer from MTBE made corn ethanol the first to come out of the gate.
There is enormous short-term upside – driven by the same people who brought
us the dotcom boom and bust.
Ethanol stocks now follow the daily ups and downs of oil
prices. Crude oil, volatile as it is, has been nonetheless trading within a
narrow range. Ethanol stocks following crude oil has been a zero sum game.
It is questionable whether there is gain from this.
It is also possible that at the first sign of crude oil price
softening, "big money" will get out of ethanol investments. This in turn
could reduce political support for ethanol, in which case the farm state
Senators may not be sufficient to maintain the ethanol tariffs and tax
breaks. We have taken the political stand of advocating the continuation of
the ethanol incentives, both for the sake of investors and because domestic
ethanol promotes American energy independence and reduces polluting
emissions. However, if the incentives are removed, which some politicians
want, American ethanol companies will face shrinking profit margins.
8. Celebrity Endorsements: Ethanol has almost reached tabloid
stardom. We are inundated with stories about celebrity endorsements of
ethanol. For example, many of us have read about Richard Branson's dinner
with Ted Turner at which ethanol was discussed. It is worth noting that
cellulosic ethanol was discussed at that dinner. Ethanol stocks got a boost
when Bill Gates invested $84 million in an ethanol company. What is little
discussed is that he purchased preference shares at roughly half the price
of common stock, making this a smart investment regardless of the price of
ethanol. As his preferred stock converts at one share to two shares of
common stock, it can be said that Gates paid roughly one fourth the price
that the average investor paid to invest in that company on the same day of
that transaction. The terms of Gates' investment also gives him considerable
control over the company. The average investor will not receive the same
terms as celebrity investors. Big names involved in ethanol may distract
investors from the hard data of the ethanol industry.
Conclusion: Cautious Optimism
It is our firmly held belief that the next great fortunes are
going to be made in the alternative energy industry. Unfortunately, corn
ethanol is not a simple opportunity of this kind, for the reasons described
above. Although this industry may be profitable for the next five years, it
is highly probable that the American corn ethanol industry, except possibly
for small co-ops, will face strong pressure from corn supply concerns,
sugarcane ethanol imports from Brazil, and new cellulosic ethanol technology
in five to ten years. Competition from gasoline will be brutal if oil prices
fall, and profit margins will suffer fatal blows if government incentives
like the tariff are removed. Companies overwhelmed by these factors will
probably cause the ethanol bubble to burst by the end of the decade.
Hopefully, the major American ethanol producers will find ways to weather
this storm, particularly by exploiting new cellulosic technologies or
securing cheap corn supplies, in order to achieve long-term profitability.
We are pro-ethanol and we believe that investment in the
ethanol industry is necessary to grow capacity to promote the environment
and to secure our energy independence. Clean energy is necessary to prevent
global warming, and energy independence will free us from reliance upon
politically unstable foreign oil. As such, ethanol has a value that cannot
be defined in dollars and cents, and it deserves our support. It is also
clear that certain factors, such as government initiatives and high oil
prices, make ethanol an attractive investment in an industry with strong
growth potential. However, investments in ethanol should be based upon
statistical data from specific companies, including stability of raw
material supply, manufacturing cost, competition, and other market
conditions, as well as each company's long-term plans, rather than investing
in ethanol because of its surge in media popularity. In other words,
investors should seek good long-term investment opportunities in ethanol
rather than short-term investments which may lose money if the factors
mentioned above cause the short-term ethanol bubble to burst, but leave
ethanol producers' long-term prospects optimistic.
There are opportunities for companies able to secure corn supply and
exploit government incentives to remain competitive, particularly if demand
is strong and oil prices remain high. However, the major long-term
opportunities are with cellulosic ethanol. We hope that American ethanol
companies can find a way to be on the cutting edge of ethanol technology in
order to achieve strong long-term stability. Going back to the analogy of
the dotcom bubble, many dotcom companies that were overpriced collapsed when
the bubble burst, but the better companies survived and are still
interesting for investors to this day. The ethanol industry may follow a
similar path, meaning that the investors who buy fool's gold will suffer
losses, but there are still golden opportunities for smart investors.
================================
Are these valid statements, or just more conjecture and "political
opinion" on the alt-energy market? Thanks!
Regards,
Will Thurmond
Managing Director
Emerging Markets Online
Phone 713 429 4905 (Houston, TX)
Mobile 281 825 1968
AltEmail :wt@...
Skype: emergingmarkets
Yahoo! Groups Links
--
Regards,
Will Thurmond
Managing Director
Emerging Markets Online
Phone 713 429 4905 (Houston, TX)
Mobile 281 825 1968
AltEmail :wt@...
Skype: emergingmarkets
- Will,Here is another interesting insight on ethanol. I got this data from a variety of USDA and Ethanol WEB sites. The data may be outdated and I recommend that you do the research to get the most recent numbers before publishing anything.DOE estimated that 500 to 600 million tons of plant matter could be grown and harvested annually in addition to our food and feed needs. Plant matter has an energy content of about 13 million Btu/ton. The potential energy content amounts to 6.5 Quadrillion Btu (42 billion gal oil equivalent), but only a fraction of that can be converted to ethanol. This includes waste streams like corn stover and soy oil as well as dedicated energy crops like willow coppice or miscanthus.Corn yields on good land are about, 120 bushels/acre/yr (4.2 tons per acre); at 100 gallons of ethanol per ton of biomass, each acre can produce 10 barrels of ethanol per year. Improvements may raise the number to 20 barrels per acre per year as genetic changes improve crop yields and enzymes improve the conversion of cellulose and hemi cellulose into convertible sugars so that more of the plant is fermented. The residence time for hydrolysis and fermentation is 1 to 2 days. A proposed policy of 5 vol% ethanol in gasoline would require production rates of 6.5 billion gallons per year. Ethanol production is supposed to reach 5 billion gallons in 2006 (Up from 1.7 billion gallons in 2001).Point #1 - How profit intensive ($/acre) is ethanol farming?I think that in order to make ethanol competitive with other farming options, ethanol must be about $4/gal.Point #2 - How much ethanol can we make in the USA?My calculations show if ALL available farmland not currently used for feed and food were used to grow ethanol, then we could match 20% of the gasoline consumption (match, but not replace - see point #3).Point #3 - How much energy independence does Ethanol give the US?Since ethanol has a negative or slightly positive net energy production, and since the C5s have to be removed from the gasoline pool to meet RVP regulations, and since lower gas mileage has been observed since the addition of ethanol to gasoline, NO gasoline is replaced by using ethanol. Both the large farm corporations and the oil companies profit more by requiring ethanol in the gasoline pool.In my opinion, there are more efficient ways of converting biomass to useable energy. The most efficient being to burn it like coal to generate electricity.Regards,Chris
-..
- Greetings,
Actually there is much better information available on the internet at either or several of the yahoo groups on biodiesel. The problem with Josh is that he does not recommend washing the fuel and more than one engine has been ruined. My Volkswagon Gold gets better gas miliage on biodiesel than it does on dino diesel, making it that much better a solution.
Bright Blessings,
Kim
At 02:40 PM 7/16/2006, you wrote:.
- .
Your message has been successfully submitted and would be delivered to recipients shortly.
|
https://groups.yahoo.com/neo/groups/hreg/conversations/topics/4544?l=1
|
CC-MAIN-2017-22
|
refinedweb
| 4,001
| 62.68
|
Concurrent programming from scratch (ten) - synchronization tool class
6 synchronization tools
6.1 Semaphore
Semaphore, that is, semaphore, provides concurrent access control over the number of resources. Its code is very simple, as shown below:
The function of the parameter method tryAcquire (long timeout, TimeUnit unit) is to try to obtain a license within a specified time. If it cannot be obtained, it returns false.
You can use Semphore to achieve a simple seat Grab:
public class Main { public static void main(String[] args) throws InterruptedException { Semaphore semaphore = new Semaphore(2); for (int i = 0; i < 5; i++) { Thread.sleep(500); new MySemphore(semaphore).start(); } } } public class MySemphore extends Thread{ private Semaphore semaphore; public MySemphore(Semaphore semaphore){ this.semaphore = semaphore; } @Override public void run() { try { semaphore.acquire(); System.out.println(Thread.currentThread().getName()+": working"); Thread.sleep(1000); System.out.println(Thread.currentThread().getName()+": releasing"); semaphore.release(); } catch (InterruptedException e) { e.printStackTrace(); } } }
As shown in the figure below, suppose that there are n threads to obtain 10 resources in Semaphore (n > 10), only 10 of the n threads can obtain them, and other threads will block. No other thread can get the resource until a thread releases the resource.
When the initial number of resources is 1, Semaphore degenerates into an exclusive lock. Because of this, the implementation principle of Semaphone is very similar to that of lock. It is based on AQS and can be divided into fair and unfair. The inheritance system of Semaphore related classes is shown in the following figure:
Since the implementation principles of Semaphore and lock are basically the same. The total number of resources is the initial value of state. In acquire, CAS subtraction is performed on the state variable. After it is reduced to 0, the thread is blocked; Add CAS to the state variable in release.
6.2 CountDownLatch
6.2.1 CountDownLatch usage scenario
Suppose a main thread needs to wait for five Worker threads to finish executing before exiting. You can use CountDownLatch to implement:
Thread:
public class MyThread extends Thread{ private final CountDownLatch countDownLatch; private final Random random = new Random(); public MyThread(String name ,CountDownLatch countDownLatch){ super(name); this.countDownLatch = countDownLatch; } @Override public void run() { try { Thread.sleep(random.nextInt(1000)); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " End of operation"); countDownLatch.countDown(); } }
Main class:
public class Main { public static void main(String[] args) throws InterruptedException { CountDownLatch countDownLatch = new CountDownLatch(5); for (int i = 0; i < 5; i++) { new MyThread("THREAD"+i,countDownLatch).start(); } //Current thread waiting countDownLatch.await(); System.out.println("End of program operation"); } }
The following figure shows the inheritance hierarchy of related classes of CountDownLatch. The principle of CountDownLatch is similar to that of Semaphore. It is also based on AQS, but there is no distinction between fair and unfair.
6.2.2 await() implementation analysis
await() calls the AQS template method, and CountDownLatch.Sync re implements the tryAccuqireShared method.
From the implementation of the tryacquiresered (...) method, as long as state= 0, the thread calling await() method will be put into the AQS blocking queue and enter the blocking state.
6.2.3 countDown() implementation analysis
Tryrereleaseshared (...) in the AQS template method releaseShared() called by countDown() is implemented by CountDownLatch.Sync. As can be seen from the above code, reduce the value of state through CAS. Only when state=0, tryrereleaseshared (...) will return true, and then execute doReleaseShared(...) to wake up all blocked threads in the queue at one time.
Summary: because it is implemented based on AQS blocking queue, multiple threads can be blocked under the condition of state=0. Reduce the state through countDown(), and wake up all threads at once after it is reduced to 0. As shown in the figure below, assuming that the initial total number is m, N threads await(), and M threads countDown(), N threads are awakened after being reduced to 0.
6.3 CyclicBarrier - circulating barrier
6.3.1 usage scenario of cyclicbarrier
Cyclic Barrier literally means a recyclable Barrier. What it needs to do is to block a group of threads when they reach a Barrier (also known as synchronization point). The Barrier will not open until the last thread reaches the Barrier, and all threads intercepted by the Barrier will continue to run.
CyclicBarrier is easy to use:
//Create CyclicBarrier CyclicBarrier cyclicBarrier = new CyclicBarrier(3); CyclicBarrier cyclicBarrier = new CyclicBarrier(3, new Runnable() { @Override public void run() { // When all threads are awakened, Runnable is executed. System.out.println("do something"); } }); //The thread enters the barrier to block cyclicBarrier.await();
Implementation phase operation:
Main:
public class Main { public static void main(String[] args) { CyclicBarrier cyclicBarrier = new CyclicBarrier(3, new Runnable() { @Override public void run() { System.out.println("finish"); } }); for (int i = 0; i < 3; i++) { new MyThread(cyclicBarrier).start(); } } }
MyThread:
public class MyThread extends Thread{ private final CyclicBarrier cyclicBarrier; private final Random random = new Random(); public MyThread(CyclicBarrier cyclicBarrier){ this.cyclicBarrier = cyclicBarrier; } @Override public void run() { try { Thread.sleep(random.nextInt(2000)); System.out.println(Thread.currentThread().getName()+" A begin"); cyclicBarrier.await(); Thread.sleep(2000); System.out.println(Thread.currentThread().getName()+" B begin"); cyclicBarrier.await(); Thread.sleep(2000); System.out.println(Thread.currentThread().getName()+" C begin"); } catch (InterruptedException | BrokenBarrierException e) { e.printStackTrace(); } } }
In the whole process, there are 2 synchronization points. Only after all threads have reached the synchronization point, the last incoming thread will wake up all blocked threads.
6.3.2 implementation principle of cyclicbarrier
CyclicBarrier is implemented based on ReentrantLock+Condition
//This internal class is used to indicate the status of the current loop barrier. When broken is true, it indicates that an exception has occurred to the barrier private static class Generation { boolean broken = false; } //Display lock inside CyclicBarrier private final ReentrantLock lock = new ReentrantLock(); //Through the Condition variable obtained from the above explicit lock, the barrier can block and wake up multiple threads, which is fully benefited from this Condition private final Condition trip = lock.newCondition(); //Critical value: when the number of threads blocked by the barrier is equal to parties, that is, count=0, the barrier will wake up all currently blocked threads through trip private final int parties; //Conditional thread: when the barrier is broken, execute the thread before the barrier wakes up all blocked threads through trip. This thread can act as a main thread, and those blocked threads can act as child threads, that is, it can call the main thread when all child threads reach the barrier private final Runnable barrierCommand; //The internal class Generation variable represents the state of the current CyclicBarrier private Generation generation = new Generation(); //Counter, which is used to calculate how many threads still have not reached the barrier. The initial value should be equal to the critical value parties private int count;
Construction method:
Implementation process of await() method:
//timed: indicates whether the waiting time is set //nanos wait time (nanoseconds) private int dowait(boolean timed, long nanos) throws InterruptedException, BrokenBarrierException, TimeoutException { final ReentrantLock lock = this.lock; //Use the display lock defined by CyclicBarrier to avoid concurrency problems lock.lock(); try { //Status of current circulation barrier final Generation g = generation; //If true, it indicates that an exception occurred before the barrier, and the exception BrokenBarrierException is thrown if (g.broken) throw new BrokenBarrierException(); //Is the current thread interrupted if (Thread.interrupted()) { breakBarrier();//This method resets the count value count to parties, wakes up all blocked threads and changes the state Generation throw new InterruptedException(); } //Barrier counter minus one int index = --count; //If the index is equal to 0, the number of threads reaching the barrier is equal to the number of parties set at the beginning if (index == 0) { // tripped boolean ranAction = false; try { final Runnable command = barrierCommand; //If the conditional thread is not empty, the conditional thread is executed if (command != null) command.run(); ranAction = true; //Wake up all blocked threads and reset the counter count to generate a new state generation nextGeneration(); return 0; } finally { if (!ranAction)//If ranAction is true, it means that the above code has not finished successfully, and an exception has occurred to the barrier. Call breakBarrier to reset the counter, and set generation.broken=true to indicate the current state breakBarrier(); } } // When the counter is zero, the Condition's wake-up method is called, or the broken is true, or the thread is interrupted, or when waiting for timeout, an exception pops up for (;;) { try { //Block the current thread. If timed is false, the waiting time is not set if (!timed) //The thread is blocked indefinitely, and execution will continue only after the wake-up method is called trip.await(); else if (nanos > 0L) //Wait for nanos milliseconds nanos = trip.awaitNanos(nanos); } catch (InterruptedException ie) { //If an exception occurs when the await method is called, and the CyclicBarrier has not called the nextGeneration() method to reset the counter and generation if (g == generation && ! g.broken) { breakBarrier();//This method will wake up all blocked threads and reset the counter, and setting generation.broken = true indicates that an exception has occurred in the blocker. throw ie; } else { //Interrupt current thread Thread.currentThread().interrupt(); } } //g.broken is true, indicating that an exception has occurred in the obstacle and an exception is thrown if (g.broken) throw new BrokenBarrierException(); //The wake-up operation with index=0 was successfully completed, so the generation was updated through the nextGeneration() method. Since generation is a shared variable in the thread, the current thread is g= generation if (g != generation) return index; //If timed is true, it means that the thread blocking time is set, and then the time nanos is less than or equal to 0, if (timed && nanos <= 0L) { breakBarrier();//At this time, reset the counter and set generation.broken=true to indicate that the obstacle is abnormal throw new TimeoutException(); } } } finally { lock.unlock(); } } //Wake up all threads, reset counter count and regenerate generation private void nextGeneration() { trip.signalAll(); count = parties; generation = new Generation(); } //Set generation.broken=true to indicate the exception of the barrier, reset the counter count, and wake up all blocked threads private void breakBarrier() { generation.broken = true; count = parties; trip.signalAll(); }
There are several explanations for the above method:
CyclicBarrier can be reused. Taking the application scenario as an example, there are 10 threads. These 10 threads wait for each other, wake up together when they arrive, and execute the next logic respectively; Then, the 10 threads continue to wait for each other and wake up together. Each round is called a Generation, which is a synchronization point.
CyclicBarrier will respond to the interrupt. If 10 threads fail to arrive, if any thread receives an interrupt signal, all blocked threads will be awakened, which is the breakBarrier() method above. Then count is reset to the initial value (parties) and restarted.
breakBarrier() will only be executed once by the 10th thread (before waking up the other 9 threads), rather than once each of the 10 threads.
6.4 Exchanger
6.4.1 usage scenario
Exchange is used to exchange data between threads. Its code is very simple. It is an exchange(...) method. Examples are as follows:
public class Main { private static final Random random = new Random(); public static void main(String[] args) { // Create an exchange object shared by multiple threads // Pass the exchange object to three thread objects. Each thread calls exchange in its own run method and takes its data as a parameter. // The return value is the parameter passed in by another thread calling exchange Exchanger<String> exchanger = new Exchanger<>(); new Thread("Thread 1") { @Override public void run() { while (true) { try { // If no other thread calls exchange, the thread blocks until another thread calls exchange. String otherData = exchanger.exchange("Exchange data 1"); System.out.println(Thread.currentThread().getName() + "obtain<==" + otherData); Thread.sleep(random.nextInt(2000)); } catch (InterruptedException e) { e.printStackTrace(); } } } }.start(); new Thread("Thread 2") { @Override public void run() { while (true) { try { String otherData = exchanger.exchange("Exchange data 2"); System.out.println(Thread.currentThread().getName() + "obtain<==" + otherData); Thread.sleep(random.nextInt(2000)); } catch (InterruptedException e) { e.printStackTrace(); } } } }.start(); new Thread("Thread 3") { @Override public void run() { while (true) { try { String otherData = exchanger.exchange("Exchange data 3"); System.out.println(Thread.currentThread().getName() + "obtain<==" + otherData); Thread.sleep(random.nextInt(2000)); } catch (InterruptedException e) { e.printStackTrace(); } } } }.start(); } }
In the above example, three threads call exchange(...) concurrently and will interact with data in pairs, such as 1 / 2, 1 / 3 and 2 / 3.
6.4.2 realization principle
Like Lock, the core mechanism of exchange is CAS+park/unpark.
park/unpark recommended reading:
First, in exchange, there are two internal classes: Participant and Node. The code is as follows:
When each thread calls the exchange(...) method to exchange data, it will first create a Node object.
This Node object is the wrapper of the thread, which contains three important fields: the first is the data that the thread wants to interact with, the second is the data exchanged by the other thread, and the last is the thread itself.
A Node can only support data exchange between two threads. To realize parallel data exchange between multiple threads, multiple nodes are required. Therefore, the Node array is defined in exchange:
private volatile Node[] arena;
6.4.3 exchange (V x) implementation analysis
slotExchange is used for one-to-one data exchange, and arena exchange is used in other cases.
In the above method, if arena is not null, it means that arena mode data exchange is enabled. If arena is not null and the thread is interrupted, an exception is thrown.
If arena is not null, but the return value of arena exchange is null, an exception is thrown. The null value exchanged by the other thread is encapsulated as NULL_ITEM object, not null.
If the return value of slotExchange is null and the thread is interrupted, an exception is thrown.
If the return value of slotExchange is null and the return value of areaExchange is null, an exception is thrown.
Implementation of slotExchange:
Implementation of arena exchange:
6.5 Phaser phase shifter
6.5.1 replace CyclicBarrier and CountDownLatch with Phaser
Starting from JDK7, a synchronization tool class Phaser is added, which is more powerful than CyclicBarrier and CountDownLatch.
CyclicBarrier solves the problem that CountDownLatch cannot be reused, but it still has the following shortcomings:
1) The counter value cannot be dynamically adjusted. If the number of threads is not enough to break the barrier, you can only reset or add more threads, which is obviously unrealistic in practical application
2) Each await consumes only one counter value, which is not flexible enough
Phaser is used to solve these problems. Phaser divides the tasks executed by multiple threads into multiple stages. Each stage can have any participant. Threads can register and participate in a stage at any time.
Instead of CountDownLatch:
public class PhaserInsteadOfCountDownLatch { public static void main(String[] args) { Phaser phaser = new Phaser(5); for (int i = 0; i < 5; i++) { new Thread("thread-"+(i+1)){ private final Random random = new Random(); @Override public void run() { System.out.println(getName()+" start"); try { Thread.sleep(random.nextInt(1000)); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(getName()+" end"); phaser.arrive(); } }.start(); } System.out.println("threads start finish"); phaser.awaitAdvance(phaser.getPhase()); System.out.println("threads end finish"); } }
Instead of CyclicBarrier:
Main:
public class PhaserInsteadOfCyclicBarrier { public static void main(String[] args) { Phaser phaser = new Phaser(5); for (int i = 0; i < 5; i++) { new MyThread(phaser).start(); } phaser.awaitAdvance(0); } }
MyThread:
public class MyThread extends Thread{ private final Phaser phaser; private final Random random = new Random(); public MyThread(Phaser phaser){ this.phaser = phaser; } @Override public void run() { try { System.out.println("start a"); Thread.sleep(500); System.out.println("end a"); phaser.arriveAndAwaitAdvance(); System.out.println("start b"); Thread.sleep(500); System.out.println("end b"); phaser.arriveAndAwaitAdvance(); System.out.println("start c"); Thread.sleep(500); System.out.println("end c"); } catch (InterruptedException e) { e.printStackTrace(); } } }
arriveAndAwaitAdance() is the combination of arrive() and awaitAdvance(int), which means "I have reached this synchronization point myself, and I have to wait for everyone to reach this synchronization point, and then move forward together".
6.5.2 new features of phaser
Dynamically adjust the number of threads
The number of threads to be synchronized by CyclicBarrier is specified in the construction method and cannot be changed later. Phaser can dynamically adjust the number of threads to be synchronized during operation. Phaser provides the following methods to increase and decrease the number of threads to be synchronized.
Hierarchical Phaser
Multiple phasers can form a tree structure as shown in the following figure, which can be realized by passing in the parent Phaser in the construction method.
public Phaser(Phaser parent, int parties){ //.... }
The tree structure is stored through the parent node:
private final Phaser parent;
It can be found that in the internal structure of Phaser, each Phaser records its own parent node, but does not record its own child node list. Therefore, each Phaser knows who its parent node is, but the parent node does not know how many child nodes it has. The operation on the parent node is realized through the child nodes.
How to use the tree Phaser? Consider the following code to form the tree Phaser in the figure below.
Phaser root = new Phaser(2); Phaser c1 = new Phaser(root,3); Phaser c2 = new Phaser(root,2); Phaser c3 = new Phaser(c1,0);
Originally, root has two participants, and then two sub phasers (c1, c2) are added to it. Each sub Phaser will be counted as one participant, and the participants of root will become 2 + 2 = 4. c1 originally had 3 participants. A child Phaser c3 was added to it, and the number of participants became 3 + 1 = 4. The participant of c3 is initially 0, and can be added later by calling the register() method.
Each node on the tree Phaser can be regarded as an independent Phaser, and its operation mechanism is the same as that of a separate Phaser.
The parent Phaser does not need to be aware of the existence of the child Phaser. When the number of participants registered in the child Phaser is greater than 0, it will register itself with the parent node; When the number of participants registered in the child Phaser equals 0, the parent node will be deregistered automatically. The parent Phaser treats the child Phaser as a normal thread.
6.5.3 state variable parsing
After a general understanding of the usage and new features of phaser, let's carefully analyze its implementation principle. Phaser is not implemented based on AQS, but it has the core features of AQS: state variable, CAS operation and blocking queue. Let's start with the state variable.
private volatile long state;
The 64 bit state variable is divided into four parts:
Phaser provides a series of member methods to get several numbers in the figure above from state. Let's take a look at how the state variable is assigned in the construction method:
Among them, the following has been defined:
private static final int EMPTY = 1; private static final int PHASE_SHIFT = 32; private static final int PARTIES_SHIFT = 16;
When parties=0, state is given an EMPTY constant, which is 1;
When parties= 0, shift the phase value left by 32 bits; Move the parties to the left by 16 bits; Then, parties are also used as the lowest 16 bits, and the three values are assigned to state.
6.5.4 Treiber Stack
Based on the above state variable, perform CAS operation, block and wake up accordingly. As shown in the following figure, the mainline on the right will call awaitAdvance() to block; The arrive() on the left will perform CAS decrement operation on the state. When the number of unreachable threads decreases to 0, wake up the blocked main thread on the right.
Here, blocking uses a data structure called Treiber Stack instead of AQS's two-way linked list. Treiber Stack is a lock free stack. It is a one-way linked list. Both out of the stack and in the stack are at the head of the linked list. Therefore, only a head pointer is required instead of a tail pointer. The following implementation:
In order to reduce concurrency conflicts, two linked lists, that is, two Treiber stacks, are defined here. When the phase is an odd number of rounds, the blocking thread is placed in the oddQ; When the phase is an even number of rounds, the blocking thread is placed in evenQ. The code is as follows:
6.5.5 arrive() method analysis
Let's see how the arrive() method operates on the state variable and wakes up the thread.
Where, variables are defined:
private static final int ONE_ARRIVAL = 1; private static final int ONE_PARTY = 1 << PARTIES_SHIFT; private static final int ONE_DEREGISTER = ONE_ARRIVAL\ONE_PARTY; private static final int PARTIES_SHIFT = 16;
Both arrive() and arriveAndDeregister() internally call the doArrive(boolean) method.
The difference is that the former only reduces the "number of threads not reached" by 1; The latter reduces "number of threads not reached" and "number of bus processes in the next round" by 1. Let's take a look at the implementation of the doArrive(boolean) method.
The above methods are described as follows:
- Two constants are defined as follows. When deregister=false, only the lowest 16 bits need to be subtracted by 1, adj=ONE_ARRIVAL; When deregister=true, the two 16 bits in the lower 32 bits need to be subtracted by 1, adj=ONE_ARRIVAL|ONE_PARTY.
- Reduce the number of unreachable threads by 1. After subtraction, if it has not reached 0, do nothing and return directly. If it reaches 0, two things will be done: first, reset the state, reset the number of unreachable threads in the state to the total number of registered threads, and add 1 to phase; Second, wake up the thread in the queue.
Let's take a look at the wake-up method:
Traverse the whole stack. As long as the phase of the node in the stack is not equal to the phase of the current phase, it indicates that the node is not from the current round, but from the previous round and should be released and awakened.
6.5.6 awaitAdvance() method analysis
The following while loop has four branches:
Initially, node==null, enter the first branch to spin. After the spin times are met, a new QNode node will be created;
Then execute the 3rd and 4th branches to stack and block the node respectively.
The ForkJoinPool.managedBlock(ManagedBlocker blocker) method is called to block the thread corresponding to node. Managerdblock is an interface in ForkJoinPool, which is defined as follows:
QNode implements the interface. The implementation principle is Park (), as shown below. The reason why park()/unpark() is not directly used to realize blocking and wake-up, but the ManagedBlocker layer is encapsulated, mainly for convenience. On the one hand, Park () may be awakened by interrupt, on the other hand, Park () with timeout encapsulates both.
I understand that arrive() and awaitAdvance(), arriveAndAwaitAdvance() are a combined version of both.
|
https://programmer.help/blogs/concurrent-programming-from-scratch-synchronization-tool-class.html
|
CC-MAIN-2022-21
|
refinedweb
| 3,839
| 54.32
|
Auto import
When you reference a PHP class that is defined outside the current file, PhpStorm locates the class definition and lets you do one of the following:
Automatically complete the fully qualified class name, including the namespace the class is defined in.
Automatically complete the short class name and import the namespace the class is defined in.
Import the namespace manually using a quick-fix.
The
use statement is added to the imports section, but the caret does not move from the current position, and your current editing session does not suspend. This feature is known as the Import Assistant.
In JavaScript and TypeScript files, PhpStorm automatically adds import statements for modules, classes, components, and any other symbols that can be exported, as well as for XML namespaces. Learn more from Auto import in JavaScript, Auto import in TypeScript and Importing an XML namespace.
Automatically add import statements
You can configure the IDE to automatically add import statements if there are no options to choose from.
In the Settings/Preferences dialog (Ctrl+Alt+S), click .
In the PHP section, configure automatic namespace import.
To have PhpStorm automatically add
usestatements for classes and methods in pasted blocks of code, choose the desired behavior from the Insert imports on paste list:
All: import statements will be added automatically for all missing classes and methods found in pasted blocks of code.
Ask: PhpStorm will prompt you to select which classes and methods you want to import.
If the pasted class is already referenced in the target code via an alias, PhpStorm will prompt you to reuse this alias instead of creating a new import statement.
None: no import statements will be added, you won't be asked about unresolved references.
Note that adding imports on paste is only possible if the copied element is properly resolved in code (that is, not highlighted by the Undefined class or Undefined method inspections), and project indexing is finished.
To have automatic namespace import applied when you are typing in a file that does not belong to any specific namespace, select the Enable auto-import in file scope checkbox.
To have PhpStorm automatically import PHP namespaces, add use statements, and complete short class names on the fly when you are typing in a class or file that belongs to a certain namespace, select the Enable auto-import in namespace scope checkbox. This checkbox is selected by default.
If necessary, configure auto-import from the global namespace separately for classes, functions, and constants.
Prefer FQN: If selected, PhpStorm automatically inserts the fully-qualified name of a symbol from the global namespace, prepended with a backslash, for example:namespace A; $myException = new \Exception(); $a = \strlen("Test"); echo \PHP_EOL;
Prefer Import: If selected, PhpStorm automatically adds
usestatements for symbols
usestatement. The fallback global functions or constants are preferred in this case, for example:namespace A; use Exception; $myException = new Exception(); $a = strlen("Test"); echo PHP_EOL;
Import a PHP namespace on-the-fly
Enable on-the-fly namespace import.
Open the desired file for editing and start typing the short name of a class.
From the code completion suggestion list, select the desired class name. PhpStorm will complete the short class name and insert the
usestatement with the namespace where the selected class is defined.
Import a class by using a quick fix
Open a file for editing and reference a PHP class. If the referenced class is not bound, PhpStorm will highlight it:
Press Alt+Enter and accept the suggestion to import the namespace where the declaration of the class is detected.
PhpStorm inserts a namespace declaration statement (
usestatement).
Shorten fully qualified class names with Code Cleanup
PhpStorm provides the following inspections and quick-fixes for shortening fully qualified class names:
Fully qualified name usage inspection highlights the fully qualified class names that can be removed by adding a
usestatement.
Unnecessary fully qualified name inspection highlights the fully qualified class names that can be removed without adding a
usestatement.
You can apply the corresponding quick-fixes to a given scope automatically by using Code Cleanup.
Clean up code on a given scope
From the main menu, select Code | Code Cleanup.
In the Specify Code Cleanup Scope dialog that opens, select ths scope to which you want the inspection profile to be applied.
Select the inspection profile from the list, or click
to configure a new profile in the Code Cleanup Inspections dialog that opens. You can also click
to check which fixes will be applied and make sure that the Unnecessary fully qualified name and Fully qualified name usage inspections are enabled.
Click OK to launch code cleanup.
Clean up code in the current file
In the editor, position the caret at a fully qualified class name highlighted by the Unnecessary fully qualified name or Fully qualified name usage inspection.
Click
or press Alt+Enter, and select Cleanup code from the popup menu.
.
When optimizing imports, PhpStorm can automatically sort the
use statements either alphabetically or by their length. To choose the preferred option, in the Settings/Preferences dialog (Ctrl+Alt+S), go to and switch to the Code Conversion tab. Then select the Sort use statements checkbox and choose how the
use statements should be sorted.
Optimize imports in a single file
Place the caret at the import statement and press Alt+Enter (or use the intention action
icon).
Select Remove use statement.
Automatically optimize imports in modified files
If your project is under version control, you can instruct PhpStorm to optimize imports in modified files before committing them to VCS.
From the main menu, select(or press Ctrl+K).
In the Before commit area of the Commit Changes dialog, select the Optimize imports checkbox.
|
https://www.jetbrains.com/help/phpstorm/2019.1/creating-and-optimizing-imports.html
|
CC-MAIN-2021-49
|
refinedweb
| 947
| 50.77
|
Graphics::MNG - Perl extension for the MNG library from Gerard Juyn (gerard@libmng.com)
# OO-interface use Graphics::MNG; my $it=['user data']; my $obj = new Graphics::MNG ( ); # w/o user data my $obj = new Graphics::MNG ( undef ); # w/o user data my $obj = new Graphics::MNG ( $it ); # w/ user data my $obj = Graphics::MNG::new( ); # w/o name w/o data my $obj = Graphics::MNG::new('Graphics::MNG' ); # w/ name w/o data my $obj = Graphics::MNG::new('Graphics::MNG',$it); # w/ name w/ data $obj->set_userdata(['user data']); my $data = $obj->get_userdata(); print @$data[0],"\n"; undef $obj; # functional interface use Graphics::MNG qw( :fns ); my $handle = initialize( ['more user data'] ); die "Can't get an MNG handle" if ( MNG_NULL == $handle ); my $rv = reset( $handle ); die "Can't reset the MNG handle" unless ( MNG_NOERROR == $rv ); my $data = get_userdata( $handle ); print @$data[0],"\n"; $rv = cleanup( $handle ); die "handle not NULL" unless ( MNG_NULL == $handle );
This is alpha stage software. Use at your own risk. Please visit to learn all about the new MNG format. MNG (which stands for Multiple Network Graphics) is an extension of the PNG format, which is already gaining popularity over the GIF format. MNG adds the aspect of animation that PNG lacks. The Gd module (by Lincoln Stein) supports PNG formats, but MNG is more complicated. It would be cumbersome to add support to the Gd interface for MNG. Gerard Juyn as been kind enough to bring us a C-library that supports MNG, so now I thought I'd do my part in bringing you a Perl interface to that library. The Graphics::MNG module is an attempt to provide an "accurate" interface to the MNG graphics library. This means that the Perl methods supported in this module should look very much like the functions in the MNG library interface. This module supports both a functional and an OO interface to the MNG library.
Everthing under the :constants tag is exported by default. Ideally, you'll use one of the incantations of new() to get yourself an object reference, and you'll call methods on that.
:all -- everything :callback_types -- enum list of callback types (MNG_TYPE_*) :canvas -- constants for canvas ops (MNG_CANVAS_*) :canvas_fns -- functions for canvas ops (MNG_CANVAS_*) :chunk_fns -- functions for chunk ops (getchunk_*,putchunk_*) :chunk_names -- constants for chunk ops (MNG_UINT_*) :chunk_properties -- constants for chunk ops :compile_options -- constants describing how this extension was built :constants -- constants which are commonly used (MNG_FALSE, MNG_TRUE, MNG_NOERROR, MNG_NULL, MNG_INVALIDHANDLE) :errors -- constants returned as error values :fns -- functions for the MNG functional interface :misc -- constants misc. (MNG_SUSPEND*) :util_fns -- pure PERL default implementations of callback functions (see section "UTILITY FUNCTIONS" below) :version -- functions to return various version numbers (MNG,PNG,draft,etc.) :IJG -- constants IJG parameters for compression :ZLIB -- constants zlib compression params for deflateinit2
The OO-I/F is the same as the functional interface, except that you new() your handle into existence, and you undef() it out. Also, you don't pass it as the first parameter to any of the methods -- that's done for you when you use the -> calling syntax to call a method. There are a *lot* of interface functions in the MNG library. I'd love to list them all here, but you're really better off opening up the libmng.h file, related documentation, or the Graphics/MNG.pm file and looking at the list of exported methods. I'll try to make a list here of the methods that deviate in interface characteristics from those found in the MNG library itself. I doubt that I've implemented the Perl interface correctly for all of them. You will find bugs. Sorry about that. In some cases it is convenient to change the Perl interface to make it more convenient to use from within Perl. A good example of this is any mng_get*() methods that returned values via pointers in the parameter list. Most or all of these will return a list of values (with the status as the first element), and will only accept the input parameters. On error, only the status code is returned. The method getlasterror() behaves in a similiar manner, except that it will return the list of parameters only when there is an error. Otherwise, it just returns the status (in this case MNG_NOERROR). The method initialize() currently takes only one argument -- a scalar (typically a reference) to user data. If the MNG library is not compiled with MNG_INTERNAL_MEMMNGMT, then this Perl interface will provide default memory allocation support. You can use other interface methods to enable/disable trace support. I've also added some new methods to the interface: my ($texterror) = error_as_string([$hHandle,] MNG_NOERROR()); my ($name, $type) = getchunk_name([$hHandle,] $iChunktype); my ($rv, $href) = getchunk_info($hHandle, $hChunk, $iChunktype) my ($rv) = putchunk_info($hHandle, [$iChunktype,] \%chunkHash) - error_as_string(): This method takes an mng_retcode and translates it into the corresponding string. For example, 0 => 'MNG_NOERROR'. This class method may also be called as a function. - getchunk_name(): This method takes the chunktype and returns the ASCII name of the chunk, and also a string containing the hexadecimal representation of the chunktype. This class method may also be called as a function. - getchunk_info(): This method uses the $iChunktype parameter to look up the correct getchunk_*() method to call on the $hHandle object to get the chunk information related to $hChunk. It returns a list of status and a hash reference containing all of the chunk information. If called in a scalar context, an array reference containing this list is returned. The key names of the hash correspond to the libmng parameter names for the appropriate mng_getchunk_*() function. There are two additional fields added to the returned hash: 'iChunktype' : the type as passed in by $iChunktype 'pChunkname' : the chunk name (from getchunk_name($iChunktype)) This hash reference can be passed directly to putchunk_info(). - putchunk_info(): This method uses the $iChunktype parameter to look up the correct putchunk_*() method to call on the $hHandle object. The key names of the hash must correspond to the libmng parameter names for the mng_putchunk_*() function that will be called. If the $iChunktype parameter is excluded, then the hash is examined for a field named 'iChunktype'. If any fields are excluded, they default to '0', which (before presentation to the libmng interface) will translate to a string for array and pointer types, and will translate to zero for integer types. This seems safe because most arrays and pointer types are accompanied by a length field, which will also default to zero if it is excluded. This method is mostly useful for directly copying chunks from one file to another in conjunction with the getchunk_info() method.
This section documents the list of added interfaces provided by the MNG module which do not exist in libmng. They have been added for your convenience. They can be imported under the ':util_fns' tag. - FileOpenStream( $hHandle ) This is a default callback implementation for use with setcb_openstream. - FileCloseStream( $hHandle ) This is a default callback implementation for use with setcb_closestream. - FileReadData( $hHandle, \$pBuf, $iSize, \$pRead ) This is a default callback implementation for use with setcb_readdata. - FileReadHeader( $hHandle, $iWidth, $iHeight ) This is a default callback implementation for use with setcb_processheader. - FileWriteData( $hHandle, $pBuf, $iBuflen, \$pWritten ) This is a default callback implementation for use with setcb_writedata. - FileIterateChunks( $hHandle, $hChunk, $iChunktype, $iChunkseq ) This is a default callback implementation for use with iterate_chunks. - FileReadChunks( $filename [, \&iteration_function] ) NOTE: This is not an object method. This is a convenience function which will return a list of two elements (status, MNG object). The userdata portion of the returned MNG object will contain the following keys: 'filename' => <filename>, 'width' => <width of image>, 'height' => <height of image>, 'chunks' => [ <list of image chunks> ], You can specify your own chunk iteration function, or you can leave it out and the default (FileIterateChunks()) will be used. - FileWriteChunks( $filename, \@chunks ) NOTE: This is not an object method. This is a convenience function which will accept a list of image chunks (as returned by FileReadChunks) and will write them to the specified filename. The status of the entire operation is returned.
The MNG library is designed around the concept of callbacks. I've tried to make the Perl interface closely model the library interface. That means that you'll be working with callback functions. Depending on your point of view, that's a limitation. If you want to write a file with the MNG library, you'll have to call create() before writing chunks. That's just how libmng works. If you forget, you'll be disappointed with the results. This Perl module is in the alpha stage of development. That means that you'll be lucky to compile it, let alone use it effectively without tripping over bugs. The MNG library may have limitations of its own, please visit the MNG homepage to learn about them.
You'll need a compiled MNG library, complete with header files, in order to build this Perl module. MNG requires some or all of the following support libraries: - lcms (little CMS) - libjpeg - libz Specifically, I compile the MNG library (static library, NOT a DLL) using MSVC++ with the following compilation flags: MNG_FULL_CMS, MNG_INTERNAL_MEMMNGMT, NON_WINDOWS, MNG_BUILD_SO, MNG_SUPPORT_TRACE
Since this is alpha software... - compile the MNG as a static library (Win32) or as a shared library - edit Makefile.PL as appropriate for your header file and lib paths Then you can install this module by typing the following: perl Makefile.PL make make test make install
There is a suite of tests packaged with this module. Test #0 is really just a setup script that has been pieced together from other sources. It uses pure PERL to generate a test case MNG file for later tests. If you have GD, it will also generate the necessary PNG images. Since all of the output of this script is already packaged in the distribution, you probably won't need to run it. It's just there for your reference and my convenience. The last couple of tests actually read and write MNG files. There are some good examples in there, it's worth checking out. If you're on cygwin, 'make test' may not work correctly. If it complains about not being able to open up t/*.t, just type this at the command prompt in the Graphics/MNG directory: perl -Mblib test.pl
I have successfully read and written MNG files with this interface. If you can't write (simple) MNG files, you may be doing something wrong. See the section LIMITATIONS for related topics. You may have noticed that the "mng_" prefix has been removed from all of the functions. This was done to make the OO-I/F look prettier. However, if you import the functional interface, you'll get read() and write() in your namespace, thus clashing with Perl's built-in functions. I may change the name for these in the future (i.e. an interface deviation). In the meantime, I suggest that you use sysread() and syswrite() in your callbacks. Even better, use the OO-I/F and don't import qw(:fns). I'm developing exclusively on Win32 for now, although everything *should* work well for any other platform that the MNG library supports. I'm pretty sure that I have *not* gotten all of the appropriate #ifdef protection around parts of the XS code that may be affected by MNG compilation flags.
This is alpha software. Expect the worst. Hope for the best. For any functions that return or accept an array of integers or structs, I plan (eventually) to provide a Perl interface that accepts an array of integers or structs (the structs themselves probably being represented as arrays or hashes). Right now, you'll need to pack() and unpack() the string. I may add a convenience method to insert PNG or JNG files into the MNG stream. This would make use of getchunk_*() and putchunk_*() methods. I need to add a questionaire to the Makefile.PL script to ask the user how the libmng was built. I may also automate a search for the appropriate header files, and prompt the user if they can't be found. This interaction may look much like the setup/install scripts for GD or PPM.
David P. Mott (dpmott@sep.com)
I'd love to support this interface full time, but my work schedule won't allow that. If you see a problem, try to fix it. If you can fix it, write a test case for it. If you get all of that done, send me the fix and the test case, and I'll include it in the next release. If you can't fix it, or don't know how to test it, go ahead and send me some email. I'll see what I can do. If you want to maintain this module, by all means mail me and I'll get you set up. Releases will happen approximately whenever I feel like I have something worthwhile to release, or whenever I get a whole bunch of email from people like you demanding a release.
The Graphics::MNG module is Copyright (c) 2001 David P. Mott, USA (dpmott@sep.com) All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself (i.e. GPL or Artistic). See the the Perl README file for more details. (maybe here:) For more info on GNU software and the GPL see For more info on the Artistic license see THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
L<perl>. The PNG homepage: The MNG homepage: The PNG specification: The MNG specification: The JPEG homepage: The Lcms homepage: The Zlib homepage: The GD module: [download it from your favorite CPAN server] The GD homepage: The Freetype homepage:
|
http://search.cpan.org/~mott/Graphics-MNG-0.04/MNG.pm
|
CC-MAIN-2015-11
|
refinedweb
| 2,312
| 62.78
|
»
Mobile
»
Java Micro Edition
Author
Newbie: End app after alert
Stephen Pride
Ranch Hand
Joined: Sep 14, 2000
Posts: 121
posted
Oct 31, 2003 07:55:00
0
I wrote a small application to understand the J2ME WTK, and I'm having a problem with displaying an Alert and then ending the app gracefully after it is found the screen is too small to run the app. For now, I have the following code:
public class MyApp extends MIDletimplements CommandListener { Command CMD_EXIT = new Command("Exit", Command.EXIT, 99); MyAppCanvas canvas; boolean exitApp = false; public MyApp() { } public void startApp() { try { Display display = Display.getDisplay(this); canvas = new MyAppCanvas(this); if ( !exitApp ) { canvas.start(); canvas.addCommand(CMD_EXIT); canvas.setCommandListener(this); display.setCurrent(canvas); } else { Alert alert = new Alert("Error!"); alert.setTimeout(Alert.FOREVER); alert.setString("Screen size is too small to run app!"); display.setCurrent(alert); notifyDestroyed(); // leave in or out or something else??? } } catch(java.io.IOException ioe) { } } public void setExit() { exitApp = true; } public void pauseApp() { } public void destroyApp(boolean unconditional) { } public void commandAction(Command cmd, Displayable dsp) { if ( cmd == CMD_EXIT ) { canvas.stop(); notifyDestroyed(); } } } and in another file ... public class MyClassApp extends GameCanvas implements Runnable { public PairedUpCanvas(PairedUp p) throws java.io.IOException { // checks screen size // if it is out of bounds for the app, do the following ... p.setExit(); return; // otherwise, continue on } public void start() { (new Thread(this)).start(); } // other code ... }
The problem is trying to exit the app after the Alert box is displayed. If I don't issue notifyDestroyed() after the Alert box, the device shows a blank screen (i.e., no menu for the app to run again). If I insert the notifyDestroyed() after the Alert box, the error message is displayed for a split second, and the user is returned to the device menu.
Does anyone know how to get this to work properly?
Thanks!
SCJP
Michael Yuan
author
Ranch Hand
Joined: Mar 07, 2002
Posts: 1427
posted
Oct 31, 2003 10:02:00
0
I think the best UI design is to put a "quit now" button on the alert and ask the user to click it when they are ready. That allows the user to read the alert message at his own pace.
If you have to do automatic quitting, you can put the whole thing into a separate thread and have it sleep for a couple of seconds before calling notifydestropyed
Seam Framework:
Ringful:
Stephen Pride
Ranch Hand
Joined: Sep 14, 2000
Posts: 121
posted
Oct 31, 2003 10:29:00
0
Thanks, Michael. I thought about the separate thread way, but haven't implemented it yet. I was trying to see if there was a "less coding" way of doing it, but perhaps not. Its funny, but with all the examples available on the net regarding J2ME, I haven't seen this particular scenario addressed exactly. Most of the apps I've seen address showing an Alert before continuing with the program vs. ending it. Thanks again.
David Price
Ranch Hand
Joined: Jan 22, 2003
Posts: 93
posted
Oct 31, 2003 10:58:00
0
If you're using MIDP 2.0, I think you should be able to call setCommandListener on the Alert, and then recognize its special Alert.DISMISS_COMMAND in your commandAction method and call notifyDestroyed there. I've not tried this though, and as it's rather obscure new MIDP 2.0 functionality you should be prepared for MIDP implementations to get it wrong. See the JavaDocs for class Alert for info on this approach.
With MIDP 1.0 you can't call setCommandListener on an Alert, so this solution doesn't work. I'd suggest using Michael's approach, or alternatively just ignore the Alert class and use a Form. If you want to get over-clever you could create a trivial subclass of Canvas with an empty paint() method and a showNotify() method that just calls the midlet's notifyDestroyed. Then display the alert using display.setCurrent(alert, new SneakyCanvas(this)), and when the alert leaves the screen your sneaky canvas will be shown, showNotify will be called, and it will call notifyDestroyed.
As I say, probably too clever for its own good - I might do this out of curiosity, but not in a production MIDlet
.
Stephen Pride
Ranch Hand
Joined: Sep 14, 2000
Posts: 121
posted
Oct 31, 2003 11:30:00
0
Cool! David, using your first approach works great. Here is what I did ...
public void startApp() { try { Display display = Display.getDisplay(this); canvas = new MyAppCanvas(this); if ( !exitApp ) { canvas.start(); canvas.addCommand(CMD_EXIT); canvas.setCommandListener(this); display.setCurrent(canvas); } else { Alert alert = new Alert("PairedUp!"); alert.setTimeout(Alert.FOREVER); alert.setString("Screen size is too small to run app!"); /* NEW */ alert.addCommand(CMD_EXIT); /* NEW */ alert.setCommandListener(new CommandListener() { public void commandAction(Command cmd, Displayable dsp) { if ( cmd == CMD_EXIT ) notifyDestroyed(); } }); display.setCurrent(alert); /* NEW */ // notifyDestroyed(); } } catch(java.io.IOException ioe) { } }
Thanks again to both of you for the help!
[ October 31, 2003: Message edited by: Stephen Pride ]
Alexander Traud
Greenhorn
Joined: Jul 07, 2004
Posts: 16
posted
Jul 07, 2004 11:05:00
0
Sorry for moving up this question but it showed up as the only result on Google and David's second idea is so great, here is the code for that:
alert.setTimeout(Alert.FOREVER); screen.setCurrent(alert, new Canvas() { protected void showNotify() { try { destroyApp(false); } catch (MIDletStateChangeException e) { e.printStackTrace(); } notifyDestroyed(); } protected void paint(Graphics g) {} });
Really great and conforms with MIDP 1.0.
[ July 07, 2004: Message edited by: Alexander Traud ]
I agree. Here's the link:
subject: Newbie: End app after alert
Similar Threads
Command buttons display on screen
Recording midlet with save function
User-Agent is not being send + midlet
Why my UI code can't work ?!
ItemCommandListener is not invoked on selection of MessageItem
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
JForum
|
Paul Wheaton
|
http://www.coderanch.com/t/227523/JME/Mobile/Newbie-app-alert
|
CC-MAIN-2015-35
|
refinedweb
| 986
| 55.24
|
DVX
Installing a dongle
Updating a dongle for DVX 7.5
Networking
About the lexicon...
Keyboard Shortcuts
Number checks
Paragraph
delimiter is not working
Exporting
an unfinished translation
Special Fonts
Would you like to add
missing spaces...?
Backing up for disaster (DVX)
or what to backup
"?" is placed
in the beginning of the sentence
Autopropagation is
not working
Ctrl (Alt) + Down Arrow freezes
DV
Problems with windows
(docking, losing, etc.)
How to export a partially
done translation
Where is the error log?
Changes are not reflected in a different view
Non-documented patches
Repetition Count
EXTERNAL VIEW
I cannot export to External
View
Weird fonts and formatting
in External View
TERMINOLOGY DATABASE
Entering new terms
MEMORY DATABASE
Wildcards in
Memory Searches
Before working
in two different computers... (MS Jet Version)
Backing
up your memory database
Installing a dongle in
Windows NT, 2000 (DV3)
Run setupdrv.exe in the Déjà Vu's folder
To uninstall a usb dongle:
Run setupdrv.exe /u /usb to uninstall USB drivers. (Needed only
if you are having trouble installing a parallel dongle.)
Top
- Home/Disclaimer
Updating a dongle
for DVX 7.5
From Atril's website:
Installation requirements
As part of our support
for Windows Vista in Déjà Vu
X 7.5, we are including a new version of the dongle drivers,
both for 32 bit (x86) and 64 bit (x64) editions of Windows.
The new dongle drivers
required some changes in Déjà Vu
X 7.5 which make it incompatible with previous versions of the
drivers, so if you are using Déjà Vu X with a dongle,
you must update the dongle drivers to the latest version. In
order to update them correctly, follow these steps:
1. Unplug the dongle.
2. Uninstall the drivers installed in your computer. To do so, open the Start
menu, click on Run and copy and execute the following line:
"C:\Program Files\ATRIL\Deja Vu X\Dongle\setupdrv.exe" /u
If you installed Déjà Vu X in a different location, you will
need to change this path.
3. Restart your computer.
4. Install the drivers by double-clicking on the setupdrv.exe file in the folder "C:\Program
Files\ATRIL\Deja Vu X\Dongle\"
5. Turn off your computer.
6. Connect the dongle to your computer.
7. Turn on your computer.
8. Your dongle will be recognized by Windows and you will be ready to use Déjà Vu
X 7.5
Top - Home/Disclaimer
Networking
- DVX
It
is possible to use Déjà Vu on a net. You can share
your memory database, terminology database, project (files), and
Déjà Vu's settings. When sharing, it is possible
for more than one translator to use the same memory and terminology
databases, to work in the same project/file, and to share the
same settings file.
In the Configuration window (Project
Parameters tab), set source and output directories using a
server's net name (or computer's net name. E.g.: \\myserver\translation\clientA).
In the Languages tab, you should point
to your memory and terminology databases using your server's
net name. E.g.: \\myserver\translation\dvmemories).
Be sure to share all relevant directories/folders.
We recommend to share Déjà
Vu's settings as well (list of clients, subjects, etc.).
To share DVX settings:
Place settings file (Settings.dvset) in a shared directory
Go to Tools > Options and select the General tab.
Under "Miscelaneous", in "Shared settings
location:", point to the shared settings file.
Emilio's
Note: Apart from the network being 100 mbps, it is advisable to
use switches rather than hubs. The Workgroup edition of DVX will
include the possibility of accessing databases via COM+, which
results in higher overall speed.
WARNING:
If you open DV and there is no access to its settings file, DV
will present an error message asking to reinstall it. Close DV,
and make sure you have access to the appropriate computer/directory.
For DV3 Networking information, see "DV3
Settings Info."
About
the lexicon...
For
info about Déjà Vu's Lexicon, please visit Ruud
Harmsen's site.
Keyboard
Shortcuts (DVX)
See
page 554 of DVX's Manual for a list of shortcuts. Keyboard shortcuts
can be reconfiguredsee page 23 of the manual.
DVX:
DVX has a shortcut for checking numbers in
a project: SHIFT+CTRL+F7
First,
be sure "Prevent segmentation" is not selected in the
import filter.
If
this is not the case, remember:
(Judy Ann Schoen's explanation).
To
find a carriage return, type ^013 inside
the find box; to find a new line, type ^010.
Replace them with normal paragraph marks.
Exporting
an unfinished translation (DVX)
Klas
Törnquist
A workaround (proceed carefully) is to populate
the empty segments. You can either do this on a copy of the project
file (safer) or do it straight in the project.
You first need to verify whether you have
a "free" row status marking. Let's assume that you haven't
used "Pending" to mark rows.
Switch view to All empty target rows and
select the command Populate. Don't change the view, but select
all rows and mark as Pending.
Export the file.
After export switch view to Pending
rows, right click and select "Clear all".
Special Fonts -
Veronika DV
Endre Both
Endre Both modified a couple of fonts to
be used in DV. To download them, click
here.
From Endre:
The fonts Veronika Sans DV and Veronika
Serif DV are adapted from the Bitstream Vera Sans and Bitstream
Vera Serif fonts, respectively. Please read Bitstream's original
The following modifications have been applied:
1. The space character (unicode no. 0020) has
been replaced with the middot character (unicode no. 00B7, the
character used in Microsoft Word for displaying spaces when the
option "Tools/Options/View/Formatting marks/Spaces"
or ".../Formatting marks/All" is checked).
2. The non-breaking space character (unicode
no. 00A0) has been replaced with the degree character (unicode
no. 00B0, the character used in Microsoft Word for displaying
non-breaking spaces when the option "Tools/Options/View/Formatting
marks/Spaces" or ".../Formatting marks/All" is
checked).
N.B. Both the dot in the space character and
the degree sign in the non-breaking space character are placed
lower than the original middot and degree signs to facilitate
differentiation between them.
Please send comments and suggestions to "abo
at endreboth dot com"
Thank you.
Endre Both
2005 March 22
Would
you like to add missing spaces in the end of a target sentence?
It
is not really an error message, but an option.
Because
we are translating cells, it is pretty easy to forget to put a
space after a period. This would generate a text without spaces
between sentences.
E.g.:
I love dogs.I love cats.
This
option puts existing spaces of the source cell into the target
cell. In a normal situation, this is what you want. Click YES.
Backing up for disaster
(DVX)
Victor Dewsbery, Patrick Germain, Daniel
Benito
What you should back up:
- Your main MDB or MDBs (extensions dvmdb;
dvmdx; and [lang. code.]dvmdi)
each of which consists of at least 4 files, and all are equally
essential..
- Your TDB or TDBs (extension dvtdb).
- The settings file (settings.dvset), which
is normally located in the directory Programs > Atril >
Deja Vu X.
- Keyboard Layout and shortcuts data is kept
in the "menulayout" registry key: HKEY_CURRENT_USER\Software\Atril\DejaVuX.
- Current project be careful, in some
cases it may be necessary to have the same directory structure
(This was true in DV3 for Powerpoint, Excel, etc.)
Tip:
Suggested utility to (selectively) back up the registry: Moon
Software Registry Key Backup (freeware).
Suggested utility for data backup: Syncback
(freeware).
"?"
is placed in the beginning of the project
Close and open your project.
Autopropagation
is not working
Repair your project (Tools > Repair > Project).
Ctrl (Alt) + Down Arrow
Freezes DV (v 7.0.273)
Try to work outside the grid.
Tools > Options > Environment and select "Edit in
separate text area"
Problems
with windows (docking, losing, etc.)
Jenny Zonneveld / Lorenzo Benito
There is a utility in the files section to reset the registry
entry which causes this, or this utility via the Atril site
Close DVX, download and execute the following file:
Alternatively if you are ok on editing the registry yourself
just delete the entry HKEY_CURRENT_USER\Software\ATRIL\DejaVuX\MenuLayout
How to
export a partially done translation
Based on a tip from Paul Cowan
DV needs all codes in the target text to export a project. To
accomplish this:
Press Alt+F5 to populate all rows (or select all rows and
press F5).
Export your file.
To continue your work:
Select "All unfinished rows" in the row selector,
right-click a target cell and select "Clear all translations."*
-- ATTENTION: Be careful when using "Clear all translations".
* Assuming all unfinished rows should be deleted. If this is
not the case, and you want to delete Populated cells only, run
this SQL line.
* Assuming all unfinished rows should be deleted. If this is
not the case, and you want to delete Populated cells only, run
this SQL line.
Where is the
error log?
Alex Seidanis
When you get an error message, the error log is placed in the
Clipboard. Open a text editor (Notepad, Wordpad, Word, etc.) and
place the contents of the clipboard in the text editor (Ctrl+v).
Changes are not reflected
in a different view
Many times, one is working in one view, e.g. one file, and when
switching to another view, e.g. project view, one cannot see the
changes made in the first view reflected in the second.
The problem
sometimes happen when switching from, e.g. "Unpainted rows"
to "All rows" or any other DV filter.
To avoid it, before switching views, go to Project > Find duplicate
sentences and click OK to "Find sets of duplicate source sentences."
(Jorge Gorín and others)
Alternatively
one can "simply toggle the
alphabetical/natural sorting button which seems to refresh
the screen
and only takes a fraction of a second." (Dave Turner)
Non-documented patches
Engine patches:
It seems the patches above are not cumulative, but the patch below
is.
Template patches:
(Contains a .ppt
file)
Gudmund Areskoug
"To install it, locate the file dvxengine.dll (usually located
in the
folder "C:\Program Files\ATRIL\Deja Vu X") and overwrite
it with the
downloaded file"
The above patches are not cumulative, you use one or another,
not many
on top of each other.
Patches from 3 and upwards AFAIK address specific problems and
were not
meant for public use (could someone please fill in what they solve?).
Patch 2 should AFAIR solve or alleviate certain assembly problems.
It's
not perfect, but seems to improve things, at least here.
IMNSHO, openness about the patches, what they're supposed to solve,
and
public official announcements of them no matter how small or special
the
targeted problem may *seem*, would be hugely beneficial to everyone.
Top - Home/Disclaimer
Repetition Count
DVX counts repetition as expected. That is, the total word count
includes everything. The repetition counts includes repetitions only
-- the first instance of a cell is NOT counted as repetition.
E.g.:
That is nice.
That is nice.
That is nice.
DVX will count a total of 9 words and 6 repeated words.
Top - Home/Disclaimer
I cannot export
to External View (EV)
You can only export your whole file to External View if you have
DV's Workgroup edition. If you do not have it, DV will export
translated cells, propagated cells, and cells containing a comment.
That is, if you have translated the whole file and want somebody
else to edit it, it is possible to export it to External View
independently of the DV's edition you have. If you want somebody
to translate the whole file in External View, you should have
DV's Workgroup edition.
If you do not have the Workgroup edition and still need to export
everything to External View, you have to place a comment in each
blank or populated cell of your project.
Weird fonts and
formatting in External View (EV)
When you first open the document, it looks
ok. By the second time you do not see anything OR you see hidden
hollow fonts (as above). To solve the problem, when you first
open the document, Save As a Word file (.doc). Get rid of the
RTF and use only the new saved document.
Miri Ofek
Another tip about external view: if the file is large, importing
it back into the project might take a very long time, but if you
save it as rtf and import it as such, it would take just a few
seconds.
Alternatively
The first time you open the doc, copy the whole table to a new
document.
Entering new
terms
Dave Turner
I find by far the fastest way to select (highlight) one or more
words to be put into the TDB or Lexicon is to double-click on
the fist word (which includes the trailing space) and then hold
down shift+control and press right arrow to select the following
word or words (including the final trailing space).
It's much more reliable than using the mouse (if your not careful,
you quite often cut off the first or last letter(s) in the portion).
Yves Maurer's TIP: The trailing space will
be cut off before sending it to the TDB, so you don't have to
worry about that. Just check inside the text boxes in the "Add
Term Pair" window -- the trailing space is not there.
Marco Amans
This has been said here before, but this information might be
useful for new users.
"Shift+F11" doesn't do the same as "F11".
The term is saved *without* the attributes "subject"
and "client".
Marie Gouin
I try to use the mouse as little as possible, so I don't even
double click on the first word. I just position the cursor in
front of the first word I want to highlight and hold down Shift+Control
and then press the right arrow to select the rest of the words.
Searching
the memory using wildcard
Emilio
Benito
Are
you aware that in Déjà Vu you can use asterisks
in your searches?
For
example, you can type con* fil* in
target, select the text, right-click and select 'Scan as source'
from the context menu. Déjà Vu will return MDB pairs
which contain words beginning with 'con' and 'fil', such as:
Config Filename:
Config filename:
Confirm File
Move
Config file:
configuration
file
Confirm File
Confirm
of Read-Only File
Config Filename:
Config filename:
Confirm File
Move
Config file:
configuration
file
Confirm File
Confirm
of Read-Only File
Config Filename:
Config filename:
Confirm File
Move
Config file:
configuration
file
Confirm File
Confirm
of Read-Only File
etc.
Before working in two
different computers... (MS Jet Engine Versions)
Herbert Eppel (and Atril's Team)
Be sure all your computers are using the same MS Jet Engine version.
If all computers are using the same DV version, this is normally
not a problem. Different Jet Engine versions can corrupt your
database. Check Microsoft's
page.
To understand how the subject affects DVX, read
this message and corresponding thread.
Backing up your
memory database
Lorenzo Benito
You can leave the associated files behind, and only copy the
files .dvmdb and .dvtdb, but if you do you must
repair these databases later on before you use them.
The associated files (extensions dvmdb; dvmdx; and [lang.
code.]dvmdi) contain the indexes for the databases, and
the repair function can generate them again.
You must also ensure that the databases are not read only, otherwise
access from Déjà Vu X will be impossible; needless
to say, you cannot access them from Déjà Vu X if
they are still on the CD.
|
http://www.necco.ca/dv/working_with_dvx.htm
|
CC-MAIN-2018-05
|
refinedweb
| 2,631
| 64.41
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.