SICP – cap. 2 – Dati gerarchici e closure – esercizi – 22

Continuo da qui, un esercizio, qui.

Exercise 2.18: Define a procedure reverse that takes a list as argument and returns a list of the same elements in reverse order:

(reverse (list 1 4 9 16 25))
(25 16 9 4 1)

Non ci sono riuscito, provo a giustificarmi 😯

La mia idea è di usare last-pair definita nell’esercizio precedente … c’è però il problema … non ho idea come farlo … mi sa che sbircio Bill the Lizard 😊

Arghhh!!! 👿
Come ho fatto a non pensarci! Bisogna ragionare ricorsivamente e basta appendere il car della lista al reverse del cdr della lista 😊

See how easy it is to start thinking in Scheme? dice Bill, rockz! 🚀
La mia stessa difficoltà la trovo in sicp-ex, non sono solo io 😙

OK 😡 sono troppo condizionato all’abitudine di ragionare à la Algol 🐙

Ma forse il problema (mio) è un altro: l’esercizio è semplicissimo, basta applicare quello detto “a lezione”; il guaio (mio) è che sono solo, non sono a lezione, non ho qualcuno cui confrontarmi.
E così ci ho ripensato parecchio, troppo, anche non volendo 😯


NumPy – 35 – introduzione agli oggetti Pandas – 1

Continuo da qui iniziando Pandas, copio qui.

At the very basic level, Pandas objects can be thought of as enhanced versions of NumPy structured arrays in which the rows and columns are identified with labels rather than simple integer indices. As we will see during the course of this chapter, Pandas provides a host of useful tools, methods, and functionality on top of the basic data structures, but nearly everything that follows will require an understanding of what these structures are. Thus, before we go any further, let’s introduce these three fundamental Pandas data structures: the Series, DataFrame, and Index.

We will start our code sessions with the standard NumPy and Pandas imports:

Gli oggetti Series
A Pandas Series is a one-dimensional array of indexed data. It can be created from a list or array as follows:

As we see in the output, the Series wraps both a sequence of values and a sequence of indices, which we can access with the values and index attributes. The values are simply a familiar NumPy array:

The index is an array-like object of type pd.Index, which we’ll discuss in more detail momentarily.

Like with a NumPy array, data can be accessed by the associated index via the familiar Python square-bracket notation:

As we will see, though, the Pandas Series is much more general and flexible than the one-dimensional NumPy array that it emulates.

Series come NumPy array generalizzato
From what we’ve seen so far, it may look like the Series object is basically interchangeable with a one-dimensional NumPy array. The essential difference is the presence of the index: while the Numpy Array has an implicitly defined integer index used to access the values, the Pandas Series has an explicitly defined index associated with the values.

This explicit index definition gives the Series object additional capabilities. For example, the index need not be an integer, but can consist of values of any desired type. For example, if we wish, we can use strings as an index, and the item access works as expected:

We can even use non-contiguous or non-sequential indices:

Series come dictionary specializzato
In this way, you can think of a Pandas Series a bit like a specialization of a Python dictionary. A dictionary is a structure that maps arbitrary keys to a set of arbitrary values, and a Series is a structure which maps typed keys to a set of typed values. This typing is important: just as the type-specific compiled code behind a NumPy array makes it more efficient than a Python list for certain operations, the type information of a Pandas Series makes it much more efficient than Python dictionaries for certain operations.

The Series-as-dictionary analogy can be made even more clear by constructing a Series object directly from a Python dictionary:

By default, a Series will be created where the index is drawn from the sorted keys. From here, typical dictionary-style item access can be performed:

Unlike a dictionary, though, the Series also supports array-style operations such as slicing:

We’ll discuss some of the quirks of Pandas indexing and slicing in Data Indexing and Selection.

Costruire oggetti Series
We’ve already seen a few ways of constructing a Pandas Series from scratch; all of them are some version of the following:

pd.Series(data, index=index)

where index is an optional argument, and data can be one of many entities.

For example, data can be a list or NumPy array, in which case index defaults to an integer sequence:

data can be a scalar, which is repeated to fill the specified index:

data can be a dictionary, in which index defaults to the sorted dictionary keys:

In each case, the index can be explicitly set if a different result is preferred:

Notice that in this case, the Series is populated only with the explicitly identified keys.


