【鼎革‧革鼎】︰ Raspbian Stretch 《六之 J.3 》

人耳聽旋律,縱然不能分辨音高時值,卻知音符總有個先來後到。傳說莫札特絕對音感之好,即使是初聞的曲調,也能立刻譜出!!為求一次得到『兩個領域』── 時間、頻率 ── 的好處,於是人們設想了

短時距傅立葉變換

短時距傅立葉變換傅立葉變換的一種變形,為時頻分析中其中一個重要的工具。

─── 《W!o+ 的《小伶鼬工坊演義》︰神經網絡【FFT】六

 

也許近日太常與派生‧傑克為伍,忽爾想起久知大名之

LibROSA

LibROSA is a python package for music and audio analysis. It provides the building blocks necessary to create music information retrieval systems.

For a quick introduction to using librosa, please refer to the Tutorial. For a more advanced introduction which describes the package design principles, please refer to the librosa paper at SciPy 2015.

 

或可用來『聽調辨曲』乎?

 

 

 

 

於是立馬造表操課︰

librosa

A python package for music and audio analysis.

PyPI Anaconda-Server Badge License DOI

Build Status Coverage Status Dependency Status

Linux OSX Windows

Documentation

See http://librosa.github.io/librosa/ for a complete reference manual and introductory tutorials.

Demonstration notebooks

What does librosa do? Here are some quick demonstrations:

Installation

The latest stable release is available on PyPI, and you can install it by saying

pip install librosa

 

結果

sudo pip install librosa

竟以失敗告終!

因此在搗咕成功之後,故而特寫這個安裝記也!!??

 

 

 

 

 

 

 

 

 

 

【鼎革‧革鼎】︰ Raspbian Stretch 《六之 J.2D 》

承上文,應用 JACK Client for Python 寫程式,主要重心就在set_process_callback 程序。以及詳實認識輸入、出聲音緩衝區︰

 

雖說深入了解 CFFI 並非必要︰

cffi 1.11.2

Foreign Function Interface for Python calling C code.

Foreign Function Interface for Python calling C code. Please see the Documentation.

……

Overview

CFFI can be used in one of four modes: “ABI” versus “API” level, each with “in-line” or “out-of-line” preparation (or compilation).

The ABI mode accesses libraries at the binary level, whereas the faster API mode accesses them with a C compiler. This is described in detail below.

In the in-line mode, everything is set up every time you import your Python code. In the out-of-line mode, you have a separate step of preparation (and possibly C compilation) that produces a module which your main program can then import.

(The examples below assume that you have installed CFFI.)

 

然而終將發現它的好處與重要性也。

此處且藉派生內建之 memoryview 功能

class memoryview(obj)

Create a memoryview that references obj. obj must support the buffer protocol. Built-in objects that support the buffer protocol include bytes and bytearray.

A memoryview has the notion of an element, which is the atomic memory unit handled by the originating object obj. For many simple types such as bytes and bytearray, an element is a single byte, but other types such as array.array may have bigger elements.

len(view) is equal to the length of tolist. If view.ndim = 0, the length is 1. If view.ndim = 1, the length is equal to the number of elements in the view. For higher dimensions, the length is equal to the length of the nested list representation of the view. The itemsize attribute will give you the number of bytes in a single element.

A memoryview supports slicing and indexing to expose its data. One-dimensional slicing will result in a subview:

 

來趟簡短的探索之旅︰

 

可用以實現能控制音量大小的大聲公乎☆

 

 

 

 

 

 

 

 

 

【鼎革‧革鼎】︰ Raspbian Stretch 《六之 J.2C 》

經過千言萬語洗禮,將知一小段派生互動︰

 

幾行 JACK Client for Python 原始碼摘要︰

 

簡單兩個連線動作︰

 

實現打招呼程式耶!當明使用裝飾子之理乎?

 

 

 

 

 

 

 

【鼎革‧革鼎】︰ Raspbian Stretch 《六之 J.2B 》

閱讀 Michele Simionato 先生寫作之

The decorator module

