cit. & LOLL – 1

Pare funzioni la raccolta delle cose meno seriose viste in settimana; vediamo se le prove devono continuare. E poi oggi c’è da ricordare un avvenimento speciale😀

Image-of-eagle-on-the-moon

the reason python is the best numerical language
::: moorepants

pare che piace
::: f_126_ck

it’s really very hard to identify the funnest part of this document
::: johnregehr

OH: “What’s systemd?”
::: QEDunham

Come to the nerd side…
::: SciencePorn

Cn0rpGeUMAAwR88

Equally true of #programming #imho
::: Symbo1ics

Durante il #GolpeTurchia #Erdogan per salvarsi usa i social network
::: SteBiotech

Looks like my colleague and I have gained a reputation
::: sanityinc

teachers
::: SciencePorn

A Phylogeny and Evolutionary History of the Pokémon
::: Improbable Research

apollo-11-crew

Pratchett moment at @curry_on_conf
::: alcortesm1

how to be a wizard programmer
::: b0rk

IT HAS BEGUN #curryon
sì, vale il tutto-maiuscolo
::: bodil ::: bodil

Git Merge
::: manisha72617183

5K people turn up to catch Pokémon in Chicago
::: TechCrunch

CnzQGGTXYAAEfBz

Larry Wall is wearing a shirt that says “Need New Haters
::: cmeik

Nell’informatica si capisce subito quando ti propongono un lavoro di merda
::: PTKDev

There are 10 types of people
::: pyjokes_bot

fucktrumpeting
::: DynamicWebPaige

I think I found a bug in ENIAC…
::: PyBeeWare

CnzisAGWAAAfCHJ

Octave – stringhe – VII – 23

thewiz

Sempre stringhe, continuo da qui e oggi affronto un argomento speciale, le regexps, copiando qui.

Built-in Function: [s, e, te, m, t, nm, sp] = regexp (str, pat)
Built-in Function: [...] = regexp (str, pat, "opt1", ...)

Regular expression string matching.
Search for pat in str and return the positions and substrings of any matches, or empty values if there are none.

The matched pattern pat can include any of the standard regex operators, including:

  • . Match any character
  • * + ? {} Repetition operators, representing
  • * Match zero or more times
  • + Match one or more times
  • ? Match zero or one times
  • {n} Match exactly n times
  • {n,} Match n or more times
  • {m,n} Match between m and n times
  • [...] [^...] List operators. The pattern will match any character listed between “[” and “]“. If the first character is “^” then the pattern is inverted and any character except those listed between brackets will match.
    Escape sequences defined below can also be used inside list operators. For example, a template for a floating point number might be [-+.\d]+.
  • () (?:) Grouping operator. The first form, parentheses only, also creates a token.
  • | Alternation operator. Match one of a choice of regular expressions. The alternatives must be delimited by the grouping operator () above.
  • ^ $ Anchoring operators. Requires pattern to occur at the start (^) or end ($) of the string.

In addition, the following escaped characters have special meaning.

  • \d Match any digit
  • \D Match any non-digit
  • \s Match any whitespace character
  • \S Match any non-whitespace character
  • \w Match any word character
  • \W Match any non-word character
  • \< Match the beginning of a word
  • \> Match the end of a word
  • \B Match within a word

Implementation Note: For compatibility with MATLAB, escape sequences in pat (e.g., “\n” => newline) are expanded even when pat has been defined with single quotes. To disable expansion use a second backslash before the escape sequence (e.g., “\\n“) or use the regexptranslate function.

The outputs of regexp default to the order given below

  • s The start indices of each matching substring
  • e The end indices of each matching substring
  • te The extents of each matched token surrounded by (...) in pat
  • m A cell array of the text of each match
  • t A cell array of the text of each token matched
  • nm A structure containing the text of each matched named token, with the name being used as the fieldname. A named token is denoted by (?<name>...).
  • sp A cell array of the text not returned by match, i.e., what remains if you split the string based on pat.

Particular output arguments, or the order of the output arguments, can be selected by additional opt arguments. These are strings and the correspondence between the output arguments and the optional argument are

'start'            s
'end'              e
'tokenExtents'     te
'match'            m
'tokens'           t
'names'            nm
'split'            sp