JavaScript 6 – struttura dei programmi – 4

Continuo da qui a copiare qui.

Cicli while e do
Consider a program that prints all even numbers from 0 to 12. One way to write this is as follows:


lo salvo nel file c0.js e lo eseguo nel terminale, viene meglio

That works, but the idea of writing a program is to make something less work, not more. If we needed all even numbers less than 1,000, the previous would be unworkable. What we need is a way to repeat some code. This form of control flow is called a loop (ciclo):

Looping control flow allows us to go back to some point in the program where we were before and repeat it with our current program state. If we combine this with a variable that counts, we can do something like this (come sopra, lo metto nel file c1.js):

var number = 0;
while (number <= 12) {
  number = number + 2;

A statement starting with the keyword while creates a loop. The word while is followed by an expression in parentheses and then a statement, much like if. The loop executes that statement as long as the expression produces a value that is true when converted to Boolean type.

In this loop, we want to both print the current number and add two to our variable. Whenever we need to execute multiple statements inside a loop, we wrap them in curly braces ({ and }). Braces do for statements what parentheses do for expressions: they group them together, making them count as a single statement. A sequence of statements wrapped in braces is called a block.

Many JavaScript programmers wrap every single loop or if body in braces. They do this both for the sake of consistency and to avoid having to add or remove braces when changing the number of statements in the body later. In this book, I will write most single-statement bodies without braces, since I value brevity. You are free to go with whichever style you prefer.

The variable number demonstrates the way a variable can track the progress of a program. Every time the loop repeats, number is incremented by 2. Then, at the beginning of every repetition, it is compared with the number 12 to decide whether the program has done all the work it intended to do.

Nota: si può scrivere la { su una riga a sé come fanno i C-isti, così:

var number = 0;
while (number <= 12) 
  number = number + 2;

As an example that actually does something useful, we can now write a program that calculates and shows the value of 210 (2 to the 10th power). We use two variables: one to keep track of our result and one to count how often we have multiplied this result by 2. The loop tests whether the second variable has reached 10 yet and then updates both variables (file c2.js). Ovviamente si tratta solo di un esempio, lo stesso risultato si ottiene con Math.pow(2, 10).

// file c2.js (questo è un commento)
var result = 1;
var counter = 0;
while (counter < 10) {
  result = result * 2;
  counter = counter + 1;

The counter could also start at 1 and check for <= 10, but, for reasons that will that will become apparent in Chapter 4, it is a good idea to get used to counting from 0.

The do loop is a control structure similar to the while loop. It differs only on one point: a do loop always executes its body at least once, and it starts testing whether it should stop only after that first execution. To reflect this, the test appears after the body of the loop:

do {
  var yourName = prompt("Who are you?");
} while (!yourName);

This program will force you to enter a name. It will ask again and again until it gets something that is not an empty string. Applying the ! operator will convert a value to Boolean type before negating it, and all strings except “” convert to true. This means the loop continues going round until you provide a name that is not the empty string.

L’esempio può essere eseguito solo nel browser perché c’è la chiamata a prompt; propongo di rifare il precedente usando do al posto di while, file c3.js:

// file c3.js

var result = 1;
var counter = 0;

do {
  result = result * 2;
  counter = counter + 1;
} while (counter < 10)



NumPy – 34 – manipolare dati con Pandas

Continuo da qui iniziando a copiare da un capitolo nuovo, qui.

Finora abbiamo visto gli oggetti di ndarray forniti da NumPy. Ma c’è il package Pandas: Pandas is a newer package built on top of NumPy, and provides an efficient implementation of a DataFrame. DataFrames are essentially multidimensional arrays with attached row and column labels, and often with heterogeneous types and/or missing data. As well as offering a convenient storage interface for labeled data, Pandas implements a number of powerful data operations familiar to users of both database frameworks and spreadsheet programs.

As we saw, NumPy’s ndarray data structure provides essential features for the type of clean, well-organized data typically seen in numerical computing tasks. While it serves this purpose very well, its limitations become clear when we need more flexibility (e.g., attaching labels to data, working with missing data, etc.) and when attempting operations that do not map well to element-wise broadcasting (e.g., groupings, pivots, etc.), each of which is an important piece of analyzing the less structured data available in many forms in the world around us. Pandas, and in particular its Series and DataFrame objects, builds on the NumPy array structure and provides efficient access to these sorts of “data munging” tasks that occupy much of a data scientist’s time.

We will focus on the mechanics of using Series, DataFrame, and related structures effectively. We will use examples drawn from real datasets where appropriate, but these examples are not necessarily the focus.

Installare Pandas
Basta seguire le istruzioni della documentazione.
Once Pandas is installed, you can import it and check the version:

Just as we generally import NumPy under the alias np, we will import Pandas under the alias pd:

Nota sulla documentazione
IPython gives you the ability to quickly explore the contents of a package (by using the tab-completion feature) as well as the documentation of various functions (using the ? character). (Refer back to Help and Documentation in IPython if you need a refresher on this.)
For example, to display all the contents of the pandas namespace, you can type pd.<TAB>:

Questo è solo l’inizio, lunghissimissimo l’elenco.
And to display Pandas’s built-in documentation, you can use this:

More detailed documentation, along with tutorials and other resources, can be found here.


JavaScript 5 – struttura dei programmi – 3

Continuo da qui con le istruzioni copiando qui.

Controllo del flusso
When your program contains more than one statement, the statements are executed, predictably, from top to bottom. As a basic example, this program has two statements. The first one asks the user for a number, and the second, which is executed afterward, shows the square of that number.

var theNumber = Number(prompt("Pick a number", ""));
alert("Your number is the square root of " +
      theNumber * theNumber);

Nota: viene eseguita solo nel browser, ho costruito il collage 😊

The function Number converts a value to a number. We need that conversion because the result of prompt is a string value, and we want a number. There are similar functions called String and Boolean that convert values to those types.

Here is the rather trivial schematic representation of straight control flow:

Esecuzione condizionale
Executing statements in straight-line order isn’t the only option we have. An alternative is conditional execution, where we choose between two different routes based on a Boolean value, like this:

Conditional execution is written with the if keyword in JavaScript. In the simple case, we just want some code to be executed if, and only if, a certain condition holds. For example, in the previous program, we might want to show the square of the input only if the input is actually a number.

var theNumber = Number(prompt("Pick a number", ""));
if (!isNaN(theNumber))
  alert("Your number is the square root of " +
        theNumber * theNumber);

With this modification, if you enter “cheese” [o “otto” o qualunque cosa che non sia un numero], no output will be shown.

The keyword if executes or skips a statement depending on the value of a Boolean expression. The deciding expression is written after the keyword, between parentheses, followed by the statement to execute.

The isNaN function is a standard JavaScript function that returns true only if the argument it is given is NaN. The Number function happens to return NaN when you give it a string that doesn’t represent a valid number. Thus, the condition translates to “unless theNumber is not-a-number, do this”.

You often won’t just have code that executes when a condition holds true, but also code that handles the other case. This alternate path is represented by the second arrow in the diagram. The else keyword can be used, together with if, to create two separate, alternative execution paths.

var theNumber = Number(prompt("Pick a number", ""));
if (!isNaN(theNumber))
  alert("Your number is the square root of " +
        theNumber * theNumber);
  alert("Hey. Why didn't you give me a number?");

If we have more than two paths to choose from, multiple if/else pairs can be “chained” together. Here’s an example:

var num = Number(prompt("Pick a number", "0"));

if (num < 10)
else if (num < 100)

The program will first check whether num is less than 10. If it is, it chooses that branch, shows “Small”, and is done. If it isn’t, it takes the else branch, which itself contains a second if. If the second condition (< 100) holds, that means the number is between 10 and 100, and “Medium” is shown. If it doesn’t, the second, and last, else branch is chosen.

The flow chart for this program looks something like this:


Visto nel Web – 279

Quasi primavera –sapete l’equinozio– per noi; altri ci sono da un po’. Intanto ecco cosa ho wisto nel Web.

insect – a repl-style scientific calculator with support for physical quantities
#:linguaggi di programmazione
::: sharkdp86

Children prefer to read books on paper rather than screens
me too 🍓
::: thenewsminute

Tim Berners-Lee calls for tighter regulation of online political advertising
#:Web, Internet
::: guardian ::: fabiochiusi ::: demartin

Report: Up To 15% Of Twitter Accounts Are Bots
l’app citata nel testo da 50-50 circa per tutti; funziona?
#:Web, Internet
::: Slashdot

Will WebAssembly Replace JavaScript?
#:linguaggi di programmazione #:Web, Internet
::: Slashdot

A Prenda Copyright Troll Finally Pleaded Guilty
#:sicurezza, spionaggio, virus
::: Slashdot

Munich’s IT Lead: ‘No Compelling Reason’ To Switch Back To Windows From Linux
#:free open source software
::: Slashdot

Linux Foundation Chief: Businesses ‘Will Fail’ If They Don’t Use Open Source Code
#:free open source software
::: Slashdot

How The FBI Used Geek Squad To Increase Secret Public Surveillance
#:sicurezza, spionaggio, virus
::: Slashdot

Navigating the Wild West of non-peer-reviewed #science
::: RadioProzac

Excited to launch a new email course on The Fundamentals of Functional Programming
#:programmazione funzionale
::: iam_preethi

There are a few in-browser Python Shells, but I like @replit best, and my students do too
#:Web, Internet
::: tech_magpie

Quesito con la Susi n. 940
oggi Perl6 & considerazioni
#:linguaggi di programmazione
::: Muapna

I rischi delle blockchain
#:Web, Internet
::: ElectroYou

La politica digitale – Italia 2017
#:Web, Internet #:innovazioni, futuro
::: mante

Wasm is on by default in major browsers
Why We Need WebAssembly: An Interview with Brendan Eich – JavaScript Scene
#:Web, Internet #:linguaggi di programmazione
::: _ericelliott

MIT @medialab sets up Disobedience Award with prize of $250,000
#:innovazioni, futuro
::: fpietrosanti ::: demartin

What The CIA WikiLeaks Dump Tells Us: Encryption Works
#:sicurezza, spionaggio, virus
::: Slashdot

Playing the Game with PLT Redex
über questo nerd! 👽

::: Leandro Facchinetti

LLVM 4.0 is now available for download
#:linguaggi di programmazione
::: echristo

ipyvolume 0.3 is out! #python 3d plotting for the @ProjectJupyter notebook
#:linguaggi di programmazione
::: maartenbreddels

Shell Scripts Matter
#:programming, codice, snippet
::: ThePracticalDev

So you want to be a wizard
#:programming, codice, snippet
::: b0rk

If you do it right, it works: Italian military share LibreOffice eLearning course
#:free open source software
::: lothar_becker

The impact GitHub is having on your software career
::: dcavedon

The Most Striking Thing About the WikiLeaks CIA Data Dump Is How Little Most People Cared
#:sicurezza, spionaggio, virus
::: Slashdot

How Android and iOS devices really get hacked – most of the time it’s not very sexy…
#:sicurezza, spionaggio, virus
::: MalwareJake

Tor stinks – The Dark Web Is Disappearing
#:sicurezza, spionaggio, virus
::: thegrugq

It is possible to decriminalise users of the internet
::: communia_eu

It lives!! Learn an easy and reliable way to get your Clojure site online
#:programmazione funzionale #:Web, Internet
::: nonrecursive

Why NULL references are a bad idea
#:programming, codice, snippet
::: ThePracticalDev

I deleted my social media apps because they were turning me into an idiot
già sentita anche qui in locale? è vero? capita anche a me?
#:social media
::: guardiantech

Teach Yourself Computer Science
tante rsisorse (anche free online, ma non tutte)
#:programming, codice, snippet
::: Bradfield School of Computer Science

Computing in Your Pocket: The Prehistory of the iPhone in Silicon Valley
::: Computer History Museum

Ah, at that stage of writing a book where I spend a day or two trying to figure out if there isn’t something better to use than Emacs
#:tools, componenti software
::: peterseibel ::: peterseibel

I tweet di Beppe Grillo non sono suoi
#:social media
::: manteblog

Google’s DeepMind makes AI program that can learn like a human
But it is not clear whether drawing on past skills made the AI perform better
#:artificial intelligence
::: fabiochiusi

We knew @Google’s #Allo was a privacy disaster, but we never thought it’d send your search history to your friends
#:sicurezza, spionaggio, virus
::: Snowden

Introduction to the ZFS Filesystem
#:sistemi operativi
::: b3h3m0th

Congratulazioni @phisaz @nexacenter ! Politecnico, una sfida da 300 mila dollari
#:innovazioni, futuro
::: df_francesca

Top Twitter accounts hacked by Erdogan supporters
#:sicurezza, spionaggio, virus
::: fabiochiusi

Shocking #LuxLeaks verdict. Whistleblowing is not a crime! EU must step up to protect heroes like Deltour & Halet!
#:sicurezza, spionaggio, virus
::: Senficon

Introducing Ubuntu 12.04 ESM (Extended Security Maintenance)
#:sistemi operativi
::: dcavedon

Want to start with Python? Beginner’s Day @pyconit is your chance to get a head start
#:linguaggi di programmazione
::: nicolaiarocci

If American Robots Had Their Own Economy, It’d Be Bigger Than Switzerland
#:artificial intelligence
::: Slashdot

Contemporary Processors Are Leaky – and There’s Nothing You Can Do About It
#:sicurezza, spionaggio, virus
::: johnregehr

Inside a Phishing Gang That Targets Victims of iPhone Theft
#:sicurezza, spionaggio, virus
::: Slashdot

NetBSD 7.1 Released
#:sistemi operativi
::: Slashdot

NSA, DOE Say China’s Supercomputing Advances Put US At Risk
#:innovazioni, futuro
::: Slashdot

A cosa serve il computer Linux edition
#:sistemi operativi
::: Ubutile

AMD Announces Ryzen 5 Processors With 4 and 6-Core Chips Starting At $169
::: Slashdot

Python tricks for artists: How to add interactivity to any Python script
#:linguaggi di programmazione
::: lucaciavatta

Ubuntu 16.04 un anno dopo
#:sistemi operativi
::: Nerd Slider

Parallel Python
#:linguaggi di programmazione
::: nicolaiarocci

Beautiful Racket, a book on making languages in Racket, has been officially released!
per chi vuole farsi il proprio linguaggio usando il migliore di quelli esistenti
::: racketlang

Ha ragione Guido: il rischio è che nascano azioni punitive verso *tutti* i blog o spazi online
::: fabiochiusi

Psychopathic CEOs Are Rife In Silicon Valley, Experts Say
::: Slashdot

Microsoft To End Support For Windows Vista In Less Than a Month
#:sistemi operativi
::: slashdot

Autocrats are mastering online propaganda in ways that democracies are unable to keep up with
#:sicurezza, spionaggio, virus
::: fabiochiusi

Is Facebook A Structural Threat To Free Society?
#:social media
::: asymco

Ebook Pirates Are Relatively Old and Wealthy, Study Finds
#:Web, Internet
::: Slashdot

Racketscript is getting more usable professionally
compila Racket scripts in JavaScript –funziona 😄 💥
#lisp #:lang
::: prathyvsh

The FBI arrested a man for sending a seizure-inducing GIF to journalist Kurt Eichenwald
::: nytimes

Windows 10 UAC Bypass Uses Backup and Restore Utility
#:sicurezza, spionaggio, virus
::: Slashdot

Raspberry Pi Becomes Third Best-Selling General Purpose Computer of All Time, Beating Commodore 64
::: Slashdot

Writing down my career
ottimi suggerimenti 😊
#:programming, codice, snippet
::: b0rk

Java e Firefox
#:Web, Internet
::: Siamo Geek

I’ve been writing some Racket macro exercises to help some coworkers learn, and I figured I’d make them public
::: lexi_lambda

Preseeding Full Disk Encryption
#:sicurezza, spionaggio, virus
::: b3h3m0th

Bruce Schneier on the Internet of Things security
#:sicurezza, spionaggio, virus
::: b3h3m0th

sei mesi fa a #Torino si parlava di migrazione a #Linux, oggi di migrazione a #Google
#:free open source software
::: LinuxTorino

Predicting future popularity of programming languages, JavaScript frameworks, and databases
gran lavoro ma who cares?
#:linguaggi di programmazione
::: CompSciFact

SICP – cap. 2 – Dati gerarchici e closure – esercizi – 21

Continuo da qui copiando qui.

Exercise 2.17: Define a procedure last-pair that returns the list that contains only the last element of a given (nonempty) list:

(last-pair (list 23 72 149 34))

Sarebbe molto facile se si potesse usare tutto Scheme (cioè Racket) ma non vale; non sono ancora stati annunciati. E allora… 👿
Dalle lezioni precedenti, tutta la storia di box-and-arrow e il cdr finale che contiene nil 💡

Molto simile alla soluzione di Bill the Lizard che spiega in dettaglio.
sicp-ex ha diverse soluzioni; non tutte valide (usa rest). Sconsigliata la versione che usa length, perché onerosa. Ripensandoci: rest è solo un sinonimo di cdr.


NumPy – 33 – dati strutturati – arrays strutturati di NumPy – 2

Continuo da qui, copio qui.

Creare arrays strutturati
Structured array data types can be specified in a number of ways. Earlier, we saw the dictionary method:

For clarity, numerical types can be specified using Python types or NumPy dtypes instead:

A compound type can also be specified as a list of tuples:

If the names of the types do not matter to you, you can specify the types alone in a comma-separated string:

The shortened string format codes may seem confusing, but they are built on simple principles. The first (optional) character is < or >, which means “little endian” or “big endian,” respectively, and specifies the ordering convention for significant bits. The next character specifies the type of data: characters, bytes, ints, floating points, and so on (see the table below). The last character or characters represents the size of the object in bytes.

Character Description            Example
'b'       Byte                   np.dtype('b')
'i'       Signed integer         np.dtype('i4') == np.int32
'u'       Unsigned integer       np.dtype('u1') == np.uint8
'f'       Floating point         np.dtype('f8') == np.int64
'c'       Complex floating point np.dtype('c16') == np.complex128
'S', 'a'  String                 np.dtype('S5')
'U'       Unicode string         np.dtype('U') == np.str_
'V'       Raw data (void)        np.dtype('V') == np.void

Ancora sui tipi composti avanzati
It is possible to define even more advanced compound types. For example, you can create a type where each element contains an array or matrix of values. Here, we’ll create a data type with a mat component consisting of a 3×3 floating-point matrix:

Now each element in the X array consists of an id and a 3×3 matrix. Why would you use this rather than a simple multidimensional array, or perhaps a Python dictionary? The reason is that this NumPy dtype directly maps onto a C structure definition, so the buffer containing the array content can be accessed directly within an appropriately written C program. If you find yourself writing a Python interface to a legacy C or Fortran library that manipulates structured data, you’ll probably find structured arrays quite useful!

RecordArrays: arrays strutturati con il turbo
NumPy also provides the np.recarray class, which is almost identical to the structured arrays just described, but with one additional feature: fields can be accessed as attributes rather than as dictionary keys. Recall that we previously accessed the ages by writing:

ho dovuto ricostruire l’array, ovviamente 😉

If we view our data as a record array instead, we can access this with slightly fewer keystrokes:

The downside is that for record arrays, there is some extra overhead involved in accessing the fields, even when using the same syntax. We can see this here:

Whether the more convenient notation is worth the additional overhead will depend on your own application.

Ma c’è Pandas
This section on structured and record arrays is purposely at the end of this chapter, because it leads so well into the next package we will cover: Pandas. Structured arrays like the ones discussed here are good to know about for certain situations, especially in case you’re using NumPy arrays to map onto binary data formats in C, Fortran, or another language. For day-to-day use of structured data, the Pandas package is a much better choice, and we’ll dive into a full discussion of it in the chapter that follows.

OK Jake; aspettiamo Pandas 😀


JavaScript 4 – struttura dei programmi – 2

Continuo copiando qui.

The collection of variables and their values that exist at a given time is called the environment. When a program starts up, this environment is not empty. It always contains variables that are part of the language standard, and most of the time, it has variables that provide ways to interact with the surrounding system. For example, in a browser, there are variables and functions to inspect and influence the currently loaded website and to read mouse and keyboard input.

Qui Marijn la fa lunga, più del necessario per un corso introduttivo. Inoltre fa spesso riferimento al browser che io non uso (qui). Ma le cose fondamentali saltano comunque fuori.

A lot of the values provided in the default environment have the type function. A function is a piece of program wrapped in a value. Such values can be applied in order to run the wrapped program. For example, in a browser environment, the variable alert holds a function that shows a little dialog box with a message. It is used like this:

alert("Good morning!");

Executing a function is called invoking, calling, or applying it. You can call a function by putting parentheses after an expression that produces a function value. Usually you’ll directly use the name of the variable that holds the function. The values between the parentheses are given to the program inside the function. In the example, the alert function uses the string that we give it as the text to show in the dialog box. Values given to functions are called arguments. The alert function needs only one of them, but other functions might need a different number or different types of arguments.

La funzione console.log
The alert function can be useful as an output device when experimenting, but clicking away all those little windows will get on your nerves. In past examples, we’ve used console.log to output values. Most JavaScript systems (including all modern web browsers and Node.js) provide a console.log function that writes out its arguments to some text output device. In browsers, the output lands in the JavaScript console. This part of the browser interface is hidden by default, but most browsers open it when you press F12 or, on Mac, when you press Command-Option-I. If that does not work, search through the menus for an item named “web console” or “developer tools”.

When running the examples, or your own code, on the pages of this book, console.log output will be shown after the example, instead of in the browser’s JavaScript console. Nel sito da cui copio, nel browser per eseguire gli fare click sul codice e premere Ctrl-Invio.

Though variable names cannot contain period characters, console.log clearly has one. This is because console.log isn’t a simple variable. It is actually an expression that retrieves the log property from the value held by the console variable. We will find out exactly what this means [prossimamente].

Valori ritornati
Showing a dialog box or writing text to the screen is a side effect. A lot of functions are useful because of the side effects they produce. Functions may also produce values, and in that case, they don’t need to have a side effect to be useful. For example, the function Math.max takes any number of number values and gives back the greatest.

When a function produces a value, it is said to return that value. Anything that produces a value is an expression in JavaScript, which means function calls can be used within larger expressions. Here a call to Math.min, which is the opposite of Math.max, is used as an input to the plus operator:

Prossimamente vedremo come scrivere le nostre funzioni.

prompt e confirm
Browser environments contain other functions besides alert for popping up windows. You can ask the user an OK/Cancel question using confirm. This returns a Boolean: true if the user clicks OK and false if the user clicks Cancel.

confirm("Shall we, then?");

The prompt function can be used to ask an “open” question. The first argument is the question, the second one is the text that the user starts with. A line of text can be typed into the dialog window, and the function will return this text as a string.

prompt("Tell me everything you know.", "...");

These two functions aren’t used much in modern web programming, mostly because you have no control over the way the resulting windows look, but they are useful for toy programs and experiments.

Continua :mrgreen:

NumPy – 32 – dati strutturati – arrays strutturati di NumPy – 1

Continuo da qui a copiare qui.

While often our data can be well represented by a homogeneous array of values, sometimes this is not the case. This section demonstrates the use of NumPy’s structured arrays and record arrays, which provide efficient storage for compound, heterogeneous data. While the patterns shown here are useful for simple operations, scenarios like this often lend themselves to the use of Pandas Dataframes, which we’ll explore [prossimamete].

Imagine that we have several categories of data on a number of people (say, name, age, and weight), and we’d like to store these values for use in a Python program. It would be possible to store these in three separate arrays:

But this is a bit clumsy. There’s nothing here that tells us that the three arrays are related; it would be more natural if we could use a single structure to store all of this data. NumPy can handle this through structured arrays, which are arrays with compound data types.

Recall that previously we created a simple array using an expression like this:

We can similarly create a structured array using a compound data type specification:

Here ‘U10‘ translates to “Unicode string of maximum length 10,” ‘i4‘ translates to “4-byte (i.e., 32 bit) integer,” and ‘f8‘ translates to “8-byte (i.e., 64 bit) float.” We’ll discuss other options for these type codes in the following section.

Now that we’ve created an empty container array, we can fill the array with our lists of values:

As we had hoped, the data is now arranged together in one convenient block of memory.

The handy thing with structured arrays is that you can now refer to values either by index or by name:

Using Boolean masking, this even allows you to do some more sophisticated operations such as filtering on age:

Nota per me: notare la specificazione di data, 2 volte non come mi verrebbe da pensare, vengo dal Fortran 😜

Note that if you’d like to do any operations that are any more complicated than these, you should probably consider the Pandas package, covered [prossimamente]. As we’ll see, Pandas provides a Dataframe object, which is a structure built on NumPy arrays that offers a variety of useful data manipulation functionality similar to what we’ve shown here, as well as much, much more.