MacOSX Services使用技巧

Posted by 4Aiur on 02/23/2011 in MacOSX with Comments closed |

MacOSX Services使用技巧

在MacOSX中利用Services快速完成某些工作,下面我举几个小例子演示一下。

  1. 简繁字转换
    在文本编辑器中选中需要转换的文字后点击桌面左上角的编辑器名 -> Services -> Text -> Convert Selected Simplified Chinese Text
    Services Convert Text
  2. 快速把文档当作附件发送
    在Finder中选中文件后点击桌面左上角的Finder -> Services -> Messaging -> New Email With Attachment
    Services new Email With Attachment
  3. 使用Textmate打开文件夹
    打开Automator新建Service,在Actions中搜索Open Finder Items,双击或者把“Open Finder Items”拖动到右边,在右边的Open with:中选中Textmate,保存为Open in TextMate。
    之后有需要新项目需要用TextMate打开,就可以直接掉用Services了。
    Finder -> Services -> Files and Folders -> Open in TextMate
    Services Open in Text Mate

附:
Textmate官网提供了一个Finder中的Toolsopen in textmate from finder,用这个工具也挺方便的。
安装好后在Finder中选中要打开的Folder,点击OpenInTextMate即可。

Tags: , ,

使用python实现简易的文件共享

Posted by 4Aiur on 01/21/2011 in Python with Comments closed |

使用python实现简易的文件共享

可以利用python的SimpleHTTPServer共享自己的文件给其他人

python -m SimpleHTTPServer 8000

需要从其他人那拷贝东西到自己机器上时可以用python的CGIHTTPServer这个模块,写一个CGI程序来接收文件。

# alias
alias cgiserver="ifconfig | grep --color -o 'inet 1[79]2[^ ]*'; python -m CGIHTTPServer 8000" # cgi_directories ['/cgi-bin', '/htbin']

# Create directory
mkdir incoming/
cd incoming/
mkdir cgi-bin/ files
# Create save file CGI program
cat > cgi-bin/save_file.py 
%s
cgiserver

其他人通过访问http://uripaddress:8000/upload.html来上传文件。

Tags: ,

修改gb2312网页编码为utf-8

Posted by 4Aiur on 01/10/2011 in Shell with Comments closed |

修改gb2312网页编码为utf-8

find html/ -type f -name "*.html" | \
while read line
do
    mkdir -p foo/dirname $line/
    iconv -f GB18030 -t UTF-8 $line 2>/dev/null | \
    sed /charset=gb2312/'s/charset=gb2312/charset=utf-8/' \
    > foo/$line
done

Tags:

Install GetBundles

Posted by 4Aiur on 01/10/2011 in MacOSX with Comments closed |

Install GetBundles

管理TextMate Bundle的工具,方便查找、安装、更新TextMate Bundle的工具。

mkdir -p ~/Library/Application\ Support/TextMate/Bundles
cd !$
svn co http://svn.textmate.org/trunk/Review/Bundles/GetBundles.tmbundle/
osascript -e 'tell app "TextMate" to reload bundles'

Tags: ,

OpenSolaris rsync install script

Posted by 4Aiur on 12/21/2010 in OpenSolaris with Comments closed |

OpenSolaris rsync install script

#!/bin/bash
# OpenSolaris rsync installer
# Created by 4Aiur on 2010-12-21.

# define function
check_rsync_config () {
    if [ ! -d /opt/local/etc/rsync/ ]; then
        mkdir -p /opt/local/etc/rsync/
    fi

    if [ ! -f /opt/local/etc/rsync/rsyncd.conf ]; then
        cat > /opt/local/etc/rsync/rsyncd.conf  /opt/local/etc/rsync/rsyncd.secrets  /var/svc/manifest/network/rsync.xml 



EOF
    fi
}

rotate_log () {
    logadm -w rsync -s 10m -C 10 -t '/var/log/rsync.log.%Y-%m' \
    -a '/usr/sbin/svcadm restart rsync' /var/log/rsync.log
}

# Main
echo "setup rsync server start"
# Check rsync package
if ! pkgin list | grep rsync >/dev/null; then
    pkgin -y in rsync
fi

# Check rsync server config file
check_rsync_config

# Check rsync service config
check_svc_rsync