Additional arguments are summarized below.

  • ‘once’ Return only the first occurrence of the pattern.
  • ‘matchcase’ Make the matching case sensitive. (default)
    Alternatively, use (?-i) in the pattern.
  • ‘ignorecase’ Ignore case when matching the pattern to the string.
    Alternatively, use (?i) in the pattern.
  • ‘stringanchors’ Match the anchor characters at the beginning and end of the string. (default)
    Alternatively, use (?-m) in the pattern.
  • ‘lineanchors’ Match the anchor characters at the beginning and end of the line.
    Alternatively, use (?m) in the pattern.
  • ‘dotall’ The pattern . matches all characters including the newline character. (default)
    Alternatively, use (?s) in the pattern.
  • ‘dotexceptnewline’ The pattern . matches all characters except the newline character.
    Alternatively, use (?-s) in the pattern.
  • ‘literalspacing’ All characters in the pattern, including whitespace, are significant and are used in pattern matching. (default)
    Alternatively, use (?-x) in the pattern.
  • ‘freespacing’ The pattern may include arbitrary whitespace and also comments beginning with the character ‘#’.
    Alternatively, use (?x) in the pattern.
  • ‘noemptymatch’ Zero-length matches are not returned. (default)
  • ‘emptymatch’ Return zero-length matches.
    regexp ('a', 'b*', 'emptymatch') returns [1 2] because there are zero or more ‘b‘ characters at positions 1 and end-of-string.

Built-in Function: [s, e, te, m, t, nm, sp] = regexpi (str, pat)
Built-in Function: [...] = regexpi (str, pat, "opt1", ...)

Case insensitive regular expression string matching.
Search for pat in str and return the positions and substrings of any matches, or empty values if there are none. See regexp, for details on the syntax of the search pattern.

Built-in Function: outstr = regexprep (string, pat, repstr)
Built-in Function: outstr = regexprep (string, pat, repstr, "opt1", ...)

Replace occurrences of pattern pat in string with repstr.
The pattern is a regular expression as documented for regexp.

o134

Options in addition to those of regexp are

  • ‘once’ Replace only the first occurrence of pat in the result.
  • ‘warnings’ This option is present for compatibility but is ignored.

Implementation Note: For compatibility with MATLAB, escape sequences in pat (e.g., “\n” => newline) are expanded even when pat has been defined with single quotes. To disable expansion use a second backslash before the escape sequence (e.g., “\\n“) or use the regexptranslate function.

Function File: regexptranslate (op, s)
Translate a string for use in a regular expression.
This may include either wildcard replacement or special character escaping.
The behavior is controlled by op which can take the following values

  • "wildcard" The wildcard characters ., *, and ? are replaced with wildcards that are appropriate for a regular expression.
  • "escape" The characters $.?[], that have special meaning for regular expressions are escaped so that they are treated literally.

o135

Function File: untabify (t)
Function File: untabify (t, tw)
Function File: untabify (t, tw, deblank)

Replace TAB characters in t with spaces.
The input, t, may be either a 2-D character array, or a cell array of character strings. The output is the same class as the input.
The tab width is specified by tw, and defaults to eight.
If the optional argument deblank is true, then the spaces will be removed from the end of the character data.

The following example reads a file and writes an untabified version of the same file with trailing spaces stripped.
Uso un file ottenuto copiando una parte di un file di sistema (di Octave), questo:

function [varargout] = getfields (s, varargin)

	if (! all (isfield (s, varargin)))
		error ("getfields: some fields not present");
	endif

	if (all (size (s) <= 1))
		varargout = fields2cell (s, varargin);
	else
		error ("getfields: structure must be scalar or empty");
	endif

endfunction

o136

Adesso come faccio a far vedere che ha funzionato e i tab (8 char) sono stati sostituiti da spazi? Uh! c’è diff:

o137

Le regexps sono abbastanza simili alle solite per cui niente screenshots inutili. E –al solito– quando si dovessero usare si dovranno fare tentativi, senza perdere la pazienza, senza scoraggiarsi😉

:mrgreen:

Memo per me quando uso Windows

Best

A volte mi capita –e potrebbe capitare anche a altri– di dover usare Windows (10 o altri) per fare cose sensate, tipo quelle che si fanno nel terminale; quello che là è conosciuto come Prompt dei comandi.

Ogni volta è il solito dramma, e poi per i post su AWK –prossimamente– servirebbe…
OK, questa volta me lo scrivo, tutto per bene.
Uso uno script (che là si chiama batch; io che sono vecchio ricordo che il batch era una cosa completamente differente, come dice il nome, ma tant’è), questo (udt.bat):

@echo off
echo sono %username%
echo sono nella cartella
dir
pause

Sono ospite sul ‘puter della figlia di mio fratello (che ringrazio) per cui tutto da penna USB, con divieto di rovinare qualcosa😉

