L’ecosistema, Racket e un tutorial

Tin_Woodman
Un post che ho scritto e poi riscritto (stravolgendolo) in seguito a un colloquio con un ex-collega Mr.X che rockz😀
Inizialmente c’era solo la parte Racket –una delle mie passioni– ma quando Mr.X ha letto la bozza mi ha indotto a cambiare qualcosa, adesso vi conto.

Ci sono cose belle (sexy) ma spesso capita di doverne usare altre perché si usano quelle; cioè dove lavori tutti usano quelle.
Mr.X parla in questo caso di ecosistema. E per lui l’ecosistema e Windows, sempre più 10 ma con ancora qualche 7. E per i linguaggi quelli ammessi sono pochissimi, in funzione del task, si potrebbe parlare di sub-ecosistema. Per esempio per il Web solo HTML, CSS, JavaScript. JavaScript (come NodeJs) potrebbe essere usato anche da se. Altrimenti Java. O il VisualBasic. Assolutamente niente altro, meno che mai Lisp, linguaggi funzionali di moda solo nei blog ma non nella pratica. Ah! niente Python, a meno che usi solo quello, ma non per il Web.
E siccome tutti usano Windows niente Linux.

Ovviamente non sono d’accordo ma riporto questa opinione, credo anzi di approfondire l’argomento in futuro.
Altrettanto ovviamente continuerò peraltro a occuparmi anche delle cose che i piacciono, anche –e specie se– sono fuori della lista delle cose approvate. Per esempio Coconut, Haskell (forse, in futuro) e Racket. Ecco ero partito con Racket, questo che segue.

prl
Twitter vi fornisce consigli e suggerimenti che voi non tweeps non potete minimamente immaginare. Tutto sta nella scelta a chi followare e poi la magia segue, gratis😀

Comincio dal suggerimento più semplice (e fondamentale): il blog Inside PRL è da seguire. Obbligatorio (se volete, nèh!). Forse non tutti sanno che PRL sta per Programming Research Laboratory e fa parte del College of Computer and Information Science della Northeastern University, quella di Racket, nella città più sexy del Universo.

Nel blog –c’è altro ma devo ancora perlustrare– c’è questo Tutorial: Zero to Sixty in Racket. È per via di questo post che ho scoperto il blog, via questo cinguettio.
Uh! a proposito di @racketlang per me ha 17 Followers you know (su un totale di 220 (circa, numero soggetto a variazioni come il meteo).

OK, vengo al post di Ben Greenman: Racket is excellent for incrementally growing scripts into full-fledged programs. This post steps through the evolution of one small program and highlights the Racket tools that enable incremental advances… E continua, mica posso copiare tutto😳

Il compito che si pone è un indice KWIC (se non sapete cos’è un motivo in più per andarci, e protrete dire TIL KWIC), roba che secondo la letteratura richiede parecchio tempo (e poi ci sarebbe la Legge di Hofstadter che Ben colpevolmente non cita) ma c’è anche Yannis e –OK, 20 minuti dice Ben.

Siccome Ben è OK da per scontato che l’aspirante racketeer usi l’ambiente integrato, Dr Racket, manco sta a ricordarvelo. Io di solito uso la REPL, quella di una volta, mi sono pure fatto l’alias, alias rre='racket -il xrepl' ma solo perché sono vecchio (però non tanto vecchio da rientrare nella classe “non puoi insegnare un gioco nuovo a un cane vecchio”, nèh!), ma in questo cas è OK.

Nel codice trovate subito un’altra nerdata: λ invece di scrivere lambda. Il codice Unicode di λ è 03BB, per ottenerlo con Linux si sua Ctrl-Maiusc-U, compare una u sottolineata e si scrive il codice voluto. Con Windows chissà… (googlate). Ma potete benissimo scrivere lambda, come facevano i nostri vecchi (e me).

Poi basta seguire Ben, rockz!😀 Costruisce le funzioni che gli servono, spiegando quello che fa, visualizza il codice completo dello script, 79 righe compresi i commenti. Eseguendolo (tasto run) si ottiene test.txt ma è solo il primo passo.

Ben crea un submodule, lo esegue con raco, passa alla versione typed, aggiunge l’interfaccia per la command-line e testa il tutto. E continuerà –promette– con la documentazione e la creazione del package per condividerlo (shararlo).

I tempi? forse Ben è un po’ troppo ottimista c’è la legge di Hofstadter, io non sono così smart) ma OK: Racket & Ben rockzs😀
Io sono occupato con cose promesse da finire ma il blog l’ho RSSato subito.

:mrgreen:

Octave – valutazione – 40

hypatia

Oggi, continuando da qui, sono giunto qui.