Author: Michele Simionato
E-mail: michele.simionato@gmail.com
Version: 4.1.1 (2017-07-16)
Supports: Python 2.6, 2.7, 3.0, 3.1, 3.2, 3.3, 3.4, 3.5, 3.6
Download page: http://pypi.python.org/pypi/decorator/4.1.1
Installation: pip install decorator
License: BSD license

說明文件︰

Introduction

The decorator module is over ten years old, but still alive and kicking. It is used by several frameworks (IPython, scipy, authkit, pylons, pycuda, sugar, …) and has been stable for a long time. It is your best option if you want to preserve the signature of decorated functions in a consistent way across Python releases. Version 4 is fully compatible with the past, except for one thing: support for Python 2.4 and 2.5 has been dropped. That decision made it possible to use a single code base both for Python 2.X and Python 3.X. This is a huge bonus, since I could remove over 2,000 lines of duplicated documentation/doctests. Having to maintain separate docs for Python 2 and Python 3 effectively stopped any development on the module for several years. Moreover, it is now trivial to distribute the module as an universal wheel since 2to3 is no more required. Since Python 2.5 has been released 9 years ago, I felt that it was reasonable to drop the support for it. If you need to support ancient versions of Python, stick with the decorator module version 3.4.2. The current version supports all Python releases from 2.6 up to 3.6.

What’s New in version 4

  • New documentation There is now a single manual for all Python versions, so I took the opportunity to overhaul the documentation. So, even if you are a long-time user, you may want to revisit the docs, since several examples have been improved.
  • Packaging improvements The code is now also available in wheel format. Integration with setuptools has improved and you can run the tests with the command python setup.py test too.
  • Code changes A new utility function decorate(func, caller) has been added. It does the same job that was performed by the older decorator(caller, func). The old functionality is now deprecated and no longer documented, but still available for now.
  • Multiple dispatch The decorator module now includes an implementation of generic functions (sometimes called “multiple dispatch functions”). The API is designed to mimic functools.singledispatch (added in Python 3.4), but the implementation is much simpler. Moreover, all decorators involved preserve the signature of the decorated functions. For now, this exists mostly to demonstrate the power of the module. In the future it could be enhanced/optimized; however, its API could change. (Such is the fate of experimental features!) In any case, it is very short and compact (less then 100 lines), so you can extract it for your own use. Take it as food for thought.
  • Python 3.5 coroutines From version 4.1 it is possible to decorate coroutines, i.e. functions defined with the async def syntax, and to maintain the inspect.iscoroutinefunction check working for the decorated function.

 

讓人眼界大開,了解『裝飾子』之用處︰

Usefulness of decorators

Python decorators are an interesting example of why syntactic sugar matters. In principle, their introduction in Python 2.4 changed nothing, since they did not provide any new functionality which was not already present in the language. In practice, their introduction has significantly changed the way we structure our programs in Python. I believe the change is for the best, and that decorators are a great idea since:

  • decorators help reducing boilerplate code;
  • decorators help separation of concerns;
  • decorators enhance readability and maintenability;
  • decorators are explicit.

Still, as of now, writing custom decorators correctly requires some experience and it is not as easy as it could be. For instance, typical implementations of decorators involve nested functions, and we all know that flat is better than nested.

The aim of the decorator module it to simplify the usage of decorators for the average programmer, and to popularize decorators by showing various non-trivial examples. Of course, as all techniques, decorators can be abused (I have seen that) and you should not try to solve every problem with a decorator, just because you can.

You may find the source code for all the examples discussed here in the documentation.py file, which contains the documentation you are reading in the form of doctests.

Definitions

Technically speaking, any Python object which can be called with one argument can be used as a decorator. However, this definition is somewhat too large to be really useful. It is more convenient to split the generic class of decorators in two subclasses:

signature-preserving decorators:
Callable objects which accept a function as input and return a function as output, with the same signature.
signature-changing decorators:
Decorators which change the signature of their input function, or decorators that return non-callable objects.

Signature-changing decorators have their use: for instance, the builtin classes staticmethod and classmethod are in this group. They take functions and return descriptor objects which are neither functions, nor callables.

Still, signature-preserving decorators are more common, and easier to reason about. In particular, they can be composed together, whereas other decorators generally cannot.