Inserendo la penna (ehi! al primo tentativo!) si apre il file manager full-screen da ridurre in finestra. Nella cartella giusta, E:\dos, posso fare doppio-click su udt (nota: niente estensione anche se si potrebbe, ma non io su questa macchina, settare diversamente) ottengo

1

che è proprio quel che volevo. Notare il messaggio “Premi un tasto …”, indotto dal comando pasue. Sì perché al termine dello script .bat la finestra del terminale si chiude.

Comportamento scomodo per chi deve interagire con il terminale in modo continuo. Ma c’è un modo semplice per avere il terminale come con Linux. Tra i millemila modi windoziani io uso la scorciatoia che mi sembra più semplice: premere in tasti Win+R e scrivere cmd😀 Fatto.

2

Ci sono un po’ di cose da notare (per i linuxiani):

  • la directory (cartella) corrente è automaticamente esaminata per il comando, prima di cercarlo nella path; quindi basta udt invece di .\udt o ./udt;
  • non c’è distinzione (per i comandi) tra maiuscolo e minuscolo;
  • il comando pause che termina lo script ovviamente non chiude il terminale.

Una cosa che potrebbe servire a noi linuxiani: inserire la directory corrente nella PATH, come si vede non c’è:

3

Si può fare, io uso una combinazione alias + script; non so se c’è un modo più semplice. L’alias da me, per ragioni storiche, si chiama agpa (da aggiungi alla path): alias agpa='source ~/bin/ag_pa

Lo script ~/bin/ag_pa semplicissimo:

#!/bin/bash
export PATH=$PWD:$PATH
echo $PATH

ed ecco:

4

OK; ovviamente chiudendo il terminale la PATH torna quella originaria😀

:mrgreen:

Octave – stringhe – VI – 22

1106

Continuo da qui con le funzioni di manipolazione delle stringhe, copiando qui.

Function File: [a, ...] = strread (str)
Function File: [a, ...] = strread (str, format)
Function File: [a, ...] = strread (str, format, format_repeat)
Function File: [a, ...] = strread (str, format, prop1, value1, ...)
Function File: [a, ...] = strread (str, format, str, prop1, value1, ...)

Read data from a string.
The string str is split into words that are repeatedly matched to the specifiers in format. The first word is matched to the first specifier, the second to the second specifier and so forth. If there are more words than specifiers, the process is repeated until all words have been processed.
The string format describes how the words in str should be parsed. It may contain any combination of the following specifiers:

  • %s The word is parsed as a string.
  • %f, %n The word is parsed as a number and converted to double.
  • %d, %u The word is parsed as a number and converted to int32.
  • %*', '%*f', '%*s The word is skipped.
  • For %s and %d, %f, %n, %u and the associated %*s ... specifiers an optional width can be specified as %Ns, etc. where N is an integer > 1. For %f, format specifiers like %N.Mf are allowed.
  • literal In addition the format may contain literal character strings; these will be skipped during reading.

Parsed word corresponding to the first specifier are returned in the first output argument and likewise for the rest of the specifiers.
By default, format is “%f“, meaning that numbers are read from str. This will do if str contains only numeric fields.

o130

Optional numeric argument format_repeat can be used for limiting the number of items read:

  • -1 (default) read all of the string until the end.
  • N Read N times nargout items. 0 (zero) is an acceptable value for format_repeat.

The behavior of strread can be changed via property-value pairs. The following properties are recognized:

  • "commentstyle" Parts of str are considered comments and will be skipped. value is the comment style and can be any of the following.
  • "shell" Everything from # characters to the nearest end-of-line is skipped.
  • "c" Everything between /* and */ is skipped.
  • "c++" Everything from // characters to the nearest end-of-line is skipped.
  • "matlab" Everything from % characters to the nearest end-of-line is skipped.
    user-supplied. Two options: (1) One string, or 1x1 cell string: Skip everything to the right of it; (2) 2x1 cell string array: Everything between the left and right strings is skipped.
  • "emptyvalue" Value to return for empty numeric values in non-whitespace delimited data. The default is NaN. When the data type does not support NaN (int32 for example), then default is zero.
  • "multipledelimsasone" Treat a series of consecutive delimiters, without whitespace in between, as a single delimiter. Consecutive delimiter series need not be vertically "aligned".
  • "treatasempty" Treat single occurrences (surrounded by delimiters or whitespace) of the string(s) in value as missing values.
  • "returnonerror" If value true (1, default), ignore read errors and return normally. If false (0), return an error.
  • "whitespace" Any character in value will be interpreted as whitespace and trimmed; the string defining whitespace must be enclosed in double quotes for proper processing of special characters like “\t“. In each data field, multiple consecutive whitespace characters are collapsed into one space and leading and trailing whitespace is removed. The default value for whitespace is “ \b\r\n\t” (note the space). Whitespace is always added to the set of delimiter characters unless at least one “%s” format conversion specifier is supplied; in that case only whitespace explicitly specified in "delimiter" is retained as delimiter and removed from the set of whitespace characters. If whitespace characters are to be kept as-is (in e.g., strings), specify an empty value (i.e., “”) for "whitespace"; obviously, whitespace cannot be a delimiter then.

