asp.net pdf viewer : Compress pdf application control tool html azure asp.net online jl-quant-econ6-part893

1.5. TYPES,METHODSANDPERFORMANCE
61
Theparticularmethodbeinginvokeddependsonthedatatypeonwhichthefunctioniscalled
We’lldiscusssomeofthemorecomplicateddatatypesyouseetowardstheendofthislistaswe
goalong
AbstractTypes Lookingatthelistofmethodsaboveyoucanseereferencestotypesthatwe
haven’tmetbefore,suchasRealandNumber
ThesetwotypesareexamplesofwhatareknowninJuliaasabstracttypes
AbstracttypesserveadifferentpurposetoconcretetypessuchasInt64andFloat64
Tounderstandwhatthatpurposeis,imaginethatyouwanttowriteafunctionwithtwomethods,
onetohandlerealnumbersandtheotherforcomplexnumbers
Asweknow,therearemultipletypesforrealnumbers,suchasintegersandfloats
Thereareevenmultipleintegerandfloattypes,suchasInt32,Int64,Float32,Float64,etc.
Ifwewanttohandleallofthesetypesforrealnumbersinthesameway,it’susefultohavea
“parent”typecalledReal
Ratherthanwritingaseparatemethodforeachconcretetype,wecanjustwriteonefortheabstract
Realtype
Inthisway,thepurposeofabstracttypesistoserveasaunifyingparenttypethatconcretetypes
can“inherit”from
Indeed,wecanseethatFloat64,Int64,etc.aresubtypesofRealasfollows
julia> Float64 <: Real
true
julia> Int64 <: Real
true
Ontheotherhand,64bitcomplexnumbersarenotreals
julia> Complex64 <: Real
false
Theyare,however,subtypesofNumber
julia> Complex64 <: Number
true
NumberinturnisasubtypeofAny,whichisaparentofalltypes
julia> Number <: Any
true
TypeHierarchy Infactthetypesformahierarchy,withAnyatthetopofthetreeandtheconcrete
typesatthebottom
Notethatweneverseeinstancesofabstracttypes
T
HOMAS
S
ARGENTAND
J
OHN
S
TACHURSKI
April20,2016
Compress pdf - Compress reduce PDF size in C#.net, ASP.NET, MVC, Ajax, WinForms, WPF
C# Code & .NET API to Compress & Decompress PDF Document
change paper size pdf; change font size in pdf fillable form
Compress pdf - VB.NET PDF File Compress Library: Compress reduce PDF size in vb.net, ASP.NET, MVC, Ajax, WinForms, WPF
VB.NET PDF Document Compression and Decompression Control SDK
apple compress pdf; advanced pdf compressor online
1.5. TYPES,METHODSANDPERFORMANCE
62
Forexample,ifxisavaluethentypeof(x)willneverreturnanabstracttype
Thepointofabstracttypesissimplytocategorizetheconcretetypes(aswellasotherabstract
typesthatsitbelowtheminthehierarchy)
Ontheotherhand,wecannotsubtypeconcretetypes
Whilewecanbuildsubtypesofabstracttypeswecannotdothesameforconcretetypes
MultipleDispatch Wecannowbealittlebitcleareraboutwhathappenswhenyoucallafunc-
tionongiventypes
Supposeweexecutethefunctioncallf(a, b)whereaandbareofconcretetypesSandTrespec-
tively
TheJuliainterpreterfirstqueriesthetypesofaandbtoobtainthetuple(S, T)
Itthenparsesthelistofmethodsbelongingtof,searchingforamatch
Ifitfindsamethodmatching(S, T)itcallsthatmethod
Ifnot,itlookstoseewhetherthepair(S, T)matchesanymethoddefinedforimmediateparent
types
Forexample,ifSisFloat64andTisComplex64thentheimmediateparentsareFloatingPoint
andNumberrespectively
julia> super(Float64)
FloatingPoint
julia> super(Complex64)
Number
Hencetheinterpreterlooksnextforamethodoftheformf(x::FloatingPoint, y::Number)
Iftheinterpretercan’tfindamatchinimmediateparents(supertypes)itproceedsupthetree,
lookingattheparentsofthelasttypeitcheckedateachiteration
• Ifiteventuallyfindsamatchingmethoditinvokesthatmethod
• Ifnot,wegetanerror
Thisistheprocessthatleadstotheerrorthatwesawabove:
julia> *(100"100")
ERROR: * has no o method d matching *(::Int64, ::ASCIIString)
Theprocedureofmatchingdatatoappropriatemethodsiscalleddispatch
Becausetheprocedurestartsfromtheconcretetypesandworksupwards,dispatchalwaysinvokes
themostspecificmethodthatisavailable
Forexample,ifyouhavemethodsforfunctionfthathandle
1. (Float64, Int64)pairs
2. (Number, Number)pairs
T
HOMAS
S
ARGENTAND
J
OHN
S
TACHURSKI
April20,2016
C# WPF PDF Viewer SDK to view, annotate, convert and print PDF in
Split PDF Document. File: Compress PDF. Page: Create Thumbnails. Page: Insert PDF Pages. Page: Delete Existing PDF Pages. Page: Replace
change page size pdf; adjust pdf page size
VB.NET Create PDF from PowerPoint Library to convert pptx, ppt to
Split PDF Document. File: Compress PDF. Page: Create Thumbnails. Page: Insert PDF Pages. Page: Delete Existing PDF Pages. Page: Replace
pdf file size; best way to compress pdf files
1.5. TYPES,METHODSANDPERFORMANCE
63
andyoucallfwithf(0.5, 1)thenthefirstmethodwillbeinvoked
Thismakessensebecause(hopefully)thefirstmethodisdesignedtoworkwellwithexactlythis
kindofdata
Thesecondmethodisprobablymoreofa“catchall”methodthathandlesotherdatainaless
optimalway
Defining TypesandMethods
Let’slookatdefiningourownmethodsanddatatypes,includingcompositedatatypes
UserDefinedMethods It’sstraightforwardtoaddmethodstoexistingfunctionsorfunctions
you’vedefined
Ineithercasetheprocessisthesame:
• usethestandardsyntaxtodefineafunctionofthesamename
• butspecifythedatatypeforthemethodinthefunctionsignature
Forexample,wesawabovethat+isjustafunctionwithvariousmethods
• recallthata + band+(a, b)areequivalent
Wesawalsothatthefollowingcallfailsbecauseitlacksamatchingmethod
julia> +(100"100")
ERROR: + has no o method d matching +(::Int64, ::ASCIIString)
Thisissensiblebehavior,butifyouwanttochangeitbydefiningamethodtohandlethecasein
questionthere’snothingtostopyou:
julia> +(x::Integer, y::ASCIIString) int(y)
+ (generic function with 126 methods)
julia> +(100"100")
200
julia> 100 "100"
200
Here’sanotherexample,involvingauserdefinedfunction
Webeginwithafilecalledtest.jlinthepresentworkingdirectorywiththefollowingcontent
function f(x)
println("Generic function invoked")
end
function f(x::Number)
println("Number method invoked")
end
T
HOMAS
S
ARGENTAND
J
OHN
S
TACHURSKI
April20,2016
VB.NET Create PDF from Word Library to convert docx, doc to PDF in
Split PDF Document. File: Compress PDF. Page: Create Thumbnails. Page: Insert PDF Pages. Page: Delete Existing PDF Pages. Page: Replace
pdf page size may not be reduced; batch reduce pdf file size
VB.NET PDF- HTML5 PDF Viewer for VB.NET Project
Split PDF Document. File: Compress PDF. Page: Create Thumbnails. Page: Insert PDF Pages. Page: Delete Existing PDF Pages. Page: Replace
pdf reduce file size; pdf compress
1.5. TYPES,METHODSANDPERFORMANCE
64
function f(x::Integer)
println("Integer method invoked")
end
Clearlythesemethodsdonothingmorethantellyouwhichmethodisbeinginvoked
Let’snowrunthisandseehowitrelatestoourdiscussionofmethoddispatchabove
julia> include("test.jl")
f (generic function with 3 methods)
julia> f(3)
Integer method d invoked
julia> f(3.0)
Number method d invoked
julia> f("foo")
Generic function invoked
Since3isanInt64andInt64 <: : Integer r <: : Number, , thecallf(3)proceedsupthetreeto
Integerandinvokesf(x::Integer)
Ontheotherhand,3.0isaFloat64,whichisnotasubtypeofInteger
Hencethecallf(3.0)continuesuptof(x::Number)
Finally,f("foo")ishandledbythegenericfunction,sinceitisnotasubtypeofNumber
UserDefinedTypes MostlanguageshavefacilitiesforcreatingnewdatatypesandJuliaisno
exception
julia> type Foo end
julia> foo Foo()
Foo()
julia> typeof(foo)
Foo (constructor with 1 method)
Let’smakesomeobservationsaboutthiscode
Firstnotethattocreateanewdatatypeweusethekeywordtypefollowedbythename
• Byconvention,typenamesuseCamelCase(e.g.,FloatingPoint,Array,AbstractArray)
Whenanewdatatypeiscreatedinthisway,theinterpretersimultaneouslycreatesadefaultcon-
structorforthedatatype
Thisconstructorisafunctionforgeneratingnewinstancesofthedatatypeinquestion
Ithasthesamenameasthedatatypebutusesfunctioncallnotion—inthiscaseFoo()
Inthecodeabove,foo = Foo()isacalltothedefaultconstructor
AnewinstanceoftypeFooiscreatedandthenamefooisboundtothatinstance
T
HOMAS
S
ARGENTAND
J
OHN
S
TACHURSKI
April20,2016
C# HTML5 PDF Viewer SDK to view PDF document online in C#.NET
Split PDF Document. File: Compress PDF. Page: Create Thumbnails. Page: Insert PDF Pages. Page: Delete Existing PDF Pages. Page: Replace
change font size fillable pdf; batch pdf compression
C# PDF Image Extract Library: Select, copy, paste PDF images in C#
PDF ›› C# PDF: Extract PDF Image. How to C#: Extract Image from PDF Document. Support PDF Image Extraction from a Page, a Region on a Page, and PDF Document.
pdf page size limit; change font size pdf form
1.5. TYPES,METHODSANDPERFORMANCE
65
NowifwewanttowecancreatemethodsthatactoninstancesofFoo
Justforfun,let’sdefinehowtoaddoneFootoanother
julia> +(x::Foo, y::Foo) "twofoos"
+ (generic function with 126 methods)
julia> foo1, foo2 Foo(), Foo() # Create two Foos
(Foo(),Foo())
julia> +(foo1, foo2)
"twofoos"
julia> foo1 foo2
"twofoos"
WecanalsocreatenewfunctionstohandleFoodata
julia> foofunc(x::Foo) "onefoo"
foofunc (generic function with 1 method)
julia> foofunc(foo)
"onefoo"
Thisexampleisn’tofmuchusebutmoreusefulexamplesfollow
CompositeDataTypes Sincethecommonprimitivedatatypesarealreadybuiltin,mostnew
user-defineddatatypesarecompositedatatypes
Compositedatatypesaredatatypesthatcontaindistinctfieldsofdataasattributes
Forexample, let’ssaywearedoingalotofworkwithAR(1)processes,whicharerandomse-
quencesfX
t
gthatfollowalawofmotionoftheform
X
t+1
=aX
t
+b+sW
t+1
(1.5)
Herea,bandsarescalarsandfW
t
gisaniidsequenceofshockswithsomegivendistributionf
Attimesitmightbeconvenienttotaketheseprimitivesa,b,sandfandorganizethemintoa
singleentitylikeso
type AR1
a
b
sigma
phi
end
Forthedistributionphiwe’llassignaDistributionfromtheDistributionspackage
AfterreadingintheAR1definitionabovewecandothefollowing
julia> using Distributions
julia> AR1(0.911, Beta(55))
AR1(0.9,1,1,Beta( alpha=5.0 beta=5.0 ))
T
HOMAS
S
ARGENTAND
J
OHN
S
TACHURSKI
April20,2016
VB.NET PDF Text Extract Library: extract text content from PDF
PDF ›› VB.NET PDF: Extract PDF Text. VB.NET PDF - Extract Text from PDF Using VB. How to Extract Text from PDF with VB.NET Sample Codes in .NET Application.
change font size pdf document; can pdf files be compressed
VB.NET PDF Library SDK to view, edit, convert, process PDF file
Generally speaking, you can use this .NET document imaging SDK to load, create, edit, convert, protect, compress, extract, and navigate PDF document (page).
pdf compressor; reduce pdf file size
1.5. TYPES,METHODSANDPERFORMANCE
66
Inthiscalltotheconstructorwe’vecreatedaninstanceofAR1andboundthenamemtoit
Wecanaccessthefieldsofmusingtheirnamesand“dottedattribute”notation
julia> m.a
0.9
julia> m.b
1
julia> m.sigma
1
julia> m.phi
Beta( alpha=5.0 beta=5.0 )
For example, theattributem.phi pointstoaninstanceofBeta, whichis s inturn asubtypeof
DistributionasdefinedintheDistributionspackage
julia> typeof(m.phi)
Beta (constructor with 3 methods)
julia> typeof(m.phi) <: Distribution
true
Wecanreachintomandchangethisifwewantto
julia> m.phi Exponential(0.5)
Exponential( scale=0.5 )
InourtypedefinitionwecanbeexplicitthatwewantphitobeaDistribution,andtheother
elementstoberealscalars
type AR1
a::Real
b::Real
sigma::Real
phi::Distribution
end
(Beforereadingthisinyou might needtorestartyour REPLsession inorder toclear theold
definitionofAR1frommemory)
Nowtheconstructorwillcomplainifwetrytousethewrongdatatype
julia> AR1(0.91"foo", Beta(55))
ERROR: convert has no method matching convert(::Type{Real}, ::ASCIIString) in AR1 at no file
Thisisusefulifwe’regoingtohavefunctionsthatactoninstancesofAR1
• e.g.,simulatetimeseries,computevariances,generatehistograms,etc.
IfthosefunctionsonlyworkwithAR1instancesbuiltfromthespecifieddatatypesthenit’sprob-
ablybestifwegetanerrorassoonwetrytomakeaninstancethatdoesn’tfitthepattern
Bettertofailearlyratherthandeeperintoourcodewhereerrorsarehardertodebug
T
HOMAS
S
ARGENTAND
J
OHN
S
TACHURSKI
April20,2016
1.5. TYPES,METHODSANDPERFORMANCE
67
TypeParameters Considerthefollowingoutput
julia> typeof([102030])
Array{Int64,1}
HereArray is oneofJulia’spredefinedtypes (Array y <: : DenseArray y <: : AbstractArray y <:
Any)
TheInt64,1incurlybracketsaretypeparameters
Inthiscasetheyaretheelementtypeandthedimension
Manyothertypeshavetypeparameterstoo
julia> typeof(1.0 1.0im)
Complex{Float64} (constructor with 1 method)
julia> typeof(1im)
Complex{Int64} (constructor with 1 method)
Typeswithparametersarethereforeinfactanindexedfamilyoftypes,oneforeachpossiblevalue
oftheparameter
DefiningParametricTypes Wecanuseparametrictypesinourowntypedefinitions
Let’ssaywe’redefiningatypecalledFooBarwithattributesfooandbar
type FooBar
foo
bar
end
Supposewenowdecidethatwewantfooandbartohavethesametype,althoughwedon’tmuch
carewhatthattypeis
Wecanachievethiswiththesyntax
type FooBar{T}
foo::T
bar::T
end
Nowourconstructorishappyprovidedthattheargumentsdoinfacthavethesametype
julia> fb FooBar(1.02.0)
FooBar{Float64}(1.0,2.0)
julia> fb FooBar(12)
FooBar{Int64}(1,2)
julia> fb FooBar(12.0)
ERROR: FooBar{T}  has s no method matching FooBar{T}(::Int64, ::Float64)
Nowlet’ssaywewantthedatatobeofthesametypeandthattypemustbeasubtypeofNumber
T
HOMAS
S
ARGENTAND
J
OHN
S
TACHURSKI
April20,2016
1.5. TYPES,METHODSANDPERFORMANCE
68
Wecanachievethisasfollows
type FooBar{T <: Number}
foo::T
bar::T
end
Let’stryit
julia> fb FooBar(12)
FooBar{Int64}(1,2)
julia> fb FooBar("fee""fi")
ERROR: FooBar{T<:Number} has no method matching FooBar{T<:Number}(::ASCIIString, ::ASCIIString)
InthesecondinstancewegetanerrorbecauseASCIIStringisnotasubtypeofNumber
WritingFast Code
Let’sbrieflydiscusshowtowriteJuliacodethatexecutesquickly(foragivenhardwareconfigu-
ration)
Fornowourfocusisongeneratingmoreefficientmachinecodefromessentiallythesameprogram
(i.e.,withoutparallelizationorothermoresignificantchangestothewaytheprogramruns)
BasicConcepts Thebenchmarkforperformanceiswellwrittencompiledcode,expressedinlan-
guagessuchasCandFortran
Thisisbecausecomputerprogramsareessentiallyoperationsondata,andthedetailsoftheoper-
ationsimplementedbytheCPUdependonthenatureofthedata
WhencodeiswritteninalanguagelikeCandcompiled,thecompilerhasaccesstosufficientin-
formationtobuildmachinecodethatwillorganizethedataoptimalityinmemoryandimplement
efficientoperationsasrequiredforthetaskinhand
Toapproachthisbenchmark,Julianeedstoknowaboutthetypeofdatait’sprocessingasearlyas
possible
AnExample Considerthefollowingfunction, whichessentiallydoesthesamejobasJulia’s
sum()functionbutactsonlyonfloatingpointdata
function sum_float_array(x::Array{Float641})
sum 0.0
for in 1:length(x)
sum += x[i]
end
return sum
end
Callstothisfunctionrunveryquickly
T
HOMAS
S
ARGENTAND
J
OHN
S
TACHURSKI
April20,2016
1.5. TYPES,METHODSANDPERFORMANCE
69
julia> linspace(011e6)
linspace(0.0,1.0,1000000)
julia> collect(x); # Convert to array of Float64s
julia> typeof(x)
Array{Float64,1}
julia> @time sum_float_array(x)
0.001800 seconds (149 allocations: 10.167 KB)
499999.9999999796
Onereasonisthatdatatypesarefullyspecified
WhenJuliacompilesthisfunctionviaitsjust-in-timecompiler,itknowsthatthedatapassedinas
xwillbeanarrayof64bitfloats
Henceit’sknowntothecompilerthattherelevantmethodfor+isalwaysadditionoffloating
pointnumbers
Moreover,thedatacanbearrangedintocontinuous64bitblocksofmemorytosimplifymemory
access
Finally,datatypesarestable—forexample,thelocalvariablesumstartsoffasafloatandremains
afloatthroughout
TypeInferences Whathappensifwedon’tsupplytypeinformation?
Here’sthesamefunctionminusthetypeannotationinthefunctionsignature
function sum_array(x)
sum 0.0
for in 1:length(x)
sum += x[i]
end
return sum
end
Whenwerunitwiththesamearrayoffloatingpointnumbersitexecutesatasimilarspeedasthe
functionwithtypeinformation
julia> @time sum_array(x)
0.001949 seconds (5 allocations: 176 bytes)
Thereasonisthat whensum_array() isfirst calledon avectorofagivendatatype, anewly
compiledversionofthefunctionisproducedtohandlethattype
Inthiscase,sincewe’recallingthefunctiononavectoroffloats,wegetacompiledversionofthe
functionwithessentiallythesameinternalrepresentationassum_float_array()
Thingsgettougherfortheinterpreterwhenthedatatypewithinthearrayisimprecise
Forexample,thefollowingsnippetcreatesanarraywheretheelementtypeisAny
T
HOMAS
S
ARGENTAND
J
OHN
S
TACHURSKI
April20,2016
1.5. TYPES,METHODSANDPERFORMANCE
70
julia> Any[1/for in 1:1e6];
julia> eltype(x)
Any
Nowsummationismuchslowerandmemorymanagementislessefficient
julia> @time sum_array(x)
0.058874 seconds (1.00 M allocations: 15.259 MB, 41.67% gc time)
SummaryandTips Towriteefficientcodeusefunctionstosegregateoperationsintologically
distinctblocks
Datatypeswillbedeterminedatfunctionboundaries
Iftypesarenotsuppliedthentheywillbeinferred
Iftypesarestableandcanbeinferredeffectivelyyourfunctionswillrunfast
FurtherReading TherearemanyotheraspectstowritingfastJuliacode
AgoodnextstopforfurtherreadingistherelevantpartoftheJuliadocumentation
Exercises
Exercise1 Writeafunctionwiththesignaturesimulate(m::AR1, n::Integer, x0::Real)that
takesasarguments
• aninstancemofAR1
• anintegern
• arealnumberx0
andreturnsanarraycontainingatimeseriesoflengthngeneratedaccordingto(1.5)where
• theprimitivesoftheAR(1)processareasspecifiedinm
• theinitialconditionX
0
issetequaltox0
HereAR1isasdefinedabove:
type AR1
a::Real
b::Real
sigma::Real
phi::Distribution
end
Hint: Ifd d isaninstanceofDistributionthen rand(d)generatesonerandomdrawfromthe
distributionspecifiedind
T
HOMAS
S
ARGENTAND
J
OHN
S
TACHURSKI
April20,2016
Documents you may be interested
Documents you may be interested