Valutazione delle espressioni
Normally, you evaluate expressions simply by typing them at the Octave prompt, or by asking Octave to interpret commands that you have saved in a file.
Sometimes, you may find it necessary to evaluate an expression that has been computed and stored in a string, which is exactly what the eval function lets you do.

Built-in Function: eval (try)
Built-in Function: eval (try, catch)

If execution fails, evaluate the optional string catch.
The string try is evaluated in the current context, so any results remain available after eval returns.
The following example creates the variable A with the approximate value of 3.1416 in the current workspace.

o236

Notare i diversi modi di scrittura; l’ultima è più tradizionale, quella usata in altri linguaggi.

If an error occurs during the evaluation of try then the catch string is evaluated, as the following example shows:

o237

Programming Note: if you are only using eval as an error-capturing mechanism, rather than for the execution of arbitrary code strings, Consider using try/catch blocks or unwind_protect/unwind_protect_cleanup blocks instead. These techniques have higher performance and don’t introduce the security considerations that the evaluation of arbitrary code does.

Pronto a passare qui.

Chiamare una funzione per nome
The feval function allows you to call a function from a string containing its name. This is useful when writing a function that needs to call user-supplied functions. The feval function takes the name of the function to call as its first argument, and the remaining arguments are given to the function.

The following example is a simple-minded function using feval that finds the root of a user-supplied function of one variable using Newton’s method. No, non messa: non sono riuscito a farla funzionare e non ho trovato esempi simili googlando.

Built-in Function: feval (name, ...)
Evaluate the function named name.
Any arguments after the first are passed as inputs to the named function. For example, calls the function acos with the argument ‘-1

o238

The function feval can also be used with function handles of any sort (see Function Handles).
Historically, feval was the only way to call user-supplied functions in strings, but function handles are now preferred due to the cleaner syntax they offer. For example,

o239

are equivalent ways to call the function referred to by f. If it cannot be predicted beforehand whether f is a function handle, function name in a string, or inline function then feval can be used instead.

A similar function run exists for calling user script files, that are not necessarily on the user path

Command: run script
Function File: run ("script")

Run script in the current workspace.
Scripts which reside in directories specified in Octave’s load path, and which end with the extension “.m“, can be run simply by typing their name. For scripts not located on the load path, use run.
The file name script can be a bare, fully qualified, or relative filename and with or without a file extension. If no extension is specified, Octave will first search for a script with the “.m” extension before falling back to the script name without an extension.
Implementation Note: If script includes a path component, then run first changes the working directory to the directory where script is found. Next, the script is executed. Finally, run returns to the original working directory unless script has specifically changed directories.

Ecco lo script p-run:

# script p-run
# per i piemontesi: no nessun coniglio

n = 6 * 7
l = log(n)
r = exp(l)

eseguo:

o240

lo stesso script rinominato c_run.m viene eseguito in questo modo:

o241

Nota perso: ovvio che il nome non può contenere caratteri come -, +, *, …

Avanti, passo qui.

Valutazione in un diverso contesto
Before you evaluate an expression you need to substitute the values of the variables used in the expression. These are stored in the symbol table. Whenever the interpreter starts a new function it saves the current symbol table and creates a new one, initializing it with the list of function parameters and a couple of predefined variables such as nargin. Expressions inside the function use the new symbol table.
Sometimes you want to write a function so that when you call it, it modifies variables in your own context. This allows you to use a pass-by-name style of function, which is similar to using a pointer in programming languages such as C.

Consider how you might write save and load as m-files. For example:

o242

With evalin, you could write save as follows:

o243

Here, ‘caller’ is the create_data function and name1 is the string "x", which evaluates simply as the value of x.
You later want to load the values back from mydata in a different context:

function process_data
  load mydata
  ... do work ...
endfunction

With assignin, you could write load as follows:

o244

Here, ‘caller’ is the process_data function.
You can set and use variables at the command prompt using the context ‘base’ rather than ‘caller’.
These functions are rarely used in practice. One example is the fail (‘code’, ‘pattern’) function which evaluates ‘code’ in the caller’s context and checks that the error message it produces matches the given pattern. Other examples such as save and load are written in C++ where all Octave variables are in the ‘caller’ context and evalin is not needed.

Alquanto misterioso, occorrerebbe provare in un caso particolare ma pare si usi raramente, praticamente mai.

Built-in Function: evalin (context, try)
Built-in Function: evalin (context, try, catch)

Like eval, except that the expressions are evaluated in the context context, which may be either "caller" or "base".

Built-in Function: assignin (context, varname, value)
Assign value to varname in context context, which may be either "base" or "caller".

:mrgreen:

Visto nel Web – 249

Le ferie stanno finendo; riparte il campionato di calcio per cui devo defolloware twittatori compulsivi (pro- e contro- il Metodo); ripartono –prossimamente– anche i nerdsprogrammers; intanto ecco cosa ho visto nel Web.