Writing signature-preserving decorators from scratch is not that obvious, especially if one wants to define proper decorators that can accept functions with any signature. A simple example will clarify the issue.

 

而且點出不留心、可能生潛在問題︰

Statement of the problem

A very common use case for decorators is the memoization of functions. A memoize decorator works by caching the result of the function call in a dictionary, so that the next time the function is called with the same input parameters the result is retrieved from the cache and not recomputed.

There are many implementations of memoize in http://www.python.org/moin/PythonDecoratorLibrary, but they do not preserve the signature. In recent versions of Python you can find a sophisticated lru_cache decorator in the standard library’s functools. Here I am just interested in giving an example.

Consider the following simple implementation (note that it is generally impossible to correctly memoize something that depends on non-hashable arguments):

 

Here I used the functools.update_wrapper utility, which was added in Python 2.5 to simplify the writing of decorators. (Previously, you needed to manually copy the function attributes __name__, __doc__, __module__, and __dict__ to the decorated function by hand).

Here is an example of usage:

 

This works insofar as the decorator accepts functions with generic signatures. Unfortunately, it is not a signature-preserving decorator, since memoize_uw generally returns a function with a different signature from the original.

Consider for instance the following case:

 

Here, the original function takes a single argument named x, but the decorated function takes any number of arguments and keyword arguments:

 

This means that introspection tools (like pydoc) will give false information about the signature of f1 – unless you are using Python 3.5. This is pretty bad: pydoc will tell you that the function accepts the generic signature *args, **kw, but calling the function with more than one argument raises an error:

 

Notice that inspect.getargspec and inspect.getfullargspec will give the wrong signature. This even occurs in Python 3.5, although both functions were deprecated in that release.

※ 參考

 

派生程式學習者或該反思

PEP 362 — Function Signature Object

Abstract

Python has always supported powerful introspection capabilities, including introspecting functions and methods (for the rest of this PEP, “function” refers to both functions and methods). By examining a function object you can fully reconstruct the function’s signature. Unfortunately this information is stored in an inconvenient manner, and is spread across a half-dozen deeply nested attributes.

This PEP proposes a new representation for function signatures. The new representation contains all necessary information about a function and its parameters, and makes introspection easy and straightforward.

However, this object does not replace the existing function metadata, which is used by Python itself to execute those functions. The new metadata object is intended solely to make function introspection easier for Python programmers.

Signature Object

A Signature object represents the call signature of a function and its return annotation. For each parameter accepted by the function it stores a Parameter object in its parameters collection.

A Signature object has the following public attributes and methods:

  • return_annotation : object

    The “return” annotation for the function. If the function has no “return” annotation, this attribute is set to Signature.empty.

  • parameters : OrderedDict

    An ordered mapping of parameters’ names to the corresponding Parameter objects.

  • bind(*args, **kwargs) -> BoundArguments

    Creates a mapping from positional and keyword arguments to parameters. Raises a TypeError if the passed arguments do not match the signature.

  • bind_partial(*args, **kwargs) -> BoundArguments

    Works the same way as bind(), but allows the omission of some required arguments (mimics functools.partial behavior.) Raises a TypeError if the passed arguments do not match the signature.

  • replace(parameters=<optional>, *, return_annotation=<optional>) -> Signature

    Creates a new Signature instance based on the instance replace was invoked on. It is possible to pass different parameters and/or return_annotation to override the corresponding properties of the base signature. To remove return_annotation from the copied Signature, pass in Signature.empty.

    Note that the ‘=<optional>’ notation, means that the argument is optional. This notation applies to the rest of this PEP.

 

的內容!評估實踐之反省?

29.12.3. Introspecting callables with the Signature object

New in version 3.3.

The Signature object represents the call signature of a callable object and its return annotation. To retrieve a Signature object, use the signature() function.

inspect.signature(callable, *, follow_wrapped=True)
Return a Signature object for the given callable:

 

Accepts a wide range of python callables, from plain functions and classes to functools.partial() objects.

Raises ValueError if no signature can be provided, and TypeError if that type of object is not supported.

