Posts tagged ‘Linux’

DreamPie with virtualenv

2012-05-10 20:44

If you haven't heard about it, DreamPie is an awesome GUI application layered on top of standard Python shell. I use it for elaborate prototyping where its multi-line input box is a significant advance over raw, terminal UX of IPython.

However, up until recently I didn't know how to make DreamPie cooperate with virtualenv. Because it's a GUI program, I scoured its menu and all the preference windows, searching for any trace of option that would allow me to set the Python executable. Having failed, I was convinced that authors didn't think about including it - which was rather surprising, though.

But hey, DreamPie is open source! So I went to look around its code to see whether I can easily enhance it with an ability to specify Python binary. It wasn't too long before I stumbled into this vital fragment:

def main():
    usage = "%prog [options] [python-executable]"
    version = 'DreamPie %s' % __version__
    parser = OptionParser(usage=usage, version=version)
    # ...
    opts, args = parser.parse_args()

The conclusions we could draw from this anecdote are thereby as follows:

  • It is indeed true that source code is often the best documentation...
  • ...especially for open source programs where actual docs often suck.

With this newfound knowledge about dreampie arguments, it wasn't very hard to make it use current virtualenv:

$ dreampie $(which python)

And after doing some more research, I ended up adding the following line to my ~/.bash_aliases:

alias dp='(dreampie $(which python) &>/dev/null &)'

Now I can simply type dp to get a DreamPie instance operating within current virtualenv but independent from terminal session. Very useful!

Tags: , , , ,
Author: Xion, posted under Applications, Programming » Add comment

Counting Lines in Multiple Files

2012-04-06 13:40

Looks like using Linux is really bound to slowly - but steadily - improve your commandline-fu. As evidence, today I wanted to share a little piece of shell acolyte's magic that I managed to craft without very big trouble. It's about counting lines in files - code lines in code files, to be specific.

For a single file, getting the number of text rows is very simple:

$ wc -l some.file
  142 some.file

Although the name wc comes from "word count", the -l switch changes its mode of operation into counting rows. The flexibility of this little program doesn't end here; for example, it can also accept piped input (as stdin):

$ cat some.file | wc -l
142

as well as multiple files:

$ wc -l some.file other.file
  142 some.file
   54 other.file
  196 all

or even wildcards, such as wc -l *.file. With these we could rather easily count the number of lines of code in our project:

$ wc -l **/*.py
    3 foo/__init__.py
  189 foo/main.py
   89 foo/utils.py
   24 setup.py
  133 tests.py
  438 all

Unfortunately, the exact interpretation of **/* wildcard seems to vary between shells. In zsh it works as shown above, but in bash I had it omit files from current directory. While it might make some sense here (as it would give a total without setup script and tests), I'm sure it won't be the case all projects.

And so we need something smarter.

Pimp My WLAN

2012-03-03 20:41

About two weeks ago I moved to Netherlands, landing in a medium-sized but cozy town of Groningen. This of course deserves a general blogpost on its own right (more than a single one, in fact), but the story I wanted to share today is extremely specific. For the most part, it's also purely technical, exhibiting typical hacker's dynamics. An overarching theme is an "itch" that needs to be scratched.

Let's start then, first by defining the problem at hand.

On architectural features

I happen to live in a square which is referred to as town's center, where significant fraction of buildings - maybe even majority - look kinda like this. Don't pay too much attention to the outside appearance, as it can be very misleading. Despite their seemingly old architectural style, they're often quite new and modern, but have been "retrofitted" to match the surrounding urban landscape. Final effect is rather pleasing aesthetically, I'd say.

What is more important and relevant here, though, is the size of windows. By my standards at least, they are simply enormous - and this fact precludes simple evaluation. (On one hand, there's a lot of sunlight! On the other hand, there's a lot of sunlight...). Moreover, it hints at how remarkably long the vertical distance between floor and the ceiling is. In my case, it's about 2.8 m (that's 9 ft for you Imperalists), having a significant impact on how spacious the apartment feels.

On insufficiently vertical waves

But for the issue I want to talk about, this was actually a downside. The matter concerns Internet access, which is shared among mine and three neighboring apartments through a Wi-Fi network with a single access point. In theory, the area it has to cover spans just couple of meters. In practice, however, it's hindered not only by walls and doors, but also - and maybe even primarily - but this significant distance along the vertical axis.