When the number of words in str doesn’t match an exact multiple of the number of format conversion specifiers, strread’s behavior depends on the last character of str:

  • last character = “\n” Data columns are padded with empty fields or Nan so that all columns have equal length
  • last character is not “\n” Data columns are not padded; strread returns columns of unequal length

No, niente immagine, niente prove, sperando di non dovermici trovare a usarla😳

Built-in Function: newstr = strrep (str, ptn, rep)
Built-in Function: newstr = strrep (cellstr, ptn, rep)
Built-in Function: newstr = strrep (..., "overlaps", val)

Replace all occurrences of the pattern ptn in the string str with the string rep and return the result.
The optional argument "overlaps" determines whether the pattern can match at every position in str (true), or only for unique occurrences of the complete pattern (false). The default is true.
s may also be a cell array of strings, in which case the replacement is done for each element and a cell array is returned.

o131

Function File: substr (s, offset)
Function File: substr (s, offset, len)

Return the substring of s which starts at character number offset and is len characters long.
Position numbering for offsets begins with 1. If offset is negative, extraction starts that far from the end of the string.
If len is omitted, the substring extends to the end of s. A negative value for len extracts to within len characters of the end of the string.

o132

A questo punto ci sono le regexps; pausa😉
:mrgreen:

SICP – cap. 1 – Esempio: test di primalità – esercizi – 33

wizard-of-oz

Sempre esercizi, qui, continuando da qui.

Exercise 1.27.  Demonstrate that the Carmichael numbers listed […]  [below] really do fool the Fermat test. That is, write a procedure that takes an integer n and tests whether an is congruent to a modulo n for every a<n, and try your procedure on the given Carmichael numbers.

Carmichael numbers
Numbers that fool the Fermat test are called Carmichael numbers, and little is known about them other than that they are extremely rare. There are 255 Carmichael numbers below 100,000,000. The smallest few are 561, 1105, 1729, 2465, 2821, and 6601. In testing primality of very large numbers chosen at random, the chance of stumbling upon a value that fools the Fermat test is less than the chance that cosmic radiation will cause the computer to make an error in carrying out a “correct” algorithm. Considering an algorithm to be inadequate for the first reason but not for the second illustrates the difference between mathematics and engineering.

Uhmmm… basta eseguire il test di Fermat precedentemente visto in questo post, inserendo i valori elencati.
Determino dapprima i fattori componenti i numeri di Carmichael:

s58

Questo è il codice usato

(define (square x)
  (* x x))

(define (expmod base exp m)
  (cond ((= exp 0) 1)
        ((even? exp)
         (remainder (square (expmod base (/ exp 2) m))
                    m))
        (else
         (remainder (* base (expmod base (- exp 1) m))
                    m))))

(define (fermat-test n)
  (define (try-it a)
    (= (expmod a n n) a))
  (try-it (+ 1 (random (- n 1)))))
(define (fast-prime? n times)
  (cond ((= times 0) true)
        ((fermat-test n) (fast-prime? n (- times 1)))
        (else false)))

e ottengo:

s59

e

s60.png

Bill the Lizard raggruppa i test, è più bravo lui😀
Molto sintetico (non ho verificato) Ken Dick.
Simile la soluzione di s-sol.
Spaceman Aki è OK, molto simile ai precedenti.

In conclusione sono stato troppo banale, dovevo elaborare il codice, non limitarmi ad applicarlo nella forma già usata; promesso per il futuro. Rileggendo scopro che non ho risolto l’esercizio; devo fare più attenzione😳

:mrgreen:

Octave – stringhe – V – 21

ndr-society

ndr society

Continuo da qui, sempre sulle stringhe, copio qui.

Function File: str = strjoin (cstr)
Function File: str = strjoin (cstr, delimiter)