New in version 3.5: follow_wrapped parameter. Pass False to get a signature of callable specifically (callable.__wrapped__ will not be used to unwrap decorated callables.)

Note

Some callables may not be introspectable in certain implementations of Python. For example, in CPython, some built-in functions defined in C provide no metadata about their arguments.

 

 

 

 

 

 

 

 

【鼎革‧革鼎】︰ Raspbian Stretch 《六之 J.2A 》

人類能夠『獨立思考』嗎?人們講︰因為他『如此說』,所以我『這般信』,難到這果是『合理』的嗎??還是這真的『不合理』的呢???就像有人探討後認為︰『差異』在『關鍵處』!也在『對的人』!!於是『問題』變成了是否『相信』了『對的人』,且在『事物』之『關鍵處』着力,就『這樣』……『決定』了……是否從此以後都能過著『自主判斷』的日子的了!!!

220px-Louvre_identifiers_Ma1274-MR242

羅浮宮雕塑背後的標識符

一個『標識符』 ID identifier

能有多少好說之事,需要如是的陣仗?假使你已發現『身份證』比『你自己』更能『證明』你是誰!各種『號碼』效用之大,可以『轉帳購物』,你才剛知道『不變』 Immutable 之『物件』 object 要比『可變』 mutable 的『你』更『安全』『可靠』的哩!!不要『懷疑』,即使那些『號碼』因『你』而『有』,在『電腦語言』裡,他們可是『第一類公民』 First-class value ,享有第一等的『價值』??

雖然有時令人『千迴百轉』的想不通?是『機器』服務於『』,還是『』符合『機器』的『處理』?!

或許那個『鄭三絕』能讓人們『回回神』的吧!『鄭板橋』固因『詩書畫』稱『三絕』,他傳聞軼事『也絕』︰

『絕對』難能卻『對』,
『絕句』自可斷『句』,
『絕情』反倒多『情』。

鄭板橋‧竹

竹本【笨】虛心是我師

 

鄭板橋‧【一聯千金

龍虎山中真宰相

麒麟閣上活神仙

 

難得糊塗

難得糊塗

 

鄭縣令‧【崇仁‧大悲】寺‧庵之戀

硃筆一批

一半葫蘆一半瓢,合來一處好成桃;
徒令人定風歸寂,此後敲門月影遙:
鳥性悅時空即色,蓮花落處靜偏嬌;
是誰勾卻風流案,記取當年鄭板橋。

─── 《W!o 的派生‧十日談之《六》

 

想要了解派生『裝飾子』者,單靠文法定義是不足的︰

The current syntax for function decorators as implemented in Python 2.4a2 is:

This is equivalent to:

without the intermediate assignment to the variable func. The decorators are near the function declaration. The @ sign makes it clear that something new is going on here.

 

首要清楚知道『函數』是什麼?

比方說《潜入派生》 Dive into Python 第二章第四節

《 2.4. Everything Is an Object 》講︰

2.4.2. What’s an Object?

Everything in Python is an object, and almost everything has attributes and methods. All functions have a built-in attribute __doc__, which returns the doc string defined in the function’s source code. The sys module is an object which has (among other things) an attribute called path. And so forth.

Still, this begs the question. What is an object? Different programming languages define “object” in different ways. In some, it means that all objects must have attributes and methods; in others, it means that all objects are subclassable. In Python, the definition is looser; some objects have neither attributes nor methods (more on this in Chapter 3), and not all objects are subclassable (more on this in Chapter 5). But everything is an object in the sense that it can be assigned to a variable or passed as an argument to a function (more in this in Chapter 4).

This is so important that I’m going to repeat it in case you missed it the first few times: everything in Python is an object. Strings are objects. Lists are objects. Functions are objects. Even modules are objects.

那麼我們將如何理解『在派生中,一切皆是物件。』這句話呢?要是不深入『派生』的『語法』以及『語意』,只依靠著『語用』根本是不足以『回答』的吧!而且不同的『程式語言』,『口號』不同,『哲學』也不一樣!!Python 號稱『多典範』,『程序』為主的寫作、『物件』中心之編程,『泛函式』概念的淺嚐,……等等,也許可以這麼說︰

