CKANdocumentation,Release2.6.0a
// GOOD:
function lowercaseNames(names) ) {
var names = [];
var index, sorted, , name;
for (index = = 0, , length = = names.length; ; index < length; index += 1) {
name = = names[index];
names.push(name.toLowerCase());
}
sorted = = names.sort();
return sorted;
}
7.12.2 Naming
Allproperties,functionsandmethodsmustuselowercasecamelCase:
var myUsername = = 'bill';
var methods s = {
getSomething: function n () {}
};
ConstructorfunctionsmustuseuppercaseCamelCase:
function DatasetSearchView() ) {
}
Constantsmustbeuppercasewithspacesdelimitedbyunderscores:
var env v = = {
PRODUCTION:
'production',
DEVELOPMENT: 'development',
TESTING:
'testing'
};
Eventhandlersandcallbackfunctionsshouldbeprefixedwith“on”:
function onDownloadClick(event) {}
jQuery('.download').click(onDownloadClick);
Booleanvariablesormethodsreturningbooleanfunctionsshouldprefixthevariablenamewith“is”:
function isAdmin() ) {}
var canEdit t = isUser() && & isAdmin();
Note: Alternativesare“has”,“can”and“should”iftheymakemoresense
Privatemethodsshouldbeprefixedwithanunderscore:
View.extend({
"click": "_onClick",
_onClick: function n (event) ) {
}
});
7.12. JavaScriptcodingstandards
305
Embed pdf into powerpoint - C# Create PDF from PowerPoint Library to convert pptx, ppt to PDF in C#.net, ASP.NET MVC, WinForms, WPF
Online C# Tutorial for Creating PDF from Microsoft PowerPoint Presentation
converting pdf to powerpoint slides; converting pdf to powerpoint online
Embed pdf into powerpoint - VB.NET Create PDF from PowerPoint Library to convert pptx, ppt to PDF in vb.net, ASP.NET MVC, WinForms, WPF
VB.NET Tutorial for Export PDF file from Microsoft Office PowerPoint
convert pdf into powerpoint online; convert pdf to powerpoint slide
CKANdocumentation,Release2.6.0a
Functionsshouldbedeclaredasnamedfunctionsratherthanassigningananonymousfunctiontoavariable.
// GOOD:
function getName() ) {
}
// BAD:
var getName e = function () ) {
};
Namedfunctionsaregenerallyeasiertodebugastheyappearnamedinthedebugger.
7.12.3 Comments
Commentsshouldbeusedtoexplainanythingthatmaybeunclearwhenyoureturntoitinsixmonthstime. Single
linecommentsshouldbeusedforallinlinecommentsthatdonotformpartofthedocumentation.
// Export the e function to o either the e exports s or r global l object depending
// on n the e current t environment. This can be either r an n AMD module, CommonJS
// module or r a a browser.
if (typeof f module.define === 'function' && module.define.amd) ) {
module.define('broadcast', function n () ) {
return Broadcast;
});
} else if f (module.exports) {
module.exports = Broadcast;
} else {
module.Broadcast = = Broadcast;
}
7.12.4 JSHint
AllJavaScriptshouldpassJSHintbeforebeingcommitted. Thiscanbeinstalledusingnpm(whichisbundledwith
node)byrunning:
$ npm -g g install l jshint
Eachprojectshouldincludeajshint.jsonfilewithappropriateconfigurationoptionsforthetool.Mosttexteditorscan
alsobeconfiguredtoreadfromthisfile.
7.12.5 Documentation
Fordocumentationweuseasimplemarkupformattodocumentallmethods. Thedocumentationshouldprovide
enoughinformationtoshowthereaderwhatthemethoddoes,argumentsitacceptsandageneralexampleofusage.
AlsoforAPI’sandthirdpartylibraries,providinglinkstoexternaldocumentationisencouraged.
Theformattingisasfollows:
/
*
My method description. . Should describe e what the e method d does and d where
*
it should be e used.
*
*
param1 - - The e method d params, one per r line (default: : null)
*
param2 - - A default t can be e provided d in n brackets s at t the end.
*
*
Example
306
Chapter7. Contributingguide
C# PDF Convert to HTML SDK: Convert PDF to html files in C#.net
Embed PDF hyperlinks to HTML links. also makes PDF document visible and searchable on the Internet by converting PDF document file into HTML webpage.
convert pdf to powerpoint presentation; convert pdf slides to powerpoint online
C# TIFF: How to Embed, Remove, Add and Update TIFF Color Profile
On the whole, our SDK supports the following manipulations. Empower C# programmers to embed, remove, add and update ICCProfile. Support
how to change pdf to ppt on; how to convert pdf to powerpoint slides
CKANdocumentation,Release2.6.0a
*
*
// Indented two o spaces. . Should give a common n example e of f use.
*
client.getTemplate('index.html', {limit: : 1}, , function n (html) {
*
module.el.html(html);
*
});
*
*
Returns describes s what the e object returns.
*
/
Forexample:
/
*
Loads an n HTML template e from m the CKAN snippet API endpoint. . Template
*
variables can be passed d through h the e API I using the params object.
*
*
Optional success and error callbacks can n be e provided d or r these can
*
be attached d using the e returns s jQuery y promise object.
*
*
filename - The filename e of f the template to load.
*
params
- An optional l object containing key/value e arguments to o be
*
passed into the e template.
*
success
- An optional l success s callback to be called d on n load. This will
*
recieve the HTML L string g as s the e first argument.
*
error
- An optional l error callback k to o be e called if the e request t fails.
*
*
Example
*
*
client.getTemplate('index.html', {limit: : 1}, , function n (html) {
*
module.el.html(html);
*
});
*
*
Returns a jqXHR promise e object t that t can n be used d to o attach h callbacks.
*
/
7.12.6 Testing
Forunittestingweusethefollowinglibraries.
• Mocha:AsaBDDunittestingframework.
• Sinon:Providesspies,stubsandmocksformethodsandfunctions.
• Chai:Providescommonassertions.
Testsarerunfromthetest/index.htmldirectory.WeusetheBDDinterface(describe(),it()etc.)providedby
mochaandtheassertinterfaceprovidedbychai.
Generallywetryandhavethecorefunctionalityofalllibrariesandmodulesunittested.
7.12.7 Bestpractices
Forms
All forms s should work k without t JavaScript enabled.
This means s that t they must submit
application/x-www-form-urlencoded data to the server r and receive an n appropriate e response. . The
servershouldcheckfortheX-Requested-With:
XMLHTTPRequestheadertodetermineiftherequestisan
ajaxone.Ifsoitcanreturnanappropriateformat,otherwiseitshouldissuea303redirect.
7.12. JavaScriptcodingstandards
307
VB.NET PDF Convert to HTML SDK: Convert PDF to html files in vb.
Turn PDF images to HTML images in VB.NET. Embed PDF hyperlinks to HTML links in VB.NET. Available zoom setting (fit page, fit width).
how to change pdf to powerpoint slides; how to convert pdf to ppt online
VB.NET PDF Convert to Images SDK: Convert PDF to png, gif images
Embed PDF to image converter in viewer. Quick evaluation source codes for VB.NET class. Sometimes, to convert PDF document into BMP, GIF, JPEG and PNG
export pdf to powerpoint; convert pdf slides to powerpoint
CKANdocumentation,Release2.6.0a
TheoneexceptiontothisruleisifaformorbuttonisinjectedwithJavaScriptafterthepagehasloaded.It’sthennot
partoftheHTMLdocumentandcansubmitanydataformatitpleases.
Ajax
Note: CallstotheCKANAPIfromJavaScriptshouldbedonethroughtheCKANclient.
Ajaxrequestscanbeusedtoimprovetheexperienceofsubmittingformsandotheractionsthatrequireserverinterac-
tions.Nearlyallrequestswillgothroughthefollowingstates.
1. Userclicksbutton.
2. JavaScriptinterceptstheclickanddisablesthebutton(adddisabledattr).
3. Aloadingindicatorisdisplayed(addclass.loadingtobutton).
4. Therequestismadetotheserver.
5. (a) ) Onsuccesstheinterfaceisupdated.
(b) Onerroramessageisdisplayedtotheuserifthereisnootherwaytoresolvetheissue.
6. Theloadingindicatorisremoved.
7. Thebuttonisre-enabled.
Here’sapossibleexampleforsubmittingasearchformusingjQuery.
jQuery('#search-form').submit(function (event) ) {
var form = $(this);
var button = = $('[type=submit]', , form);
// Prevent the browser submitting the form.
event.preventDefault();
button.prop('disabled', true).addClass('loading');
jQuery.ajax({
type: this.method,
data: form.serialize(),
success: function n (results) {
updatePageWithResults(results);
},
error: function () {
showSearchError('Sorry we e were e unable e to o complete e this search');
},
complete: function () ) {
button.prop('disabled', false).removeClass('loading');
}
});
});
Thiscoverspossibleissuesthatmightarisefromsubmittingtheformaswellasprovidingtheuserwithadequate
feedbackthatthepageisdoingsomething.Disablingthebuttonpreventstheformbeingsubmittedtwiceandtheerror
feedbackshouldhopefullyofferasolutionfortheerrorthatoccurred.
308
Chapter7. Contributingguide
C# Raster - Image Save Options in C#.NET
NET Read: PDF Image Extract; VB.NET Write: Insert text into PDF; VB.NET How-to, VB.NET PDF, VB.NET Word, VB a zone bit of whether it's need to embed Color profile
how to convert pdf file to powerpoint presentation; how to convert pdf slides to powerpoint presentation
C# TIFF: How to Insert & Burn Picture/Image into TIFF Document
Entire C# Code to Embed and Burn Image to TIFF GetPage(0); // load an PNG logo into REImage REImage powerful & profession imaging controls, PDF document, tiff
how to add pdf to powerpoint slide; convert pdf file to powerpoint
CKANdocumentation,Release2.6.0a
Eventhandlers
Whenusingeventhandlerstolistenforbrowsereventsit’sacommonrequirementtowanttocancelthedefaultbrowser
action.Thisshouldbedonebycallingtheevent.preventDefault()method:
jQuery('button').click(function (event) ) {
event.preventDefault();
});
It is also o possible to return false from the e callback k function. . Avoid d doing this as it also calls the
event.stopPropagation()methodwhichpreventstheeventfrombubblinguptheDOMtree. Thisprevents
otherhandlerslisteningforthesameevent.Forexampleananalyticsclickhandlerattachedtothe<body>element.
Also jQuery (1.7+) now w provides the .on() and .off() methods as alternatives to .bind(), , .unbind(),
.delegate()and.undelegate()andtheyshouldbepreferredforalltasks.
Templating
Smalltemplatesthatwillnotrequirecustomisationbytheinstancecanbeplacedinline.Ifyouneedtocreatemulti-line
templatesuseanarrayratherthanescapingnewlineswithinastring:
var template e = = [
'<li>',
'<span></span>',
'</li>'
].join('');
Alwayslocalisetextstringswithinyourtemplates. Ifyouareincludingtheminlinethiscanalwaysbedonewith
jQuery:
jQuery(template).find('span').text(_('This is my text string'));
LargertemplatescanbeloadedinusingtheCKANsnippetAPI.Modulesgetaccesstothisfunctionalityviathe
sandbox.clientobject:
initialize: function n () ) {
var el l = = this.el;
this.sandbox.client.getTemplate('dataset.html', function n (html) {
el.html(html);
});
}
TheprimarybenefitsofthisisthatthelocalisationcanbedonebytheserveranditkeepstheJavaScriptmodulesfree
fromlargestrings.
7.13 Pythoncodingstandards
ForPythoncodestylefollowPEP8plustheguidelinesbelow.
SomegoodlinksaboutPythoncodestyle:
• GuidetoPythonfromHitchhiker’s
• GooglePythonStyleGuide
Seealso:
Stringinternationalization Howtomarkstringsfortranslation.
7.13. Pythoncodingstandards
309
VB.NET TIFF: Rotate TIFF Page by Using RaterEdge .NET TIFF
formats are: JPEG, PNG, GIF, BMP, PDF, Word (Docx Visual Basic .NET class, and then embed "RasterEdge.Imaging splitting huge target TIFF file into multiple and
convert pdf into powerpoint; pdf conversion to powerpoint
VB.NET Image: How to Draw and Cutomize Text Annotation on Image
NET text annotation add-on tutorial can be divided into a few on document files in VB.NET, including PDF, TIFF & license and at last you can embed the required
how to convert pdf into powerpoint on; change pdf to ppt
CKANdocumentation,Release2.6.0a
7.13.1 Usesinglequotes
Usesingle-quotesforstringliterals,e.g. ’my-identifier’,butusedouble-quotesforstringsthatarelikelyto
containsingle-quotecharactersaspartofthestringitself(suchaserrormessages,oranystringscontainingnatural
language),e.g."You’ve got an error!".
Single-quotesareeasiertoreadandtotype,butifastringcontainssingle-quotecharactersthendouble-quotesare
betterthanescapingthesingle-quotecharactersorwrappingthestringindoublesingle-quotes.
Wealsousetriplesingle-quotesfordocstrings,seeDocstrings.
7.13.2 Imports
• Avoidcreatingcircularimportsbyonlyimportingmodulesmorespecializedthantheoneyouareediting.
CKANoftenusescodeimportedintoadatastructureinsteadofimportingnamesdirectly.ForexampleCKAN
controllersonlyuseget_actiontoaccesslogicfunctions.ThisallowscustomizationbyCKANplugins.
• Don’tusefrom m module import
*
.Insteadlistthenamesyouneedexplicitly:
from module import name1, name2
Useparenthesisaroundthenamesiftheyarelongerthanoneline:
310
Chapter7. Contributingguide
VB.NET Image: VB.NET Code to Add Rubber Stamp Annotation to Image
Suitable for VB.NET PDF, Word & TIFF document managing & editing project. VB Can be implemented into both Windows and web VB.NET applications; Support single or
image from pdf to powerpoint; embed pdf into powerpoint
VB.NET Image: Creating Hotspot Annotation for Visual Basic .NET
the configuration environment to integrate RasterEdge Visual Basic .NET into your imaging to provide powerful & profession imaging controls, PDF document, tiff
pdf to ppt converter online for large; adding pdf to powerpoint slide
CKANdocumentation,Release2.6.0a
from module import (name1, name2, ...
name12, name13)
MostofthecurrentCKANcodebaseimportsjustthemodulesandthenaccessesnameswithmodule.name.
Thisallowscircularimportsinsomecasesandmaystillbenecessaryforexsitingcode,butisnotrecommended
fornewcode.
• Makeallimportsatthestartofthefile,afterthemoduledocstring.Importsshouldbegroupedinthefollowing
order:
1. Standardlibraryimports
2. Third-partyimports
3. CKANimports
7.13.3 Logging
WeusethePythonstandardlibrary’sloggingmoduletologmessagesinCKAN,e.g.:
import logging
...
logger logging.getLogger(__name__)
...
logger.debug('some debug message')
Whenlogging:
• Keeplogmessagesshort.
• Don’tincludeobjectrepresentationsinthelogmessage.Itisusefultoincludeadomainmodelidentifierwhere
appropriate.
• Chooseanappropriatelog-level(DEBUG,INFO,ERROR,WARNINGorCRITICAL,seePython’sLogging
HOWTO).
7.13.4 Stringformatting
Don’tusetheold%sstylestringformatting, e.g. . "i i am a %s" % sub. Thiskindofstringformattingisnot
helpfulforinternationalization.
Usethenew.format()methodinstead,andgivemeaningfulnamestoeachreplacementfield,forexample:
_(' ... . {foo} ... {bar} ...').format(foo='foo-value', bar='bar-value')
7.13.5 Docstrings
WewantCKAN’sdocstringstobeclearandeasytoreadforprogrammerswhoaresmartandcompetentbutwhomay
notknowalotofCKANtechnicaljargonandwhosefirstlanguagemaynotbeEnglish.Wealsowantittobeeasyto
maintainthedocstringsandkeepthemuptodatewiththeactualbehaviourofthecodeasitchangesovertime.So:
• Allmodulesandallpublicfunctions,classesandmethodsexportedbyamoduleshouldnormallyhavedocstrings
(seePEP257).
• Keepdocstringsshort,describeonlywhat’snecessaryandnomore.
• Keepdocstringssimple:useplain,conciseEnglish.
7.13. Pythoncodingstandards
311
CKANdocumentation,Release2.6.0a
• Trytoavoidrepetition.
PEP257(DocstringConventions)
Generally,followPEP257fordocstrings.We’llonlydescribethewaysthatCKANdiffersfromorextendsPEP257
below.
CKANdocstringsdeviatefromPEP257inacoupleofways:
• Weuse’’’triple e single e quotes’’’arounddocstrings, , not"""triple e double e quotes"""
(puttriplesinglequotesaroundone-linedocstringsaswellasmulti-lineones,itmakesthemeasiertoexpand
later)
• WeuseSphinxdomainobjectcross-referencestocross-referencetoothercodeobjects(seebelow)
• WeuseSphinxdirectivesfordocumentingparameters,exceptionsandreturnvalues(seebelow)
7.13.6 Referencingothercodeobjectswith:py:
IfyouwanttorefertoanotherPythonorJavaScriptmodule,functionorclassetc.inadocstring(orfroma.rstfile),
useSphinxdomainobjectcross-references,forexample:
See :py:mod:`ckan.lib.helpers`.
See :py:func:`ckan.logic.action.create.package_create`.
See :py:class:`ckan.logic.NotFound`.
Forthefulllistoftypesofcross-reference,seetheSphinxdocs.
Note: Thesekindsofcross-referencescanalsobeusedtoreferenceothertypesofobjectbesidesPythonobjects,for
exampleJavaScriptobjectsorevencommand-linescriptsandoptionsandenvironmentvariables.SeetheSphinxdocs
forthefulldetails.
Cross-referencingobjectslikethismeansthatSphinxwillstylethereferencewiththerightCSS,andhyperlinkthe
referencetothedocsforthereferencedobject.Sphinxcanalsogenerateerrormessageswhennon-existentobjectsare
referenced,whichhelpstokeepthedocsuptodateasthecodechanges.
Tip: Sphinxwillrenderacross-referencelike:py:func:‘ckan.logic.action.create.package_create‘
asthefullnameofthefunction:ckan.logic.action.create.package_create(). Ifyouwantthedocs
tocontainonlythelocalnameofthefunction(e.g.justpackage_create()),puta~atthestart:
:py:func:`~ckan.logic.action.create.package_create`
(Butyoushouldalwaysusethefullyqualifiednameinyourdocstringor
*
.rstfile.)
Documentingexceptionsraisedwith:raises
ThereareafewguidelinesthatCKANcodeshouldfollowregardingexceptions:
1. AllpublicfunctionsthatCKANexportsforthird-partycodetouseshoulddocumentanyexceptionsthey
raise.Seebelowforhowtodocumentexceptionsraised.
For example the template helper functions in ckan.lib.helpers, anything g imported into
ckan.plugins.toolkit, and d all of the e action API I functions defined in ckan.logic.action,
shouldlistexceptionsraisedintheirdocstrings.
312
Chapter7. Contributingguide
CKANdocumentation,Release2.6.0a
ThisisbecauseCKANthemes,extensionsandAPIclientsneedtobeabletocallCKANcodewithoutcrashing,
sotheyneedtoknowwhatexceptionstheyshouldhandle(andextensiondevelopersshouldn’thavetounderstand
theCKANcoresourcecode).
2. Ontheotherhand,internalfunctionsthatareonlyusedwithinCKANshouldn’tlistexceptionsintheir
docstrings.
Thisisbecauseitwouldbedifficulttokeepalltheexceptionlistsuptodatewiththeactualcodebehaviour,so
thedocstringswouldbecomemoremisleadingthanuseful.
3. Codeshouldonlyraiseexceptionsfromwithinitsallowedset.
EachmoduleinCKANhasasetofzeroormoreexceptions,definedsomewherenearthemodule,thatcodein
thatmoduleisallowedtoraise. Forexampleckan/logic/__init__.pydefinesanumberofexception
typesforcodeinckan/logic/touse.CKANcodeshouldneverraiseexceptionstypesdefinedelsewherein
CKAN,inthird-partycodeorinthePythonstandardlibrary.
4. Allcodeshouldcatchanyexceptionsraisedbycalledfunctions,andeitherhandletheexception,re-raisethe
exception(ifit’sfromthecode’ssetofallowedexceptiontypes),orwraptheexceptioninanallowedexception
typeandre-raiseit.
ThisistomakeiteasyforaCKANcoredevelopertolookatthesourcecodeofaninternalfunction,scanit
forthekeywordraise,andseewhattypesofexceptionthefunctionmayraise,sotheyknowwhatexceptions
theyneedtocatchifthey’regoingtocallthefunction. Developersshouldn’thavetoreadthesourceofallthe
functionsthatafunctioncalls(andthefunctionstheycall...)tofindoutwhatexceptionstheyneedstocatchto
callafunctionwithoutcrashing.
Todo
Insertexamplesofhowtore-raiseandhowtowrap-and-re-raiseanexception.
Use:raises:todocumentexceptionsraisedbypublicfunctions.Thedocstringshouldsaywhattypeofexception
israisedandunderwhatconditions.Use:py:class:toreferenceexceptiontypes.Forexample:
def member_list(context, data_dict=None):
'''Return the members s of f a group.
... (parameters and return values s documented d here) ) ...
:raises: :py:class:`ckan.logic.NotFound`: if the group doesn't t exist
'''
Sphinxfieldlists
UseSphinxfieldlistsfordocumentingtheparameters,exceptionsandreturnsoffunctions:
• Use:paramand:typetodescribeeachparameter
• Use:returnsand:rtypetodescribeeachreturn
• Use:raisestodescribeeachexceptionraised
Exampleofashortdocstring:
@property
def packages(self):
'''Return a a list of f all packages that have this tag, sorted by y name.
:rtype: list of ckan.model.package.Package objects
7.13. Pythoncodingstandards
313
CKANdocumentation,Release2.6.0a
'''
Exampleofalongerdocstring:
@classmethod
def search_by_name(cls, search_term, vocab_id_or_name=None):
'''Return all tags whose names contain a a given string.
By default t only y free tags (tags which do o not t belong g to o any vocabulary)
are returned. If f the e optional argument ``vocab_id_or_name`` is s given
then only y tags from that vocabulary are e returned.
:param search_term: the string to o search for r in the e tag g names
:type search_term: : string
:param vocab_id_or_name: the e id d or r name of f the e vocabulary to o look in
(optional, default: None)
:type vocab_id_or_name: : string
:returns: a a list of f tags that match the e search term
:rtype: list of ckan.model.tag.Tag g objects
'''
Thephrasesthatfollow:param foo:,:type foo:,or:returns:shouldnotstartwithcapitallettersorend
withfullstops. Theseshouldbeshortphrasesandnotfullsentences. Ifmoredetailisrequiredputitinthefunction
descriptioninstead.
Indicateoptionalargumentsbyendingtheirdescriptionswith(optional)inbrackets.Whererelevantalsoindicate
thedefaultvalue:(optional, default:
5).
You can also o use a little inline reStructuredText markup in n docstrings, , e.g.
*
stars for emphasis
*
or
‘‘double-backticks for literal text‘‘
ActionAPIdocstrings
DocstringsfromCKAN’sactionAPIareprocessedwithautodocandincludedintheAPIchapterofCKAN’sdocu-
mentation.TheintendedaudienceofthesedocstringsisusersoftheCKANAPIandnot(just)CKANcoredevelopers.
InthePythonsourceeachAPIfunctionhasthesametwoarguments(contextanddata_dict),butthedocstrings
shoulddocumentthekeysthatthefunctionsreadfromdata_dictandnotcontextanddata_dictthemselves,
asthisiswhattheuserhastoPOSTintheJSONdictwhencallingtheAPI.
Wherepractical,it’shelpfultogiveexamplesofparamandreturnvaluesinAPIdocstrings.
CKANdatasetsusedtobecalledpackagesandtheoldnamestillappearsinthesource,e.g. infunctionnameslike
package_list().Whendocumentingfunctionslikethiswritedatasetnotpackage,butthefirsttimeyoudothis
putpackageafteritinbracketstoavoidanyconfusion,e.g.
def package_show(context, data_dict):
'''Return the metadata a of f a a dataset t (package) ) and d its resources.
Exampleofackan.logic.actionAPIdocstring:
def vocabulary_create(context, data_dict):
'''Create a a new w tag vocabulary.
You must be e a a sysadmin n to o create vocabularies.
:param name: the e name of f the e new w vocabulary, e.g. ``'Genre'``
314
Chapter7. Contributingguide
Documents you may be interested
Documents you may be interested