Join the elements of the cell string array, cstr, into a single string.
If no delimiter is specified, the elements of cstr are separated by a space.
If delimiter is specified as a string, the cell string array is joined using the string. Escape sequences are supported.
If delimiter is a cell string array whose length is one less than cstr, then the elements of cstr are joined by interleaving the cell string elements of delimiter. Escape sequences are not supported.

o124

Function File: strmatch (s, A)
Function File: strmatch (s, A, "exact")

Return indices of entries of A which begin with the string s.
The second argument A must be a string, character matrix, or a cell array of strings.
If the third argument "exact" is not given, then s only needs to match A up to the length of s. Trailing spaces and nulls in s and A are ignored when matching.

o125

Caution: strmatch is scheduled for deprecation. Use strncmp (normal case), or strcmp ("exact" case), or regexp in all new code.

Function File: [tok, rem] = strtok (str)
Function File: [tok, rem] = strtok (str, delim)

Find all characters in the string str up to, but not including, the first character which is in the string delim.
str may also be a cell array of strings in which case the function executes on every individual string and returns a cell array of tokens and remainders.
Leading delimiters are ignored. If delim is not specified, whitespace is assumed.
If rem is requested, it contains the remainder of the string, starting at the first delimiter.

o126

Function File: [cstr] = strsplit (str)
Function File: [cstr] = strsplit (str, del)
Function File: [cstr] = strsplit (..., name, value)
Function File: [cstr, matches] = strsplit (...)

Split the string str using the delimiters specified by del and return a cell string array of substrings.
If a delimiter is not specified the string is split at whitespace {" ",   "\f", "\n", "\r", "\t", "\v"}. Otherwise, the delimiter, del must be a string or cell array of strings. By default, consecutive delimiters in the input string s are collapsed into one resulting in a single split.
Supported name/value pair arguments are:

  • collapsedelimiters which may take the value of true (default) or false.
  • delimitertype which may take the value of "simple" (default) or "regularexpression". A simple delimiter matches the text exactly as written.  Otherwise, the syntax for regular expressions outlined in regexp is used.

The optional second output, matches, returns the delimiters which were matched in the original string.

Examples with simple delimiters:

o127

Examples with regularexpression delimiters:

o128

Function File: [cstr] = ostrsplit (s, sep)
Function File: [cstr] = ostrsplit (s, sep, strip_empty)

Split the string s using one or more separators sep and return a cell array of strings.
Consecutive separators and separators at boundaries result in empty strings, unless strip_empty is true. The default value of strip_empty is false.
2-D character arrays are split at separators and at the original column boundaries.

o129

Pausa che poi arriva un argomento lungo😀
:mrgreen:

Octave – stringhe – IV – 20

sg5.png

Sempre a copiare, qui, proseguendo a raccontare, da qui.

Manipolare stringhe
Octave supports a wide range of functions for manipulating strings. Since a string is just a matrix, simple manipulations can be accomplished using standard operators. The following example shows how to replace all blank characters with underscores:

0114

Nota completamente fuori posto ma scoperta adesso: per spezzare una riga si usa ... in questo modo:

o115

OK, torno alle stringhe😳

For more complex manipulations, such as searching, replacing, and general regular expressions, the following functions come with Octave.

Function File: deblank (s)
Remove trailing whitespace and nulls from s.
If s is a matrix, deblank trims each row to the length of longest string. If s is a cell array of strings, operate recursively on each string element.

o116

sì, pessima immagine, non si vedono gli spazi😦

Function File: strtrim (s)
Remove leading and trailing whitespace from s.
If s is a matrix, strtrim trims each row to the length of longest string. If s is a cell array of strings, operate recursively on each string element.

o117

Function File: strtrunc (s, n)
Truncate the character string s to length n.
If s is a character matrix, then the number of columns is adjusted.
If s is a cell array of strings, then the operation is performed on each cell element and the new cell array is returned.

o118

Function File: findstr (s, t)
Function File: findstr (s, t, overlap)
Return the vector of all positions in the longer of the two strings s and t where an occurrence of the shorter of the two starts.
If the optional argument overlap is true (default), the returned vector can include overlapping positions.

o119

Caution: findstr is scheduled for deprecation. Use strfind in all new code.

Function File: idx = strchr (str, chars)
Function File: idx = strchr (str, chars, n)
Function File: idx = strchr (str, chars, n, direction)
Function File: [i, j] = strchr (...)

