2016年8月8日 星期一

[RR Python] Matplotlib with VNC

while using VNC with matplotlib, I found that there is error "_tkinter.tclerror couldn't connect to display 1.0"

the solution is here 

quote as below

===
Write these few lines to etc/sudoers*:
Defaults    env_reset
Defaults    secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
Defaults    env_keep += "DISPLAY"
Defaults    env_keep += "XAUTHORITY"
And these few lines to ~/.bashrc:
if [ -z "$XAUTHORITY" ]; then
    if [ -e $HOME/.Xauthority ]; then
        export XAUTHORITY=$HOME/.Xauthority;
    fi;
fi
===

2016年5月26日 星期四

[RR Python] Autocompletion in Python Interpreter

search for a while and found here

follows are capture and credit to Stefano Palazzo



down voteaccepted
First, create a new file called .pythonstartup.py in your home directory. Put the following script in it:
try:
    import readline
except ImportError:
    print("Module readline not available.")
else:
    import rlcompleter
    readline.parse_and_bind("tab: complete")
The parentheses around the string ensure that it works with both Python 2 and Python 3.
Every time the interactive interpreter is started, it executes a script defined in $PYTHONSTARTUP, if there is one. To set it to execute the above script, type
export PYTHONSTARTUP=".pythonstartup.py"
You should write this line to your .bashrc or .bash_profile file, so that it's automatically executed when a new shell is started.

2016年3月6日 星期日

[RR Python] PyBluez Example, beacon_scan.py beacon.py executing problem

While running PyBluez examples, beacon_scan.py beacon.py, at the first time, there is error messages

    from gattlib import *ImportError: No module named gattlib

Apparently the module gattlib which is not installed causes this error.

