Return to site

Babel: Choice 1 0

broken image


Table of Contents

  • Code Blocks
  • Source Code Execution
  1. Express VPN Best for privacy. Number of IP addresses: 30,000 Number of servers: 3,000+ 3 months free with 1-year plan.
  2. BABEL offers you direct access to singles worldwide. More than 25 000 people log on BABEL every day for dialogue and exchange with men and women from all backgrounds. A FREE APP FOR ALL SINGLES Whatever your situation, all profiles are welcome to socialize on BABEL! To protect your identity, BABEL is an anonymous app.

Introduction

Babel is about letting many different languages work together.Programming languages live in blocks inside natural languageOrg-mode documents. A piece of data may pass from a table to aPython code block, then maybe move on to an R code block, andfinally end up embedded as a value in the middle of a paragraph orpossibly pass through a gnuplot code block and end up as a plotembedded in the document.

Babel Guest House apartment offers a pleasant stay in Santa Marta for up to 6 guests. This accommodation consists of 2 bedrooms and 2 bathrooms. The venue is located in Centro Historico district, about 1.8 km from Parroquia de Nuestra Senora de la Medalla Milagrosa. Cerro Kennedy can be reached in 20 minutes by foot. My question is: What's the difference between babel-preset-stage-0,babel-preset-stage-1,babel-preset-stage-2 and babel-preset-stage-3, and what's the best choice when we develop with ES6? Ecmascript-6 babel.

Through extending Org-mode with several features for editingexporting and executing source code Babel turns Org-mode into a toolfor both Literate Programming and Reproducible Research.

Babel augments Org-mode support for code blocks by providing:

  • interactive and on-export execution of code blocks;
  • code blocks as functions that can be parameterised, refer toother code blocks, and be called remotely; and
  • export to files for literate programming.

Overview

Babel provides new features on a few different fronts, anddifferent people may want to start in different places.

Using 'src' blocks in Org mode
If you are not familiar with creating 'src' blocks in an Org-modebuffer, and moving between that buffer and the language major-modeedit buffer, then you should have a look at the relevant sectionin the Org manual and below, try it out, and come back.
Executing code
The core of Babel is its ability to execute code in Org-mode'src' blocks, taking input from other blocks and tables, withoutput to further blocks and tables. This is described startinghere.
Literate Programming
If you are a programmer writing code that you would normallyexecute in some other way (e.g. from the command line, or sourcingit into an interactive session), then a simple introduction toBabel is to place your code in blocks in an Org-mode file, and touse Babel's Literate Programming support to extract pure codefrom your Org files.

All of these use cases, as well as exhaustive documentation of thefeatures of Babel are covered in the Working with Source Codesection of the Org manual.

Initial Configuration

If you have a working Emacs installation, then getting started withBabel is a simple process.

  1. If you are running Emacs24 a current version of Org-mode withBabel is already available by default. Otherwise, it is stronglyrecommended that you update to the latest version of Org-mode bykeeping current with Org-mode development. As of Org-mode 7.0,Babel is included as part of Org-mode.
  2. Optionally activate the subset of languages that you will wantto execute with Babel. See Configure active languagesinstructions. Emacs Lisp is activated by default so this stepcan be skipped for now and all emacs-lisp examples will stillwork as expected.
  3. If you have made any changes don't forget to evaluate yourmodified .emacs.

Code Blocks

Code Blocks in Org

Babel is all about code blocks in Org-mode. If you areunfamiliar with the notion of a code block in Org-mode, where theyare called 'src' blocks, please have a look at the Org-mode manualbefore proceeding.

Code blocks in supported languages can occur anywhere in anOrg-mode file. Code blocks can be entered directly into theOrg-mode file, but it is often easier to enter code with thefunction org-edit-src-code, which is called with the keyboardshortcut, C-c '. This places the code block in a new buffer withthe appropriate mode activated.

For example, a code block of ruby code looks like this inan Org-mode file:

Code Blocks in Babel

Babel adds some new elements to code blocks. The basicstructure becomes:

language
The language of the code in the source-code block. Validvalues must be members of org-babel-interpreters.
header-arguments
Header arguments control many facets of theevaluation and output of source-code blocks. See theHeaderArguments section for a complete review of available headerarguments.
body
The source code to be evaluated. An important key-bindingis =​C-c '​. This calls =org-edit-src-code, a function that bringsup an edit buffer containing the code using the Emacs major modeappropriate to the language. You can edit your code blockas you regularly would in Emacs.

Source Code Execution

Babel: Choice 1 0 3

Babel executes code blocks for interpreted languages suchas shell, python, R, etc. by passing code to the interpreter, whichmust be installed on your system. You control what is done with theresults of execution.