CqLlw6mWcAAf2Y8

Obsolesced: rise and fall of the Gopher protocol
seguire il link nel post
#:storia
::: OS news

the bad guys are not so smart (fortunately for us)
#:sicurezza, spionaggio
::: glipari

Voting Machines Can Be Easily Compromised, Symantec Demonstrates
#:sicurezza, spionaggio
::: Slashdot

Il machine learning e i suoi fratelli: un percorso tra python, la libreria scikit-learn e diversi modelli di classificazione
dal Carnevale della Matematica n. 100
#:linguaggi di programmazione
::: Math is in the air

Why Facebook Is Really Blocking the Ad Blockers
un motivo in più per non usare FB
#:spam
::: The New Yorker

13932956_904059803055857_4894999812372504515_n

Can We Avoid Government Surveillance By Leaving The Grid?
#:sicurezza, spionaggio
::: Slashdot

Billionaire Launches Free Code College in California
#:free open source software
::: Slashdot

Go 1.7 has been released!
#:linguaggi di programmazione
::: golang

Il ‘padre del web’ Tim Berners Lee vuole restituire Internet ai cittadini
#:Web, Internet
::: valigiablu

The hack of an NSA malware staging server is not unprecedented, but the publication of the take is. Here’s what you need to know: (1/x)
#:sicurezza, spionaggio
::: Snowden

13934882_10210411446588264_8035874917780759505_n

China Launches World’s First Quantum Communications Satellite
da verificare, nèh!
#:sicurezza, spionaggio
::: Slashdot

Twitter per la scienza #icanhazpdf
::: iamscicomm

Why Cory Doctorow Thinks Apple’s Disappearing Headphone Jack Should Scare You
#:copyright
::: Fast Company

Internet Explorer came out #otd in 1995 & reigned supreme pre-Chrome
#:Web, Internet
::: MIT_CSAIL

1 to 1 Billion: Eight Exponential Entrepreneurial Stories
#:ditte
::: Computer History Museum

CqM3M7dUAAAqltP

Windows vs. Unix: Those pesky line terminators
questa è una delle cose che continuo a dimenticare da 30 anni; lo ricordo perfettamente
#:tools, componenti software
::: ComputerWorld

The Document Foundation & FSFE strengthen their relationship
#:free open source software
::: tdforg

Quand tu as besoin d’une info pendant l’été
#:umorismo
::: CommitStrip

Confirmed: hacking tool leak came from “omnipotent” NSA-tied group
#:sicurezza, spionaggio
::: Ars Technica

CEO Tim Cook Decides Apple Doesn’t Have to Pay Corporate Tax Rate Because It’s “Unfair”
bello poter are come Apple😉
#:ditte
::: The Intercept

13912392_996359827148117_7795579242630715053_n

From Now On You’ll Be Able To Access NASA Research For Free
#:Web, Internet #:free open source software
::: Slashdot

Microsoft Says Upcoming Project Scorpio Might Be the Last Console Generation
#:hardware #:innovazioni, futuro
::: Slashdot

Apple steps up environmental efforts in China
#:ditte
::: Macworld

I wrote this! Making documentation easy with Read the Docs
#:free open source software #:manuali, how to
::: FunnelFiasco

Announcing Rust 1.11
#:linguaggi di programmazione
::: The Rust Programming Language

13934760_665304710291595_186973354821035046_n

How bad is the Windows command line really?
#:sistemi operativi
::: Grab the Blaster ::: Grab the Blaster

I wrote a short blog post about programming languages, abstraction, and tradeoffs
troppo difficile per commentarlo; concordo in parte –ovviamente da niubbo (beginner dice lei)😉
#:linguaggi di programmazione
::: lexi_lambda

Happy Learn Haskell Tutorial Volume 1
lodevole iniziativa😀 lo metto nella pagina dei manuali
#:programmazione funzionale
::: Leanpub

Happy Learn Haskell Tutorial
#:programmazione funzionale
::: Happy Learn Haskell Tutorial

Microsoft Wants To Pay You To Use Its Windows 10 Browser Edge
mahhhh…😳
#:ditte
::: Slashdot

CqJ4vPdWYAAVlAz

The Link Tax is Running Out of Fuel: You Can Stop It Here
una pazzia della Comunità Europea, peggiore di quella sulla segnalazione dei cookies
#:copyright
::: OpenMedia

Google Will Kill Chrome Apps For Windows, Mac, and Linux In Early 2018
#:Web, Internet #:ditte
::: Slashdot ::: Grab the Blaster

Oracle Is Funding a New Anti-Google Group
mi ricorda tanto SCO
#:ditte
::: Slashdot

