Tuesday, April 30, 2013

Python string permutation

很多時候需要有枚舉一串字的需求

Python 內建的 itertools 其實就有內建了

再加上 generator 語法可以很簡單的解決問題


In [1]: import itertools

In [2]: S = "abc"

In [3]: ("".join(i) for i in (itertools.permutations(sorted(S))))
Out[3]: <generator object <genexpr> at 0x1aa02d0>

In [4]: print ["".join(i) for i in (itertools.permutations(sorted(S)))]
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']

In [5]: for i in ("".join(i) for i in (itertools.permutations(sorted(S)))): print i,
abc acb bac bca cab cba



"".join 是常用的 list->string 的標準作法,因為原本拿出來的結果是一個個的 tuple



In [6]: list(i for i in (itertools.permutations(sorted(S))))
Out[6]:
[('a', 'b', 'c'),
 ('a', 'c', 'b'),
 ('b', 'a', 'c'),
 ('b', 'c', 'a'),
 ('c', 'a', 'b'),
 ('c', 'b', 'a')]

Sunday, April 28, 2013

Perl Dumpvalue

Perl 寫程式時,常遇到複雜物件的處理,尤其是從 CPAN 上面拿到的 modules 有的  doc 往往標示不清,要用時不確定物件的確實結構,不知如何下手。

除了 Data::Dumper 以外,今天看到 Dumpvalue 這個也是內建的好用物件解析工具



使用方法:

#!/usr/bin/perl
use 5.014;
 
sub show {
    require Dumpvalue;
    state $prettily = Dumpvalue->new( compactDump => 1, veryCompact => 1);
    state $ugly = Dumpvalue->new();

    say "-"x40;
    $prettily->dumpValue(\@_);
    say "-"x30;
    $ugly->dumpValue(\@_);
    say "-"x40;
}
 
my @AoA = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
my @AoH = ({1 => 2}, {2 => 3}, {3 => 4});
show(@AoA);
show(@AoH);


output:

----------------------------------------
0  ARRAY(0x9661910)
   0  0..2  1 2 3
   1  0..2  4 5 6
   2  0..2  7 8 9
------------------------------
0  ARRAY(0x9661910)
   0  ARRAY(0x9653068)
      0  1
      1  2
      2  3
   1  ARRAY(0x9653c58)
      0  4
      1  5
      2  6
   2  ARRAY(0x9653d18)
      0  7
      1  8
      2  9
----------------------------------------
----------------------------------------
0  1 => 2
1  2 => 3
2  3 => 4
------------------------------
0  HASH(0x9653c68)
   1 => 2
1  HASH(0x9661ad0)
   2 => 3
2  HASH(0x9661b10)
   3 => 4
----------------------------------------


Ref.

perldoc lol


http://perldoc.perl.org/Dumpvalue.html



Python bytearray

在寫接近 C 的想法時,會想要在 Python 使用想是 C 的 array of char

之前一直為這個問題困擾很久,因為我只會用 Python string XD

看了點攻略,其實有這個可以用

於是乎就可以爽爽的用可變長度的 array of char in python 啦~


In [18]: a = bytearray(b'\x41\x42\x43\x44')    # create 'ABCD' in array of bytes

In [19]: a
Out[19]: bytearray(b'ABCD')

In [20]: a.lower()                             # to lowercase
Out[20]: bytearray(b'abcd')

In [21]: a[0] = 0x45                           # assign values just like char[] in C language

In [22]: a
Out[22]: bytearray(b'EBCD')

In [23]: a.decode('ascii')                     # get a string in ASCII
Out[23]: 'EBCD'

In [24]: a.append(ord('F'))                    # variable length

In [25]: a
Out[25]: bytearray(b'EBCDF')



很棒的是,基本上 string 的方法都可以用



In [27]: bytearray.
bytearray.append      bytearray.isalnum     bytearray.mro         bytearray.split
bytearray.capitalize  bytearray.isalpha     bytearray.partition   bytearray.splitlines
bytearray.center      bytearray.isdigit     bytearray.pop         bytearray.startswith
bytearray.count       bytearray.islower     bytearray.remove      bytearray.strip
bytearray.decode      bytearray.isspace     bytearray.replace     bytearray.swapcase
bytearray.endswith    bytearray.istitle     bytearray.reverse     bytearray.title
bytearray.expandtabs  bytearray.isupper     bytearray.rfind       bytearray.translate
bytearray.extend      bytearray.join        bytearray.rindex      bytearray.upper
bytearray.find        bytearray.ljust       bytearray.rjust       bytearray.zfill
bytearray.fromhex     bytearray.lower       bytearray.rpartition
bytearray.index       bytearray.lstrip      bytearray.rsplit
bytearray.insert      bytearray.maketrans   bytearray.rstrip



