JavaScript 69 – progetto di un linguaggio di programmazione – 4

Continuo da qui, copio qui.
Post da vedersi come continuazione dei 3 precedenti 😎

What we have built is an interpreter. During evaluation, it acts directly on the representation of the program produced by the parser.

Compilation is the process of adding another step between the parsing and the running of a program, which transforms the program into something that can be evaluated more efficiently by doing as much work as possible in advance. For example, in well-designed languages it is obvious, for each use of a variable, which variable is being referred to, without actually running the program. This can be used to avoid looking up the variable by name every time it is accessed and to directly fetch it from some predetermined memory location.

Traditionally, compilation involves converting the program to machine code, the raw format that a computer’s processor can execute. But any process that converts a program to a different representation can be thought of as compilation.

It would be possible to write an alternative evaluation strategy for Egg, one that first converts the program to a JavaScript program, uses new Function to invoke the JavaScript compiler on it, and then runs the result. When done right, this would make Egg run very fast while still being quite simple to implement.

Ma no, non si fa, a meno che, dice Marijn: If you are interested in this topic and willing to spend some time on it, I encourage you to try to implement such a compiler as an exercise.

When we defined if and while, you probably noticed that they were more or less trivial wrappers around JavaScript’s own if and while. Similarly, the values in Egg are just regular old JavaScript values.

If you compare the implementation of Egg, built on top of JavaScript, with the amount of work and complexity required to build a programming language directly on the raw functionality provided by a machine, the difference is huge. Regardless, this example hopefully gave you an impression of the way programming languages work.

And when it comes to getting something done, cheating is more effective than doing everything yourself. Though the toy language in this chapter doesn’t do anything that couldn’t be done better in JavaScript, there are situations where writing small languages helps get real work done.

Such a language does not have to resemble a typical programming language. If JavaScript didn’t come equipped with regular expressions, you could write your own parser and evaluator for such a sublanguage.

Or imagine you are building a giant robotic dinosaur and need to program its behavior. JavaScript might not be the most effective way to do this. You might instead opt for a language that looks like this:

behavior walk
  perform when
    destination ahead
    move left-foot
    move right-foot

behavior attack
  perform when
    Godzilla in-view
    fire laser-eyes
    launch arm-rockets

This is what is usually called a domain-specific language, a language tailored to express a narrow domain of knowledge. Such a language can be more expressive than a general-purpose language because it is designed to express exactly the things that need expressing in its domain and nothing else.


SciPy – 3 – creare arrays

Continuo da qui, copio qui.

You have now seen how to inspect your array and to make adjustments in the data type of it, but you haven’t explicitly seen hwo to create arrays. You should already know that you can use np.array() to to this, but there are other routines for array creation that you should know about: np.eye() and np.identity().

The np.eye() function allows you to create a square matrix with dimensions that are equal to the positive integer that you give as an argument to the function. The entries are generally filled with zeros, only the matrix diagonal is filled with ones. The np.identity() function works and does the same and also returns an identity array.

However, note that np.eye() can take an additional argument k that you can specify to pick the index of the diagonal that you want to populate with ones.

Nota per me che a volte la memoria… 😉: qui si trovano gli indici delle funzioni di NumPy e di SciPy, da bookmarkare prima di subito 😊

Other array creation functions that will most definitely come in handy when you’re working with the matrices for linear algebra are the following:

  • The np.arange() function creates an array with uniformly spaced values between two numbers. You can specify the spacing between the elements,
  • The latter also holds for np.linspace(), but with this function you specify the number of elements that you want in your array.
  • Lastly, the np.logspace() function also creates arrays with uniformly spaced values, but this time in a logarithmic scale. This means that the spacing is now logarithmical: two numbers are evenly spaced between the logarithms of these two to the base of 10.

Adesso dice la prof Karlijn: Now that you have refreshed your memory and you know how to handle the data types of your arrays, it’s time to also tackle the topic of indexing and slicing. Prossimamente.


JavaScript 68 – progetto di un linguaggio di programmazione – 3

Continuo da qui, copio qui.

Sempre alle prese con l’esercizio lungo 😎 Il post è comprensibile solo come continuazione dei fue precedenti.