Page maison de Simon Plouffe
il sito è in inglese, contiene infinite risorse principalmene matematiche ma che possono servire per la programmaione; devo mica dirvi chi è Simon, vero?
#:manuali, how to
::: Simon Plouffe ::: Wikipedia

Fedora 25 To Run Wayland By Default Instead Of X.Org Server
#:sistemi operativi
::: Slashdot

Computer Science Professor Mocks The NSA’s Buggy Code
mah… sarà davvero così o *gomblotto*—–😳
#:sicurezza, spionaggio
::: Slashdot

kiss

SICP – cap. 1 – formulare astrazioni con procedure di ordine superiore – esercizi – 37

Cg5

Copiando qui proseguo da qui.

Exercise 1.30: The sum procedure above generates a linear recursion. The procedure can be rewritten so that the sum is performed iteratively. Show how to do this by filling in the missing expressions in the following definition:

(define (sum term a next b)
  (define (iter a result)
    (if 
        (iter )))
  (iter ))

Si tratta di mettere a frutto quanto visto in precedenza, verifica se siete stati attenti. Uno che è sempre attento è Bill the Lizard, un modello (lo propongo come capoclasse e incaricato di cancellare la lavagna (si usa ancora, vero?)). E spiega bene-bene il tutto, qui.

Il risultato è:

(define (sum term a next b)
  (define (iter a result)
    (if (> a b)
        result
        (iter (next a) (+ (term a) result))))
  (iter a 0))

Sostituisco questa definizione alla vecchia usata per l’esercizio precedente ottenendo:

(define (cube x) (* x x x))

(define (sum term a next b)
  (define (iter a result)
    (if (> a b)
        result
        (iter (next a) (+ (term a) result))))
  (iter a 0))

(define (integral f a b dx)
  (define (add-dx x) (+ x dx))
  (* (sum f (+ a (/ dx 2.0)) add-dx b)
     dx))
     
(define (simpson f a b n)
  (define h (/ (- b a) n))
  (define (inc x) (+ x 1))
  (define (y k)
    (f (+ a (* k h))))
  (define (term k)
    (* (cond ((odd? k) 4)
             ((or (= k 0) (= k n)) 1)
             ((even? k) 2))
       (y k)))
  (/ (* h (sum term 0 inc n)) 3))

s79

Molto sintetici (e inutili) Ken Dyck, S-sol (che lo applica a un calcolo differente) e Spaceman Aki.

:mrgreen:

Octave – espressioni VII – 39

1352

Copio qui, continuando da qui.

Operatori d’incremento

Increment operators increase or decrease the value of a variable by 1. The operator to increment a variable is written as ‘++’. It may be used to increment a variable either before or after taking its value.
For example, to pre-increment the variable x, you would write ++x. This would add one to x and then return the new value of x as the result of the expression. It is exactly the same as the expression x = x + 1.
To post-increment a variable x, you would write x++. This adds one to the variable x, but returns the value that x had prior to incrementing it. For example, if x is equal to 2, the result of the expression x++ is 2, and the new value of x is 3.
For matrix and vector arguments, the increment and decrement operators work on each element of the operand.

Here is a list of all the increment and decrement expressions.

++x
This expression increments the variable x. The value of the expression is the new value of x. It is equivalent to the expression x = x + 1.

--x
This expression decrements the variable x. The value of the expression is the new value of x. It is equivalent to the expression x = x - 1.

x++
This expression causes the variable x to be incremented. The value of the expression is the old value of x.

x--
This expression causes the variable x to be decremented. The value of the expression is the old value of x.

😀 proprio come nel C (e derivati e successori).

Avanti, sono qui.

Precedenza tra operatori
Operator precedence determines how operators are grouped, when different operators appear close by in one expression. For example, ‘*’ has higher precedence than ‘+’. Thus, the expression a + b * c means to multiply b and c, and then add a to the product (i.e., a + (b * c)).
You can overrule the precedence of the operators by using parentheses. You can think of the precedence rules as saying where the parentheses are assumed if you do not write parentheses yourself. In fact, it is wise to use parentheses whenever you have an unusual combination of operators, because other people who read the program may not remember what the precedence is in this case. You might forget as well, and then you too could make a mistake. Explicit parentheses will help prevent any such mistake.
When operators of equal precedence are used together, the leftmost operator groups first, except for the assignment operators, which group in the opposite order. Thus, the expression a - b + c groups as (a - b) + c, but the expression a = b = c groups as a = (b = c).
The precedence of prefix unary operators is important when another operator follows the operand. For example, -x^2 means -(x^2), because ‘-’ has lower precedence than ‘^’.
Here is a table of the operators in Octave, in order of decreasing precedence. Unless noted, all operators group left to right.

function call and array indexing, cell array indexing, and structure element indexing
()’ ‘{}’ ‘.