See, most of the typical household wireless routers have directional antennae which are deliberately set to output signal mostly in the horizontal plane. While this allows for a single AP to easily cover even big apartment, it is also a liability in a setting similar to mine. Because the access point is on ground floor, it fails to appropriately cover the higher levels. And since this includes the very place I'm living in, I've been having rather annoying problems caused by signal's low strength and quality: dropped packets, lost connections, and all that stuff. Even web browsing (or similar activities that doesn't really depend on latency) has been very cumbersome, despite sitting less than 5 meters in straight line from the access point! It's almost amazing how one can get screwed over by such simple design limitation like the direction of an antenna.

So, you can easily see how this was a problem that yearned to be solved. But how? One does not simply make the waves go further, right?...

On re-purposing of the old hardware

Actually, this is perfectly possible: devices known as WLAN repeaters do just that. Serving as sort of amplifier, they can extend the range of wireless network by relaying its signal between base access point and the final receiver, e.g. WLAN interface in a laptop. Basic physics suggest that it obviously cannot be done for free, so side effects include decreased performance of such range-extended networks due to reduced bandwidth. But where applicable, this solution is usually worth its while.


The Router

My scenario was definitely one of those, as I vastly prefer "not ideal Wi-Fi connectivity" to "almost no Wi-Fi connectivity at all". So I went to investigate how I could procure such a device. Specifically, I had an old router lying around unplugged and useless - and it quickly gained my attention.

I cannot say that I'm any sort of expert when it comes to telecommunication, electronics or hardware of any kind (that's vastly below the level abstraction I typically operate on), but I have some basic idea of what a wireless router really is. Elementary deduction suggest it's a transceiver, an equipment able to receive and send out radio signals. What those signals are - that should be pretty much irrelevant, as long as (1) they fit into physical characteristics of the device and (2) the only thing we want to do is to propagate them further.

In short, it should be capable of acting as a repeater! Yay?

On awesomeness of the open source

Well, not really - not at a first glance, at least. While many routers feature the repeater option in their firmware, mine is somewhat old and low-end model: it doesn't even support IPv6, not to mention goodies like the 802.11n band. Acting as a relay was also on this "nay" list, because being an ordinary access point is pretty much the only thing this inconspicuous black box used to know.

But thanks to one impressive piece of hackery, it was possible for its limitations to be lifted. What I'm talking about is DD-WRT - a community project that provides a custom firmware for variety of different models of popular routers. This firmware is very powerful and allows to easily tap into device's hidden power, exposing capabilities omitted in vendor software. In my case, it promised to provide the crucial Client Bridge feature: ability to create more then one virtual, wireless interface and form a bridge between them in order to relay network traffic.

On thrills & perils of low-level hacking

I set to try it out - and it turned out to be non-trivial, to say the least. Some steps of the process were amusing due to their obscurity - like setting up a local server for the archaic TFTP protocol. Turns out it was needed for the actual transfer of new firmware and a small Linux distro that works on top of that. I suppose you have to do same when installing Linux on a microwave, but admittedly, I haven't tried that just yet ;)

The most troublesome part was actually the very beginning. It involved connecting to the device via Ethernet wire and then telnetting at the right moment during it's boot-up. This way, it is possible to access the RedBoot bootstrapping shell and perform all kinds of surgery on software internals.
Unfortunately, the instruction for making this happen was hopelessly unclear. I spent good several quarters troubleshooting any potential issues, even going as far as to use Wireshark to monitor any traffic originating from the router, looking into how it identifies itself within this crude two-node network.

Fortunately, I've later found a much better instruction that didn't lack the rather important part about holding down the RESET button for, well, long time. From there everything went rather smoothly.

On trickery of network management

The last part was tweaking numerous options and settings in DD-WRT's web interface in order to make the router talk to its cousin downstairs. This level of abstraction was obviously much more comfortable for me to work at. Still, there was some sorcery involved, as in deciding whether I'd like to have my own subnet or operate within existing one - essentially a choice between WLAN-to-WLAN router or "switch". The second option was of course much more appealing because it was completely transparent to clients. Choosing it, I didn't have to reconfigure the vast multitude of my 3 (three) devices that use Wi-Fi :)

This variant ended up being more complicated, though. And again, I have found both good and rather crappy instructions on how to make it happen - but unlike last time, now they were both coming from the DD-WRT wiki. Well, seems like documentation is not among the strongest sides of this project...

It works!

But rest assured: this story has a happy ending :) Yes, it was preceded by juggling IP configuration of my PC and few reboots of the router, but it would be malicious to consider this as something more than a little nuisance.

