Category Archives: Code

OracleでFIRST_DAY

先輩に聞く前に、

  • まずよく考えみて、
  • わからなければ調べて、
  • それでもダメなら聞く、

という癖をつけないとなあ。厳しいぞ。

/* Oracle PL/SQLで日付からその月の1日を求める*/

/* to_date、to_charを使えるなら、考えればできる */
create or replace function first_day(thedate date) return date is
begin
    return to_date(to_char(thedate,'YYYY-MM')||'-01','YYYY-MM-DD');
end;

/* 調べてみれば、こっちがスマートだとわかる */
create or replace function first_day(thedate date) return date is
begin
    return trunc(thedate,'MONTH');
end;

/***** ついでに *****/

/* 年の最初の日 1月1日 */
create or replace function first_day2(thedate date) return date is
begin
    return trunc(thedate,'YEAR');
end;

/* 週の始まり日曜日(※NLSの設定次第) */
create or replace function first_day3(thedate date) return date is
begin
    return trunc(thedate,'DAY');
end;

最後に問題。月の日数を求めるにはどうする?

urllib2でプロキシを参照しないようにする

urllib.urlopenはステータス404でも例外を発生してくれない。
urllib2.urlopenは404で例外を発生してくれるけれど、そのままだと環境変数のプロキシ設定を参照するようで、ちょっと困る場合があった。
というわけで、urllib2.urlopenでプロキシを設定|参照しないようにする方法。

#!/usr/bin/env python
"""Python urllib2 proxy usage sample
"""
import urllib2

#今回はプロキシ設定を空にしておく
#proxies = {'http': 'http://www.example.com:3128/'}
proxies = {}

#プロキシハンドラーを作成して
handler = urllib2.ProxyHandler(proxies)

#プロキシハンドラーを指定してURL Openerを作成して
opener = urllib2.build_opener(handler)

#作成したURL Openerをインストールしてから
urllib2.install_opener(opener)

#普通にurlopenすると例外が発生してくれる
try:
    u = urllib2.urlopen('http://www.example.com/404NotFound.html')
    print u.read()
except IOError,error:
    print error

Gist:227549

Pythonカテゴリ作ってみた。

Pythonで月末、月初。ついでに月を加減するadd_months

月初はまあいいとしても、月末、月の足し引きは、こんな方法しか思いつかず。

カッコ悪いが使えることは使える、と思う。

2008.3.14追記

  • calendarモジュールを使って月の日数を取得することで、月末計算をシンプルに。
  • add_monthsも見直し。