postfix increment, and postfix decrement
++’ ‘--
These operators group right to left.

transpose and exponentiation
'’ ‘.'’ ‘^’ ‘**’ ‘.^’ ‘.**

unary plus, unary minus, prefix increment, prefix decrement, and logical “not
+’ ‘-’ ‘++’ ‘--’ ‘~’ ‘!

multiply and divide
*’ ‘/’ ‘\’ ‘.\’ ‘.*’ ‘./

add, subtract
+’ ‘-

colon
:

relational
<’ ‘<=’ ‘==’ ‘>=’ ‘>’ ‘!=’ ‘~=

element-wise “and
&

element-wise “or
|

logical “and
&&

logical “or
||

assignment
=’ ‘+=’ ‘-=’ ‘*=’ ‘/=’ ‘\=’ ‘^=’ ‘.*=’ ‘./=’ ‘.\=’ ‘.^=’ ‘|=’ ‘&=
These operators group right to left.

:mrgreen:

Coconut – Notazione di funzione – 10

74

Coconut mi piace, tanto che continuando da qui oggi copio qui.

Operatori di funzione
Coconut uses a simple operator function short-hand: surround an operator with parentheses to retrieve its function. Similarly to iterator comprehensions, if the operator function is the only argument to a function, the parentheses of the function call can also serve as the parentheses for the operator function.

c46

A very common thing to do in functional programming is to make use of function versions of built-in operators: currying them, composing them, and piping them. To make this easy, Coconut provides a short-hand syntax to access operator functions.

La lista completa