So, what's the point in all of this?... I guess the bottom line would be about not being afraid to experiment if something needs to be improved. Risk aversion is powerful, true - but sometimes even failure is not that bad, especially if everything remains inside the realm of software. Here, even if you "blow" something up there will be no holes left to cover with duct tape ;-)

Nieoficjalne debugowanie na Androidzie

2010-12-22 22:00

System Android, jak powszechnie wiadomo, jest licencjonowany kategorią open source, więc istnieje możliwość w miarę łatwego umieszczenia go na urządzeniach mobilnych bez konieczności współpracy z Google. Wykorzystują to producenci różnego rodzaju mniej lub bardziej "nieoficjalnego" sprzętu, działającego pod kontrolą tego systemu. Mogą to być produkty, które trudno klasyfikować inaczej niż jako tanie imitacje, ale także sprzęt produkowany przez (u)znane firmy - jak choćby tablet stworzony przez Creative. Ich wspólną cechą jest domyślny brak wsparcia przez narzędzia wspomagające pisanie aplikacji dostępne w ramach SDK Androida - przede wszystkim Android Debug Bridge (adb), czyli usługę umożliwiającą między innymi debugowanie aplikacji bezpośrednio na urządzeniu. Dla zwykłego użytkownika to oczywiście żadna wada, ale co mają zrobić biedni programiści?...
Okazuje się jednak, że przeszkodę tę da się pokonać. Dzisiaj udała mi się ta sztuka ze wspomnianym tabletem Creative'a i dlatego czuję się upoważniony podzielić się swoim rozwiązaniem :) Wydaje się ono przy tym na tyle ogólne, że powinno stosować do dowolnego urządzenia.

Tags: , , , , ,
Author: Xion, posted under Programming » Add comment

Więcej pulpitów

2010-12-09 23:23

Pracując przez chwilę na Linuksie, odkryłem poważną zaletę jego interfejsu graficznego, którą Windows domyślnie nie może się pochwalić. Wirtualne pulpity, bo o nich mowa, to koncept, który w pierwszej chwili może wydawać się nieco dezorientujący. W końcu czasami ma się problem z ogarnięciem okien na jednym tylko pulpicie, więc co dopiero powiedzieć o - powiedzmy - czterech? :) Ale więcej miejsca na bałagan to także więcej miejsca na porządek i jeśli tylko potrafimy dobrze tę powiększoną przestrzeń zagospodarować, możemy znacznie zyskać na efektywności. Ograniczamy bowiem konieczność przełączania między programami za pomocą powolnych i niewygodnych metod, takich jaki klikanie w przyciski na pasku zadań czy pracowite przechodzenie po liście okien za pomocą przełącznika Alt+Tab.

To doprawdy wstyd, że Windows nie oferuje takiego mechanizmu wbudowanego w system. Jakby się jednak chwilę nad nim zastanowić, nie jest on żadnym rodzajem magii. Można go przynajmniej symulować za pomocą odpowiednio przemyślanego ukrywania i odkrywania okien na żądanie użytkownika, przechodzącego między kolejnymi "wirtualnymi «wirtualnymi pulpitami»". Zdaje się, że właśnie na takiej zasadzie działają programy, które uzupełniają system Windows o tę pożyteczną funkcjonalność.
Rozwiązaniem wypróbowanym przeze mnie jest VirtuaWin. Jest to bardzo mała, ale całkiem zmyślna aplikacja. Bez widocznego narzutu na zasoby systemowe (kilka megabajtów w pamięci) wprowadza ona możliwość przełączania się między wirtualnymi pulpitami przy pomocy typowych kombinacji klawiszy (czyli Ctrl+Alt+strzałki). I to niemal dowolną liczbą wirtualnych pulpitów, do których można automatycznie przypisywać okna na podstawie ustalonych (bazujących np. na klasie okna lub jego tytule). Jedyne, czego tu brakuje, to ładna animacja przełączania zamiast znikających i pojawiających się okien... ale cóż, nie można mieć wszystkiego ;)

W każdym razie polecam przyjrzenie się możliwości powielenia swojego pulpitu nawet bez przyłączania dodatkowych ekranów. Opłaca się.

Tags: , ,
Author: Xion, posted under Applications » 2 comments

Triki z PowerShellem #17 – Stan baterii

2010-11-02 18:27