Search for the string str for occurrences of characters from the set chars.
The return value(s), as well as the n and direction arguments behave identically as in find.
This will be faster than using regexp in most cases.

o120

Uhmmm… mica capito tanto bene; approfondisco:

o121

il mystero permane: non usarla in questo modo😀

Function File: index (s, t)
Function File: index (s, t, direction)
Return the position of the first occurrence of the string t in the string s, or 0 if no occurrence is found.
s may also be a string array or cell array of strings.

o122

Function File: rindex (s, t)
Return the position of the last occurrence of the character string t in the character string s, or 0 if no occurrence is found.
The rindex function is equivalent to index with direction set to "last".

Built-in Function: idx = strfind (str, pattern)
Built-in Function: idx = strfind (cellstr, pattern)
Built-in Function: idx = strfind (..., "overlaps", val)

Search for pattern in the string str and return the starting index of every such occurrence in the vector idx.
If there is no such occurrence, or if pattern is longer than str, or if pattern itself is empty, then idx is the empty array [].
The optional argument "overlaps" determines whether the pattern can match at every position in str (true), or only for unique occurrences of the complete pattern (false). The default is true.
If a cell array of strings cellstr is specified then idx is a cell array of vectors, as specified above.

o123

Pausa; l’argomento durerà parecchio😉
:mrgreen:

Visto nel Web – 244

Settimana terribile! Che mi fa sentire vecchio e stanco già di prima mattina; ma basta lamentele, ecco cosa ho visto nel Web.

hate

The code that took America to the moon was just published to GitHub, and it’s like a 1960s time capsule
#:programmazione funzionale #:storia
::: Quartz ::: glipari ::: Siamo Geek

TIOBE’s Language-Popularity Index Sees A New Top 10 Language: Assembly
#:linguaggi di programmazione
::: Slashdot

C++ 17: A Newer Version of C++ to bring more power and simplicity
::: Technotification

Rust and Rest
Rust è OK😀
#:linguaggi di programmazione
::: Armin Ronacher

HMD global to Create New Generation of Nokia Mobile Phones
Micro$oft diversamente da HP con Apollo lascerà viva Nokia –forse
#:dispositivi mobili #:hardware
::: Technotification

Lifestyle of Software Engineers

Grenoble continues to move schools to open source
#:free open source software
::: Joinup

Stuxnet/Cyberwar Documentary Reviewer: ‘The U.S. Has Pwned Iran’
#:sicurezza, spionaggio
::: Slashdot

‘Pokémon Go’ is already bigger than Tinder, and it’s about to overtake Twitter
#:dispositivi mobili #:Web, Internet
::: Business Insider ::: Donearm ::: Slashdot ::: IGIhosT ::: Black Bag ::: mikko ::: fabiochiusi ::: pixelatedboat ::: Slashdot

shlex — Parse Shell-style Syntaxes
prima o poi serve; io per esempio…
#:programming, codice, snippet
::: PyMOTW-3

@jakevdp and I are excited to announce the 1.0 release of Altair
#:programming, codice, snippet
::: ellisonbg ::: LorenaABarba

13615176_631492917008246_2539766788368549500_n

Linkage 001
ehi! mi fa concorrenza: tanti link, vari
#:Web, Internet
::: Send More Paramedics

How To Activate God Mode On Windows 7,8 and 10
riporto, non è che m’interessi, nèh!
#:sistemi operativi
::: Technotification

Evolution of an Erlang Programming Style
adoro queste storie di vecchi (come me; più smart di me)😀
#:programmazione funzionale #:storia
::: Programming in the 21st Century

Altair
Altair is a declarative statistical visualization library for Python
#:programming, codice, snippet
::: ellisonbg

Ubuntu Phone su altri dispositivi, grazie a Marius
#:dispositivi mobili
::: Dario Cavedon

chickeneels

MIT Says Their Anonymity Network Is More Secure Than Tor
#:sicurezza, spionaggio
::: Slashdot

Open Source Intelligence: cos’è e a cosa serve?
#:sicurezza, spionaggio
::: Tech Economy

Shipping Rust in Firefox
#:linguaggi di programmazione #:Web, Internet
::: Mozilla Hacks

Really, really cool browser based, Markdownesque Diagram Generator
#:tools, componenti software #:Web, Internet
::: rit

Alan Kay Wikia
tutto su un visionario cui dobbiamo tante cose
#:storia #:protagonisti
::: Alan Kay Wikia

13406746_632550776908630_7212103799529263018_n

The Egison Programming Language
Egison is a programming language that realizes non-linear pattern-matching against non-free data types
#:linguaggi di programmazione
::: Egison