(|>)     => # pipe forward
(|*>)    => # multi-arg pipe forward
(<|)     => # pipe backward
(<*|)    => # multi-arg pipe backward
(..)     => # function composition
(.)      => (getattr)
(::)     => (itertools.chain) # will not evaluate its arguments lazily
($)      => (functools.partial)
(+)      => (operator.__add__)
(-)      => # 1 arg: operator.__neg__, 2 args: operator.__sub__
(*)      => (operator.__mul__)
(**)     => (operator.__pow__)
(/)      => (operator.__truediv__)
(//)     => (operator.__floordiv__)
(%)      => (operator.__mod__)
(&)      => (operator.__and__)
(^)      => (operator.__xor__)
(|)      => (operator.__or__)
(<<)     => (operator.__lshift__)
(>>)     => (operator.__rshift__)
(<)      => (operator.__lt__)
(>)      => (operator.__gt__)
(==)     => (operator.__eq__)
(<=)     => (operator.__le__)
(>=)     => (operator.__ge__)
(!=)     => (operator.__ne__)
(~)      => (operator.__inv__)
(@)      => (operator.__matmul__)
(not)    => (operator.__not__)
(and)    => # boolean and
(or)     => # boolean or
(is)     => (operator.is_)
(in)     => (operator.__contains__)

c47

 

Creare scorciatoie di funzione
Coconut allows for shorthand in-line function definition, where the body of the function is assigned directly to the function call. The syntax for shorthand function definition is

def <name>(<args>) = <expr>

where <name> is the name of the function, <args> are the functions arguments, and <expr> evaluates the value that the function should return.

Note: Shorthand function definition can be combined with infix and pattern-matching function definition.

Coconut’s shorthand function definition is as easy to write as assignment to a lambda, but will appear named in tracebacks, as it compiles to normal Python function definition.

c48

Finzioni infisse
Coconut allows for infix function calling, where a function is surrounded by backticks and then can have arguments placed in front of or behind it. Backtick calling has a precedence in-between chaining and piping.

Coconut also supports infix function definition to make defining functions that are intended for infix usage simpler. The syntax for infix function definition is

def <arg> `<name>` <arg>:
    <body

where <name> is the name of the function, the <arg>s are the function arguments, and <body> is the body of the function. If an <arg> includes a default, the <arg> must be surrounded in parentheses.

Note: Infix function definition can be combined with shorthand and pattern-matching function definition.

A common idiom in functional programming is to write functions that are intended to behave somewhat like operators, and to call and define them by placing them between their arguments. Coconut’s infix syntax makes this possible.

c49

Con la tastiera italiana ` si ottiene con AltGr+' (nota per me che la memoria…)😉

Pattern-matching di funzioni
Coconut supports pattern-matching / destructuring assignment syntax inside of function definition. The syntax for pattern-matching function definition is

[match] def <name>(<pattern>, <pattern>, ... [if <cond>]):
    <body>

where <name> is the name of the function, <cond> is an optional additional check, <body> is the body of the function, and <pattern> is defined by Coconut’s match statement. The match keyword at the beginning is optional, but is sometimes necessary to disambiguate pattern-matching function definition from normal function definition, which will always take precedence. Coconut’s pattern-matching function definition is equivalent to a match statement that looks like:

def <name>(*args):
    match (<pattern>, <pattern>, ...) in args:
        <body>
    else:
        err = MatchError(<error message>)
        err.pattern = "def <name>(<pattern>, <pattern>, ...):"
        err.value = args
        raise err

If pattern-matching function definition fails, it will raise a [MatchError]((#matcherror) object just like destructuring assignment.

Note: Pattern-matching function definition can be combined with shorthand and infix function definition.

c50

In Python can’t be done without a long series of checks at the top of the function. See the compiled code for the Python syntax.

:mrgreen:

 

with, un complemento a REPL

lambda
Appena finito di postare una cosa sulla REPL ecco un tweet che mi constringe a fermare tutto quello che dovrei fare e compilare un post di aggiornamento && completamento al precedente.

Intanto –prima di subito– bravo Michael!😀 (come si vedrà a breve).
Tutto nasce da un tweet –come farei senza Tswitter?– questo: Awesome little script from @_mchav – seems great for building up complex commands with ‘+’🙂

C’è l’indirizzo Twitter dell’autore, ci vado (sapete sono addict a λ) e scopro che è nuovo di pakka, chissà…

mchav

Uh! solo 2 followers, no ‘spetta 3: ci sono anch’io (me).
Il Git conferma l’asserzione di TomNomNom.

il README.md recita

# with
Program prefixing for continuous workflow using a single tool.

### Usage

`with <program>`

Starts an interactive shell with where every command is prefixed using `<program>`.

Da provare prima di subito; è uno script Bash, non lo pubblico, c’è di là. Funziona, ecco:

mc0
C’è l’autocompletamento del path (quello con Tab), c’è l’editing della command-line (quello delle frecce). Leggendo lo script mi viene da dire “oh! basta là!”.

mc1
Insomma faccio un paio di piccole personalizzazioni (p.es. quando si esce deve andare a capo) e lo abilito con chmod.
E terrò d’occhio @_mchav, merita tanti followers😀 anzi –promesso, giurin-giuretta, parola di ex-Giovane Marmotta– un #FF dopodomani (lo farei subito ma non è stagione).

:mrgreen:

cit. & loll – 5

Ferie; ma stanno quasi finendo, intanto ecco…

Cp_9rBLWAAABGw6


…and here is Animal No. 25🙂, “Yakkety Yak”. Inspired by #Ubuntu release 16.10

Sylvia rockz!😀
::: sylvia_ritter

Translation fail #Dell #humor
::: dcavedon

When I install software and the installer asks me to accept the GPL I cheer inside
::: jonoxer

Software is eating the world
::: maccaw

Oh good we’re disrupting God
::: WarrenIsDead

13921208_996257330491590_7208473635748038218_n


if (currentTime.minutes % 5 == 0) {

::: Mark_cpp

That’s…that’s not how graphs work
::: ejmaroun

emacs: command not found
::: wallingf

Amazon q&a is there for the customer
::: johnregehr

Pro-tip: Only ask for a *finite* amount of tape
::: StephenPiment

CqAz9YLWcAAlgTw


[faccina kwy]

::: ThePracticalDev

The existence of Twitter is forever validated by the following exchange
Twitter rockz!😀 JK, la twittatrice che non ti asetti, anche😀
::: jk_rowling

Le C++, une arme de terroristes
::: nizarus

Appena defollato account che si stava autoretwittando compulsivamente. eccheccazz
::: SteffRomagnoli

Apple: If we’re forced to build a tool to hack iPhones, someone will steal it
::: csoghoian

dibba_di_maio_innamorati

Octave – espressioni VI – 38

0grav

Continuando da qui sono qui.

Espressioni booleane
Uh! ‘na pagina di smistamento, passo qui.

Operatori booleani elemento per elemento
An element-by-element boolean expression is a combination of comparison expressions using the boolean operators “or” (‘|’), “and” (‘&’), and “not” (‘!’), along with parentheses to control nesting. The truth of the boolean expression is computed by combining the truth values of the corresponding elements of the component expressions. A value is considered to be false if it is zero, and true otherwise.

Element-by-element boolean expressions can be used wherever comparison expressions can be used. They can be used in if and while statements. However, a matrix value used as the condition in an if or while statement is only true if all of its elements are nonzero.

Like comparison operations, each element of an element-by-element boolean expression also has a numeric value (1 if true, 0 if false) that comes into play if the result of the boolean expression is stored in a variable, or used in arithmetic.

Here are descriptions of the three element-by-element boolean operators.

boolean1 & boolean2
Elements of the result are true if both corresponding elements of boolean1 and boolean2 are true.

boolean1 | boolean2
Elements of the result are true if either of the corresponding elements of boolean1 or boolean2 is true.

! boolean
~ boolean
Each element of the result is true if the corresponding element of boolean is false.

These operators work on an element-by-element basis. For example, the expression returns a two by two identity matrix.

o233

For the binary operators, broadcasting rules apply. See Broadcasting. In particular, if one of the operands is a scalar and the other a matrix, the operator is applied to the scalar and each element of the matrix.

For the binary element-by-element boolean operators, both subexpressions boolean1 and boolean2 are evaluated before computing the result. This can make a difference when the expressions have side effects. For example, in the expression the value of the variable b is incremented even if the variable a is zero.

o234

This behavior is necessary for the boolean operators to work as described for matrix-valued operands.

Built-in Function: z = and (x, y)
Built-in Function: z = and (x1, x2, ...)

Return the logical AND of x and y.
This function is equivalent to the operator syntax x & y. If more than two arguments are given, the logical AND is applied cumulatively from left to right: (... ((x1 & x2) & x3) & ...).
At least one argument is required.

Built-in Function: z = not (x)
Return the logical NOT of x.
This function is equivalent to the operator syntax ! x.
Nota: certo che si può scrivere !x.

Built-in Function: z = or (x, y)
Built-in Function: z = or (x1, x2, ...)

Return the logical OR of x and y.
This function is equivalent to the operator syntax x | y. If more than two arguments are given, the logical OR is applied cumulatively from left to right: (... ((x1 | x2) | x3) | ...).
At least one argument is required.

Pronto a passare qui.

Short-circuit con operatori booleani
Combined with the implicit conversion to scalar values in if and while conditions, Octave’s element-by-element boolean operators are often sufficient for performing most logical operations. However, it is sometimes desirable to stop evaluating a boolean expression as soon as the overall truth value can be determined. Octave’s short-circuit boolean operators work this way.

boolean1 && boolean2
The expression boolean1 is evaluated and converted to a scalar using the equivalent of the operation all (boolean1(:)). If it is false, the result of the overall expression is 0. If it is true, the expression boolean2 is evaluated and converted to a scalar using the equivalent of the operation all (boolean2(:)). If it is true, the result of the overall expression is 1. Otherwise, the result of the overall expression is 0.

Warning: there is one exception to the rule of evaluating all (boolean1(:)), which is when boolean1 is the empty matrix. The truth value of an empty matrix is always false so [] && true evaluates to false even though all ([]) is true.

boolean1 || boolean2
The expression boolean1 is evaluated and converted to a scalar using the equivalent of the operation all (boolean1(:)). If it is true, the result of the overall expression is 1. If it is false, the expression boolean2 is evaluated and converted to a scalar using the equivalent of the operation all (boolean2(:)). If it is true, the result of the overall expression is 1. Otherwise, the result of the overall expression is 0.

Warning: the truth value of an empty matrix is always false, see the previous list item for details.

The fact that both operands may not be evaluated before determining the overall truth value of the expression can be important. For example, in the expression a && b++ the value of the variable b is only incremented if the variable a is nonzero.

This can be used to write somewhat more concise code. For example, it is possible write

function f (a, b, c)
  if (nargin > 2 && ischar (c))
    ...

instead of having to use two if statements to avoid attempting to evaluate an argument that doesn’t exist. For example, without the short-circuit feature, it would be necessary to write

function f (a, b, c)
  if (nargin > 2)
    if (ischar (c))
      ...

Writing

function f (a, b, c)
  if (nargin > 2 && ischar (c))
    ...

would result in an error if f were called with one or two arguments because Octave would be forced to try to evaluate both of the operands for the operator ‘&’.

MATLAB has special behavior that allows the operators ‘&’ and ‘|’ to short-circuit when used in the truth expression for if and while statements. Octave also behaves the same way by default, though the use of the ‘&’ and ‘|’ operators in this way is strongly discouraged. Instead, you should use the ‘&&’ and ‘||’ operators that always have short-circuit behavior. Saggezza qui😀

Finally, the ternary operator (?:) is not supported in Octave. If short-circuiting is not important, it can be replaced by the ifelse function.

Built-in Function: merge (mask, tval, fval)
Built-in Function: ifelse (mask, tval, fval)

If mask is a logical scalar, the other two arguments can be arbitrary values. Otherwise, mask must be a logical array, and tval, fval should be arrays of matching class, or cell arrays. In the scalar mask case, tval is returned if mask is true, otherwise fval is returned.

o235

In the array mask case, both tval and fval must be either scalars or arrays with dimensions equal to mask. The result is constructed as follows:

result(mask) = tval(mask);
result(! mask) = fval(! mask);

mask can also be arbitrary numeric type, in which case it is first converted to logical.

:mrgreen:

Fare una REPL

phone-humour

L’altro giorno con GG si ragionava che certe operazioni ripetitive sarebbero semplificate usando una REPL, come quelle che uso di solito per Racket, Octave, Coconut, … E anche Python usato interattivamente anche se non si usa chiamarlo REPL è esattamente quella. Ma tra il dire e il fare…

La versione elementare è qualcosa come questa:

while read -p "> " st ; do
    echo $st
    if [[ $st == "Q" ]]; then
        exit 0
    fi
done

r0

Ma…

r1

non funzionano le frecce e i comandi di editing usuali (quelli che i giovani non conoscono, questi qui).

Aggiornamento: per l’edit della linea e l’uso delle frecce vedi il man di read e lo script with, qui.

La stessa cosa capita con Python:

#!/usr/bin/python3

while True:
    st = input('> ')
    print(st)
    if st.strip()[0] == 'Q': exit(0)

r2

Uhmmm… è un compito più impegnativo. Ma se provassimo a googlare?

Sì sorprese in quantità😀 come al solito spesso c’è qualche nerd da qualche parte che ci ha già pensato –e forse risolto😀
Ecco qualche esempio.

Ottimo Derick Bailey: Build Your Own App Specific REPL For Your NodeJS App con soluzioni per Ruby e NodeJS. Solo che andrebbe personalizzato e non sono i linguaggi preferiti (almeno non da entrambi).
Ancora più bella la soluzione di nodejitsu: How to create and use a custom REPL.

#!/usr/bin/node

var net = require("net"),
    repl = require("repl");

var mood = function () {
    var m = [ "^__^", "-___-;", ">.<", "" ];
    return m[Math.floor(Math.random()*m.length)];
};

//A remote node repl that you can telnet to!
net.createServer(function (socket) {
  var remote = repl.start("node::remote> ", socket);
  //Adding "mood" and "bonus" to the remote REPL's context.
  remote.context.mood = mood;
  remote.context.bonus = "UNLOCKED";
}).listen(5001);

console.log("Remote REPL started on port 5001.");

//A "local" node repl with a custom prompt
var local = repl.start("node::local> ");

// Exposing the function "mood" to the local REPL's context.
local.context.mood = mood;

r3

Albert Latacz ha la soluzione per Java: Java REPL – Java REPL is a simple Read-Eval-Print-Loop for Java language. Lo vedrà GG, prossimamente.

OK, finora abbiamo visto linguaggi non proprio miei (GG prossimamente, dopo le ferie, …) ma ecco Python, su Stack Overflow: How to implement a Python REPL that nicely handles asynchronous output?
Sembra interessante.
Il post fa riferimento a un modulo ad hoc, sclapp ma non risulta più attivo, benché presente (non all’URL indicato); non provato.
Con qualche aggiornamento essendo codice scritto per la versione 2.x, ecco r-so.py:

#!/usr/bin/python3

import readline
import threading

PROMPT = '> '

def interrupt():
    print(readline.get_line_buffer(), sep='', end='')

def cli():
    print('Interrupting cow -- moo!')
    while True:
        cli = str(input(PROMPT))
        print(cli)
        if cli.strip() == 'q!': exit(0)

if __name__ == '__main__':
    threading.Thread(target=cli).start()
    threading.Timer(2, interrupt).start()

r4

Sembra tutto OK; la riga print(cli) va sostituita con un case (se si usa Coconut) o un if colossale che è meglio mettere in una funzione. Da completare, prossimamente…
Però c’è anche questo: cmd – Create line-oriented command processors.
Il modulo cmd è tra quelli automaticamente installati con Python.

Da provare prima di subito; questo è l’esempio del post (r-cmd.py):

#!/usr/bin/python3

import cmd

class HelloWorld(cmd.Cmd):
    """Simple command processor example."""
    
    def do_greet(self, line):
        print("hello")
    
    def do_EOF(self, line):
        return True
    
if __name__ == '__main__':
    HelloWorld().cmdloop()

r5

Vediamo se ho capito, personalizzo (r-cmd-mod.py):

#!/usr/bin/python3

import cmd
import os

class HelloWorld(cmd.Cmd):
    """Simple command processor example."""
    
    def preloop(self):
        self.prompt = "$ > "
    
    def do_greet(self, line):
        print("hello")
    
    def do_EOF(self, line):
        print("")
        return True
    
    def do_mycmd(self, line):
        os.system("pwd;date")
        
if __name__ == '__main__':
    HelloWorld().cmdloop()

r6

😀 OK!

Conclusione
Si può fare, chissà se si farà, chissà se il mio giovane collaboratore über-nerd… Per adesso l’ho messo tra le cose da fare, quasi urgenti ma non urgenti per davvero😉

:mrgreen:

Iscriviti

Ricevi al tuo indirizzo email tutti i nuovi post del sito.

Segui assieme ad altri 95 follower