Wykonywałem ostatnio skomplikowane akrobacje z bashem, plikiem /etc/rc.local, modułami kernela i innymi linuksowymi wynalazkami, aby uruchomić system spod znaku pingwina na swoim laptopie. Problem leżał w posiadaniu przezeń dwóch kart graficznych, działających w trybie hybrydowym, z których jedna (zintegrowana) działa zawsze, natomiast druga (zewnętrzna) budzi się na żądanie w celu obsłużenia bardziej skomplikowanych aplikacji graficznych i gier. Naturalnie Linux nie jest przygotowany do współpracy z tą technologią. więc o bezproblemowym działaniu X-owych okienek (poza trybem recovery) nie mogło być mowy.
Rozwiązaniem było całkowite wyłączenie zewnętrznej karty i to w niezbyt delikatny sposób, bo poprzez... pozbawienie jej zasilania za pomocą odpowiedniego polecenia modułu acpi. O tym, czy polecenie to faktycznie coś dało, mogłem się natomiast przekonać przy pomocy obserwacji szybkości rozładowywania się baterii, dostępnej w pliku /proc/acpi/battery/BAT1/state i wyglądającej mniej więcej tak:

present:                 yes
capacity state:          ok
charging state:          discharging
present rate:            13634 mW
remaining capacity:      57720 mWh
present voltage:         15947 mV

Tak to właśnie wygląda na systemie, który podobno "po prostu działa" ;-) Żarty żartami, ale powyższy raport nt. stanu zasilania jest zbiorem całkiem interesujących informacji, które byłyby pożyteczne także i w systemie Windows. Pomyślałem więc, czy i tam nie udało by się pozyskać podobnych danych. Odpowiedź - jak można się domyślić - jest oczywiście pozytywna.

Tags: , , , ,
Author: Xion, posted under Applications, Programming » Add comment

Partycja na plik wymiany

2010-10-28 18:25

Instalując ostatnio Linuksa zauważyłem, iż standardową praktyką tego systemu jest wydzielanie zupełnie osobnej partycji na plik stronnicowania (pagefile), zwany też potocznie plikiem wymiany. Mówiąc zresztą ściślej, Linux nie tworzy tam żadnych plików i zamiast tego korzysta z partycji bezpośrednio jako źródła miejsca dla pamięci wirtualnej.

Skąd taki pomysł, skoro Windows domyślnie radzi sobie całkiem dobrze, trzymając swoje dane stronnicowania w zwykłym pliku?... No cóż, to jest jedna z tych rzeczy, które Linux akurat robi lepiej. Umieszczenie pliku wymiany na innej partycji niż systemowa ma bowiem uzasadnienie wydajnościowe. W najlepszym wypadku ona sama powinna zresztą znajdować się na zupełnie osobnym dysku, dzięki czemu możliwe byłoby równolegle korzystanie z pliku wymiany i "normalnych" danych. Oczywiście nie zawsze jest to możliwe, zwłaszcza w komputerach przenośnych, siłą rzeczy dysponujących tylko jednym fizycznym dyskiem.

Co dokładnie daje umieszczenie pliku wymiany na jego własnej partycji? Myślę, że nietrudno się tego domyślić: chodzi o brak fragmentacji. Ponieważ brak jest kontaktu z jednostkami alokacji innych rodzajów danych, możliwe jest zachowanie integralności pliku wymiany, który w dodatku położony będzie zawsze blisko początku swojej partycji. To zaś przyspiesza do niego dostęp.
Znaczenie ma również położenie samej partycji na dysku. W idealnym przypadku powinna być ona na samym początku dysku, ale niestety jest to właściwie nie do osiągnięcia, jako że tam zwykle znajduje się już system operacyjny. Jeżeli nie chcemy go reinstalować, to dobrym rozwiązaniem jest umieszczenie partycji swap pośrodku dysku, między częścią systemową a partycją z danymi. Minimalizujemy wtedy drogę głowicy do pliku wymiany, jeśli już znajduje się ona nad którąś ze wspomnianych dwóch części. Wadą tego rozwiązania jest kłopotliwe powiększanie którejś z nich, jeśli kiedyś okaże się, że potrzebujemy więcej miejsca na system kosztem danych lub odwrotnie. Nie ma bowiem wtedy innej opcji jak usunięcie partycji wymiany i stworzenie jej na nowo.

Tags: , ,
Author: Xion, posted under Computer Science & IT » 16 comments
 


© 2012 Karol Kuczmarski "Xion". Layout by Urszulka. Powered by WordPress with QuickLaTeX.com.