# Import rsync.xml
if ! svcs -a | grep net-snmp >/dev/null; then
    svccfg import /var/svc/manifest/network/rsync.xml
fi
svcadm enable rsync

# Add log rotate config
rotate_log

echo "setup rsync server done"

Tags: ,

Logrotate on OpenSolaris

Posted by 4Aiur on 12/21/2010 in OpenSolaris with Comments closed |

Logrotate on OpenSolaris

On OpenSolaris, you use the logadm command, with the actual rotation being specified in /etc/logadm.conf

logadm -v -w rsync -s 10m -C 10 \
-t '/var/log/rsync.log.%Y-%m' \
-a '/usr/sbin/svcadm restart rsync' \
/var/log/rsync.log

Testing with logadm -p now rsync seems to work just fine.

Tags: ,

OpenSolaris net-snmp install script

Posted by 4Aiur on 12/16/2010 in OpenSolaris with Comments closed |

OpenSolaris net-snmp install script

#!/bin/bash
# OpenSolaris net-snmp installer
# Created by 4Aiur on 2010-12-14.

# define function
check_netsnmp_config () {
    if [ ! -f /var/net-snmp/snmpd.local.conf ]; then
        cat > /var/net-snmp/snmpd.local.conf 

###############################################################################
# Process checks.
# Make sure sshd is running
proc sshd

###############################################################################
# disk checks
# disk PATH [MIN=DEFDISKMINIMUMSPACE]
# Check the / partition and make sure it contains at least 20 percent.
disk / 20%

###############################################################################
# load average checks
# load [1MAX=DEFMAXLOADAVE] [5MAX=DEFMAXLOADAVE] [15MAX=DEFMAXLOADAVE]
load 12 14 14

###############################################################################
# Executables/scripts
# exec NAME PROGRAM [ARGS ...]
exec echotest /bin/echo hello world
EOF
    fi
    chmod 600 /var/net-snmp/snmpd.local.conf
}

check_svc_netsnmp () {
    if [ ! -f /var/svc/manifest/application/management/net-snmp.xml ]; then
        cat > /var/svc/manifest/application/management/net-snmp.xml 




EOF
    fi
}
# Check net-snmp package
if ! pkgin list | grep net-snmp >/dev/null; then
    pkgin -y in net-snmp
fi

# Check directory
if [ ! -d /var/net-snmp/ ]; then
    mkdir -p /var/net-snmp/
fi

# Check net-snmp config file.
check_netsnmp_config

# Check net-snmp service config
check_svc_netsnmp

# Import net-snmp.xml
if ! svcs -a | grep net-snmp >/dev/null; then
    svccfg import /var/svc/manifest/application/management/net-snmp.xml
fi
svcadm enable net-snmp
sleep 3
echo "Install net-snmp done."
echo "check net-snmp log."
tail /var/svc/log/application-management-net-snmp:default.log
echo "lookup net-snmp listen port"
netstat -an -P udp | grep 161

Tags: ,

使用python获取mp3中的歌词

Posted by 4Aiur on 12/09/2010 in Python with Comments closed |

使用python获取mp3中的歌词

安装依赖库eyeD3

$ sudo port install py26-eyed3
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
dump_mp3_lyris.py

