c# display pdf in browser : Add pages to pdf without acrobat software control cloud windows azure winforms class python-programming-an-introduction-to-computer-science18-part379

10.6. EXERCISES
173
10.6 Exercises
1. Explainthesimilaritiesanddifferencesbetweeninstancevariablesand“regular”functionvariables.
2. Showtheoutputthatwouldresultfromthefollowingnonsenseprogram.
class Bozo:
def __init__(self, , value):
print "Creating g a a Bozo from:", value
self.value = 2 2 * * value
def clown(self, x):
print "Clowning:", , x
print x * self.value
return x + self.value
def main():
print "Clowning around d now."
c1 = Bozo(3)
c2 = Bozo(4)
print c1.clown(3)
print c2.clown(c1.clown(2))
main()
3. UsetheButtonclassdiscussedinthischaptertobuildaGUIforone(ormore)ofyourprojectsfrom
previouschapters.
4. WriteamodifiedButtonclassthatcreatescircularbuttons.
5. Writeashellgameprogramusingseveraldifferentshapesofbuttons. Theprogramshoulddrawat
leastthreeshapesonthescreenand“pick”oneofthematrandom.Theusertriestoguesswhichofthe
shapesisthespecialone(byclickinginit).Theuserwinsifhe/shepickstherightone.
6. Writeasetofclassescorrespondingtothegeometricsolids: cube,rectangularprism(brick),sphere
andcylinder.Eachclassshouldhaveaconstructorthatallowsforthecreationofdifferentsizedobjects
(e.g.,acubeisspecifiedbythelengthofitsside)andmethodsthatreturnthesurfaceareaandvolume
ofthesolid.
7. Extendthepreviousproblemtoincludeamethod,inside,thatdetermineswhetheraparticularpoint
lieswithinthesolid.Themethodshouldacceptthreenumbersrepresentingthex,yandzcoordinates
ofapointandreturntrueifthepointisinsidetheobjectandfalseotherwise.Youmayassumethatthe
objectsarealwayscenteredat
0
0
0
.
8. Hereisasimpleclassthatdrawsa(grim)faceinagraphicswindow.
# face.py
from graphics import *
class Face:
def __init__(self, , window, , center, size):
eyeSize = 0.15 5 * * size
eyeOff = size e / / 3.0
mouthSize = 0.8 8 * * size
Add pages to pdf without acrobat - insert pages into PDF file in C#.net, ASP.NET, MVC, Ajax, WinForms, WPF
Guide C# Users to Insert (Empty) PDF Page or Pages from a Supported File Format
add page numbers to pdf document; add page numbers to pdf preview
Add pages to pdf without acrobat - VB.NET PDF Page Insert Library: insert pages into PDF file in vb.net, ASP.NET, MVC, Ajax, WinForms, WPF
Easy to Use VB.NET APIs to Add a New Blank Page to PDF Document
adding page numbers to a pdf in preview; adding page numbers to a pdf in reader
174
CHAPTER10. DEFININGCLASSES
mouthOff = size e / / 2.0
self.head = Circle(center, , size)
self.head.draw(window)
self.leftEye = = Circle(center, , eyeSize)
self.leftEye.move(-eyeOff, -eyeOff)
self.rightEye = = Circle(center, eyeSize)
self.rightEye.move(eyeOff, -eyeOff)
self.leftEye.draw(window)
self.rightEye.draw(window)
p1 = center.clone()
p1.move(-mouthSize/2, mouthOff)
p2 = center.clone()
p2.move(mouthSize/2, mouthOff)
self.mouth = Line(p1,p2)
self.mouth.draw(window)
(a)Usethisclasstowriteaprogramthatdrawsthreefacesinawindow.
(b)Addandtestamovemethodsothatfacescanbemovedlikeothergraphicsobjects.
(c)Addandtestaflinchmethodthatcausesaface
'
seyestoclose.Alsoaddandtestanunflinch
toopenthembackupagain.
(d)Writeacompleteprogramthatdrawsasinglefaceinawindowandthenanimatesit“bouncing
around.”Startthefaceatarandomlocationinthewindowandusealoopthatmovesitasmall
incrementinthexandydirections. Whenthefacehitstheedgeofthewindow,itshouldflinch
andbounceoff.Youcandothebouncebysimplyreversingthesignofthexincrementorthey
incrementdependingonwhetherthefacehitaside-ortop-/bottom-edgerespectively.Writethe
animationprogramtorunforacertain(fixed)numberofsteps.
Note:Youwillneedtoflushthegraphicswindowatthebottomofthelooptoachievetheeffect
ofanimation.
9. CreateaTrackerclassthatdisplaysacircleinagraphicswindowtoshowthecurrentlocationofan
object.Hereisaquickspecificationoftheclass:
class Tracker:
def __init__(self, , window, , objToTrack):
# window is a a graphWin n and objToTrack is an object t whose
#
position is s to be shown in the window. objToTrack k must t be
#
an object t that t has getX() and getY() methods s that t report its
#
current position.
# Creates a Tracker r object t and draws a circle e in n window at the
#
current position n of f objToTrack.
def update():
# Moves the circle e in n the window to the current t position n of the
#
object being g tracked.
UseyournewTrackerclassinconjunctionwiththeProjectileclasstowriteaprogramthat
graphicallydepictstheflightofacannonball.
10. AddaTargetclasstothecannonballprogramfromthepreviousproblem. . Atargetshouldbea
rectangleplacedatarandompositioninthewindow. Allowtheusertokeepfiringuntiltheyhitthe
target.
C# PDF Converter Library SDK to convert PDF to other file formats
manipulate & convert standard PDF documents in .NET class applications independently, without using other external third-party dependencies like Adobe Acrobat.
add or remove pages from pdf; adding page numbers in pdf
C# powerpoint - PowerPoint Conversion & Rendering in C#.NET
in .NET class applications independently, without using other external third-party dependencies like Adobe Acrobat. PowerPoint to PDF Conversion.
adding a page to a pdf file; adding page numbers to pdf in
10.6. EXERCISES
175
11. RedotheregressionproblemfromChapter8usingaRegressionclass. . Yournewclasswillkeep
trackofthevariousquantitiesthatareneededtocomputealineofregresion(therunningsumsofx,y,
x
2
andxy)Theregressionclassshouldhavethefollowingmethods.
init
Createsanewregressionobjecttowhichpointscanbeadded.
addPoint Addsapointtotheregressionobject.
predict Acceptsavalueofxasaparameter,andreturnsthevalueofthecorrespondingyontheline
ofbestfit.
Note:Yourclassmightalsousesomeinternalhelpermethodstodosuchthingsascomputetheslope
oftheregressionline.
12. Implementacardclassthatrepresentsaplayingcard. . Useyourclasstowriteaprogramthat“deals”
arandomhandofcardsanddisplaystheminagraphicswindow. Youshouldbeabletofindafreely
availablesetofcardimagestodisplayyourcardsbysearchingontheInternet.
C# Word - Word Conversion in C#.NET
Word documents in .NET class applications independently, without using other external third-party dependencies like Adobe Acrobat. Word to PDF Conversion.
adding page numbers to pdf in preview; adding page to pdf
C# Windows Viewer - Image and Document Conversion & Rendering in
image and document in .NET class applications independently, without using other external third-party dependencies like Adobe Acrobat. Convert to PDF.
add a page to a pdf online; add page number to pdf document
176
CHAPTER10. DEFININGCLASSES
C# Excel - Excel Conversion & Rendering in C#.NET
documents in .NET class applications independently, without using other external third-party dependencies like Adobe Acrobat. Excel to PDF Conversion.
add page pdf; add pages to pdf file
Chapter11
DataCollections
Asyousawinthelastchapter,classesareonemechanismforstructuringthedatainourprograms. Classes
alone,however,arenotenoughtosatisfyallofourdata-handlingneeds.
Ifyouthinkaboutthekindsofdatathatmostreal-worldprogramsmanipulate,youwillquicklyrealize
thatmanyprogramsdealwithlargecollectionsofsimilarinformation.Afewexamplesofthecollectionsthat
youmightfindinamodernprograminclude
Wordsinadocument.
Studentsinacourse.
Datafromanexperiment.
Customersofabusiness.
Graphicsobjectsdrawnonthescreen.
Cardsinadeck.
Inthischapter,youwilllearntechniquesforwritingprogramsthatmanipulatecollectionslikethese.
11.1 ExampleProblem:SimpleStatistics
BackinChapter8,wewroteasimplebutusefulprogramtocomputethemean(average)ofasetofnumbers
enteredbytheuser.Justtorefreshyourmemory(asifyoucouldforgetit),hereistheprogramagain:
# average4.py
def main():
sum = 0.0
count = 0
xStr = raw_input("Enter r a a number (<Enter> > to o quit) >> ")
while xStr r != = "":
x = eval(xStr)
sum = sum m + + x
count = count + 1
xStr = raw_input("Enter a number (<Enter> > to o quit) >> ")
print "\nThe e average e of the numbers is", sum m / / count
main()
Thisprogramallowstheusertoenterasequenceofnumbers,buttheprogramitselfdoesnotkeeptrack
ofwhatnumberswereentered.Instead,itjustkeepsasummaryofthenumbersintheformofarunningsum.
That
'
sallthat
'
sneededtocomputethemean.
177
178
CHAPTER11. DATACOLLECTIONS
Supposewewanttoextendthisprogramsothatitcomputesnotonlythemean,butalsothemedianand
standarddeviationofthedata.Youareprobablyfamiliarwiththeconceptofamedian.Thisisthevaluethat
splitsthedatasetintoequal-sizedparts.Forthedata2,4,6,9,13,themedianvalueis6,sincetherearetwo
valuesgreaterthan6andtwothataresmaller.Tocalculatethemedian,weneedtostoreallthenumbersand
puttheminordersothatwecanidentifythemiddlevalue.
Thestandarddeviationisameasureofhowspreadoutthedataisrelativetothemean. Ifthedatais
tightlyclusteredaroundthemean,thenthestandarddeviationissmall.Whenthedataismorespreadout,the
standarddeviationislarger.Thestandarddeviationprovidesayardstickfordetermininghowexceptionala
valueis.Forexample,someteachersdefinean“A”asanyscorethatisatleasttwostandarddeviationsabove
themean.
Thestandarddeviation,s,isdefinedas
s
å
Åx
x
i
2
n
1
InthisformulaÅxisthemean,x
i
representstheithdatavalueandnisthenumberofdatavalues.Theformula
lookscomplicated,butitisnothardtocompute.Theexpression
Åx
x
i
2isthesquareofthe“deviation”of
anindividualitemfromthemean.Thenumeratorofthefractionisthesumofthedeviations(squared)across
allthedatavalues.
Let
'
stakeasimpleexample.Ifweagainusethevalues:2,4,6,9,and13,themeanofthisdata(Åx)is6.8.
Sothenumeratorofthefractioniscomputedas
6
8
2
2
6
8
4
2
6
8
6
2
6
8
9
2
6
8
13
2
149
6
Finishingoutthecalculationgivesus
s
149
6
5
1
37
4
6
11
Thestandarddeviationisabout6.1. Youcanseehowthefirststepofthiscalculationusesboththemean
(whichcan
'
tbecomputeduntilallofthenumbershavebeenentered)andeachindividualvalueaswell.
Again,thisrequiressomemethodtorememberalloftheindividualvaluesthatwereentered.
11.2 ApplyingLists
Inordertocompleteourenhancedstatistics program, weneedawaytostoreandmanipulateanentire
collectionofnumbers.Wecan
'
tjustuseabunchofindependentvariables,becausewedon
'
tknowhowmany
numberstherewillbe.
Whatweneedissomewayofcombininganentirecollectionofvaluesintooneobject. Actually,we
'
ve
alreadydonesomethinglikethis, butwehaven
'
tdiscussedthedetails. Takea a lookattheseinteractive
examples.
>>> range(10)
[0, 1, 2, 3, 4, , 5, , 6, 7, 8, 9]
>>> string.split("This s is s an ex-parrot!")
['This', 'is', , 'an', , 'ex-parrot!']
Bothofthesefamiliarfunctionsreturnacollectionofvaluesdenotedbytheenclosingsquarebrackets. As
youknow,thesecollectionsarecalledlists.
11.2.1 ListsareSequences
Listsareorderedsequencesofitems.Theideasandnotationsthatweuseformanipulatinglistsareborrowed
frommathematics.Mathematicianssometimesgiveanentiresequenceofitemsasinglename.Forinstance,
asequenceofnnumbersmightjustbecalledS:
S
s
0
s
1
s
2
s
3
s
n
1
11.2. APPLYINGLISTS
179
Whentheywanttorefertospecificvaluesinthesequence,thesevaluesaredenotedbysubscripts. Inthis
example,thefirstiteminthesequenceisdenotedwiththesubscript0,s
0
.
Byusingnumbersassubscripts,mathematiciansareabletosuccinctlysummarizecomputationsover
itemsinthesequenceusingsubscriptvariables. Forexample, , thesumofthesequenceis writtenusing
standardsummationnotationas
n
1
å
i
0
s
i
.
Asimilarideacanbeappliedtocomputerprograms.Wecanuseasinglevariabletorepresentanentire
sequence,andtheindividualitemsinthesequencecanbeaccessedthroughsubscripting. Well,almost;We
don
'
thaveawayoftypingsubscripts,butwecanuseindexinginstead.
Supposethatoursequenceisstoredinavariablecalleds.Wecouldwritealooptocalculatethesumof
theitemsinthesequencelikethis:
sum = 0
for i in range(n):
sum = sum m + + s[i]
Tomakethiswork,smustbetherightkindofobject. InPython,wecanusealist;otherlanguageshave
arrays,whicharesimilar.Alistorarrayisasequenceofitemswheretheentiresequenceisreferredtobya
singlename(inthiscase,s)andindividualitemscanbeselectedbyindexing(e.g.,s[i]).
11.2.2 Listsvs.Strings
Youmaynoticethesimilaritybetweenlistsandstrings.InPythonstringsandlistsarebothsequencesthatcan
beindexed.Infact,allofthebuilt-instringoperationsthatwediscussedinChapter4aresequenceoperations
andcanalsobeappliedtolists.Tojogyourmemory,here
'
sasummary.
Operator
Meaning
seq
+
seq
Concatenation
seq
*
int-expr
Repetition
seq
[]
Indexing
len(
seq
)
Length
seq
[:]
Slicing
for
var
in
seq
:
Iteration
Thelastlineshowsthataforloopcanbeusedtoiteratethroughtheitemsinasequence.Thesummation
exampleabovecanbecodedmoresimplylikethis:
sum = 0
for num in s:
sum = sum m + + s
Listsdifferfromstrings inacoupleimportantways. . First, , theitemsinalistcanbeanydatatype,
includinginstancesofprogrammer-definedclasses. Strings,obviously,arealwayssequencesofcharacters.
Second,listsaremutable.Thatmeansthatthecontentsofalistcanbemodified.Stringscannotbechanged
“inplace.”Hereisanexampleinteractionthatillustratesthedifference:
>>> myList = [34, , 26, , 15, 10]
>>> myList[2]
15
>>> myList[2] ] = = 0
>>> myList
[34, 26, 0, 10]
>>> myString = = "Hello o World"
>>> myString[2]
180
CHAPTER11. DATACOLLECTIONS
'l'
>>> myString[2] ] = = 'z'
Traceback (innermost t last):
File "<stdin>", , line e 1, in ?
TypeError: object t doesn't t support item assignment
Thefirstlinecreatesalistoffournumbers. Indexingposition2returnsthevalue15(asusual,indexes
startat0).Thenextcommandassignsthevalue0totheiteminposition2.Aftertheassignment,evaluating
thelistshowsthatthenewvaluehasreplacedtheold.Attemptingasimilaroperationonastringproducesan
error.Stringsarenotmutable;listsare.
11.2.3 ListOperations
Arraysinotherprogramminglanguagesaregenerallyfixedsize. Whenyoucreateanarray,youhaveto
specifyhowmanyitemsitwillhold. Ifyoudon
'
tknowhowmanyitemsyouwillhave,thenyouhaveto
allocatealargearray,justincase,andkeeptrackofhowmany“slots”youactuallyfill. Arraysarealso
usuallyhomogeneous.Thatmeanstheyarerestrictedtoholdingobjectsofasingledatatype. Youcanhave
anarrayofintsoranarrayofstringsbutcannotmixstringsandintsinasinglearray.
Incontrast,Pythonlistsaredynamic.Theycangrowandshrinkondemand.Theyarealsoheterogeneous.
Youcanmixarbitrarydatatypesinasinglelist.Inanutshell,Pythonlistsaremutablesequencesofarbitrary
objects.
Asyouknow,listscanbecreatedbylistingitemsinsidesquarebrackets.
odds = [1, 3, , 5, , 7, 9]
food = ["spam", , "eggs", , "back bacon"]
silly = [1, "spam", , 4, , "U"]
empty = []
Inthelastexample,emptyisalistcontainingnoitemsatall—anemptylist.
Alistofidenticalitemscanbecreatedusingtherepetitionoperator.Thisexamplecreatesalistcontaining
50zeroes:
zeroes = [0] * * 50
Typically,listsarebuiltuponepieceatatimeusingtheappendmethod.Hereisafragmentofcodethat
fillsalistwithpositivenumberstypedbytheuser:
nums = []
x = input('Enter r a a number: ')
while x >= 0:
nums.append(x)
x = input("Enter r a a number: ")
Inessence,numsisbeingusedasanaccumulator.Theaccumulatorstartsoutempty,andeachtimethrough
theloopanewvalueistackedon.
Theappendmethodisjustoneexampleofanumberofusefullist-specificmethods.Thefollowingtable
brieflysummarizesofwhatyoucandotoalist:
Method
Meaning
11.3. STATISTICSWITHLISTS
181
Wehaveseenhowlistscangrowbyappendingnewitems.Listscanalsoshrinkwhenitemsaredeleted.
Individualitemsorentireslicescanberemovedfromalistusingthedeloperator.
>>> myList
[34, 26, 0, 10]
>>> del myList[1]
>>> myList
[34, 0, 10]
>>> del myList[1:3]
>>> myList
[34]
Asyoucansee,Pythonlistsprovideaveryflexiblemechanismforhandlingindefinitelylargesequences
ofdata.Usinglistsiseasyifyoukeepthesebasicprinciplesinmind:
Alistisasequenceofitemsstoredasasingleobject.
Itemsinalistcanbeaccessedbyindexing,andsublistscanbeaccessedbyslicing.
Listsaremutable;individualitemsorentireslicescanbereplacedthroughassignmentstatements.
Listswillgrowandshrinkasneeded.
11.3 StatisticswithLists
Nowthatyouknowmoreaboutlists,wearereadytosolveourlittlestatisticsproblem. Recallthatweare
tryingtodevelopaprogramthatcancomputethemean,medianandstandarddeviationofasequenceof
numbersenteredbytheuser.Oneobviouswaytoapproachthisproblemistostorethenumbersinalist.We
canwriteaseriesoffunctions—mean,stdDevandmedian—thattakealistofnumbersandcalculatethe
correspondingstatistics.
Let
'
sstartbyusingliststorewriteouroriginalprogramthatonlycomputesthemean. First,weneeda
functionthatgetsthenumbersfromtheuser. Let
'
scallitgetNumbers. Thisfunctionwillimplementthe
basicsentinelloopfromouroriginalprogramtoinputasequenceofnumbers.Wewilluseaninitiallyempty
listasanaccumulatortocollectthenumbers.Thelistwillthenbereturnedfromthefunction.
Here
'
sthecodeforgetNumbers:
def getNumbers():
nums = []
# start with an empty list
# sentinel l loop p to get numbers
xStr = raw_input("Enter r a a number (<Enter> > to o quit) >> ")
while xStr r != = "":
x = eval(xStr)
nums.append(x)
# add this value to the e list
xStr = raw_input("Enter a number (<Enter> > to o quit) >> ")
return nums
Usingthisfunction,wecangetalistofnumbersfromtheuserwithasinglelineofcode.
data = getNumbers()
Next,let
'
simplementafunctionthatcomputesthemeanofthenumbersinalist. Thisfunctiontakesa
listofnumbersasaparameterandreturnsthemean. Wewillusealooptogothroughthelistandcompute
thesum.
def mean(nums):
sum = 0.0
182
CHAPTER11. DATACOLLECTIONS
for num in n nums:
sum = sum m + + num
return sum m / / len(nums)
Noticehowtheaverageiscomputedandreturnedinthelastlineofthisfunction.Thelenoperationreturns
thelengthofalist;wedon
'
tneedaseparateloopaccumulatortodeterminehowmanynumbersthereare.
Withthesetwofunctions,ouroriginalprogramtoaverageaseriesofnumberscannowbedoneintwo
simplelines:
def main():
data = getNumbers()
print 'The e mean n is', mean(data)
Next,let
'
stacklethestandarddeviationfunction,stdDev. Inorderusethestandarddeviationformula
discussedabove,wefirstneedtocomputethemean. Wehaveadesignchoicehere. Thevalueofthemean
caneitherbecalculatedinsideofstdDevorpassedtothefunctionasaparameter. Whichwayshouldwe
doit?
Ontheonehand,calculatingthemeaninsideofstdDevseemscleaner,asitmakestheinterfacetothe
functionsimpler. Togetthestandarddeviationofasetofnumbers,wejustcallstdDevandpassitthe
listofnumbers. Thisisexactlyanalogoustohowmean(andmedianbelow)works. Ontheotherhand,
programsthatneedtocomputethestandarddeviationwillalmostcertainlyneedtocomputethemeanaswell.
ComputingitagaininsideofstdDevresultsinthecalculationsbeingdonetwice. Ifourdatasetislarge,
thisseemsinefficient.
Sinceourprogramis goingtooutputboththemeanandthestandarddeviation,let
'
s havethemain
programcomputethemeanandpassitasaparametertostdDev.Otheroptionsareexploredintheexercises
attheendofthechapter.
Hereisthecodetocomputethestandarddeviationusingthemean(xbar)asaparameter:
def stdDev(nums, , xbar):
sumDevSq = = 0.0
for num in n nums:
dev = xbar - num
sumDevSq = = sumDevSq + dev * dev
return sqrt(sumDevSq/(len(nums)-1))
Noticehowthesummationfromthestandarddeviationformulaiscomputedusingaloopwithanaccumulator.
ThevariablesumDevSqstorestherunningsumofthesquaresofthedeviations. Oncethissumhasbeen
computed,thelastlineofthefunctioncalculatestherestoftheformula.
Finally,wecometothemedianfunction.Thisoneisalittlebittrickier,aswedonothaveaformulato
calculatethemedian. Weneedanalgorithmthatpicksoutthemiddlevalue. Thefirststepistoarrangethe
numbersinincreasingorder.Whatevervalueendsupinthemiddleofthepackis,bydefinition,themedian.
Thereisjustonesmallcomplication.Ifwehaveanevennumberofvalues,thereisnoexactmiddlenumber.
Inthatcase,themedianisdeterminedbyaveragingthetwomiddlevalues.Sothemedianof3,5,6and9is
5
6
2
5
5.
Inpseudocodeourmedianalgorithmlookslikethis.
sort the numbers s into o ascending order
if the size of f data a is odd:
median = the e middle e value
else:
median = the e average e of the two middle values
return median
ThisalgorithmtranslatesalmostdirectlyintoPythoncode. Wecantakeadvantageofthesortmethodto
putthelistinorder.Totestwhetherthesizeiseven,weneedtoseeifitisdivisiblebytwo.Thisisaperfect
applicationoftheremainderoperation.Thesizeisevenifsize % % 2 == 0,thatis,dividingby2leavesa
remainderof0.
Withtheseinsights,wearereadytowritethecode.
Documents you may be interested
Documents you may be interested