However, as I tried to install gattlib by pip, another error raises

    Package glib-2.0 was not found in the pkg-config search path.
    Perhaps you should add the directory containing `glib-2.0.pc'
    to the PKG_CONFIG_PATH environment variable
    No package 'glib-2.0' found
So I did 'apt-get install glib-2.0' and the error was removed. But...

    In file included from src/gattservices.cpp:12:0:
    src/gattlib.h:11:33: fatal error: boost/python/list.hpp: No such file or directory
     #include <boost/python/list.hpp>
                                     ^
    compilation terminated.

Yes, gattlib is still not installed because missing of boost. It's important to know that apt-get cannot find 'boost'. We have to install 'libboost-all-dev' instead.



After those above, 'beacon.py' and 'beacon_scan.py' are ready to go!






2016年1月14日 星期四

[RR Python] PyBluez Example, rfcomm-server.py Problem with running RFCOMM server on PORT_ANY

I always get error "_bluetooth.error: (98, 'Address already in use')" while running PyBluez example rfcomm-server.py,

The code piece is:
server_sock=BluetoothSocket( RFCOMM )
server_sock.bind(("",PORT_ANY))
server_sock.listen(1)

it's apparent that the listening port is occupied by someone since I can run it successfully if changing the port number from PORT_ANY to 2 or 3.

GoogleCodeExporter explains the issue, which might be caused by pnat server. Per discussion1 and discussion2, disabling pnat plugin in bluetooth config works. BEWARE that restart bluetooth service somehow doesn't work though, I have to reboot to make it enabled

in  /etc/bluetooth/main.confadd/append DisablePlugins = pnat
There is still question that HOW TO FIGURE OUT WHICH SERVICE/SERVER OCCUPIED WHAT PORT!!!


2015年12月23日 星期三

[RR Python] pip install pybluez 結果出現 Fatal error: Python.h: No such file or Directory

在利用pip安裝pybluez時,出現下列錯誤訊息
  In file included from bluez/btmodule.c:20:0:
  bluez/btmodule.h:4:20: fatal error: Python.h: No such file or directory
   #include "Python.h"
compilation terminated.
  error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

  ----------------------------------------
  Failed building wheel for pybluez
Failed to build pybluez
一開始以爲是權限問題(真是壞習慣,不仔細看錯誤訊息往往是欲速則不達),加了sudo後還是沒有用的。接著猜是virtualenv環境路徑没設好(這次錯怪它了)。查了Debian / Ubuntu: Fatal error: Python.h: No such file or Directory 才發現是不但没有python.h,整個python-dev都没裝啦啦啦。

sudo apt-get install python-dev

簡單裝完後再pip pybluez,結果
     #include <bluetooth/bluetooth.h>
                                     ^
    compilation terminated.
    error: command 'x86_64-linux-gnu-gcc' failed with exit status 1
 
果然代誌不是像憨人想得那麽簡單呀- libbluetooth-dev没裝

總算
Successfully installed pybluez-0.22




2015年9月10日 星期四

[RR Python] 建立獨立開發環境 virtualenv virtualenvwrapper

python的威力是有許多已經被開發的模組可以使用
讓程式設計者能專注在程式功能與邏輯上

然而寫python程式最怕的就是使用不同的版本的模組,甚至是不同版本的python
virtualenv的介紹有提到:
"
The basic problem being addressed is one of dependencies and versions, and indirectly permissions. Imagine you have an application that needs version 1 of LibFoo, but another application requires version 2. How can you use both these applications? If you install everything into /usr/lib/python2.7/site-packages (or whatever your platform’s standard location is), it’s easy to end up in a situation where you unintentionally upgrade an application that shouldn’t be upgraded.
 "

virtualenv / virtualenvwrapper (大致上)解決了這個問題

建立環境
mkvirtualenv test1

mkvirtualenv test1 -p /usr/bin/python3.3 

離開環境
deactivate
使用先前建立的環境
workon test1
刪除先前建立的環境
rmvirtualenv test1

 
 
 
 
Szymon Lipiński 有相當簡潔的安裝與使用範例

Virtualenv Tutorial Part 2

sudo pip install virtualenvwrapper

mkdir ~/.virtualenvs


A Primer on virtualenv 也提供了使用virtualenv的建議

 

2015年9月8日 星期二

[RR Python] Difference between built in repr() and str() - 兩者的不同

Official definition:
repr(object)
Return a string containing a printable representation of an object. This is the same value yielded by conversions (reverse quotes). It is sometimes useful to be able to access this operation as an ordinary function. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() method.


class str(object='')
Return a string containing a nicely printable representation of an object. For strings, this returns the string itself. The difference with repr(object) is that str(object) does not always attempt to return a string that is acceptable to eval(); its goal is to return a printable string. If no argument is given, returns the empty string, ''.
eval(expression[, globals[, locals]])
The arguments are a Unicode or Latin-1 encoded string and optional globals and locals. If provided, globals must be a dictionary. If provided, locals can be any mapping object.

The expression argument is parsed and evaluated as a Python expression (technically speaking, a condition list) using the globals and locals dictionaries as global and local namespace. If the globals dictionary is present and lacks ‘__builtins__’, the current globals are copied into globals before expression is parsed. This means that expression normally has full access to the standard __builtin__ module and restricted environments are propagated. If the locals dictionary is omitted it defaults to the globals dictionary. If both dictionaries are omitted, the expression is executed in the environment where eval() is called. The return value is the result of the evaluated expression. Syntax errors are reported as exceptions. Example:
>>
>>> x = 1
>>> print eval('x+1')
2
This function can also be used to execute arbitrary code objects (such as those created by compile()). In this case pass a code object instead of a string. If the code object has been compiled with 'exec' as the mode argument, eval()‘s return value will be None.
interesting demo below:
>>> s = "x +1"
>>> s
'x +1'
>>> print s
x +1
>>> str(s)
'x +1'
>>> print str(s)
x +1
>>> repr(s)
"'x +1'"

>>> print repr(s)
'x +1'
>>> x = 1
>>> eval(s)
2
>>> eval(str(s))
2
>>> eval(repr(s))
'x +1'
form Python Essential Reference, 4ed.
The __repr__() and __str__() methods create simple string representations of an object.The __repr__() method normally returns an expression string that can be evaluated to re-create the object.This is also the method responsible for creating the output of values you see when inspecting variables in the interactive interpreter.This method is invoked by the built-in repr() function.

a = [2,3,4,5]      # Create a list
s = repr(a)         # s = '[2, 3, 4, 5]'
b = eval(s)         # Turns s back into a list

Furthermore, Difference between __str__ and __repr__ in Python has extensively explanation of them. In short:

  1. __repr__ goal is to be unambiguous
  2. __str__ goal is to be readable
  3. Implement __repr__ for any class you implement. This should be second nature. Implement __str__ if you think it would be useful to have a string version which errs on the side of more readability in favor of more ambiguity.
  4. if you override __repr__, that's ALSO used for __str__, but not vice versa (Container’s __str__ uses contained objects’ __repr__)