Here are examples of code blocks in three different languages,followed by their output. If you are viewing the Org-mode version ofthis document in Emacs, place point anywhere inside a block and pressC-c C-c to run the code1 (and feel free to alter it!).

Ruby

In the Org-mode file:

HTML export of code:

HTML export of the resulting string:

Shell

In the Org-mode file:

HTML export of code:

HTML export of the resulting string:

R

What are the most common words in this file?In the Org-mode file:

HTML export of code:

codeorg-mode#+end_src#+begin_srcblockwithbabelthat#+name:this
85604744403835343333

ditaa

In the Org-mode file:

HTML export of code:

HTML export of the resulting image:

Capturing the Results of Code Evaluation

Babel provides two fundamentally different modes for capturingthe results of code evaluation: functional mode and scriptingmode. The choice of mode is specified by the :results headerargument.

:results value (functional mode)

The 'result' of code evaluation is the value of the laststatement in the code block. In functional mode, thecode block is a function with a return value. The returnvalue of one code block can be used as input for anothercode block, even one in a different language. In thisway, Babel becomes a meta-programming language. If the blockreturns tabular data (a vector, array or table of some sort) thenthis will be held as an Org-mode table in the buffer. Thissetting is the default.

For example, consider the following block of python code and itsoutput.

Notice that, in functional mode, the output consists of the value ofthe last statement and nothing else.

:results output (scripting mode)

In scripting mode, Babel captures the text output of thecode block and places it in the Org-mode buffer. It iscalled scripting mode because the code block contains a series ofcommands, and the output of each command is returned. Unlikefunctional mode, the code block itself has no return valueapart from the output of the commands it contains.2

Consider the result of evaluating this code block withscripting mode.

Here, scripting mode returned the text that python sent to stdout. Becausethe code block doesn't include a print() statement for the lastvalue, (2 + 2), 4 does not appear in the results.

Session-based Evaluation

For some languages, such as python, R, ruby and shell, it ispossible to run an interactive session as an 'inferior process'within Emacs. This means that an environment is created containingdata objects that persist between different source codeblocks. Babel supports evaluation of code within such sessionswith the :session header argument. If the header argument isgiven a value then that will be used as the name of the session.Thus, it is possible to run separate simultaneous sessions in thesame language.

Session-based evaluation is particularly useful for prototyping anddebugging. The function org-babel-pop-to-session can be used toswitch to the session buffer.

Once a code block is finished, it is often best to execute itoutside of a session, so the state of the environment in which itexecutes will be certain.

With R, the session will be under the control of Emacs SpeaksStatistics as usual, and the full power of ESS is thus stillavailable, both in the R session, and when switching to the R codeedit buffer with =​C-c '​=.

Arguments to Code Blocks

Babel supports parameterisation of code blocks, i.e.,arguments can be passed to code blocks, which gives themthe status of functions. Arguments can be passed to code blocks inboth functional and scripting modes.

Simple example of using a code block as a function

First let's look at a very simple example. The following sourcecode block defines a function, using python, that squares its argument.

In the Org-mode file, the function looks like this:

Now we use the source block:

(for information on thecallsyntax seeLibrary of Babel)

A more complex example using an Org-mode table as input

In this example we define a function called fibonacci-seq Pixelmator 3 8 3. , usingEmacs Lisp. The function fibonacci-seq computes a Fibonaccisequence. The function takes a single argument, in this case, areference to an Org-mode table.

Here is the Org-mode table that is passed to fibonacci-seq:

12345678910
2468101214161820

The table looks like this in the Org-mode buffer:

The Emacs Lisp source code:

Choice

In the Org-mode buffer the function looks like this:

The return value of fibonacci-seq is a table:

11235813213455
138215514437798725846765

In-line Code Blocks

Babel: Choice 1 0 Percent

Code can be evaluated in-line using the following syntax:

Code Block Body Expansion

Babel 'expands' code blocks prior to evaluation, i.e., theevaluated code comprises the code block contents augmented withcode that assigns referenced data to variables. It is possible topreview expanded contents, and also to expand code duringtangling. Expansion takes into account header arguments andvariables.

preview
C-c M-b p is bound to org-babel-expand-src-block. Itcan be used inside a code block to preview the expandedcontents. This facility is useful for debugging.
tangling

The expanded body can be tangled. Tangling this way includesvariable values that may be

  • the results of other code blocks,
  • variables stored in headline properties, or
  • tables.

Babel: Choice 1 0 4

One possible use for tangling expanded code block is for emacsinitialization. Values such as user names and passwords can bestored in headline properties or in tables. The :no-expandheader argument can be used to inhibit expansion of a code blockduring tangling.

Babel: Choice 1 0 1

Here is an example of a code block and its resulting expanded body.

The data are kept in a table:

usernamejohn-doe
passwordabc123

The code block refers to the data table:

With point inside the code block, C-c M-b p expands the contents:

A Meta-programming Language for Org-mode

Because the return value of a function written in one language can bepassed to a function written in another language, or to an Org-modetable, which is itself programmable, Babel can be used as ameta-functional programming language. With Babel, functions frommany languages can work together. You can mix and match languages,using each language for the tasks to which it is best suited.

For example, let's take some system diagnostics in the shell and graph them with R.

  1. Create a code block, using shell code, to listdirectories in our home directory, together with theirsizes. Babel automatically converts the output into an Org-modetable.
72'Desktop'
12156104'Documents'
3482440'Downloads'
2901720'Library'
57344'Movies'
16548024'Music'
120'News'
7649472'Pictures'
0'Public'
152224'Sites'
8'System'
56'bin'
3821872'mail'
10605392'src'
1264'tools'
  1. A function, written with a single line of R code, plots the datain the Org-mode table as apie-chart. Note how this code block uses the srcnameof the previous code block to obtain the data.

In the Org-mode file:

HTML export of code:

Using Code Blocks in Org Tables

In addition to passing data from tables as arguments to codeblocks, and storing results as tables, Babel can be used in athird way with Org-mode tables. First note that Org-mode's existingspreadsheet functionality allows values in cells to be computedautomatically from the values of other cells, using a #+TBLFMformula line. In this way, table computations can be carried out usingcalc and emacs lisp.

What Babel adds is the ability to use code blocks (in whateverlanguage) in the #+TBLFM line to perform the necessary computation.

Example 1: Data Summaries Using R

As a simple example, we'll fill in a cell in an Org-mode table with theaverage value of a few numbers. First, let's make some data. Thefollowing source block creates an Org-mode table filled with five randomnumbers between 0 and 1.

0.836685163900256
0.696652316721156
0.382423302158713
0.987541858805344
0.994794291909784

Now we define a source block to calculate the mean of a table column.

In the Org-mode file:

HTML export of code:

Finally, we create the table which is going to make use of the Rcode. This is done using the org-sbe ('source block evaluate') macro inthe table formula line.

In the Org-mode file:

HTML export of code:

mean
0.00

To recalculate the table formula, use C-u C-c C-c in thetable. Notice that as things stand the calculated value doesn'tchange, because the data (held in the table above namedtbl-example-data) are static. However, if you delete that data table,then the reference will be interpreted as a reference to the sourceblock responsible for generating the data; each time the table formulais recalculated the source block will be evaluated again, andtherefore the calculated average value will change.

Example 2: Babel Test Suite

While developing Babel, we used a suite of tests implementedas a large Org-mode table. To run the entire test suite we simplyevaluate the table with C-u C-c C-c: all of the tests are run,the results are compared with expectations, and the table is updatedwith results and pass/fail statistics.

Here's a sample of our test suite.

In the Org-mode file:

HTML export of code:

functionalityblockargexpectedresultspass
basic evaluationpass
emacs lispbasic-elisp244pass
shellbasic-shell66pass
rubybasic-rubyorg-babelorg-babelpass
pythonbasic-pythonhello worldhello worldpass
Rbasic-R1313pass
  • code blocks for tests

    In the Org-mode file:

    HTML export of code:

    In the Org-mode file:

    HTML export of code:

    In the Org-mode file:

    HTML export of code:

    In the Org-mode file:

    HTML export of code:

    In the Org-mode file

    HTML export of code:

    In the Org-mode file:

    HTML export of code:

The Library of Babel

(see also Org manual:Library-of-Babel)

As we saw above with the square example, once a source blockfunction has been defined it can be called using the lob notation:

But what about code blocks that you want to make available toevery Org-mode buffer?

In addition to the current buffer, Babel searches forpre-defined code block functions in the Library ofBabel. This is a user-extensible collection of ready-made sourcecode blocks for handling common tasks. One use for the Library ofBabel (not yet done!) will be to provide a choice of data graphingprocedures for data held in Org-mode tables, using languages such asR, gnuplot, asymptote, etc. If you implement something that might beof use to other Org-mode users, please consider adding it to theLibrary of Babel; similarly, feel free to request help solving aproblem using external code via Babel – there's always a chancethat other Babel users will be able to contribute some helpfulcode.

Babel comes pre-populated with the code blocks located inthe Library of Babel file – raw file at library-of-babel.org–. It is possible to add code blocks to the library from anyOrg-mode file using the org-babel-lob-ingest (bound to C-c C-v l).

Note that it is possible to pass table values or the output of asource-code block to Library of Babel functions. It is also possibleto reference Library of Babel functions in arguments to code blocks.

Literate Programming

Let us change our traditional attitude to the construction ofprograms: Instead of imagining that our main task is to instruct acomputer what to do, let us concentrate rather on explaining tohuman beings what we want a computer to do.