Friday, April 26, 2013

qsort in Python/Perl

社窩開始了 python 練習

題目是 qsort

其實就是最簡單的想法,分兩堆然後相加



第一次寫的方法是用 filter, 不過某 apua 說要用 list comprehension 才潮,所以 XD

然後後來寫了 Perl 版


Python

q = lambda l: (q(filter(lambda x: x > l[0], l)) + [l[0]] + q(filter(lambda x: x < l[0], l)) if l else [])


q = lambda l: ((q([ x for x in l if x > l[0]]) + [l[0]] + q([ x for x in l if x < l[0]])) if l else [])


print q([3, 5, 1, 2, 4, 7, 89, 9, 10])

Perl

sub qs { @_ ? (qs(grep {$_ > $_[0]} @_), $_[0], qs(grep {$_ < $_[0]} @_)): (); }

say join(", ", qs(10, 6, 2, 6, 2, 6, 4, 1, 3));




其實這想法很 FP,以下可以看看 Haskell code XD

Haskell

qsortOneLine s = case s of{[]->[];(x:xs)->qsortOneLine [y | y<-xs, y<x] ++ x : qsortOneLine [y | y<-xs, y>=x]}

Thursday, April 18, 2013

ip tools note

ifconfig 和一些 tools 已經要漸漸被拿掉了

整理一些用法

old         ->  new
=====================================
arp         ->  ip n (ip neighbor)
ifconfig    ->  ip l (ip link)
                ip a (link addr)

iptunne     ->  ip tunnel
iwconfig    ->  iw
netstat     ->  ss
                ip route (for netstat-r)
                ip -s link (for netstat -i)
                ip maddr (for netstat-g) (multicast address)

route       ->  ip r (ip route)


ip link                                             # <if>: interface something like 'enp2s0'
ip link set <if> up                                 # switch <if>
ip link set <if> down
ip link show dev <if>                               # show <if>
ip link set dev <if> mtu 1400                       # set mtu
ip link add link eth0 name eth0.10 type vlan id 10  # create vlan
ip link delete dev eth0.10                          # delete vlan

ip addr add <ip address>/<subnetmask> dev <if>      # add address
ip addr del <ip address>/<subnetmask> dev <if>      # delete address
ip addr show dev <if>                               # show address
ip addr flush dev <if>                              # removes all addresses from device <if>

ip route add default via <gateway's ip address>     # add a routing path
ip route add - add new route
ip route change - change route
ip route replace - change or add new one


ref.

wiki.archlinux.org Network Configuration
wiki.archlinux.org VLAN

miyagawa says good luck to me

非常崇拜的日本 hacker miyagawa 親自為我期中考加油耶!!!!


潮爽的~~~

14:30 | darkx > 可惜明天無法到場,否則真的很想聽 miyagawa 的 talk
14:31 | miyagawa > darkx: hmm too bad!
14:31 | darkx > :)
14:33 | FourDollars > miyagawa: You can read Chinese! Awesome!
14:33 | miyagawa > 繁体字 is easier to read :)
14:33 | miyagawa > still often needs google translate though
14:33 | FourDollars > haha
14:34 | darkx > I have to take my midterm exam tomorrow, but still really excited about your
                talk!
14:34 | miyagawa > darkx: good luck!
14:35 | darkx > miyagawa: cpanm is an excellent tool for we Perl users, it rocks!

Monday, April 8, 2013

bitcoin mining

bitcoin 應該是愈來愈重要的東西了... 所以及早入場(?

http://bitcoin.org/en/

最簡單的方法是到 pool 裏面跟大家一起挖

pools 有很多種,我是到這邊

https://mining.bitcoin.cz

然後裝 cgminer 就好了

$ git clone https://github.com/ckolivas/cgminer.git
$ cd cgminer

$ ./autogen.sh

# enable CPU mining
$ ./configure --enable-cpumining

$ make
$ sudo make install

$ cgminer -o http://api.bitcoin.cz:8332 -u <user> -p <password>


為了避免影響到其他工作可以 renice 它
$ ps aux | grep cgminer
$ renice 19 <pid>