Una lista di risorse di tutti i tipi
#:tip, suggerimenti
::: ly f(x)

15 Interesting Facts about Mobile Gaming
sarà vero? e chi non ha il dispositivo mobile?
#:dispositivi mobili
::: Technotification

Is it better to be lucky than good in Silicon Valley?
#:programming, codice, snippet
::: Computer History Museum

gluon
Gluon (previously called embed_lang) is a small, statically-typed, functional programming language designed for application embedding
#:linguaggi di programmazione
::: Marwes

fortune-cookie

MIT’s anonymous online communications protocol Riffle could beat Tor at its own game
#:sicurezza, spionaggio
::: TechCrunch

Microsoft wins landmark appeal over seizure of foreign emails
#:sicurezza, spionaggio
::: Reuters

145 Tech Leaders Say ‘Trump Would Be A Disaster For Innovation’
#:innovazioni, futuro
::: Slashdot

Wikipedia Zero sta violando la neutralità della Rete?
questione difficile; però: vogliamo lasciare tutto ai preti?
#:Web, Internet
::: Umanesimo Digitale

Python 3 for Scientists
ancora nelle pimissime fasi iniziali ma da seguire😀
#:linguaggi di programmazione
::: Python 3 for Scientists

CnUjekmWcAEbfl2

Il magico mondo del #coding: perché dovresti imparare a programmare
#:programming, codice, snippet
::: michelegentili

How the #internet was invented
#:storia
::: nilocram

Pokémon is a Go: Augmented Reality Takes the World by Storm
::: Computer History Museum

get the tweets of a user and save them in CSV
#:programming, codice, snippet
::: Python Adventures

CniBiUWXEAAEU2c

Attending Scipy 2016
#:linguaggi di programmazione #:Web, Internet
::: Qingkai Kong

Dask
Dask is a flexible parallel computing library for analytics
#:programming, codice, snippet
::: Dask

Turchia e cellulari
#:dispositivi mobili #:sicurezza, spionaggio
::: Siamo Geek

SOS sta per Scuola Open Source, ovvero quella delle utopie realizzabili (per esempio a Bari…)
#:free open source software
::: CheFuturo

Clf500lWgAAbnev

Coconut – operatori I

Chjgv5mUkAAZhoL

Continuo da qui l’esame di Coconut, qui.

Prima di tutto una nota che a me non interessa più di tanto ma chissà…

Supporto di IPython/Jupyter
If you prefer IPython (the python kernel for the Jupyter framework) to the normal Python shell, Coconut can be used as an IPython extension or Jupyter kernel.

Extension
If Coconut is used as an extension, a special magic command will send snippets of code to be evaluated using Coconut instead of IPython, but IPython will still be used as the default. The line magic %load_ext coconut will load Coconut as an extension, adding the %coconut and %%coconut magics. The %coconut line magic will run a line of Coconut with default parameters, and the %%coconut block magic will take command-line arguments on the first line, and run any Coconut code provided in the rest of the cell with those parameters.

Kernel
If Coconut is used as a kernel, all code in the console or notebook will be sent directly to Coconut instead of Python to be evaluated. The command coconut --jupyter notebook (or coconut --ipython notebook) will launch an IPython/Jupyter notebook using Coconut as the kernel and the command coconut --jupyter console (or coconut --ipython console) will launch an IPython/Jupyter console using Coconut as the kernel. Additionally, the command coconut --jupyter (or coconut --ipython) will add Coconut as a language option inside of all IPython/Jupyter notebooks, even those not launched with Coconut. This command may need to be re-run when a new version of Coconut is installed.

Operatori

Lambdas
Coconut provides the simple, clean -> operator as an alternative to Python’s lambda statements. The operator has the same precedence as the old statement.
In Python, lambdas are ugly and bulky, requiring the entire word lambda to be written out every time one is constructed. This is fine if in-line functions are very rarely needed, but in functional programming in-line functions are an essential tool.
Lambda forms (lambda expressions) have the same syntactic position as expressions. They are a shorthand to create anonymous functions; the expression (arguments) -> expression  yields a function object. The unnamed object behaves like a function object defined with:

def (arguments):
    return expression

Note that functions created with lambda forms cannot contain statements or annotations.

Esempio:

c18

Applicazione parziale (currying)
Partial application, or currying, is a mainstay of functional programming, and for good reason: it allows the dynamic customization of functions to fit the needs of where they are being used. Partial application allows a new function to be created out of an old function with some of its arguments pre-specified.