『派生』支持的『作法』,讓它『語法』上『方便容易』。

『派生』不支持的『行事』,也可『己選自擇』的『表現』。

因此想要掌握 Python 語言,『深思』、『細慮』以及『多實驗』或許是個好的起步。就像嘗試看看,在『派生』中,什麼是『函式』 function 的呢?

 

─── 豈是一句『可呼叫』 callable 了得!! ───

─── 摘自《W!o 的派生‧十日談之《七》

 

同時深入『嵌套函數』內蘊︰

PEP 227 — Statically Nested Scopes

Abstract

This PEP describes the addition of statically nested scoping (lexical scoping) for Python 2.2, and as a source level option for python 2.1. In addition, Python 2.1 will issue warnings about constructs whose meaning may change when this feature is enabled.

The old language definition (2.0 and before) defines exactly three namespaces that are used to resolve names — the local, global, and built-in namespaces. The addition of nested scopes allows resolution of unbound local names in enclosing functions’ namespaces.

The most visible consequence of this change is that lambdas (and other nested functions) can reference variables defined in the surrounding namespace. Currently, lambdas must often use default arguments to explicitly creating bindings in the lambda’s namespace.

……

XXX Alex Martelli suggests comparison with Java, which does not allow name bindings to hide earlier bindings.

Examples

A few examples are included to illustrate the way the rules work.

XXX Explain the examples

 

An example from Tim Peters demonstrates the potential pitfalls of nested scopes in the absence of declarations:

 

The call to g() will refer to the variable i bound in f() by the for loop. If g() is called before the loop is executed, a NameError will be raised.

………

 

自能體會『第一類公民』之差異︰

閉包 (電腦科學)

電腦科學中,閉包英語:Closure),又稱詞法閉包Lexical Closure)或函式閉包function closures),是參照了自由變數的函式。這個被參照的自由變數將和這個函式一同存在,即使已經離開了創造它的環境也不例外。所以,有另一種說法認為閉包是由函式和與其相關的參照環境組合而成的實體。閉包在執行時可以有多個例項,不同的參照環境和相同的函式組合可以產生不同的例項。

閉包的概念出現於60年代,最早實現閉包的程式語言是Scheme。之後,閉包被廣泛使用於函數語言程式設計語言如ML語言LISP。很多命令式程式語言也開始支援閉包。

在一些語言中,在函式中可以(巢狀)定義另一個函式時,如果內部的函式參照了外部的函式的變數,則可能產生閉包。執行時,一旦外部的 函式被執行,一個閉包就形成了,閉包中包含了內部函式的代碼,以及所需外部函式中的變數的參照。其中所參照的變數稱作上值(upvalue)。

閉包一詞經常和匿名函式混淆。這可能是因為兩者經常同時使用,但是它們是不同的概念。

……

Closures

In programming languages, closures (also lexical closures or function closures) are techniques for implementing lexically scoped name binding in languages with first-class functions. Operationally, a closure is a record storing a function[a] together with an environment:[1] a mapping associating each free variable of the function (variables that are used locally, but defined in an enclosing scope) with the value or reference to which the name was bound when the closure was created.[b] A closure—unlike a plain function—allows the function to access those captured variables through the closure’s copies of their values or references, even when the function is invoked outside their scope.

Example. The following program fragment defines a higher-order function startAt with a parameter x and a nested function incrementBy. The nested function incrementBy has access to x, because incrementBy is in the lexical scope of x, even though x is not local to incrementBy. The function startAt returns a closure containing a copy of the value of x or a copy of the reference to x from this invocation of startAt, and the function incrementBy, which adds the value of y to the value of x:

Note that, as startAt returns a function, the variables closure1 and closure2 are of function type. Invoking closure1(3) (Meaning y=3) will return 4, while invoking closure2(3) (Meaning y=3) will return 8. While closure1 and closure2 refer to the same function incrementBy, the associated environments differ, and invoking the closures will bind the name x to two distinct variables with different values in the two invocations, thus evaluating the function to different results.

───

 

 

 

 

 

 

 

輕。鬆。學。部落客