The environment accepted by evaluate is an object with properties whose names correspond to variable names and whose values correspond to the values those variables are bound to. Let’s define an environment object to represent the global scope.

To be able to use the if construct we just defined, we must have access to Boolean values. Since there are only two Boolean values, we do not need special syntax for them. We simply bind two variables to the values true and false and use those.

var topEnv = Object.create(null);

topEnv["true"] = true;
topEnv["false"] = false;

We can now evaluate a simple expression that negates a Boolean value.

var prog = parse("if(true, false, true)");
console.log(evaluate(prog, topEnv));

Per eseguire lo script nel terminale occorre raccogliere tutti i pezzi di codice visti finora, io li ho messi in p-egg.js, non lo riporto perché sta diventanto lungo:

To supply basic arithmetic and comparison operators, we will also add some function values to the environment. In the interest of keeping the code short, we’ll use new Function to synthesize a bunch of operator functions in a loop, rather than defining them all individually.

["+", "-", "*", "/", "==", "<", ">"].forEach(function(op) {
  topEnv[op] = new Function("a, b", "return a " + op + " b;");

A way to output values is also very useful, so we’ll wrap console.log in a function and call it print.

topEnv["print"] = function(value) {
  return value;

That gives us enough elementary tools to write simple programs. The following run function provides a convenient way to write and run them. It creates a fresh environment and parses and evaluates the strings we give it as a single program.

function run() {
  var env = Object.create(topEnv);
  var program = Array.prototype.slice
    .call(arguments, 0).join("\n");
  return evaluate(parse(program), env);

The use of is a trick to turn an array-like object, such as arguments, into a real array so that we can call join on it. It takes all the arguments given to run and treats them as the lines of a program.

run("do(define(total, 0),",
    "   define(count, 1),",
    "   while(<(count, 11),",
    "         do(define(total, +(total, count)),",
    "            define(count, +(count, 1)))),",
    "   print(total))");

Aggiorno il file p-egg.js inserendo le ultime aggiunte. Notare che le istruzioni di console.log precedenti vengono commentate.

This is the program we’ve seen several times before, which computes the sum of the numbers 1 to 10, expressed in Egg. It is clearly uglier than the equivalent JavaScript program but not bad for a language implemented in less than 150 lines of code.

A programming language without functions is a poor programming language indeed.

Fortunately, it is not hard to add a fun construct, which treats its last argument as the function’s body and treats all the arguments before that as the names of the function’s arguments.

specialForms["fun"] = function(args, env) {
  if (!args.length)
    throw new SyntaxError("Functions need a body");
  function name(expr) {
    if (expr.type != "word")
      throw new SyntaxError("Arg names must be words");
  var argNames = args.slice(0, args.length - 1).map(name);
  var body = args[args.length - 1];

  return function() {
    if (arguments.length != argNames.length)
      throw new TypeError("Wrong number of arguments");
    var localEnv = Object.create(env);
    for (var i = 0; i < arguments.length; i++)
      localEnv[argNames[i]] = arguments[i];
    return evaluate(body, localEnv);

Functions in Egg have their own local environment, just like in JavaScript. We use Object.create to make a new object that has access to the variables in the outer environment (its prototype) but that can also contain new variables without modifying that outer scope.

The function created by the fun form creates this local environment and adds the argument variables to it. It then evaluates the function body in this environment and returns the result.

run("do(define(plusOne, fun(a, +(a, 1))),",
    "   print(plusOne(10)))");

run("do(define(pow, fun(base, exp,",
    "     if(==(exp, 0),",
    "        1,",
    "        *(base, pow(base, -(exp, 1)))))),",
    "   print(pow(2, 10)))");

Dopo l’aggiornamento di p-egg.js ecco

😊 😎 😊 manca solo un ultimo post 😊


JavaScript 67 – progetto di un linguaggio di programmazione – 2

Continuo da qui, copio qui.

Dov’ero rimasto con il post precedente? Ah, sì, continuo 😊

Il valutatore
What can we do with the syntax tree for a program? Run it, of course! And that is what the evaluator does. You give it a syntax tree and an environment object that associates names with values, and it will evaluate the expression that the tree represents and return the value that this produces.

function evaluate(expr, env) {
  switch(expr.type) {
    case "value":
      return expr.value;

    case "word":
      if ( in env)
        return env[];
        throw new ReferenceError("Undefined variable: " +
    case "apply":
      if (expr.operator.type == "word" &&
 in specialForms)
        return specialForms[](expr.args,
      var op = evaluate(expr.operator, env);
      if (typeof op != "function")
        throw new TypeError("Applying a non-function.");
      return op.apply(null, {
        return evaluate(arg, env);

var specialForms = Object.create(null);

The evaluator has code for each of the expression types. A literal value expression simply produces its value. (For example, the expression 100 just evaluates to the number 100.) For a variable, we must check whether it is actually defined in the environment and, if it is, fetch the variable’s value.

Applications are more involved. If they are a special form, like if, we do not evaluate anything and simply pass the argument expressions, along with the environment, to the function that handles this form. If it is a normal call, we evaluate the operator, verify that it is a function, and call it with the result of evaluating the arguments.

We will use plain JavaScript function values to represent Egg’s function values. We will come back to this later, when the special form called fun is defined.

The recursive structure of evaluate resembles the similar structure of the parser. Both mirror the structure of the language itself. It would also be possible to integrate the parser with the evaluator and evaluate during parsing, but splitting them up this way makes the program more readable.

This is really all that is needed to interpret Egg. It is that simple. But without defining a few special forms and adding some useful values to the environment, you can’t do anything with this language yet.

Forme speciali
The specialForms object is used to define special syntax in Egg. It associates words with functions that evaluate such special forms. It is currently empty. Let’s add some forms.

specialForms["if"] = function(args, env) {
  if (args.length != 3)
    throw new SyntaxError("Bad number of args to if");

  if (evaluate(args[0], env) !== false)
    return evaluate(args[1], env);
    return evaluate(args[2], env);

Egg’s if construct expects exactly three arguments. It will evaluate the first, and if the result isn’t the value false, it will evaluate the second. Otherwise, the third gets evaluated. This if form is more similar to JavaScript’s ternary ?: operator than to JavaScript’s if. It is an expression, not a statement, and it produces a value, namely, the result of the second or third argument.

Egg differs from JavaScript in how it handles the condition value to if. It will not treat things like zero or the empty string as false, but only the precise value false.

The reason we need to represent if as a special form, rather than a regular function, is that all arguments to functions are evaluated before the function is called, whereas if should evaluate only either its second or its third argument, depending on the value of the first.

The while form is similar.

specialForms["while"] = function(args, env) {
  if (args.length != 2)
    throw new SyntaxError("Bad number of args to while");

  while (evaluate(args[0], env) !== false)
    evaluate(args[1], env);

  // Since undefined does not exist in Egg, we return false,
  // for lack of a meaningful result.
  return false;

Another basic building block is do, which executes all its arguments from top to bottom. Its value is the value produced by the last argument.

specialForms["do"] = function(args, env) {
  var value = false;
  args.forEach(function(arg) {
    value = evaluate(arg, env);
  return value;

To be able to create variables and give them new values, we also create a form called define. It expects a word as its first argument and an expression producing the value to assign to that word as its second argument. Since define, like everything, is an expression, it must return a value. We’ll make it return the value that was assigned (just like JavaScript’s = operator).

specialForms["define"] = function(args, env) {
  if (args.length != 2 || args[0].type != "word")
    throw new SyntaxError("Bad use of define");
  var value = evaluate(args[1], env);
  env[args[0].name] = value;
  return value;


Pausa 😎
Una nota personale: io che sono vecchio & ho interessi atipici ricordo (vagamente) PL/0 di Wirth ma (sopratutto) idee del Lisp 😎. Ma sono solo considerazioni perso. Non leggete questa frase 😎


Visto nel Web – 291

Ecco, arriva, prima di subito come al solito ecco cosa ho wisto nel Web.

RELEASE: CIA ‘Pandemic’ #Vault7
#:sicurezza, spionaggio, virus
::: wikileaks

ESR Shares A Forgotten ‘Roots Of Open Source’ Moment From 1984
#:free open source software
::: Slashdot

Rewrite the Linux kernel in Rust?
link consigliato da un lettore del blog che rockz 🚀, il lettore, Jeremie 😊
#:linguaggi di programmazione
::: Maître Carnufex

Jean Sammet, Co-Designer of a Pioneering Computer Language, Dies at 89
#:protagonisti #:storia
::: Lambda the Ultimate ::: Slashdot ::: lambdageek

Theresa May’s laughable proposal to ban cryptography explained by @doctorow
#:Web, Internet #:censura
::: TimHarford ::: hronir ::: CBlengio

A che servono Wikilieaks e un’Internet libera? A pubblicare le prove del finanziamento saudita e del Qatar al terrorismo, per esempio
#:Web, Internet
::: disinformatico

We won’t make ourselves safer by making ourselves less free
#:Web, Internet #:censura
::: _arianna

A Practical Intro to Macros in Rust 1.0
#:linguaggi di programmazione
::: b3h3m0th

Differences between tmux vs screen
#:tools, componenti software
::: b3h3m0th

Can Twitter Survive By Becoming A User-Owned Co-Op?
#:social media
::: Slashdot

WWDC 2017
::: manteblog ::: mattmight ::: grumpygamer

Gaussian correlation inequality
uh! con i packages che sto vedendo adesso; si può fare (cit.)
#:linguaggi di programmazione
::: John D. Cook

Videotapes Are Becoming Unwatchable As Archivists Work To Save Them
#:innovazioni, futuro
::: Slashdot

Social Crawling
#:Web, Internet
::: MadBob

What if shell, sed, and awk were one language?
un sito che devo esplorare:
#:linguaggi di programmazione
::: igor_chubin

Want to make a site with Racket but aren’t sure how to start?
Forza Jesse! 😎 🚀
::: alamajesse

My new blog post looks in depth at the Stanford AI system that outperforms dermatologists. It’s all about the trees!
#:artificial intelligence
::: DrLukeOR

Europe’s biggest economy is uniting tech hubs to dethrone Silicon Valley
#:Web, Internet #:economia
::: businessinsider

Office #priceless
#:free open source software
::: MarcoAlici

RESTful API design with Node.js
#:linguaggi di programmazione
::: ThePracticalDev

May wants to “regulate cyberspace to prevent the spread of extremism and terrorist planning”. How, exactly?
::: fabiochiusi

3 alternatives to LibreOffice Writer
#:tools, componenti software
::: lucaciavatta

Which is strange, given all the discussions about the Singularity
#:artificial intelligence
::: ehud

Do social media & search engines lead people to narrow echo chambers? Our data suggests opposite
#:social media
::: rasmus_kleis

Desktop Apps With JavaScript: Electron And Friends
#:linguaggi di programmazione
::: ThePracticalDev

How Functional Programming Mattered
#:programmazione funzionale
::: eric_s_smith

Major websites & groups announce day of action to save #netneutrality July 12
#:Web, Internet
::: dcavedon ::: Slashdot

Charles Babbage left a computer program in Turin in 1840. Here it is.
mitico Charles 🚀 & Bruce 🚀 & Peppe 🚀
::: peppeliberti

Before Silicon Valley, New Jersey Was Tech Capital
::: Slashdot

La solita rete italiana di pirati e pedopornografi
#:media #:Web, Internet
::: manteblog

Le argentee teste d’uovo
non so come classificarlo ma ci sono un sacco di spunti
::: dropsea

Performing Google Search Using #Python
#:linguaggi di programmazione
::: Donearm

So I wrote up a blogpost explaining how secret dots printers put on documents outed NSA leaker Reality Winner
#:sicurezza, spionaggio, virus
::: ErrataRob ::: Slashdot

Great post on optimizing a non-trivial algorithm in Python with Numba
se si vuole essere efficienti con grosse moli di dati, con Python da Jake VenderPlas; NumBa meriterebbe tutta una serie di posts, continuando da umPy
#:linguaggi di programmazione
::: math_rachel

Americans From Both Political Parties Overwhelmingly Support Net Neutrality, Poll Shows
#:Web, Internet
::: Slashdot

Why didn’t I know about machma?!
#:tools, componenti software
::: Peter Bengtsson

The Public Is Growing Tired of Trump’s Tweets, Says Voter Survey
cioè Twitter non funziona politicamente? è il mio social-coso preferito, l’unica cosa in cui mi trovo d’accordo con il POTUS Donald Silvio
::: Slashdot

How Can We Optimize AI for the Greatest Good, Instead of Profit?
#:artificial intelligence
::: hronir

Facebook e WhatsApp sopra a tutti. Tinder, Snapchat e Twitter i più abbandonati. La fotografia di Blogmeter
#:social media
::: SergioGridelli

Cool little tool for designing prime numbers using a regular expression
#:programming, codice, snippet
::: wallingf

Boeing Studies Planes Without Pilots, Plans Experiments Next Year
katz! l’algoritmo 😯
#:artificial intelligence
::: Slashdot

ma il problema ovviamente sono le fake news della Rete
#:fake news, bufale
::: demartin

DARPA Funds Development of New Type of Processor
#:innovazioni, futuro
::: Slashdot

Pirate Bay Founder: We’ve Lost the Internet, It’s All About Damage Control Now
#:Web, Internet
::: Slashdot

SciPy – 2 – oggetti essenziali di NumPy

Continuo da qui, copio qui.

Un ripasso veloce di cose già viste.

An array is, structurally speaking, nothing but pointers. It’s a combination of a memory address, a data type, a shape and strides. It contains information about the raw data, how to locate an element and how to interpret an element.

The memory address and strides are important when you dive deeper into the lower-level details of arrays, while the data type and shape are things that beginners should surely know and understand. Two other attributes that you might want to consider are the data and size, which allow you to gather even more information on your array.

You’ll see in the results of the code that is included in the code chunk above that the data type of myArray is int64. When you’re intensively working with arrays, you will definitely remember that there are ways to convert your arrays from one data type to another with the astype() method.

Nevertheless, when you’re using SciPy and NumPy together, you might also find the following type handling NumPy functions very useful, especially when you’re working with complex numbers:

Try to add print() calls to see the results of the code that is given above. Then, you’ll see that complex numbers have a real and an imaginary part to them. The np.real() and np.imag() functions are designed to return these parts to the user, respectively.

Alternatively, you might also be able to use np.cast to cast an array object to a different data type, such as float in the example above.

The only thing that really stands out in difficulty in the above code chunk is the np.real_if_close() function. When you give it a complex input, such as myArray, you’ll get a real array back if the complex parts are close to zero. This last part, “close to 0”, can be adjusted by yourself with the tol argument that you can pass to the function.

OK? 😎 continua


JavaScript 66 – progetto di un linguaggio di programmazione – 1

Continuo da qui, copio qui.

Un esercizio che tutti i programmatori hanno fatto almeno una volta, o hanno pensato di farlo, o … 😊 Anche perché [t]he evaluator, which determines the meaning of expressions in a programming language, is just another program.Hal Abelson and Gerald Sussman, Structure and Interpretation of Computer Programs (SICP).

Building your own programming language is surprisingly easy (as long as you do not aim too high) and very enlightening.

The main thing I want to show in this chapter is that there is no magic involved in building your own language. I’ve often felt that some human inventions were so immensely clever and complicated that I’d never be able to understand them. But with a little reading and tinkering, such things often turn out to be quite mundane.

We will build a programming language called Egg. It will be a tiny, simple language but one that is powerful enough to express any computation you can think of. It will also allow simple abstraction based on functions.

Il parser
The most immediately visible part of a programming language is its syntax, or notation. A parser is a program that reads a piece of text and produces a data structure that reflects the structure of the program contained in that text. If the text does not form a valid program, the parser should complain and point out the error.

Our language will have a simple and uniform syntax. Everything in Egg is an expression. An expression can be a variable, a number, a string, or an application. Applications are used for function calls but also for constructs such as if or while.

To keep the parser simple, strings in Egg do not support anything like backslash escapes. A string is simply a sequence of characters that are not double quotes, wrapped in double quotes. A number is a sequence of digits. Variable names can consist of any character that is not whitespace and does not have a special meaning in the syntax.

Applications are written the way they are in JavaScript, by putting parentheses after an expression and having any number of arguments between those parentheses, separated by commas.

do(define(x, 10),
   if(>(x, 5),

The uniformity of the Egg language means that things that are operators in JavaScript (such as >) are normal variables in this language, applied just like other functions. And since the syntax has no concept of a block, we need a do construct to represent doing multiple things in sequence.

The data structure that the parser will use to describe a program will consist of expression objects, each of which has a type property indicating the kind of expression it is and other properties to describe its content.

Expressions of type “value” represent literal strings or numbers. Their value property contains the string or number value that they represent. Expressions of type “word” are used for identifiers (names). Such objects have a name property that holds the identifier’s name as a string. Finally, “apply” expressions represent applications. They have an operator property that refers to the expression that is being applied, and they have an args property that refers to an array of argument expressions.

The >(x, 5) part of the previous program would be represented like this:

  type: "apply",
  operator: {type: "word", name: ">"},
  args: [
    {type: "word", name: "x"},
    {type: "value", value: 5}

Such a data structure is called a syntax tree. If you imagine the objects as dots and the links between them as lines between those dots, it has a treelike shape. The fact that expressions contain other expressions, which in turn might contain more expressions, is similar to the way branches split and split again.

Contrast this to the parser we wrote for the configuration file format in Chapter 9 [qui], which had a simple structure: it split the input into lines and handled those lines one at a time. There were only a few simple forms that a line was allowed to have.

Here we must find a different approach. Expressions are not separated into lines, and they have a recursive structure. Application expressions contain other expressions.

Fortunately, this problem can be solved elegantly by writing a parser function that is recursive in a way that reflects the recursive nature of the language.

We define a function parseExpression, which takes a string as input and returns an object containing the data structure for the expression at the start of the string, along with the part of the string left after parsing this expression. When parsing subexpressions (the argument to an application, for example), this function can be called again, yielding the argument expression as well as the text that remains. This text may in turn contain more arguments or may be the closing parenthesis that ends the list of arguments.

This is the first part of the parser:

function parseExpression(program) {
  program = skipSpace(program);
  var match, expr;
  if (match = /^"([^"]*)"/.exec(program))
    expr = {type: "value", value: match[1]};
  else if (match = /^\d+\b/.exec(program))
    expr = {type: "value", value: Number(match[0])};
  else if (match = /^[^\s(),"]+/.exec(program))
    expr = {type: "word", name: match[0]};
    throw new SyntaxError("Unexpected syntax: " + program);

  return parseApply(expr, program.slice(match[0].length));

function skipSpace(string) {
  var first =\S/);
  if (first == -1) return "";
  return string.slice(first);

Because Egg allows any amount of whitespace between its elements, we have to repeatedly cut the whitespace off the start of the program string. This is what the skipSpace function helps with.

After skipping any leading space, parseExpression uses three regular expressions to spot the three simple (atomic) elements that Egg supports: strings, numbers, and words. The parser constructs a different kind of data structure depending on which one matches. If the input does not match one of these three forms, it is not a valid expression, and the parser throws an error. SyntaxError is a standard error object type, which is raised when an attempt is made to run an invalid JavaScript program.

We can then cut off the part that we matched from the program string and pass that, along with the object for the expression, to parseApply, which checks whether the expression is an application. If so, it parses a parenthesized list of arguments.

function parseApply(expr, program) {
  program = skipSpace(program);
  if (program[0] != "(")
    return {expr: expr, rest: program};

  program = skipSpace(program.slice(1));
  expr = {type: "apply", operator: expr, args: []};
  while (program[0] != ")") {
    var arg = parseExpression(program);
    program = skipSpace(;
    if (program[0] == ",")
      program = skipSpace(program.slice(1));
    else if (program[0] != ")")
      throw new SyntaxError("Expected ',' or ')'");
  return parseApply(expr, program.slice(1));

If the next character in the program is not an opening parenthesis, this is not an application, and parseApply simply returns the expression it was given.

Otherwise, it skips the opening parenthesis and creates the syntax tree object for this application expression. It then recursively calls parseExpression to parse each argument until a closing parenthesis is found. The recursion is indirect, through parseApply and parseExpression calling each other.

Because an application expression can itself be applied (such as in multiplier(2)(1)), parseApply must, after it has parsed an application, call itself again to check whether another pair of parentheses follows.

This is all we need to parse Egg. We wrap it in a convenient parse function that verifies that it has reached the end of the input string after parsing the expression (an Egg program is a single expression), and that gives us the program’s data structure.

function parse(program) {
  var result = parseExpression(program);
  if (skipSpace( > 0)
    throw new SyntaxError("Unexpected text after program");
  return result.expr;

console.log(parse("+(a, 10)"));

Raccolgo nel file p-egg.js il codice inserito finora e eseguo:

It works! It doesn’t give us very helpful information when it fails and doesn’t store the line and column on which each expression starts, which might be helpful when reporting errors later, but it’s good enough for our purposes.

Continua, prossimamente 😊


SciPy – 1 – algebra lineare

Sono sempre fermo all’inizio perché chi ben comincia… 😉 e poi devo ancora decidere da dove devo copiare 😊, ci vorrebbe uno come Jake, lui spiega bene, rockz 🚀

Potrei partire da SciPy Reference Guide ma mi sembra un po’ troppo documentosa, forse è meglio il Scipy Tutorial: Vectors and Arrays (Linear Algebra) di Karlijn Willems.

Il tutorial di Karlijn mi sembra troppo corto, inoltre copre solo una parte di SciPy (a quanto vedo dall’indice della Reference) ma può essere un inizio. Anzi parto; poi si vedrà 😉 Intanto il solito mantra.

Continuo da qui, copio qui.

Much of what you need to know to really dive into machine learning is linear algebra, and that is exactly what this tutorial tackles. Today’s post goes over the linear algebra topics that you need to know and understand to improve your intuition for how and when machine learning methods work by looking at the level of vectors and matrices.

By the end of the tutorial, you’ll hopefully feel more confident to take a closer look at an algorithm!

Ho scorso con Jake tutto un notebook su NumPy, one of the core libraries for scientific computing in Python. This library contains a collection of tools and techniques that can be used to solve on a computer mathematical models of problems in Science and Engineering. Ma c’è SciPy, un package che ci consente prestazioni migliori, it’s a powerful data structure that allows you to efficiently compute arrays and matrices.

Now, SciPy is basically NumPy.

It’s also one of the core packages for scientific computing that provides mathematical algorithms and convenience functions, but it’s built on the NumPy extension of Python. This means that SciPy and NumPy are often used together.

Later on in this tutorial, it will become clear to you how the collaboration between these two libraries has become self-evident.

Interagire con NumPy e SciPy
To interact efficiently with both packages, you first need to know some of the basics of this library and its powerful data structure. To work with these arrays, there’s a huge amount of high-level mathematical functions operate on these matrices and arrays.

Vedremo adesso cosa serve per usare efficientemente SciPy. In essence, you have to know how about the array structure and how you can handle data types and how you can manipulate the shape of arrays. Ah! c’è un cheat sheet sia per NumPy che per SciPy.

Pausa 😊 in fondo ci stiamo ancora preparando alla partenza 😎


JavaScript 65 – moduli – 5

Continuo da qui, copio qui.
Sono arrivato agli esercizi, con sorprese 😜

Nomi dei mesi
Write a simple module similar to the weekDay module that can convert month numbers (zero-based, as in the Date type) to names and can convert names back to numbers. Give it its own namespace since it will need an internal array of month names, and use plain JavaScript, without any module loader system.

Davvero immediato, basta modificare il codice di weekDay visto qui. Ecco il file m6.js:

var month = function() {
  var names = ["January", "February", "March", "April", "May",
               "June", "July", "August", "September", "October",
               "November", "December"];
  return {
    name: function(number) {return names[number];},
    number: function(name) {return names.indexOf(name);}


L’esercizio successivo, “Un ritorno alla vita elettronica” riguarda la suddivisione, l’organizzazione del codice in moduli. Non si deve scrivere codice, non serve il computer ma carta, matita e gomma, siamo nella fase di progettazione o, come in questo caso, di giustificazione e documentazione del progetto. Inutile dire che è un aspetto fondamentale, a volte (spesso) trascurato. Ma come esercizio dev’essere fatto individualmente, dai c’è tutto di là.

Marijn passa poi alle “Dipendenze circolari”. Argomento importante, gestito in modo diverso dai vari linguaggi. Non credo esista una soluzione definitiva. Trasformo l’esercizio in paragrafo.

Dipendenze circolari
A tricky subject in dependency management is circular dependencies, where module A depends on B, and B also depends on A. Many module systems simply forbid this. CommonJS modules allow a limited form: it works as long as the modules do not replace their default exports object with another value and start accessing each other’s interface only after they finish loading.

Can you think of a way in which support for this feature could be implemented? Look back to the definition of require and consider what the function would have to do to allow this.

The trick is to add the exports object created for a module to require‘s cache before actually running the module. This means the module will not yet have had a chance to override module.exports, so we do not know whether it may want to export some other value. After loading, the cache object is overridden with module.exports, which may be a different value.

But if in the course of loading the module, a second module is loaded that asks for the first module, its default exports object, which is likely still empty at this point, will be in the cache, and the second module will receive a reference to it. If it doesn’t try to do anything with the object until the first module has finished loading, things will work.


JavaScript 64 – moduli – 4

Continuo da qui, copio qui.

In questo post di consigli metodologici davvero non siamo più in un approccio introduttivo al linguaggio; chissà come se la caverà Marijn?

Progetto dell’interfaccia
Designing interfaces for modules and object types is one of the subtler aspects of programming. Any nontrivial piece of functionality can be modeled in various ways. Finding a way that works well requires insight and foresight.

The best way to learn the value of good interface design is to use lots of interfaces—some good, some bad. Experience will teach you what works and what doesn’t. Never assume that a painful interface is “just the way it is”. Fix it, or wrap it in a new interface that works better for you.

If programmers can predict the way your interface works, they (or you) won’t get sidetracked as often by the need to look up how to use it. Thus, try to follow conventions. When there is another module or part of the standard JavaScript environment that does something similar to what you are implementing, it might be a good idea to make your interface resemble the existing interface. That way, it’ll feel familiar to people who know the existing interface.

Another area where predictability is important is the actual behavior of your code. It can be tempting to make an unnecessarily clever interface with the justification that it’s more convenient to use. For example, you could accept all kinds of different types and combinations of arguments and do the “right thing” for all of them. Or you could provide dozens of specialized convenience functions that provide slightly different flavors of your module’s functionality. These might make code that builds on your interface slightly shorter, but they will also make it much harder for people to build a clear mental model of the module’s behavior.

In your interfaces, try to use the simplest data structures possible and make functions do a single, clear thing. Whenever practical, make them pure functions come visto in post precedenti come questo.

For example, it is not uncommon for modules to provide their own array-like collection objects, with their own interface for counting and extracting elements. Such objects won’t have map or forEach methods, and any existing function that expects a real array won’t be able to work with them. This is an example of poor composability—the module cannot be easily composed with other code.

One example would be a module for spell-checking text, which we might need when we want to write a text editor. The spell-checker could be made to operate directly on whichever complicated data structures the editor uses and directly call internal functions in the editor to have the user choose between spelling suggestions. If we go that way, the module cannot be used with any other programs. On the other hand, if we define the spell-checking interface so that you can pass it a simple string and it will return the position in the string where it found a possible misspelling, along with an array of suggested corrections, then we have an interface that could also be composed with other systems because strings and arrays are always available in JavaScript.

Interfacce a livelli
When designing an interface for a complex piece of functionality—sending email, for example—you often run into a dilemma. On the one hand, you do not want to overload the user of your interface with details. They shouldn’t have to study your interface for 20 minutes before they can send an email. On the other hand, you do not want to hide all the details either—when people need to do complicated things with your module, they should be able to.

Often the solution is to provide two interfaces: a detailed low-level one for complex situations and a simple high-level one for routine use. The second can usually be built easily using the tools provided by the first. In the email module, the high-level interface could just be a function that takes a message, a sender address, and a receiver address and then sends the email. The low-level interface would allow full control over email headers, attachments, HTML mail, and so on.