The practitioner of literate programming can be regarded as anessayist, whose main concern is with exposition and excellence ofstyle. Such an author, with thesaurus in hand, chooses the names ofvariables carefully and explains what each variable means. He or shestrives for a program that is comprehensible because its concepts havebeen introduced in an order that is best for human understanding,using a mixture of formal and informal methods that reinforce eachother.

– Donald Knuth

Babel supports Literate Programming (LP) by allowing the act ofprogramming to take place inside of Org-mode documents. The Org-modefile can then be exported (woven in LP speak) to HTML or LaTeX forconsumption by a human, and the embedded source code can be extracted(tangled in LP speak) into structured source code files forconsumption by a computer.

To support these operations Babel relies on Org-mode's existingexporting functionality for weaving of documentation, and on theorg-babel-tangle function which makes use of Nowebreference syntaxfor tangling of code files.

The following example demonstrates the process of tangling inBabel.

Simple Literate Programming Example (Noweb syntax)

Tangling functionality is controlled by the tangle family of tangleheader arguments. These arguments can be used to turn tangling on oroff (the default), either for the code block or the Org-modeheading level.

The following code blocks demonstrate how to tangle them into asingle source code file using org-babel-tangle.

The following two code blocks have no tangle header argumentsand so will not, by themselves, create source code files. They areincluded in the source code file by the third code block, whichdoes have a tangle header argument.

In the Org-mode file:

HTML export of code:

In the Org-mode file

HTML export of code:

The third code block does have a tangle header argumentindicating the name of the file to which the tangled source code willbe written. It also has Noweb style references to the two previouscode blocks. These references will be expanded during tanglingto include them in the output file as well.

In the Org-mode file: Deep freeze 7 2019. https://ltkyj.over-blog.com/2020/12/bootstrap-studio-4-3-professional.html.

HTML export of code:

Calling org-babel-tangle will result in the following shell sourcecode being written to the hello.sh file:

In addition, the following syntax can be used to insert the resultsof evaluating a code block, in this case one named example-block.

Any optional arguments can be passed to example-block() by placing thearguments inside the parentheses following the convention defined whencalling source block functions (see the Library of babel). For example,

sets the value of argument 'a' equal to '9'. Note thatthese arguments are not evaluated in the current source-codeblock but are passed literally to example-block().

Emacs Initialization with Babel

Babel has special support for embedding your Emacs initializationinto Org-mode files. The org-babel-load-file function can be usedto load the Emacs Lisp code blocks embedded in a literateOrg-mode file in the same way that you might load a regular Emacs Lispfile, such as .emacs.

This allows you to make use of the nice features of Org-mode, such as folding, tags,notes, HTML export, etc., to organize and maintain your Emacs initialization.

To try this out, either see the simple Literate Emacs Initializationexample, or check out the Babel Literate Programming version ofPhil Hagelberg's excellent emacs-starter-kit available atOrg-babel-emacs-starter-kit.

  • Literate Emacs Initialization

    For a simple example of usage, follow these 5 steps:

    1. create a directory named .emacs.d in the base of your homedirectory;

    2. checkout the latest version of Org-mode into the src subdirectoryof this new directory;

    3. place the following code block in a file called init.el in your Emacsinitialization directory (~/.emacs.d).

    4. implement all of your Emacs customizations inside of Emacs Lispcode blocks embedded in Org-mode files in this directory;and
    5. re-start Emacs to load the customizations.

Reproducible Research

An article about computational science in a scientific publication isnot the scholarship itself, it is merely advertising of thescholarship. The actual scholarship is the complete softwaredevelopment environment and the complete set of instructions whichgenerated the figures.

– D. Donoho

Reproducible Research (RR) is the practice of distributing, along witha research publication, all data, software source code, and toolsrequired to reproduce the results discussed in the publication. Assuch the RR package not only describes the research and its results,but becomes a complete laboratory in which the research can bereproduced and extended.

Org-mode already has exceptional support for exporting to HTML andLaTeX. Babel makes Org-mode a tool for RR by activating thedata and code blocks embedded in Org-mode documents; theentire document becomes executable. This makes it possible, and natural, todistribute research in a format that encourages readers to recreateresults and perform their own analyses.

One notable existing RR tool is Sweave, which provides a mechanism forembedding R code into LaTeX documents. Sweave is a matureand very useful tool, but we believe that Babel has severaladvantages:

  • it supports multiple languages (we're not aware of other RR tools that do this);
  • the export process is flexible and powerful, including HTML as atarget in addition to LaTeX; and
  • the document can make use of Org-mode features that support projectplanning and task management.

Footnotes:

1

Calling C-c C-o on a code block will open theblock's results in a separate buffer.





broken image