それほどカッコ悪くはなくなったんじゃないかと思う。修正の経緯

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""月末、月初のdatetime.dateオブジェクトを返す。
Oracleのadd_months互換の月加減。
"""
import datetime
from calendar import monthrange

def first_day(date):
	"""月初を返す"""
	return datetime.date(date.year, date.month, 1)

def is_last_day(date):
	"""月末日付ならTrueを返す"""
	return days_of_month(date.year, date.month) == date.day

def days_of_month(year,month):
	"""年,月の日数を返す"""
	return monthrange(year, month)[1]

def last_day(date):
	"""月末を返す"""
	return datetime.date(year=date.year, month=date.month, day=days_of_month(date.year, date.month))

def add_months(date,months):
	"""月を加減する。
	dateにはdatetime.dateクラスのオブジェクト
	monthsには整数で月数を指定する。
	月末をOracleのadd_months互換の方法で処理する。
	例えば、
	2007年2月28日(月末)に1ヶ月足すと3月31日(月末)。
	2008年2月29日(月末)に1ヶ月足すと2008年3月31日(月末)。
	2008年2月28日(月末ではない)に1ヶ月足すと2008年3月28日(同じ日)。
	"""
	if months==0:
		return date

	year, month = divmod(date.month + months, 12)
	year = year + date.year

	#ちょうど割り切れたら12月で、マイナス1年。
	if month == 0:
		month = 12
		year = year - 1

	#入力日付がその月の月末なら、加算後月の日数を。
	#そうじゃなければ入力日付の日。
	day = date.day
	if date.day > days_of_month(year, month):
		day = days_of_month(year, month)
	return datetime.date(year=year, month=month, day=day)

最新版はGist:227554をどうぞ。

MoinMoinのカスタムユーザ認証スクリプトサンプル

MoinMoinを仕事で使いたい。今すでに使っている社内の認証機構を使ってユーザ管理を楽するためにはどうすればいいか? Pythonのちょっとしたスクリプトを書けばなんとかなるようだ。

ということで調べてみたら、

  1. wikiconfig.pyのConfigクラス内でカスタムスクリプトを使うように設定する。
  2. ログイン用のカスタムスクリプトを書いて、MoinMoin/auth/以下に置く。

の2つの手順でできることがわかった。MoinMoin-1.6で動くことを確認した。

以下、やってみて上手くいった手順を記録しておく。

この例では、

  • カスタムスクリプト内にユーザ情報を保持している。この部分を必要な認証機構を呼び出すようにすれば使えるはず。
  • メールアドレスと別名もMoinMoinのプロファイル外で管理していることにして、カスタムスクリプト内で設定管理している。

wikiconfig.pyの編集

class Config(DefaultConfig):
    """MoinMoinのカスタム認証スクリプトmyauth.loginを使うようにwikiconfig.py
    で認証方法を指定。
    """
    from MoinMoin.auth import moin_session,myauth
    auth = [myauth.login, moin_session]
    #MoinMoin内のPreferenceを自動的に作成する
    user_autocreate = True

Gist:232443

カスタム認証スクリプト MoinMoin/auth/myauth.py

# -*- coding: utf-8 -*-
"""MoinMoin custom user authentication sample
"""
from MoinMoin import user
#User Database
_USER_MAP = {'user1,pass1' : ('user1@example.com',u'user1'),
    'user2,pass2' : ('user2@example.com','user2')}

def login(request, **kw):
	username = kw.get('name')
	password = kw.get('password')
	login = kw.get('login')
	user_obj = kw.get('user_obj')

	if not login:
		return user_obj, True

	u = None
	user_info = _USER_MAP.get("%s,%s" % (username,password),False)

	if user_info:
		u = user.User(request,
		name=username,
		auth_username=username,
		password=password,
		auth_method='myauth',
		auth_attribs=('name', 'auth_username', 'password', 'email', 'aliasname', ))
		u.email = user_info[0]
		u.aliasname = user_info[1]
		u.create_or_update(True)
		request.log("Login OK. user=%s, email=%s, aliasname=%s." % (username,user_info[0],user_info[1]))

	return u, True

Gist:227564

Windows ショートカット作成VBスクリプト

全員のデスクトップのショートカットを揃えたほうが電話でサポートしやすいね、ということで。
VBスクリプトを使ってショートカット作成スクリプトを作ってみた。

使い方は、こんな感じ。

C:\>create-shortcuts.vbs shortcut.conf

create-shortcuts.vbs

'#####################################################
' ショートカット作成スクリプト
' 設定ファイル複数受付版
'#####################################################
Const FOR_READING = 1
Const COL_FOLDER = 0
Const COL_SUB_FOLDER = 1
Const COL_TITLE = 2
Const COL_PATH = 3
Const COL_WORK = 4

Set objArgs = WScript.Arguments
'Wscript.Echo objArgs(0)
'Wscript.Echo objArgs.length

For arg_index = 0 to objArgs.length-1

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile(objArgs(arg_index), FOR_READING)

Do Until objTextFile.AtEndOfStream
  strNextLine = objTextFile.Readline
  if strNextLine <> "" then
    conf = Split(strNextLine , ",")
    if conf(COL_FOLDER) <> "" then
        Set Shell = CreateObject("WScript.Shell")
        CreatePath = Shell.SpecialFolders(conf(COL_FOLDER))
        if CreatePath = "" then CreatePath = conf(COL_FOLDER)
        if conf(COL_SUB_FOLDER) <> "" then
          CreatePath = CreatePath & "\" & conf(COL_SUB_FOLDER)
          if not objFSO.FolderExists(CreatePath) then
          	objFSO.CreateFolder(CreatePath)
          end if
        end if
        Set link = Shell.CreateShortcut(CreatePath & "\" & conf(COL_TITLE) &".lnk")
        link.Description = conf(COL_TITLE)
        link.HotKey = ""
        link.IconLocation = conf(COL_PATH)
        link.TargetPath = conf(COL_PATH)
        '通常のウインドウ
        link.WindowStyle = 1
        link.WorkingDirectory = conf(COL_WORK)
        args = ""
        For i = COL_WORK+1 to Ubound(conf)
          args = args & " " & conf(i)
        Next
        link.Arguments = args
        ret = link.Save

'デバッグ情報
'        Wscript.Echo "タイトル:" & conf(0)
'        Wscript.Echo "パス:" & conf(1)
'        Wscript.Echo "作業ディレクトリ:" & conf(2)
'        Wscript.Echo "引数:" & args
'        Wscript.Echo ret
    end if
  end if
Loop
Next

shortcut.conf

,********************************************
, カンマで始まる行はコメント行
,********************************************

,カンマで区切って、作成場所、タイトル,パス,作業ディレクトリ,引数1,引数2,引数3,...の順に書いておくと
,作成場所(デスクトップなど)にショートカットを作る

,作成場所に指定できるのは次のものだけ
, AllUsersDesktop
, AllUsersStartMenu
, AllUsersPrograms
, AllUsersStartup
, Desktop
, Favorites
, Fonts
, MyDocuments
, NetHood
, PrintHood
, Programs
, Recent
, SendTo
, StartMenu
, Startup
, Templates

,****************************************************************
, ここからが実際のデータ
,****************************************************************
Programs,,Excel,C:\Program Files\Microsoft Office\Office11\excel.exe,H:\,
Programs,,Word,C:\Program Files\Microsoft Office\Office11\winword.exe,H:\,
Programs,,PowerPoint,C:\Program Files\Microsoft Office\Office11\powerpnt.exe,H:\,
Programs,,Visio,C:\Program Files\Microsoft Office\Visio10\visio.exe,H:\,
Programs,,Access,C:\Program Files\Microsoft Office\Office11\msaccess.exe,H:\,

Desktop,,Excel,C:\Program Files\Microsoft Office\Office11\excel.exe,H:\,
Desktop,,Word,C:\Program Files\Microsoft Office\Office11\winword.exe,H:\,
Desktop,,PowerPoint,C:\Program Files\Microsoft Office\Office11\powerpnt.exe,H:\,
Desktop,,Visio,C:\Program Files\Microsoft Office\Visio10\visio.exe,H:\,
Desktop,,Access,C:\Program Files\Microsoft Office\Office11\msaccess.exe,H:\,

ActiveDirectoryのLDAP認証もどき

python-ldapを使ってみた。

ついでに、以前から試そうと思って手をつけていなかった、ActiveDirectoryのLDAP認証も。試しに、bindしてみるだけ。平文でパスワードが流れるのでこのままではちょっと使えない。

#!/usr/bin/env python
# -*- coding: utf-8-*-
# python-ldapを使ってActiveDirectoryで認証してみる
# http://python-ldap.sourceforge.net/

def ADAuth(username,password,host,port=389):
    """ActiveDirectoryのドメイコントローラにユーザ名とパスワードでbindしてみる。
    bindできれば認証OK。認証NGなら例外が起きる。
    """
    import ldap
    url = "ldap://%s:%d" % (host,port)
    l = ldap.initialize(url)
    l.simple_bind_s(username,password)
    l.unbind_s()

if __name__=='__main__':
    if len(sys.argv)<3:
        print "Usage: %s username password" % (sys.argv[0])
    else:
        try:
            userid = sys.argv[1]
            password = sys.argv[2]
            ADAuth(userid,password,"adserver.example.com")
            print "OK"
        except:
            print "NG"

Gist:227565