Python Docs
Return a new partial object which when called will behave like func called with the positional arguments args and keyword arguments keywords. If more arguments are supplied to the call, they are appended to args. If additional keyword arguments are supplied, they extend and override keywords. Roughly equivalent to:

def partial(func, *args, **keywords):
    def newfunc(*fargs, **fkeywords):
        newkeywords = keywords.copy()
        newkeywords.update(fkeywords)
        return func(*(args + fargs), **newkeywords)
    newfunc.func = func
    newfunc.args = args
    newfunc.keywords = keywords
    return newfunc

The partial object is used for partial function application which “freezes” some portion of a function’s arguments and/or keywords resulting in a new object with a simplified signature.

Esempio:

c19

😳 un messaggio alieno😉

Pipeline
Coconut uses pipe operators for pipeline-style function application. All the operators have a precedence in-between infix calls and comparisons and are left-associative. All operators also support in-place versions. The different operators are:
(|>)  => pipe forward
(|*>) => multiple-argument pipe forward
(<|)  => pipe backward
(<*|) => multiple-argument pipe backward

Esempio:

c20

Compose
Coconut uses the .. operator for function composition. It has a precedence in-between subscription and exponentiation. The in-place operator is ..=.

Esempio:

c21

Chain
Coconut uses the :: operator for iterator chaining. Coconut’s iterator chaining is done lazily, in that the arguments are not evaluated until they are needed. It has a precedence in-between bitwise or and infix calls. The in-place operator is ::=.
A useful tool to make working with iterators as easy as working with sequences is the ability to lazily combine multiple iterators together. This operation is called chain, and is equivalent to addition with sequences, except that nothing gets evaluated until it is needed.

Python Docs
Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence. Chained inputs are evaluated lazily. Roughly equivalent to:

def chain(*iterables):
    # chain('ABC', 'DEF') --> A B C D E F
    for it in iterables:
        for element in it:
            yield element

Esempio:
Can’t be done without a complicated iterator comprehension in place of the lazy chaining. See the compiled code for the Python syntax.

c22

Questo è il file conc.coco:

def N(n=0):
    return (0,) :: N(n+1) # no infinite loop because :: is lazy

(range(-10, 0) :: N())$[5:15] |> list |> print

compilo…

c23

295 righe non proprio leggibili, ecco le ulitime:

def N(n=0):
    return _coconut.itertools.chain.from_iterable((_coconut_lazy_item()
          for _coconut_lazy_item in (lambda: (0,), 
          lambda: N(n + 1)))) # no infinite loop because :: is lazy

(print)((list)(_coconut_igetitem(
          (_coconut.itertools.chain.from_iterable((_coconut_lazy_item() 
              for _coconut_lazy_item in (lambda: range(-10, 0), 
                    lambda: N())))), _coconut.slice(5, 15))))

Nota: ho spezzato le righe a sentimento per visualizzarle, troppo lunghe.

Pausa che devo riprendermi😉
:mrgreen:

SICP – cap. 1 – Esempio: test di primalità – esercizi – 32

11134428563_2a8b1640a5_b

Sempre esercizi, continuando da qui a copiare qui.

Exercise 1.26.  Louis Reasoner is having great difficulty doing exercise 1.24. His fast-prime? test seems to run more slowly than his prime? test. Louis calls his friend Eva Lu Ator over to help. When they examine Louis’s code, they find that he has rewritten the expmod procedure to use an explicit multiplication, rather than calling square:

(define (expmod base exp m)
  (cond ((= exp 0) 1)
        ((even? exp)
         (remainder (* (expmod base (/ exp 2) m)
                       (expmod base (/ exp 2) m))
                    m))
        (else
         (remainder (* base (expmod base (- exp 1) m))
                    m))))

‘I don’t see what difference that could make,’ says Louis. ‘I do.’ says Eva. ‘By writing the procedure like that, you have transformed the O(log n) process into a O(n) process.’ Explain.

Subito ho pensato come Bill the Lizard: ogni espressione viene valutata, ogni volta anche se è la stessa ripetuta.
Il tutto è raccontato molto bene da Bill, qui.
Ken Dyck dice succintamente la stessa cosa, come pure s-sol.

OK😀 post cortissimo (ha fatto tutto Bill, l’unico esaustivo tra i solutori controllati). Personalmente continuo ad avere un po’ di difficoltà a valutare l’O()😳

:mrgreen:

Iscriviti

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

Segui assieme ad altri 95 follower