Created by 4Aiur on 2010-12-09.
"""

import os
import eyeD3

def get_mp3_file(dir):
    mp3_files = []
    files = os.listdir(dir)
    for file in files:
        if os.path.splitext(file)[1] == '.mp3':
            mp3_files.append(os.path.join(dir,file))
    return mp3_files

def dump_lyrics(mp3_file):
    print('parse %s' % (mp3_file))
    lyrics_file = '%s.txt' % (os.path.splitext(mp3_file)[0])
    fp = open(lyrics_file, 'w')
    tag = eyeD3.Tag()
    tag.link(mp3_file)
    fp.write('Title: %s\n\n' % (tag.getTitle().encode('utf-8', 'ignore')))
    lyrics = tag.getLyrics()
    for item in lyrics:
        for line in item.lyrics.splitlines():
            result = line.encode('utf-8', 'ignore')
            fp.write( result + '\n')
    fp.close()
    print('write %s done.' % (lyrics_file))
    return

def main():
    mp3_files = get_mp3_file('/Users/4aiur/Shares/englishpod')
    for mp3_file in mp3_files:
        dump_lyrics(mp3_file)

if __name__ == '__main__':
    main()

Tags:

使用python下载存放在Index中的资源

Posted by 4Aiur on 12/06/2010 in Python with Comments closed |

使用python下载存放在Index中的资源

Useing python threading download example.
like this:

wget -P result/ -nd -nH -r -l 1 -np -A pdf --http-user=book --http-password=cubook "http://www.4aiur.net/book/Programing/Python/"
#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''
thread_download.py
下载网页中某种后缀名的文件
Created by 4Aiur on 2010-12-06.
'''
__version__ = "$Revision: 0.90 $"

import threading
import httplib
import urlparse
import base64
import re
import os
from BeautifulSoup import BeautifulSoup
from Queue import Queue

download_queue = Queue()

def get_object_url(start_url, username, password, suffix):
    ''' 抓取并解析index文件,分析页面获取需要下载指定
    后缀名的元素 '''
    s = urlparse.urlparse(start_url)
    host = s.netloc
    path = s.path
    url_object = set()
    conn = httplib.HTTPConnection(host)
    params = None
    base64string = base64.encodestring('%s:%s' % (username, password))[:-1]
    headers = {'User-agent': '4Aiur Crawler',
            'Authorization': 'Basic %s' % base64string}
    conn.request('GET', path, params, headers)
    response = conn.getresponse()
    content = response.read()
    content = unicode(content, errors="ignore")
    conn.close()
    soup = BeautifulSoup()
    soup.feed(content)
    items = soup.findAll('a')
    for item in items:
        href = item.get('href')
        if href.endswith(suffix):
            full_url = urlparse.urljoin(start_url, href)
            url_object.add(full_url)
    return url_object 

def download(n, save_path):
    '''download object'''
    while True:
        download_task = download_queue.get()
        host = download_task.host
        path = download_task.path
        username = download_task.username
        password = download_task.password
        re_separate = re.compile(r'/(?:/)*')
        file_name = re.split(re_separate, path)[-1]
        local_file = os.path.join(save_path, file_name)
        print('Thread-%d: downlaod %s to %s' % (n, download_task.url, local_file))
        params = None
        base64string = base64.encodestring('%s:%s' % (username, password))[:-1]
        headers = {'User-agent': '4Aiur Crawler',
                'Authorization': 'Basic %s' % base64string}
        write_buffer = 104857600
        # 避免线程内代码出现异常,导致线程无法退出,把执行代码放入到异常判断中
        try:
            conn = httplib.HTTPConnection(host)
            conn.request('GET', path, params, headers)
            response = conn.getresponse()
            fp = open(local_file, 'wb')
            while True:
                block = response.read(write_buffer)
                if block:
                    fp.write(block)
                else:
                    break
            fp.close()
        finally:
            download_queue.task_done()

class DownloadObject(object):
    def __init__(self, url, username, password):
        self.url = url
        s = urlparse.urlparse(url)
        self.host = s.netloc
        self.path = s.path
        self.username = username
        self.password = password
        return

def main():
    num_threads = 3
    save_path = 'result'
    if not os.path.isdir(save_path):
        os.makedirs(save_path)
    # 开启下载线程
    for n in range(num_threads):
        t = threading.Thread(target=download, args=(n, save_path))
        t.setDaemon(True)
        t.start()

    start_url = 'http://www.4aiur.net/book/Programing/Python/'
    username = 'book'
    password = 'cubook'
    suffix = 'pdf'
    for url in get_object_url(start_url, username, password, suffix):
        download_queue.put(DownloadObject(url, username, password))
    # 等待线程结束
    download_queue.join()
    return

if __name__ == '__main__':
    main()

Tags:

Python 三元表达式

Posted by 4Aiur on 12/06/2010 in Python with Comments closed |

Python 三元表达式

In [1]: x = 100 if True else 200

In [2]: x
Out[2]: 100

In [3]: x = 100 if False else 200

In [4]: x
Out[4]: 200

Tags:

Copyright © 2010-2024 4Aiur All rights reserved.
This site is using the Desk Mess Mirrored theme, v2.5, from BuyNowShop.com.