code
stringlengths
1
1.72M
language
stringclasses
1 value
#!/usr/bin/python import os, sys sys.path.append(os.getcwd() + '/lib') sys.path.append(os.getcwd() + '/lib/general') sys.path.append(os.getcwd() + '/lib/gtk') sys.path.append(os.getcwd() + '/lib/c') # my libraries from CFileRunnerGUI import CFileRunnerGUI def real_main(): oApp = CFileRunnerGUI() oApp.run() return def profile_main(): # This is the main function for profiling # We've renamed our original main() above to real_main() import cProfile, pstats, StringIO, logging prof = cProfile.Profile() prof = prof.runctx("real_main()", globals(), locals()) stream = StringIO.StringIO() stats = pstats.Stats(prof, stream=stream) stats.strip_dirs() stats.sort_stats("cumulative") # Or cumulative stats.reverse_order() stats.print_stats(150) # 100 = how many to print # The rest is optional. #stats.dump_stats('profile_stats.dat') #stats.print_callees() #stats.print_callers() print stream.getvalue() #logging.info("Profile data:\n%s", stream.getvalue()) if __name__ == "__main__": if len(sys.argv) == 2: if sys.argv[1] == '-p': profile_main() # run FileRunner with statistics [profiler enabled] else: real_main() else: real_main()
Python
# Name: CFileRunnerGUI.py # Date: Sat Mar 27 09:56:02 CET 2010 # Purpose: Common FileRunner constants import os ### general const HOME = os.path.expanduser('~') #HOME = os.path.expanduser('~/tmp/filerunner_testing/CFG') VERSION = '<DEVEL-VERSION>' AUTHOR = 'Filip Husak' CFG_DIR = HOME + '/.filerunner' CFG_FILE = CFG_DIR + '/00_filerunner.cfg' HISTORY_FILE = CFG_DIR + '/history' ### GUI const WIDTH = 600 LABEL = 'F i l e R u n n e r' TOOLTIP = 'FileRunner' ICON = 'img/icon.png' ICON_TRAY = 'img/icon_tray.png' LICENSE = 'Apache License, Version 2.0' ENTRY_COMPLETION_HISTORY_SEP = '--- HISTORY MATCHES --------------------------------------------------' ENTRY_COMPLETION_ALL_SEP = '--- ALL MATCHES --------------------------------------------------' ENTRY_COMPLETION_SEPARATOR_CNT = 2 # 2 macros above # Menu items MENU_GENERATE_DB_FILE = 'Regenerate database file' MENU_ABOUT = 'About...' MENU_EXIT = 'Quit' # Messages MSG_GENERATING_DB_FILE = 'The database file is generating. Please wait...' #MSG_FILEGENERATED = 'The database file was generated successfully.' MSG_FILEGENERATED_OK = 'The database file was generated successfully.' MSG_FILEGENERATED_FAILED = 'The database file was not generated. Status code: ' MSG_ENTRY_FILES_LOADED = ' entries were loaded from the database file.' MSG_PERMISSION_DENIED = 'Cannot access the database file. Permission denied: ' MSG_DB_FILE_NOT_EXISTS = 'The database file does not exist. \n\ You can generate the database file from popup menu. This operation may take a few minutes.' #MSG_UNKNOWN_ERROR = 'Unknown error: ' MSG_SEARCH_PATH_NOT_EXIST = 'The search path directory does not exist. Check the configuration parameter SEARCH_PATH.'
Python
# Name: CDataHnd.py # Date: Tue Mar 23 23:18:22 CET 2010 # Purpose: main data class of fileRunner application. It loads data from config and data files. # Def: CDataHnd() # Inputs: import os import sys import string import fnmatch import re import commands import errno import time # my libraries from CFile import CFile from CConfigReader import CConfigReader from CProcMngr import CProcMngr from CProfile import CProfile from CExceptionHnd import CExceptionHnd import myconst import mmStrMatch #################################################################################################### class CDataHnd(CExceptionHnd): __doExit = None __oCfgReader = None oDBFile = None oHistoryFile = None oHistoryFileRO = None __oProcMngr = None oDbGen = None oExcHnd = None __entryBoxText = None # this is set when user inserts the text in the entry box __camelCaseExp = None # this is set when user inserts the text in the entry box __searchMode = None # 1st bit - wildcard, 2nd bit - regexp __entrySepCnt = None __WILDCARD_SEARCH_MODE = 1 __REGEXP_SEARCH_MODE = 2 __CAMELCASE_SEARCH_MODE = 4 __GENERAL_SECTION = 'GENERAL' __DB_FILE_OPTION = 'DB_FILE' __SEARCH_PATH_OPTION = 'SEARCH_PATH' __SYM_LINK_OPTION = 'SYM_LINK' __EXTENSIONS_SECTION = 'EXTENSIONS' __SEARCH_EXPRESSION_SECTION = 'SEARCH_EXPRESSION' __WILDCARD_OPTION = 'WILDCARD' __REGEXP_OPTION = 'REGEXP' __CAMELCASE_OPTION = 'CAMELCASE' #--------------------------------------------------------------------------------------------------- def __init__(self): self.__doExit = False self.__searchMode = 0 self.__entrySepCnt = myconst.ENTRY_COMPLETION_SEPARATOR_CNT self.__oProfile = CProfile(myconst.CFG_DIR) self.__oCfgReader = CConfigReader(myconst.CFG_FILE) self.__oProcMngr = CProcMngr() #--------------------------------------------------------------------------------------------------- def load(self, loadDbFile = True): self.__oProfile.createProfile() self.__oProfile.addFile(os.path.basename(myconst.CFG_FILE)) self.__oCfgReader.load() dbFilename = self.getDbFilename() # it is False while regenerating DB if loadDbFile is True: try: self.oDBFile = CFile(dbFilename, 'r') except IOError, e: #raise CDataHndException(e), IOError(e)#CDataHndException(CDataHndException.DB_FILE_EXC) if e.errno == errno.ENOENT: raise CDataHndDBFileNotExistExc(e) else: raise IOError(e) self.oHistoryFile = CFile(myconst.HISTORY_FILE, 'a+') self.oHistoryFileRO = CFile(myconst.HISTORY_FILE, 'r') self.setSearchMode() #--------------------------------------------------------------------------------------------------- def getErrno(self): return self.__errno #--------------------------------------------------------------------------------------------------- def setErrno(self, val): self.__errno = val #--------------------------------------------------------------------------------------------------- def getDbFilename(self): dbFile = self.__oCfgReader.getValue(self.__GENERAL_SECTION, self.__DB_FILE_OPTION) return myconst.CFG_DIR + '/' + dbFile #--------------------------------------------------------------------------------------------------- def getProcMngr(self): return self.__oProcMngr #--------------------------------------------------------------------------------------------------- def getSearchMode(self): return self.__searchMode #--------------------------------------------------------------------------------------------------- def setSearchMode(self): wildcard = str(self.__oCfgReader.getValue(self.__SEARCH_EXPRESSION_SECTION, self.__WILDCARD_OPTION)) if wildcard in '1' or wildcard in 'Yes' or wildcard in 'True': self.__searchMode = 0 | self.__WILDCARD_SEARCH_MODE # set 1st bit regexp = str(self.__oCfgReader.getValue(self.__SEARCH_EXPRESSION_SECTION, self.__REGEXP_OPTION)) if regexp in '1' or regexp in 'Yes' or regexp in 'True': self.__searchMode = self.__searchMode | self.__REGEXP_SEARCH_MODE # set 2nd bit camel = str(self.__oCfgReader.getValue(self.__SEARCH_EXPRESSION_SECTION, self.__CAMELCASE_OPTION)) if camel in '1' or camel in 'Yes' or camel in 'True': self.__searchMode = self.__searchMode | self.__CAMELCASE_SEARCH_MODE # set 3rd bit #--------------------------------------------------------------------------------------------------- def getSearchPath(self): path = self.__oCfgReader.getValue(self.__GENERAL_SECTION, self.__SEARCH_PATH_OPTION) path = path.replace('\n', ' ') path = path.replace(':', ' ') self.__checkSearchPathsExist(path) return path #--------------------------------------------------------------------------------------------------- def __checkSearchPathsExist(self, paths): for path in paths.split(' '): if os.path.exists(path) is False: raise IOError(myconst.MSG_SEARCH_PATH_NOT_EXIST) #--------------------------------------------------------------------------------------------------- def getSymLink(self): return self.__oCfgReader.getValue(self.__GENERAL_SECTION, self.__SYM_LINK_OPTION) #--------------------------------------------------------------------------------------------------- def getExtCmd(self): return self.__oCfgReader.getSettings(self.__EXTENSIONS_SECTION) #--------------------------------------------------------------------------------------------------- def getExt(self): ext = [] for i in self.getExtCmd(): ext.append(i[0]) return ext #--------------------------------------------------------------------------------------------------- # it is called when entry box text is changed def setEntryBoxText(self, entryText): self.__entryBoxText = entryText #--------------------------------------------------------------------------------------------------- # it is called when entry box text is changed def setCamelCaseExpression(self, entryText): self.__camelCaseExp = self.__camelCaseToRegExp(entryText) #--------------------------------------------------------------------------------------------------- # it is called when entry box text is changed def setModel(self, model): self.__model = model #--------------------------------------------------------------------------------------------------- def match_func_C(self, completion, key, iter, oEntry): result = False text = self.__model.get_value(iter, 0) if self.__entrySepCnt > 0: if self.__isEntrySeparator(text) is True: return True # Wildcard if self.__searchMode & self.__WILDCARD_SEARCH_MODE: if mmStrMatch.wildcard(self.__entryBoxText, text): result = True # Regexp if self.__searchMode & self.__REGEXP_SEARCH_MODE: try: if mmStrMatch.regExp(self.__entryBoxText, text): result = True except re.error: # TODO: raise exception if result is not True: result = False # CamelCase if self.__searchMode & self.__CAMELCASE_SEARCH_MODE: if self.__camelCaseExp is not None: if mmStrMatch.camelCase(self.__camelCaseExp, text): result = True return result #--------------------------------------------------------------------------------------------------- def match_func_Py(self, completion, key, iter, oEntry): result = False model = completion.get_model() text = model.get_value(iter, 0) if self.__isEntrySeparator(text) is True: return True # Wildcard if self.__searchMode & self.__WILDCARD_SEARCH_MODE: if fnmatch.fnmatch(text, self.__entryBoxText): result = True # Regexp if self.__searchMode & self.__REGEXP_SEARCH_MODE: try: if re.search(self.__entryBoxText, text): result = True except re.error: # TODO: raise exception if result is not True: result = False ## CamelCase if self.__searchMode & self.__CAMELCASE_SEARCH_MODE: if self.__camelCaseExp is not None: if re.search(self.__camelCaseExp, text): result = True return result #--------------------------------------------------------------------------------------------------- def __isEntrySeparator(self, text): if myconst.ENTRY_COMPLETION_HISTORY_SEP in text: self.__entrySepCnt = self.__entrySepCnt - 1 return True if myconst.ENTRY_COMPLETION_ALL_SEP in text: self.__entrySepCnt = self.__entrySepCnt - 1 return True return False #--------------------------------------------------------------------------------------------------- def __camelCaseToRegExp(self, camelStr): regExpStr = '' for index in range(len(camelStr)): if camelStr[index] not in string.uppercase: return None regExpStr += camelStr[index] + '[a-z]*' return regExpStr #--------------------------------------------------------------------------------------------------- def getExtFromFilename(self, filename): baseFilename = os.path.basename(filename) filenameParts = baseFilename.split('.') if len(filenameParts) > 0: ext = filenameParts[len(filenameParts) - 1] return ext else: return None #--------------------------------------------------------------------------------------------------- def runFile(self, file): ''' Return True if any file was selected from the entry completion box '' Return False if the separator entry was selected ''' cmd = None if self.__isEntrySeparator(file) is True: return False ext = self.getExtFromFilename(file) if ext is not None: cmd = self.__oCfgReader.getValue(self.__EXTENSIONS_SECTION, ext) # TODO: Message - cannot if cmd is not None: self.__oProcMngr.setCmd(cmd + ' ' + file) self.__oProcMngr.createProc() self.__addFileToHistory(file) return True #--------------------------------------------------------------------------------------------------- def __addFileToHistory(self, file): if self.__isFileInHistory(file) is False: self.oHistoryFile.getFileDesc().write(file + '\n') self.oHistoryFile.sync() #--------------------------------------------------------------------------------------------------- def __isFileInHistory(self, file): self.oHistoryFile.begin() result = False for line in self.oHistoryFile.getFileDesc(): if line.replace('\n', '') == file: result = True return result #--------------------------------------------------------------------------------------------------- # prepare function before calling match_func def prepareBeforeMatch(self, entryText): self.setEntryBoxText(entryText) self.setCamelCaseExpression(entryText) self.__entrySepCnt = myconst.ENTRY_COMPLETION_SEPARATOR_CNT #################################################################################################### #################################################################################################### # CLASS EXCEPTIONS #################################################################################################### class CDataHndDBFileNotExistExc(Exception): pass # TODO: implement CEnum own class #def __init__(self, e): #super(CDataHndException, self).__init__(e) # self.errno = e.errno # enum for exception type # CFG_FILE_EXC, DB_FILE_EXC = range(2) # # __type = None # # def __init__(self, type): # self.__type= type # # def getType(self): # return self.__type # ####################################################################################################
Python
# Name: CFileRunnerGUI.py # Date: Tue Mar 23 22:26:28 CET 2010 # Purpose: main GUI class of fileRunner application # Def: CFileRunnerGUI() # Inputs: import os import sys import gtk import gobject import time import errno from threading import Lock # my libraries from CDataHnd import CDataHnd from CTrayIcon import CTrayIcon from CSimpleMsgDlg import CSimpleMsgDlg from CAboutDlg import CAboutDlg from CKeyPressHnd import CKeyPressHnd from CProgressWndRnd import CProgressWndRnd from CGenerateDb import CGenerateDb from CExceptionHnd import CExceptionHnd from CThread import CThread import myconst # my exceptions from CProcMngr import CProcMngrStatusException from CDataHnd import CDataHndDBFileNotExistExc # http://faq.pygtk.org/index.py?file=faq20.006.htp&req=show gobject.threads_init() #################################################################################################### class CFileRunnerGUI(gtk.Window, CExceptionHnd): __height = None __vbox = None __entry = None __completion = None __listStore = None __trayIcon = None __popupMenu = None __generateDbFileItem = None __aboutItem = None __exitItem = None __oDataHnd = None __oKeyPressHnd = None oProgBarWnd = None oDbGen = None __totalCntMsg = None __cleanEntry = None lock = Lock() #--------------------------------------------------------------------------------------------------- def __init__(self): super(CFileRunnerGUI, self).__init__() self.__oDataHnd = CDataHnd() self.__oDataHnd.setExterExcHndCB(self.handleException) self.__oKeyPressHnd = CKeyPressHnd() self.__cleanEntry = False # set member from CExceptionHnd self.setDoExit(False) # window settings self.set_position(gtk.WIN_POS_CENTER) self.set_title(myconst.LABEL) gtk.window_set_default_icon_from_file(myconst.ICON) self.__createPopupMenu() self.__trayIcon = CTrayIcon(myconst.ICON_TRAY, myconst.TOOLTIP, True) self.__createInputBox() # set window size (width, self.__height) = self.__entry.size_request() self.set_size_request(myconst.WIDTH, self.__height) #--------------------------------------------------------------------------------------------------- def __createInputBox(self): self.__vbox = gtk.VBox() self.__entry = gtk.Entry() self.__completion = gtk.EntryCompletion() self.__listStore = gtk.ListStore(gobject.TYPE_STRING) self.__vbox.pack_start(self.__entry) self.add(self.__vbox) self.__completion.set_text_column(0) self.__completion.set_match_func(self.__oDataHnd.match_func_C, self.__entry) #self.__completion.set_match_func(self.__oDataHnd.match_func_Py, self.__entry) #--------------------------------------------------------------------------------------------------- def __createPopupMenu(self): self.__popupMenu = gtk.Menu() self.__generateDbFileItem = gtk.MenuItem(myconst.MENU_GENERATE_DB_FILE) self.__aboutItem = gtk.MenuItem(myconst.MENU_ABOUT) self.__exitItem = gtk.ImageMenuItem(gtk.STOCK_QUIT) self.__popupMenu.append(self.__generateDbFileItem) self.__popupMenu.append(self.__aboutItem) self.__popupMenu.append(self.__exitItem) #--------------------------------------------------------------------------------------------------- def __loadData(self): try: self.__oDataHnd.load() self.__loadInputBoxEntries() except: self.handle() #--------------------------------------------------------------------------------------------------- def __loadInputBoxEntries(self): i = 0 self.__listStore.insert(i, [myconst.ENTRY_COMPLETION_HISTORY_SEP]) i += 1 # load all entries [from history file] self.__oDataHnd.oHistoryFile.begin() for s in self.__oDataHnd.oHistoryFile.getFileDesc(): self.__listStore.insert(i, [s.replace('\n', '')]) i += 1 self.__listStore.insert(i, [myconst.ENTRY_COMPLETION_ALL_SEP]) i += 1 # load all entries [from DB file] self.__oDataHnd.oDBFile.begin() for s in self.__oDataHnd.oDBFile.getFileDesc(): self.__listStore.insert(i, [s.replace('\n', '')]) i += 1 entriesCnt = len(self.__listStore) - myconst.ENTRY_COMPLETION_SEPARATOR_CNT self.__totalCntMsg = ' ' + str(entriesCnt) + myconst.MSG_ENTRY_FILES_LOADED print self.__totalCntMsg self.__completion.set_model(self.__listStore) self.__entry.set_completion(self.__completion) # set model for DataHnd - avoid calling get_model every time when match_func is called self.__oDataHnd.setModel(self.__completion.get_model()) #--------------------------------------------------------------------------------------------------- def __cleanInputBoxEntries(self): self.__listStore = gtk.ListStore(gobject.TYPE_STRING) self.__completion.set_model(None) self.__entry.set_completion(self.__completion) #--------------------------------------------------------------------------------------------------- def __cleanEntryBox(self): self.__entry.set_text('') #--------------------------------------------------------------------------------------------------- def generateDB(self): try: self.oProgBarWnd = CProgressWndRnd(myconst.MSG_GENERATING_DB_FILE, self) # setting callback function self.oProgBarWnd.setCbFnc(self.loadData_cb) self.oProgBarWnd.start() self.oDbGen = CGenerateDb(self.__oDataHnd) self.oDbGen.setExterExcHndCB(self.handleException) # setting callback function self.oDbGen.setCbFnc(self.oProgBarWnd.stop) self.oDbGen.start() except: self.handle() #--------------------------------------------------------------------------------------------------- # set the signals [callbacks] def __loadSignals(self): # main app [window] signals self.connect("delete-event", self.__hideWndSignal_cb) self.connect("key-press-event", self.__keyPressSignal_cb) # entry box signal - while inserting text self.__entry.connect('changed', self.__entryBoxChanged_cb) # entry completion list box signal self.__completion.connect('match-selected', self.__selectCompletionEntrySignal_cb) # menu items signals self.__generateDbFileItem.connect("activate", self.__regenerateDBFileSignal_cb) self.__aboutItem.connect("activate", self.__showAboutDlgSignal_cb) self.__exitItem.connect("activate", gtk.main_quit) # tray icon signals self.__trayIcon.connect("activate", self.__showWndSignal_cb) self.__trayIcon.connect("popup-menu", self.__popupMenuSignal_cb) #--------------------------------------------------------------------------------------------------- # CALLBACKS #--------------------------------------------------------------------------------------------------- def loadData_cb(self): # do nothing if APP is going to exit, e.g. if getDoExit returns True if self.getDoExit() is False: self.__loadData() if self.__totalCntMsg is not None: gobject.idle_add(self.__showMsg, myconst.MSG_FILEGENERATED_OK + str(self.__totalCntMsg)) #--------------------------------------------------------------------------------------------------- def __hideWndSignal_cb(self, widget, event): self.__hideApp() return True #--------------------------------------------------------------------------------------------------- def __entryBoxChanged_cb(self, editable): self.__oDataHnd.prepareBeforeMatch(editable.get_text()) #--------------------------------------------------------------------------------------------------- def __keyPressSignal_cb(self, widget, event): self.__oKeyPressHnd.setEvent(event) self.__oKeyPressHnd.processEvent() #--------------------------------------------------------------------------------------------------- def __popupMenuSignal_cb(self, status_icon, button, activate_time): self.__popupMenu.show_all() self.__popupMenu.popup(None, None, None, button, activate_time, None) #--------------------------------------------------------------------------------------------------- def __regenerateDBFileSignal_cb(self, widget): self.__cleanInputBoxEntries() self.__oDataHnd.load(False) self.generateDB() #--------------------------------------------------------------------------------------------------- def __selectCompletionEntrySignal_cb(self, completion, model, iter): if self.__oDataHnd.runFile(model[iter][0]) is False: # clean input expression box self.__cleanEntry = True self.__hideApp() #--------------------------------------------------------------------------------------------------- def __showWndSignal_cb(self, icon): if self.get_property('visible') is False: self.__showApp() else: self.__hideApp() #--------------------------------------------------------------------------------------------------- def __showAboutDlgSignal_cb(self, widget): self.set_skip_taskbar_hint(False) CAboutDlg() self.set_skip_taskbar_hint(True) #--------------------------------------------------------------------------------------------------- # END OF CALLBACKS #--------------------------------------------------------------------------------------------------- def __hideApp(self): if self.oProgBarWnd is not None: self.oProgBarWnd.hideAll() self.hide_all() #--------------------------------------------------------------------------------------------------- def run(self): self.__showApp() self.__loadSignals() self.__loadData() gtk.main() #--------------------------------------------------------------------------------------------------- def __showApp(self): if self.__cleanEntry is True: self.__cleanEntryBox() self.__cleanEntry = False self.set_skip_taskbar_hint(False) if self.oProgBarWnd is not None: self.oProgBarWnd.showAll() self.show_all() self.set_skip_taskbar_hint(True) #--------------------------------------------------------------------------------------------------- def __showMsg(self, msg): self.set_skip_taskbar_hint(False) CSimpleMsgDlg(self, msg) self.set_skip_taskbar_hint(True) #--------------------------------------------------------------------------------------------------- def __doExit(self): if self.__oDataHnd.getDoExit() is True: sys.exit(self.__oDataHnd.getErrno()) #--------------------------------------------------------------------------------------------------- def handleException(self, childExcHnd = None): ''' '' Main exception handling function. The function is thread safe. ''' if self.lock.acquire(): if self.getExcType() is None: excHnd = childExcHnd else: excHnd = self #TODO: to be moved to log file print 'MAIN handleException() is called by:',excHnd print 'MAIN handleException():',excHnd.getExcType(),excHnd.getExcVal(),excHnd.getMsg() if excHnd.getExcType() is IOError: if excHnd.getExcVal().errno == errno.EACCES: self.setDoExit(True) elif excHnd.getExcVal().errno == errno.ENOENT: gobject.idle_add(self.__showMsg, excHnd.getMsg()) self.setDoExit(False) else: self.setDoExit(True) if excHnd.getExcType() is CDataHndDBFileNotExistExc: gobject.idle_add(self.__showMsg, myconst.MSG_DB_FILE_NOT_EXISTS) self.setDoExit(False) #self.generateDB() #gobject.idle_add(self.generateDB()) #if excHnd. is CDataHndException.DB_FILE_EXC: #self.setDoExit(True) if excHnd.getExcType() is CProcMngrStatusException: self.setDoExit(True) if self.getDoExit() is True: exit_text = 'The application will exit due to the following error: ' + excHnd.getMsg() gobject.idle_add(self.__showMsg, exit_text) gobject.idle_add(gtk.main_quit) excHnd.cleanExc() self.lock.release() ####################################################################################################
Python
# Name: CProfile.py # Date: Thu Apr 8 22:04:26 CEST 2010 # Purpose: Create and update profile. The profile is often created in the $HOME directory. # Def: CProfile(profileDir) # Inputs: import os # my libraries from CProcMngr import CProcMngr #################################################################################################### class CProfile(): __profileDir = None __oProcMngr = None __CMD_CREATE_DIR = 'mkdir -p ' __CMD_REMOVE_DIR = 'rm -rf ' __CMD_COPY_FILE = 'cp ' __CMD_COPY_FILE_FORCE = 'cp -r ' #--------------------------------------------------------------------------------------------------- def __init__(self, profileDir): self.__profileDir = profileDir self.__oProcMngr = CProcMngr() #--------------------------------------------------------------------------------------------------- def createProfile(self): self.__oProcMngr.execCmd(self.__CMD_CREATE_DIR + self.__profileDir) #--------------------------------------------------------------------------------------------------- def deleteProfile(self): self.__oProcMngr.execCmd(self.__CMD_REMOVE_DIR + self.__profileDir) #--------------------------------------------------------------------------------------------------- def addFile(self, file, overWrite = False): filePath = self.__profileDir + '/' + os.path.basename(file) # TODO: exception if 'file' does not exist if overWrite is True: self.__oProcMngr.execCmd(self.__CMD_COPY_FILE + file + ' ' + self.__profileDir) else: if os.path.exists(filePath) is False: self.__oProcMngr.execCmd(self.__CMD_COPY_FILE + file + ' ' + self.__profileDir) ####################################################################################################
Python
# Name: CProcMngr.py # Date: Sat Mar 27 10:42:41 CET 2010 # Purpose: Create and show about dialog # Depends: myconst module # Def: CProcMngr(widget = None) # Inputs: import os import commands #################################################################################################### class CProcMngr(): __cmd = None #--------------------------------------------------------------------------------------------------- def __init__(self, command = None): self.__cmd = command #--------------------------------------------------------------------------------------------------- def getCmd(self): return self.__cmd #--------------------------------------------------------------------------------------------------- def setCmd(self, command): self.__cmd = command #--------------------------------------------------------------------------------------------------- def getProcStatusOutput(self): (status, output) = commands.getstatusoutput(self.__cmd) if status is not 0: raise CProcMngrStatusException(status) else: return (status, output) #--------------------------------------------------------------------------------------------------- def createProc(self, runInBackground = True): if runInBackground is True: os.system(self.__cmd + ' &') else: os.system(self.__cmd) #--------------------------------------------------------------------------------------------------- def execCmd(self, command, runInBackground = False): self.setCmd(command) self.createProc(runInBackground) #################################################################################################### #################################################################################################### # CLASS EXCEPTIONS #################################################################################################### class CProcMngrStatusException(Exception): __status = None def __init__(self, status): self.__status = status def getStatus(self): return self.__status ####################################################################################################
Python
# Name: CThread.py # Date: Sat May 1 19:59:54 CEST 2010 # Purpose: The abstract thread class with callback function. # The base class (which inherits CThread) MUST call run method. # super(ClassName, self).run() # Def CThread(name) # Inputs: name - the name of the thread [string]. import threading #################################################################################################### class CThread(threading.Thread): ''' '' The abstract thread class with callback function ''' __cbFnc = None #--------------------------------------------------------------------------------------------------- def __init__(self, name): super(CThread, self).__init__() self.setName(name) #--------------------------------------------------------------------------------------------------- def setCbFnc(self, cbFunction): self.__cbFnc = cbFunction #--------------------------------------------------------------------------------------------------- def run(self): # print self.getName(),': Callback: ',self.__cbFnc if self.__cbFnc is not None: self.__cbFnc() ####################################################################################################
Python
# Name: CExceptionHnd.py # Date: Sun May 2 15:18:25 CEST 2010 # Purpose: Handles exceptions # Def CExceptionHnd(extExcHnd_cb) # Inputs: import sys #################################################################################################### class CExceptionHnd(): ''' '' Base class for handling exceptions ''' __excType = None __excVal = None __msg = None __doExit = None # callable object which should reference to external function 'handleException' in derived class __extExcHnd_cb = None #--------------------------------------------------------------------------------------------------- def __init__(self): #self.__errno = 0 self.__doExit = False #--------------------------------------------------------------------------------------------------- # def hasException(self): # if self.__errno == 0: # return False # else: # return True #--------------------------------------------------------------------------------------------------- #def handle(self, e = None): def handle(self): ''' handles known exceptions ''' self.__excType, self.__excVal = sys.exc_info()[:2] #TODO: to be moved to the log file print 'CExceptionHnd:',self.__class__,self.__excType,self.__excVal # handling general exceptions if self.__excType is IOError: if self.__excVal.filename is not None: self.__msg = self.__excVal.strerror + ": '" + self.__excVal.filename + "'" else: self.__msg = self.__excVal self.__doExit = True self.handleException() if self.__extExcHnd_cb is not None: self.__extExcHnd_cb(self) else: print 'No external exception handler defined.' #--------------------------------------------------------------------------------------------------- def cleanExc(self): self.__excType = None self.__excVal = None self.__msg = None #--------------------------------------------------------------------------------------------------- # override method in the derived class def handleException(self): pass #--------------------------------------------------------------------------------------------------- def getExcType(self): return self.__excType #--------------------------------------------------------------------------------------------------- def setExcType(self, val): self.__excType = val #--------------------------------------------------------------------------------------------------- def getExcVal(self): return self.__excVal #--------------------------------------------------------------------------------------------------- def setExcVal(self, val): self.__excVal = val #--------------------------------------------------------------------------------------------------- def getMsg(self): return str(self.__msg) #--------------------------------------------------------------------------------------------------- def setMsg(self, val): self.__msg = val #--------------------------------------------------------------------------------------------------- def getDoExit(self): return self.__doExit #--------------------------------------------------------------------------------------------------- def setDoExit(self, val): self.__doExit = val #--------------------------------------------------------------------------------------------------- def getExterExcHndCB(self): return self.__extExcHnd_cb #--------------------------------------------------------------------------------------------------- def setExterExcHndCB(self, fnc): if callable(fnc): self.__extExcHnd_cb = fnc ####################################################################################################
Python
# Name: CFile.py # Date: Tue Mar 9 15:30:27 CET 2010 # Purpose: The class handles file descriptor # Def: CFile(filename, mode) # Inputs: filename - the name of file to work with # mode - the mode in which the file is opened [r, w] import os import sys #################################################################################################### class CFile(): '''The class handles file descriptor ''' __fileName = None __mode = None __fileDesc = None #--------------------------------------------------------------------------------------------------- def __init__(self, name, mode): self.__fileName = name self.__mode = mode self.__load() #--------------------------------------------------------------------------------------------------- def __del__(self): if self.__fileDesc != None: self.__fileDesc.close() #--------------------------------------------------------------------------------------------------- def __load(self): try: self.__fileDesc = open(self.__fileName, self.__mode) except IOError, e: # TODO: Create Logger class self.__fileDesc = None raise e #sys.exit(1) #--------------------------------------------------------------------------------------------------- def getFileName(self): return self.__fileName #--------------------------------------------------------------------------------------------------- def getFileDesc(self): return self.__fileDesc #--------------------------------------------------------------------------------------------------- def begin(self): self.__fileDesc.seek(0, 0) #--------------------------------------------------------------------------------------------------- def sync(self): self.__fileDesc.flush() os.fsync(self.__fileDesc.fileno()) ####################################################################################################
Python
# Name: CConfigReader.py # Date: Sun Mar 21 19:11:46 CET 2010 # Purpose: Load and parse config file and get variables/valus for given section # Def: ConfigReader(fileName) # Inputs: filename - the name of config file import ConfigParser class CConfigReader(): ''' '' Load and parse config file and get variables/values for given section ''' __cfgFilename = None __oCfgParser = None # raw config parser object #--------------------------------------------------------------------------------------------------- def __init__(self, filename): self.__cfgFilename = filename #--------------------------------------------------------------------------------------------------- def getCfgFilename(self): return self.__cfgFilename #--------------------------------------------------------------------------------------------------- def setCfgFilename(self, filename): self.__cfgFilename = filename #--------------------------------------------------------------------------------------------------- def load(self): self.__oCfgParser = ConfigParser.RawConfigParser() self.__oCfgParser.read(self.getCfgFilename()) #--------------------------------------------------------------------------------------------------- def getSettings(self, section = None): ''' '' return all items in the appropriate section. If section is None return the list of sections ''' # TODO: raise exception if oCfgParser is None if self.__oCfgParser is None: return None if section is None: return self.__oCfgParser.sections() else: return self.__oCfgParser.items(section) #--------------------------------------------------------------------------------------------------- def getValue(self, section, option): ''' '' return value of option which is located in the appropriate section ''' # TODO: raise exception if section/option does not exist return self.__oCfgParser.get(section, option) ####################################################################################################
Python
#!/usr/bin/python from distutils.core import setup, Extension module1 = Extension('mmStrMatch', sources = ['mmStrMatch.c']) setup (name = 'mmStrMatch', version = '1.0', description = 'My Module for matching string and pattern. Module is written in C.', ext_modules = [module1])
Python
#!/usr/bin/python from distutils.core import setup, Extension module1 = Extension('mmStrMatch', sources = ['mmStrMatch.c']) setup (name = 'mmStrMatch', version = '1.0', description = 'My Module for matching string and pattern. Module is written in C.', ext_modules = [module1])
Python
# Name: CTrayIcon.py # Date: Sat Mar 27 09:41:29 CET 2010 # Purpose: # Def: CTrayIcon() # Inputs: import gtk #################################################################################################### class CTrayIcon(gtk.StatusIcon): __file = None __tooltip = None #--------------------------------------------------------------------------------------------------- def __init__(self, iconFile, iconTooltip, iconVisible = False): super(CTrayIcon, self).__init__() self.__file = iconFile self.__tooltip = iconTooltip self.set_visible(iconVisible) self.set_from_file(self.__file) self.set_tooltip(self.__tooltip) ####################################################################################################
Python
# Name: CProgressWndRnd.py # Date: Sat May 1 20:56:56 CEST 2010 # Purpose: Show random status of progress bar. It is used while running long-time operation. # Depends: CThread # Def: CProgressWndRnd() # Inputs: from threading import Event import random, time import gtk import gobject # my libraries from CThread import CThread #################################################################################################### class CProgressWndRnd(CThread): ''' ''Show random status of progress bar ''' __NAME='CProgressWndRnd Thread' __width = 450 __height = 40 __delay = 0.3 event = None #--------------------------------------------------------------------------------------------------- def __init__(self, text, parentWnd = None): super(CProgressWndRnd, self).__init__(self.__NAME) self.threadEvent = Event() #self.wnd = gtk.Dialog(text, parentWnd, gtk.DIALOG_MODAL | gtk.DIALOG_NO_SEPARATOR) self.wnd = gtk.Window(gtk.WINDOW_POPUP) self.wnd.set_position(gtk.WIN_POS_CENTER) self.wnd.set_size_request(self.__width, self.__height) self.progBar = gtk.ProgressBar() self.progBar.set_text(text) self.wnd.add(self.progBar) self.wnd.connect('destroy', self.stop) #gtk.gdk.threads_init() gobject.threads_init() #--------------------------------------------------------------------------------------------------- def run(self): #While the stopthread event isn't setted, the thread keeps going on #self.wnd.show_all() gobject.idle_add(self.wnd.show_all) while not self.threadEvent.isSet(): # Acquiring the gtk global mutex #gtk.gdk.threads_enter() #Setting a random value for the fraction #self.progBar.set_fraction(random.random()) gobject.idle_add(self.progBar.set_fraction, random.random()) # Releasing the gtk global mutex #gtk.gdk.threads_leave() time.sleep(self.__delay) #self.wnd.hide_all() gobject.idle_add(self.wnd.hide_all) super(CProgressWndRnd, self).run() #--------------------------------------------------------------------------------------------------- def stop(self, waitFor = None): if waitFor is not None: waitFor.join() self.threadEvent.set() #--------------------------------------------------------------------------------------------------- def getHeight(self): return self.__height #--------------------------------------------------------------------------------------------------- def setHeight(self, height): self.__height = height #--------------------------------------------------------------------------------------------------- def getWidth(self, width): return self.__width #--------------------------------------------------------------------------------------------------- def setWidth(self, width): self.__width = width #--------------------------------------------------------------------------------------------------- def hideAll(self): if not self.threadEvent.isSet(): self.wnd.hide_all() #--------------------------------------------------------------------------------------------------- def showAll(self): if not self.threadEvent.isSet(): self.wnd.show_all() ####################################################################################################
Python
# Name: CKeyPressHnd.py # Date: Sun Mar 28 21:24:42 CEST 2010 # Purpose: Handles key pressing # Def: CKeyPressHnd() # Inputs: import gtk #################################################################################################### class CKeyPressHnd(): __event = None #--------------------------------------------------------------------------------------------------- def __init__(self, event = None): self.__event = event #--------------------------------------------------------------------------------------------------- def getEvent(self): return self.__event #--------------------------------------------------------------------------------------------------- def setEvent(self, event): self.__event = event #--------------------------------------------------------------------------------------------------- def processEvent(self): ev = self.__event # Ctrl+Q handling if ev.state & gtk.gdk.CONTROL_MASK: if gtk.gdk.keyval_name(ev.keyval).upper() == 'Q': # TODO: use callback function in the main class instead gtk.main_quit() ####################################################################################################
Python
# Name: CAboutDlg.py # Date: Sat Mar 27 10:42:41 CET 2010 # Purpose: Create and show about dialog # Depends: myconst module # Def: CAboutDlg(widget = None) # Inputs: widget import gtk # my libraries import myconst #################################################################################################### class CAboutDlg(gtk.AboutDialog): #--------------------------------------------------------------------------------------------------- def __init__(self, widget = None, parentWnd = None): super(CAboutDlg, self).__init__() self.set_name(myconst.TOOLTIP) self.set_version(myconst.VERSION) self.set_license(myconst.LICENSE) self.set_authors([myconst.AUTHOR]) self.run() self.destroy() ####################################################################################################
Python
# Name: CSimpleMsgDlg.py # Date: Sat Mar 27 10:42:41 CET 2010 # Purpose: Create and show simple message dialog # Def: CSimpleMsgDlg(msg) # Inputs: msg - message to be diplayed in the dialog import gtk #################################################################################################### class CSimpleMsgDlg(gtk.MessageDialog): __parentWnd = None __msg = None #--------------------------------------------------------------------------------------------------- def __init__(self, parentWindow, message): self.__parentWnd = parentWindow self.__msg = message super(CSimpleMsgDlg, self).__init__(self.__parentWnd, gtk.DIALOG_MODAL, gtk.MESSAGE_INFO, gtk.BUTTONS_OK, self.__msg) self.run() self.destroy() ####################################################################################################
Python
# Name: CGenerateDb.py # Date: Sat May 1 20:37:18 CEST 2010 # Purpose: Generate DB file. # Depends: CThread, CFile # Def: CGenerateDB(dataHandler) # Inputs: dataHandler - instance of CDataHnd import sys import gtk # my libraries from CThread import CThread from CFile import CFile from CProcMngr import CProcMngrStatusException from CExceptionHnd import CExceptionHnd import myconst import time #################################################################################################### class CGenerateDb(CThread, CExceptionHnd): ''' '' Generate DB file ''' __NAME='CGenerateDb Thread' __oDataHnd = None __progBarWnd = None #--------------------------------------------------------------------------------------------------- def __init__(self, dataHandler): super(CGenerateDb, self).__init__(self.__NAME) self.__oDataHnd = dataHandler #--------------------------------------------------------------------------------------------------- def run(self): try: findCmd = self.__buildFindCmd() self.__oDataHnd.getProcMngr().setCmd(findCmd) (status, output) = self.__oDataHnd.getProcMngr().getProcStatusOutput() try: self.__oDataHnd.oDBFile = CFile(self.__oDataHnd.getDbFilename(), 'w') self.__oDataHnd.oDBFile.getFileDesc().write(output + '\n') except IOError, e: self.handle() except CProcMngrStatusException, e: self.setMsg(myconst.MSG_FILEGENERATED_FAILED + str(e.getStatus())) self.handle() except IOError, e: self.handle() finally: super(CGenerateDb, self).run() #--------------------------------------------------------------------------------------------------- def __buildFindCmd(self): followSymLink = str(self.__oDataHnd.getSymLink()) searchPath = self.__oDataHnd.getSearchPath() if followSymLink in '1' or followSymLink in 'Yes' or followSymLink in 'True': cmd = 'find -L ' else: cmd = 'find ' cmd += searchPath prependOr = False for ext in self.__oDataHnd.getExt(): if prependOr is True: cmd += ' -or' cmd += ' -iname \'*' + ext + '\'' if prependOr is False: prependOr = True return cmd ####################################################################################################
Python
import os import inspect import glob # try to import an environment first try: Import('env') except: exec open("../build/build-env.py") env = Environment() # on mac we have to tell the linker to link against the C++ library if env['PLATFORM'] == "darwin": env.Append(LINKFLAGS = "-lstdc++") # find all .cus & .cpps in the current directory sources = [] directories = [name for name in os.listdir('.') if os.path.isdir(name)] extensions = ['*.cu', '*.cpp'] for dir in directories: for ext in extensions: regexp = os.path.join(dir, ext) #sources.extend(env.Glob(regexp, strings = True)) sources.extend(glob.glob(regexp)) # compile examples for src in sources: env.Program(src)
Python
from scipy.sparse import coo_matrix from scipy.io import mmwrite from numpy.random import permutation M = N = 10 for nnz in [0, 1, 2, 5, 8, 10, 15, 20, 30, 50, 80, 100]: P = permutation(M * N)[:nnz] I = P / N J = P % N V = permutation(nnz) + 1 A = coo_matrix( (V,(I,J)) , shape=(M,N)) filename = '%03d_nonzeros.mtx' % (nnz,) mmwrite(filename, A)
Python
import os import inspect import glob # try to import an environment first try: Import('env') except: exec open("../build/build-env.py") env = Environment() # on mac we have to tell the linker to link against the C++ library if env['PLATFORM'] == "darwin": env.Append(LINKFLAGS = "-lstdc++") # find all .cus & .cpps in the current directory sources = [] directories = ['.', 'cuda'] extensions = ['*.cu', '*.cpp'] for dir in directories: for ext in extensions: regexp = os.path.join(dir, ext) #sources.extend(env.Glob(regexp, strings = True)) sources.extend(glob.glob(regexp)) # add the directory containing this file to the include path this_file = inspect.currentframe().f_code.co_filename this_dir = os.path.dirname(this_file) env.Append(CPPPATH = [this_dir]) # by default, we want to build the full unit test suite tester = env.Program('tester', sources) Default(tester) # add targets to build individual tests core_sources = ['testframework.cu', 'unittest_tester.cu'] for test in glob.glob('*.cu'): if test not in core_sources: name, ext = os.path.splitext(test) env.Program('test_'+name, core_sources+[test])
Python
import os import glob from warnings import warn cusp_abspath = os.path.abspath("../../cusp/") # try to import an environment first try: Import('env') except: exec open("../../build/build-env.py") env = Environment() # this function builds a trivial source file from a Cusp header def trivial_source_from_header(source, target, env): src_abspath = str(source[0]) src_relpath = os.path.relpath(src_abspath, cusp_abspath) include = os.path.join('cusp', src_relpath) target_filename = str(target[0]) fid = open(target_filename, 'w') fid.write('#include <' + include + '>\n') fid.close() # CUFile builds a trivial .cu file from a Cusp header cu_from_header_builder = Builder(action = trivial_source_from_header, suffix = '.cu', src_suffix = '.h') env.Append(BUILDERS = {'CUFile' : cu_from_header_builder}) # CPPFile builds a trivial .cpp file from a Cusp header cpp_from_header_builder = Builder(action = trivial_source_from_header, suffix = '.cpp', src_suffix = '.h') env.Append(BUILDERS = {'CPPFile' : cpp_from_header_builder}) # find all user-includable .h files in the cusp tree and generate trivial source files #including them extensions = ['.h'] folders = ['', # main folder 'gallery/', 'graph/', 'io/', 'krylov/', 'precond/', 'relaxation/'] sources = [] for folder in folders: for ext in extensions: pattern = os.path.join(os.path.join(cusp_abspath, folder), "*" + ext) for fullpath in glob.glob(pattern): headerfilename = os.path.basename(fullpath) cu = env.CUFile(headerfilename.replace('.h', '.cu'), fullpath) cpp = env.CPPFile(headerfilename.replace('.h', '_cpp.cpp'), fullpath) sources.append(cu) #sources.append(cpp) # TODO: re-enable this # insure that all files #include <cusp/detail/config.h> fid = open(fullpath) if '#include <cusp/detail/config.h>' not in fid.read(): warn('Header <cusp/' + folder + headerfilename + '> does not include <cusp/detail/config.h>') # and the file with main() sources.append('main.cu') tester = env.Program('tester', sources)
Python
import os import inspect import glob # try to import an environment first try: Import('env') except: exec open("../../build/build-env.py") env = Environment() # on mac we have to tell the linker to link against the C++ library if env['PLATFORM'] == "darwin": env.Append(LINKFLAGS = "-lstdc++") # find all .cus & .cpps in the current directory sources = [] directories = ['.'] extensions = ['*.cu', '*.cpp'] for dir in directories: for ext in extensions: regexp = os.path.join(dir, ext) #sources.extend(env.Glob(regexp, strings = True)) sources.extend(glob.glob(regexp)) # compile examples for src in sources: env.Program(src)
Python
import os import inspect import glob # try to import an environment first try: Import('env') except: exec open("../../build/build-env.py") env = Environment() # on mac we have to tell the linker to link against the C++ library if env['PLATFORM'] == "darwin": env.Append(LINKFLAGS = "-lstdc++") # find all .cus & .cpps in the current directory sources = [] directories = ['.'] extensions = ['*.cu', '*.cpp'] for dir in directories: for ext in extensions: regexp = os.path.join(dir, ext) #sources.extend(env.Glob(regexp, strings = True)) sources.extend(glob.glob(regexp)) # compile examples for src in sources: env.Program(src)
Python
import os import inspect import glob # try to import an environment first try: Import('env') except: exec open("../../build/build-env.py") env = Environment() # on mac we have to tell the linker to link against the C++ library if env['PLATFORM'] == "darwin": env.Append(LINKFLAGS = "-lstdc++") # find all .cus & .cpps in the current directory sources = [] directories = ['.'] extensions = ['*.cu', '*.cpp'] for dir in directories: for ext in extensions: regexp = os.path.join(dir, ext) #sources.extend(env.Glob(regexp, strings = True)) sources.extend(glob.glob(regexp)) # compile examples for src in sources: env.Program(src)
Python
import os import inspect import glob # try to import an environment first try: Import('env') except: exec open("../../build/build-env.py") env = Environment() # on mac we have to tell the linker to link against the C++ library if env['PLATFORM'] == "darwin": env.Append(LINKFLAGS = "-lstdc++") # find all .cus & .cpps in the current directory sources = [] directories = ['.'] extensions = ['*.cu', '*.cpp'] for dir in directories: for ext in extensions: regexp = os.path.join(dir, ext) #sources.extend(env.Glob(regexp, strings = True)) sources.extend(glob.glob(regexp)) # compile examples for src in sources: env.Program(src)
Python
import os import inspect import glob # try to import an environment first try: Import('env') except: exec open("../../build/build-env.py") env = Environment() # on mac we have to tell the linker to link against the C++ library if env['PLATFORM'] == "darwin": env.Append(LINKFLAGS = "-lstdc++") # find all .cus & .cpps in the current directory sources = [] directories = ['.'] extensions = ['*.cu', '*.cpp'] for dir in directories: for ext in extensions: regexp = os.path.join(dir, ext) #sources.extend(env.Glob(regexp, strings = True)) sources.extend(glob.glob(regexp)) # compile examples for src in sources: env.Program(src)
Python
#!/usr/bin/env python import os,csv device_id = '0' # index of the device to use binary_filename = '../spmv' # command used to run the tests output_file = 'benchmark_output.log' # file where results are stored # The unstructured matrices are available online: # http://www.nvidia.com/content/NV_Research/matrices.zip mats = [] unstructured_path = '~/scratch/Matrices/williams/mm/' unstructured_mats = [('Dense','dense2.mtx'), ('Protein','pdb1HYS.mtx'), ('FEM/Spheres','consph.mtx'), ('FEM/Cantilever','cant.mtx'), ('Wind Tunnel','pwtk.mtx'), ('FEM/Harbor','rma10.mtx'), ('QCD','qcd5_4.mtx'), ('FEM/Ship','shipsec1.mtx'), ('Economics','mac_econ_fwd500.mtx'), ('Epidemiology','mc2depi.mtx'), ('FEM/Accelerator','cop20k_A.mtx'), ('Circuit','scircuit.mtx'), ('Webbase','webbase-1M.mtx'), ('LP','rail4284.mtx') ] unstructured_mats = [ mat + (unstructured_path,) for mat in unstructured_mats] structured_path = '~/scratch/Matrices/stencil/' structured_mats = [('Laplacian_3pt_stencil', '3pt_1000000.mtx'), ('Laplacian_5pt_stencil', '5pt_1000x1000.mtx'), ('Laplacian_7pt_stencil', '7pt_100x100x100.mtx'), ('Laplacian_9pt_stencil', '9pt_1000x1000.mtx'), ('Laplacian_27pt_stencil', '27pt_100x100x100.mtx')] structured_mats = [ mat + (structured_path,) for mat in structured_mats] # assemble suite of matrices trials = unstructured_mats + structured_mats def run_tests(value_type): # remove previous result (if present) open(output_file,'w').close() # run benchmark for each file for matrix,filename,path in trials: matrix_filename = path + filename # setup the command to execute cmd = binary_filename cmd += ' ' + matrix_filename # e.g. pwtk.mtx cmd += ' --device=' + device_id # e.g. 0 or 1 cmd += ' --value_type=' + value_type # e.g. float or double # execute the benchmark on this file os.system(cmd) # process output_file matrices = {} results = {} kernels = set() # fid = open(output_file) for line in fid.readlines(): tokens = dict( [tuple(part.split('=')) for part in line.split()] ) if 'file' in tokens: file = os.path.split(tokens['file'])[1] matrices[file] = tokens results[file] = {} else: kernel = tokens['kernel'] results[file][kernel] = tokens kernels.add(tokens['kernel']) ## put CPU results before GPU results #kernels = ['csr_serial'] + sorted(kernels - set(['csr_serial'])) kernels = sorted(kernels) # write out CSV formatted results def write_csv(field): fid = open('bench_' + value_type + '_' + field + '.csv','w') writer = csv.writer(fid) writer.writerow(['matrix','file','rows','cols','nonzeros'] + kernels) for (matrix,file,path) in trials: line = [matrix, file, matrices[file]['rows'], matrices[file]['cols'], matrices[file]['nonzeros']] matrix_results = results[file] for kernel in kernels: if kernel in matrix_results: line.append( matrix_results[kernel][field] ) else: line.append(' ') writer.writerow( line ) fid.close() write_csv('gflops') #GFLOP/s write_csv('gbytes') #GBytes/s run_tests('float') run_tests('double')
Python
import os import inspect import glob # try to import an environment first try: Import('env') except: exec open("../../build/build-env.py") env = Environment() # on mac we have to tell the linker to link against the C++ library if env['PLATFORM'] == "darwin": env.Append(LINKFLAGS = "-lstdc++") # find all .cus & .cpps in the current directory sources = [] directories = ['.'] extensions = ['*.cu', '*.cpp'] for dir in directories: for ext in extensions: regexp = os.path.join(dir, ext) #sources.extend(env.Glob(regexp, strings = True)) sources.extend(glob.glob(regexp)) # compile examples for src in sources: env.Program(src)
Python
import os import inspect import glob # try to import an environment first try: Import('env') except: exec open("../../build/build-env.py") env = Environment() # on mac we have to tell the linker to link against the C++ library if env['PLATFORM'] == "darwin": env.Append(LINKFLAGS = "-lstdc++") # find all .cus & .cpps in the current directory sources = [] directories = ['.'] extensions = ['*.cu', '*.cpp'] for dir in directories: for ext in extensions: regexp = os.path.join(dir, ext) #sources.extend(env.Glob(regexp, strings = True)) sources.extend(glob.glob(regexp)) # compile examples for src in sources: env.Program(src)
Python
import os import inspect import glob # try to import an environment first try: Import('env') except: exec open("../../build/build-env.py") env = Environment() # on mac we have to tell the linker to link against the C++ library if env['PLATFORM'] == "darwin": env.Append(LINKFLAGS = "-lstdc++") # find all .cus & .cpps in the current directory sources = [] directories = ['.'] extensions = ['*.cu', '*.cpp'] for dir in directories: for ext in extensions: regexp = os.path.join(dir, ext) #sources.extend(env.Glob(regexp, strings = True)) sources.extend(glob.glob(regexp)) # compile examples for src in sources: env.Program(src)
Python
#!/usr/bin/env python2 import os import re def rmlast(flist): """ Given a package filename list, this function removes from the list only the latest version of the package, examples: >>> rmlast(['b-1.0', 'd-2.0', 'a-10.1', 'b-2.0', 'b-3.0', 'c-1.0', 'a-2.0']) ['a-2.0', 'b-1.0', 'b-2.0'] >>> rmlast([]) [] >>> rmlast(['a-1.2.tar.gz']) [] >>> rmlast(['j-2', 'j-1', 'gstreamer0.10-base-plugins-0.10.30-1-i686.pkg.tar.xz', 'gstreamer0.10-python-0.10.18-3-i686.pkg.tar.xz']) ['j-1'] >>> rmlast(['b-1', 'b-2', 'a-1']) ['b-1'] """ flist.sort() i, rlist, re_pkname, re_vnum = 0, [], re.compile(r'([a-z][\w\.\+]*-)+'), re.compile(r'\d+') while i < len(flist): # take this pkg name and version numbers pkg = re.match(re_pkname, flist[i]).group() vlist = [([int(x) for x in re.findall(re_vnum, flist[i])], flist[i])] # search same pkgs and append the version numbers i += 1 if i < len(flist): next_pkg = re.match(re_pkname, flist[i]).group() while i < len(flist) and pkg == next_pkg: vlist.append(([int(x) for x in re.findall(re_vnum, flist[i])], flist[i])) i += 1 if i < len(flist): # take next only if not already in the last pos next_pkg = re.match(re_pkname, flist[i]).group() # sort the version number list vlist.sort() for _, fname in vlist[:-1]: rlist.append(fname) # append all but the last item to the result return rlist if __name__ == '__main__': pacdir = '/var/cache/pacman/pkg' print '\n'.join([os.path.join(pacdir, f) for f in rmlast(os.listdir(pacdir))])
Python
"""Setup the fileupload application""" import logging from paste.deploy import appconfig from pylons import config from fileupload.config.environment import load_environment log = logging.getLogger(__name__) def setup_config(command, filename, section, vars): """Place any commands to setup fileupload here""" conf = appconfig('config:' + filename) load_environment(conf.global_conf, conf.local_conf)
Python
# -*- coding: utf-8 -*- import formencode from formencode import validators from formencode import NestedVariables __all__ = ['FileUploadForm'] class FileUploadForm(formencode.Schema): allow_extra_fields = True pre_validators = [NestedVariables()] files = formencode.ForEach(validators.FileUploadKeeper())
Python
from fileupload.lib.base import * class TemplateController(BaseController): def form(self): return render('/form.mako') def view(self, url): """By default, the final controller tried to fulfill the request when no other routes match. It may be used to display a template when all else fails, e.g.:: def view(self, url): return render('/%s' % url) Or if you're using Mako and want to explicitly send a 404 (Not Found) response code when the requested template doesn't exist:: import mako.exceptions def view(self, url): try: return render('/%s' % url) except mako.exceptions.TopLevelLookupException: abort(404) By default this controller aborts the request with a 404 (Not Found) """ abort(404)
Python
# -*- coding: utf-8 -*- import logging import shutil import os import formencode.validators from pylons.decorators import decorator from fileupload.lib.base import * from fileupload.model.forms import FileUploadForm log = logging.getLogger(__name__) class BaseUploadController(BaseController): validate_schema = None _permanent_store = None def _get_permanenr_store(self): return self._permanent_store permanent_store = property(_get_permanenr_store, doc="Путь до места хранения файлов на файловой системе.") def _store_path(self, file_): """ Формирование пути до файла, размещаемого на сервере. """ file_path = os.path.join(self.permanent_store, file_['filename']) return file_path def _write_file(self, file_): """ Метод реализует процесс записи файла. Делает вызов _store_path чтобы узнать место, кудв следует сохранять файл. """ file_path = self._store_path(file_) permanent_file = open(file_path, 'w') permanent_file.write(file_['content']) permanent_file.close() def _handle_form_error(self, error): """ Обработка ошибки обработчиа формы. """ log.error(error) def _handle_form(self): """ Обрбаботка формы запроса. """ try: self.files = self.validate_schema.to_python(request.params) except formencode.validators.Invalid, error: self._handle_form_error(error) def upload(self): self._handle_form() map(self._write_file, self.files['files']) class UploadController(BaseUploadController): _permanent_store = '/home/masted/ftp/incoming/upload/' validate_schema = FileUploadForm
Python
import os.path import paste.fileapp from pylons.middleware import error_document_template, media_path from fileupload.lib.base import * class ErrorController(BaseController): """Generates error documents as and when they are required. The ErrorDocuments middleware forwards to ErrorController when error related status codes are returned from the application. This behaviour can be altered by changing the parameters to the ErrorDocuments middleware in your config/middleware.py file. """ def document(self): """Render the error document""" page = error_document_template % \ dict(prefix=request.environ.get('SCRIPT_NAME', ''), code=request.params.get('code', ''), message=request.params.get('message', '')) return page def img(self, id): """Serve Pylons' stock images""" return self._serve_file(os.path.join(media_path, 'img', id)) def style(self, id): """Serve Pylons' stock stylesheets""" return self._serve_file(os.path.join(media_path, 'style', id)) def _serve_file(self, path): """Call Paste's FileApp (a WSGI application) to serve the file at the specified path """ fapp = paste.fileapp.FileApp(path) return fapp(request.environ, self.start_response)
Python
"""Pylons application test package When the test runner finds and executes tests within this directory, this file will be loaded to setup the test environment. It registers the root directory of the project in sys.path and pkg_resources, in case the project hasn't been installed with setuptools. It also initializes the application via websetup (paster setup-app) with the project's test.ini configuration file. """ import os import sys from unittest import TestCase import pkg_resources import paste.fixture import paste.script.appinstall from paste.deploy import loadapp from routes import url_for __all__ = ['url_for', 'TestController'] here_dir = os.path.dirname(os.path.abspath(__file__)) conf_dir = os.path.dirname(os.path.dirname(here_dir)) sys.path.insert(0, conf_dir) pkg_resources.working_set.add_entry(conf_dir) pkg_resources.require('Paste') pkg_resources.require('PasteScript') test_file = os.path.join(conf_dir, 'test.ini') cmd = paste.script.appinstall.SetupCommand('setup-app') cmd.run([test_file]) class TestController(TestCase): def __init__(self, *args, **kwargs): wsgiapp = loadapp('config:test.ini', relative_to=conf_dir) self.app = paste.fixture.TestApp(wsgiapp) TestCase.__init__(self, *args, **kwargs)
Python
"""Pylons environment configuration""" import os from pylons import config import fileupload.lib.app_globals as app_globals import fileupload.lib.helpers from fileupload.config.routing import make_map def load_environment(global_conf, app_conf): """Configure the Pylons environment via the ``pylons.config`` object """ # Pylons paths root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) paths = dict(root=root, controllers=os.path.join(root, 'controllers'), static_files=os.path.join(root, 'public'), templates=[os.path.join(root, 'templates')]) # Initialize config with the basic options config.init_app(global_conf, app_conf, package='fileupload', template_engine='mako', paths=paths) config['routes.map'] = make_map() config['pylons.g'] = app_globals.Globals() config['pylons.h'] = fileupload.lib.helpers # Customize templating options via this variable tmpl_options = config['buffet.template_options'] # CONFIGURATION OPTIONS HERE (note: all config options will override # any Pylons config options)
Python
"""Pylons middleware initialization""" from paste.cascade import Cascade from paste.registry import RegistryManager from paste.urlparser import StaticURLParser from paste.deploy.converters import asbool from pylons import config from pylons.error import error_template from pylons.middleware import error_mapper, ErrorDocuments, ErrorHandler, \ StaticJavascripts from pylons.wsgiapp import PylonsApp from fileupload.config.environment import load_environment def make_app(global_conf, full_stack=True, **app_conf): """Create a Pylons WSGI application and return it ``global_conf`` The inherited configuration for this application. Normally from the [DEFAULT] section of the Paste ini file. ``full_stack`` Whether or not this application provides a full WSGI stack (by default, meaning it handles its own exceptions and errors). Disable full_stack when this application is "managed" by another WSGI middleware. ``app_conf`` The application's local configuration. Normally specified in the [app:<name>] section of the Paste ini file (where <name> defaults to main). """ # Configure the Pylons environment load_environment(global_conf, app_conf) # The Pylons WSGI app app = PylonsApp() # CUSTOM MIDDLEWARE HERE (filtered by error handling middlewares) if asbool(full_stack): # Handle Python exceptions app = ErrorHandler(app, global_conf, error_template=error_template, **config['pylons.errorware']) # Display error documents for 401, 403, 404 status codes (and # 500 when debug is disabled) app = ErrorDocuments(app, global_conf, mapper=error_mapper, **app_conf) # Establish the Registry for this application app = RegistryManager(app) # Static files javascripts_app = StaticJavascripts() static_app = StaticURLParser(config['pylons.paths']['static_files']) app = Cascade([static_app, javascripts_app, app]) return app
Python
"""Routes configuration The more specific and detailed routes should be defined first so they may take precedent over the more generic routes. For more information refer to the routes manual at http://routes.groovie.org/docs/ """ from pylons import config from routes import Mapper def make_map(): """Create, configure and return the routes Mapper""" map = Mapper(directory=config['pylons.paths']['controllers'], always_scan=config['debug']) # The ErrorController route (handles 404/500 error pages); it should # likely stay at the top, ensuring it can always be resolved map.connect('error/:action/:id', controller='error') # CUSTOM ROUTES HERE map.connect('/', controller='template', action='form') map.connect('/upload', controller='upload', action='upload') #map.connect(':controller/:action/:id') map.connect('*url', controller='template', action='view') return map
Python
"""The base Controller API Provides the BaseController class for subclassing, and other objects utilized by Controllers. """ from pylons import c, cache, config, g, request, response, session from pylons.controllers import WSGIController from pylons.controllers.util import abort, etag_cache, redirect_to from pylons.decorators import jsonify, validate from pylons.i18n import _, ungettext, N_ from pylons.templating import render import fileupload.lib.helpers as h import fileupload.model as model class BaseController(WSGIController): def __call__(self, environ, start_response): """Invoke the Controller""" # WSGIController.__call__ dispatches to the Controller method # the request is routed to. This routing information is # available in environ['pylons.routes_dict'] return WSGIController.__call__(self, environ, start_response) # Include the '_' function in the public names __all__ = [__name for __name in locals().keys() if not __name.startswith('_') \ or __name == '_']
Python
"""The application's Globals object""" from pylons import config class Globals(object): """Globals acts as a container for objects available throughout the life of the application """ def __init__(self): """One instance of Globals is created during application initialization and is available during requests via the 'g' variable """ pass
Python
"""Helper functions Consists of functions to typically be used within templates, but also available to Controllers. This module is available to both as 'h'. """ from webhelpers import *
Python
try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages setup( name='fileupload', version="", #description='', #author='', #author_email='', #url='', install_requires=["Pylons>=0.9.6.1"], packages=find_packages(exclude=['ez_setup']), include_package_data=True, test_suite='nose.collector', package_data={'fileupload': ['i18n/*/LC_MESSAGES/*.mo']}, #message_extractors = {'fileupload': [ # ('**.py', 'python', None), # ('templates/**.mako', 'mako', None), # ('public/**', 'ignore', None)]}, entry_points=""" [paste.app_factory] main = fileupload.config.middleware:make_app [paste.app_install] main = pylons.util:PylonsInstaller """, )
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- import htmlentitydefs import logging import logging.handlers import os import re import string import sys import time import ConfigParser import cPickle as pickle SCRIPT_DIR = os.path.dirname(os.path.realpath(sys.argv[0])) CONFIG_FILE = os.path.join(SCRIPT_DIR, 'wfg.cfg') STATE_FILE = os.path.join(SCRIPT_DIR, 'wfg.dat') LOCK_FILE = os.path.join(SCRIPT_DIR, 'wfg.pid') LOG_FILE = os.path.join(SCRIPT_DIR, 'wfg.log') try: import requests except ImportError: def download_requests(): print "It seems you are missing the required 'requests' module." print "Press ENTER to automatically download and extract this module." print "Press Ctrl+C if you wish to cancel and install it manually." try: raw_input() except KeyboardInterrupt: print "You must install the 'requests' module before attempting to run this script." print "Visit http://docs.python-requests.org/en/latest/user/install/ for instructions." sys.exit(1) import urllib2 import zipfile import cStringIO as StringIO requests_zip = "https://github.com/kennethreitz/requests/archive/v2.0.1.zip" data = urllib2.urlopen(requests_zip) data = StringIO.StringIO(data.read()) data = zipfile.ZipFile(data) filelist = data.namelist() root = filelist[0] dirname = os.path.join(root, 'requests') filelist = [filename for filename in filelist if filename.startswith(dirname)] cwd = os.getcwd() os.chdir(SCRIPT_DIR) data.extractall(members=filelist) os.rename(dirname, 'requests') os.rmdir(root) os.chdir(cwd) print "Extraction complete. Will attempt to continue..." download_requests() import requests class WFGException(Exception): pass class WhatFreeGrab(object): NAME = "WhatFreeGrab" VER = "0.1" IDENT = "%s v%s" % (NAME, VER) INVALID_CHARS = r'\/:*<>|?"' HTML_RE = re.compile("&#?\w+;") headers = { 'Content-type': "application/x-www-form-urlencoded", 'Accept-Charset': "utf-8", 'User-Agent': IDENT } loginpage = "https://what.cd/login.php" ajaxpage = "https://what.cd/ajax.php" torrentpage = "https://what.cd/torrents.php" defaults = { 'log_level': "INFO", 'max_torrents': "3000", 'quiet': "false", 'template_music': "${artist} - ${groupName} (${format} ${encoding}) [${torrentId}]", 'template_other': "${groupName} [${torrentId}]" } timeformat = "%Y-%m-%d %H:%M:%S" log_size = 10 * 1024 * 1024 # 10MB def __init__(self, config_file, state_file, lock_file, log_file): self.config_file = config_file self.state_file = state_file self.lock_file = lock_file self.log_file = log_file self.instance = SingleInstance(self.lock_file) self.start_time = time.time() self.session = requests.session() self.session.headers = WhatFreeGrab.headers self.config = ConfigParser.SafeConfigParser(WhatFreeGrab.defaults) if not os.path.exists(self.config_file): self._first_run() self.config.read(self.config_file) # This is necessary because otherwise we get 'NoSectionError' even if # the value is set in the defaults. try: self.config.add_section('output') except ConfigParser.DuplicateSectionError: pass self.quiet = self.config.getboolean('output', 'quiet') self.log_level = self.config.get('output', 'log_level') numeric_level = getattr(logging, self.log_level.upper(), None) if not isinstance(numeric_level, int): raise ValueError('Invalid log level: %s' % self.log_level) self.log = logging.getLogger() self.log.setLevel(logging.INFO) handler = logging.handlers.RotatingFileHandler(filename=log_file, maxBytes=WhatFreeGrab.log_size, encoding="utf-8") formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s", datefmt=WhatFreeGrab.timeformat) handler.setFormatter(formatter) self.log.addHandler(handler) self.log.info("%s starting up", WhatFreeGrab.IDENT) self.message(WhatFreeGrab.IDENT) self.message("-" * len(WhatFreeGrab.IDENT)) self.message("Startup time: %s" % time.strftime(WhatFreeGrab.timeformat, time.localtime(self.start_time))) self.username = self.config.get('login', 'username') self.password = self.config.get('login', 'password') if not (self.username and self.password): self.quit("No username or password specified in configuration.", error=True) self.target = self.config.get('download', 'target') if not self.target: self.quit("No target directory specified in configuration.", error=True) self.target = os.path.realpath(os.path.expanduser(self.target)) if not os.path.exists(self.target): os.makedirs(self.target) self.max_torrents = self.config.getint('download', 'max_torrents') self.template_music = self.config.get('download', 'template_music') self.template_other = self.config.get('download', 'template_other') if not '${torrentId}' in (self.template_music and self.template_other): self.quit("Naming templates in configuration MUST contain ${torrentId}", error=True) self.template_music = string.Template(self.template_music) self.template_other = string.Template(self.template_other) # Look out! No default values available from here on. self.config._defaults.clear() self.filters = [] for section in self.config.sections(): if section.startswith("filter-"): self.filters.append(dict(self.config.items(section))) if not self.filters: self.filters = [{}] if os.path.exists(self.state_file): self.state = pickle.load(open(self.state_file, 'rb')) else: self.state = {} if 'cookies' in self.state: self.session.cookies = self.state['cookies'] else: self._login() self.authkey = None self.passkey = None try: self._get_accountinfo() except WFGException: # Expired/invalid cookie? try: self._login() except WFGException: self.quit("Unable to login. Check your configuration.", error=True) else: self._get_accountinfo() self.history = self.state.get('history', set()) self.torrent_list = [] self.counter = {} for key in 'total', 'downloaded', 'skipped', 'exists', 'error': self.counter[key] = 0 def _first_run(self): import getpass import random config = ConfigParser.SafeConfigParser() rand_minutes = str(random.randrange(60)).zfill(2) script_path = os.path.join(SCRIPT_DIR, sys.argv[0]) message = """ Hey there! It looks like you are running this script for the first time. Let's go ahead and create a new configuration file.""" print message while True: print "\nFirst we will need your What.CD username and password." username = raw_input("Enter your username: ") if not username: continue password = getpass.getpass("Enter your password (will not be shown on screen): ") if not password: continue print "\nGot it. The script will try to login with this info...", self.username = username self.password = password try: self._login() except WFGException: print "failed. :(" print "Let's try again." continue else: print "success!" break config.add_section('login') config.set('login', 'username', username) config.set('login', 'password', password) while True: print "\nThe directory where the script downloads .torrent files is called the target." target = raw_input("Enter target: ") full_target = os.path.realpath(os.path.expanduser(target)) if not os.path.exists(full_target): try: os.makedirs(full_target) except: print "Unable to access the '%s' directory." % target print "Let's try again." continue else: print "\nLooks good." break else: print "\nLooks good." break config.add_section('download') config.set('download', 'target', full_target) print "\nFinally, do you want to use the same filename format that Yoink! used?" print "See README for the default used otherwise, as well as other formats available." if raw_input("Use Yoink! filename format? [Y/N] ").lower().startswith("y"): config.set('download', 'template_music', "${torrentId}. ${yoinkFormat}") config.set('download', 'template_other', "${torrentId} ${yoinkFormat}") else: # Use defaults, no need to save them in config. pass with open(self.config_file, 'w') as f: config.write(f) message = """ Configuration file created successfully. ------------------------------------------------------------------------------- If you plan on adding the script to your cron file, consider using the following line: %s * * * * python %s The minutes field above has been randomly-determined. Spreading the scheduling like this helps avoid having a bunch of scripts all hitting the server every hour on the hour. Enjoy! """ % (rand_minutes, script_path) print message raw_input("Press ENTER to continue... ") def _get_accountinfo(self): response = self.request('index') self.authkey = response['authkey'] self.passkey = response['passkey'] def _login(self): data = {'username': self.username, 'password': self.password, 'keeplogged': 1, 'login': "Login" } r = self.session.post(WhatFreeGrab.loginpage, data=data, allow_redirects=False) if r.status_code != 302: raise WFGException if hasattr(self, 'state'): self.state['cookies'] = self.session.cookies self.save_state() def add_to_history(self, torrent_id): self.history.add(torrent_id) self.state['history'] = self.history self.save_state() def create_filename(self, torrent): if 'artist' in torrent: filename = self.template_music.substitute(torrent).strip() else: filename = self.template_other.substitute(torrent).strip() filename = self.unescape_html(filename) filename = self.remove_invalid_chars(filename) filename = "%s.torrent" % filename return filename def download_torrents(self): self.message("Legend: (+) downloaded (*) file exists (!) error") for torrent in self.torrent_list: torrent_id = torrent['torrentId'] if torrent_id in self.history: self.counter['skipped'] += 1 continue filename = self.create_filename(torrent) filepath = os.path.join(self.target, filename) # This is an ugly hack, but it'll have to do for now if len(filepath) > 247: # 247 + 9 for .torrent suffix = 255 filepath = filepath[:123] + "~" + filepath[-123:] if os.path.exists(filepath): self.log.info("File exists for torrent ID %s: '%s'", torrent_id, filepath) self.message("*", newline=False) self.add_to_history(torrent_id) self.counter['exists'] += 1 continue data = self.get_torrent(torrent_id) if not data: self.log.info("Error downloading torrent ID %s", torrent_id) self.message("!", newline=False) self.counter['error'] += 1 continue with open(filepath, 'wb') as f: f.write(data) self.log.info("Downloaded torrent ID %s: '%s'", torrent_id, filepath) self.message("+", newline=False) self.counter['downloaded'] += 1 self.add_to_history(torrent_id) def get_freeleech(self, page, custom_params): params = {'freetorrent': 1, 'page': page} params.update(custom_params) response = self.request('browse', **params) for group in response['results']: if 'torrents' in group: for torrent in group.pop('torrents'): yoink_format = { 'yoinkFormat': "%s - %s - %s (%s - %s - %s)" % (group['artist'][:50], group['groupYear'], group['groupName'][:50], torrent['media'], torrent['format'], torrent['encoding']) } self.torrent_list.append(dict(group.items() + torrent.items() + yoink_format.items())) else: yoink_format = {'yoinkFormat': group['groupName'][:100]} self.torrent_list.append(dict(group.items() + yoink_format.items())) return response['pages'] def get_torrent(self, torrent_id): params = {'action': 'download', 'id': torrent_id} if self.authkey: params['authkey'] = self.authkey params['torrent_pass'] = self.passkey r = self.session.get(WhatFreeGrab.torrentpage, params=params, allow_redirects=False) time.sleep(2) # Be nice. if r.status_code == 200 and 'application/x-bittorrent' in r.headers['content-type']: return r.content return None def human_time(self, t): # Yes, I know about datetime.datetime, but this was fun. m, s = divmod(t, 60) h, m = divmod(m, 60) d, h = divmod(h, 24) out = "" if h: out += "%d hours, " % h if m: out += "%d minutes, " % m out += "%.2f seconds" % s return out def message(self, msg, error=False, newline=True): if (not self.quiet) or (error): if newline: print msg else: print msg, sys.stdout.flush() def quit(self, msg, error=False): if error: log = self.log.critical else: log = self.log.info exec_time = "Script finished in: %s" % self.human_time(time.time() - self.start_time) log(msg) log(exec_time) log("-" * 40) self.message(msg, error) self.message(exec_time) sys.exit(int(error)) def request(self, action, **kwargs): params = {'action': action} if self.authkey: params['auth'] = self.authkey params.update(kwargs) r = self.session.get(WhatFreeGrab.ajaxpage, params=params, allow_redirects=False) time.sleep(2) # Be nice. try: json_response = r.json() if json_response['status'] != "success": raise WFGException return json_response['response'] except ValueError: raise WFGException def remove_invalid_chars(self, item): item = "".join(c in WhatFreeGrab.INVALID_CHARS and " " or c for c in item) item = " ".join(item.split()) return item def run(self): self.message("Building torrent list:", newline=False) self.log.info("Building torrent list") for params in self.filters: page = pages = 1 while True: # Sometimes the request() call inside get_freeleech() will # throw an exception because the site is busy. In that case we # just skip this page and we'll catch up on the next run. try: pages = self.get_freeleech(page, params) except WFGException: pass self.message(".", newline=False) if len(self.torrent_list) > self.max_torrents: self.message("") self.quit("Number of torrents found exceeds maximum limit of %s." % self.max_torrents, error=True) page +=1 if page > pages: break self.counter['total'] = len(self.torrent_list) self.log.info("%s torrents found", self.counter['total']) self.message("") self.message("%s torrents found" % self.counter['total']) self.log.info("Downloading torrents") self.download_torrents() self.log.info("%s skipped", self.counter['skipped']) self.log.info("%s exist", self.counter['exists']) self.log.info("%s errors", self.counter['error']) self.log.info("%s downloaded", self.counter['downloaded']) self.message("") self.message("%s skipped" % self.counter['skipped']) self.message("%s exist" % self.counter['exists']) self.message("%s errors" % self.counter['error']) self.message("%s downloaded" % self.counter['downloaded']) self.message("") self.quit("Process complete.") def save_state(self): pickle.dump(self.state, open(self.state_file, 'wb')) # http://effbot.org/zone/re-sub.htm#unescape-html def unescape_html(self, text): def fixup(m): text = m.group(0) if text[:2] == "&#": # character reference try: if text[:3] == "&#x": return unichr(int(text[3:-1], 16)) else: return unichr(int(text[2:-1])) except ValueError: pass else: # named entity try: text = unichr(htmlentitydefs.name2codepoint[text[1:-1]]) except KeyError: pass return text # leave as is return WhatFreeGrab.HTML_RE.sub(fixup, text) # https://github.com/pycontribs/tendo/blob/master/tendo/singleton.py class SingleInstance: def __init__(self, lockfile): import sys self.initialized = False self.lockfile = lockfile if sys.platform == 'win32': try: # file already exists, we try to remove (in case previous execution was interrupted) if os.path.exists(self.lockfile): os.unlink(self.lockfile) self.fd = os.open(self.lockfile, os.O_CREAT | os.O_EXCL | os.O_RDWR) except OSError: type, e, tb = sys.exc_info() if e.errno == 13: print "Another instance is already running, quitting." sys.exit(-1) print e.errno raise else: # non Windows import fcntl self.fp = open(self.lockfile, 'w') try: fcntl.lockf(self.fp, fcntl.LOCK_EX | fcntl.LOCK_NB) except IOError: print "Another instance is already running, quitting." sys.exit(-1) self.initialized = True def __del__(self): import sys import os if not self.initialized: return try: if sys.platform == 'win32': if hasattr(self, 'fd'): os.close(self.fd) os.unlink(self.lockfile) else: import fcntl fcntl.lockf(self.fp, fcntl.LOCK_UN) # os.close(self.fp) if os.path.isfile(self.lockfile): os.unlink(self.lockfile) except Exception as e: print "Unloggable error: %s" % e sys.exit(-1) if __name__ == '__main__': WhatFreeGrab(config_file=CONFIG_FILE, state_file=STATE_FILE, lock_file=LOCK_FILE, log_file=LOG_FILE).run()
Python
import os.path import fjol from zope.app.testing.functional import ZCMLLayer ftesting_zcml = os.path.join( os.path.dirname(fjol.__file__), 'ftesting.zcml') FunctionalLayer = ZCMLLayer(ftesting_zcml, __name__, 'FunctionalLayer')
Python
import grok class fjol(grok.Application, grok.Container): pass class Index(grok.View): pass # see app_templates/index.pt
Python
# this directory is a package
Python
# vim:fileencoding=utf-8 Include("Page.py") vPool['Head'] = "个人信息" vPool['SectionName'] = "Member" vPool['SectionLink'] = '#' vPool['PageName'] = "个人信息" sess = Session() try: try: uid = THIS.path.split('?',1)[1] other = True except (ValueError,IndexError): other = False uid = sess.user_id from buzhug import Base from datetime import date users = Base('database/user').open() the_user = users.select(user_id = uid)[0] if other: vPool['Main'] = "He/She is " + the_user.nick_name + "<br/>" *11 else: vPool['Main'] = "You are " + the_user.nick_name + "<br/>" *11 except IndexError,e: #user not exists vPool['Main'] = "<p>User %s doesn't exists</p>" %(uid,) + "<br/>" *11 except (AttributeError,NameError): vPool['Main'] = "<p>Tell Me Who you Want to see</p>" + "<br/>" *11 ShowPage()
Python
# vim:fileencoding=utf-8 from buzhug import Base from datetime import date,datetime from database import thread_to_tr from database import get_max from database import article_to_div from database import article_to_textarea article = Base('database/article').open() Include("Page.py") vPool['Head'] = "Forum" vPool['SectionName'] = "Forum" vPool['SectionLink'] = 'discuss' vPool['PageName'] = "Welcome" #vPool['Main'] = "<p>Discuss is not avaiable currently</p>" #vPool['Main'] = "" sess = Session() now = datetime(1,1,1) #always try to add new article if hasattr(sess,'user_id'): uid = sess.user_id else: uid = "Anonymous" try: if locals().has_key('_newtopic'): newtid = get_max(article,'thread_id') + 1 article.insert(problem_id = int(_problem_id),thread_id = newtid, user_id = uid, title = unicode(_title,'utf-8'), content = unicode(_con,'utf-8'),reply = 0,ptime = now.today()) vPool['Main'] = vPool['Main'] + "<div>%s</div>" %("Success Add New Topic.") elif locals().has_key('_newreply'): pid = article.select(thread_id = int(_thread_id))[0].problem_id #print _con article.insert(problem_id = pid,thread_id = int(_thread_id), user_id = uid,title = unicode("",'utf-8'),content = unicode(_con,'utf-8'), reply = -1,ptime = now.today()) update_article = article.select_for_update(thread_id = int(_thread_id))[0] article.update(update_article,reply = update_article.reply + 1) except AttributeError,e: print e if locals().has_key('_system'): #for system form just set pid to 0 _pid = 0 if locals().has_key('_tid'): articles = article.select(thread_id = int(_tid)) articles.sort_by('+__id__') #print len(articles) vPool['Main'] = ''' <div class="thread"> %s </div> <h3>你的回应</h3> <form method="post"> <input type="hidden" name="thread_id" value="%s"/> <input id="newreply" name="newreply" type="hidden" class="" value="1"/> <textarea id="con" name="con" wrap="off" class="f-code" rows="10" cols="40" ></textarea><br /> <input type="submit" value="Submit" class="f-submit" /><br /> </form> ''' %('\n'.join([article_to_div(rec) for rec in articles]),_tid) vPool['moreCSS'] = vPool['moreCSS'] + ''' <style type="text/css"> div.thread{ } div.thread div.topic span.authortime{ background-color: rgb(238, 255, 238); } div.thread div.reply span.authortime{ background-color: rgb(238, 255, 238); } div.thread div.topic{ padding-left:5px; } div.thread div.topic div.title{ font-size:16px; font-weight:bold; } div.thread div.reply{ padding-left:30px; } </style>''' elif locals().has_key('_pid'): def add_last_reply(th): replys = article.select(thread_id = th.thread_id) replys.sort_by('-__id__') th.last_reply = replys[0].ptime #return th def get_key(th): return th.last_reply if _pid == "": _pid = 0 if int(_pid) > 0: vPool['Head'] = "Forum For Problem %s" %_pid else: vPool['Head'] = "System Forum" threads = [record for record in article if record.problem_id == int(_pid) and record.reply >=0] #print len(threads) for thread in threads : add_last_reply(thread) threads.sort(key=get_key,reverse=True) #print len(threads) #articles = article.select(problem_id = _pid,reply = 0) #articles.sort_by('-thread_id') if len(threads) > 0: vPool['Main'] = ''' <table class="table1"> <tr> <th>话题</th> <th>作者</th> <th>回应</th> <th>最后回应</th> </tr> %s </table> <br/> '''%("\n".join([thread_to_tr(thread) for thread in threads])) else: vPool['Main'] = "<p>目前没有话题</p>" vPool['Main'] = vPool['Main'] + \ '''<div onclick="javascript:document.getElementById('newthread').style.display='block';document.getElementById('title').focus();">开启新话题</div> <br/> <form action="#" id="newthread" name="newthread" method="post" class="f-wrap-1" style="display:none"> <fieldset> <h3>New Thread </h3> <label for="title"><b>Title:</b> <input id="title" name="title" type="text" class="f-name" /><br /> </label> <label for="con"><b>Content:</b> <textarea id="con" name="con" wrap="off" class="f-code" rows="10" cols="40" ></textarea><br /> </label> <div class="f-submit-wrap"> <input type="submit" value="Submit" class="f-submit" /><br /> </div> </fieldset> <input id="problem_id" name="problem_id" type="hidden" class="" value="%s"/> <input id="newtopic" name="newtopic" type="hidden" class="" value="1"/> </form>'''%(_pid) else: vPool['Main'] = ''' <div> 如果您有关于题目的问题,请输入题目编号转到相关论坛.<br/> <form method="get"> <input name="pid" type="text"></input> &nbsp;&nbsp;<input type="submit" value="Go"> </form> 如果你有网站使用的问题,或者对我们有任何的建议或意见,请点<a href="discuss?system">这里</a>. </div><br/><br/><br/><br/><br/><br/> ''' ShowPage()
Python
# vim:fileencoding=utf-8 Include("Page.py") try: problem_id = _pid except (NameError): problem_id = "" vPool['Head'] = "Submit Your Answer" vPool['SectionName'] = "Problems" vPool['SectionLink'] = 'browse' vPool['PageName'] = "Submit" vPool['Main'] = ''' <form action="#" method="post" class="f-wrap-1"> <div class="req"><b>*</b> Indicates required field</div> <fieldset> <!--h3>Form title here</h3--> <label for="problem_id"><b><span class="req">*</span>Problem Id:</b> <input id="problem_id" name="problem_id" type="text" class="f-name" value="%s"/><br /> </label> <label for="lang"><b><span class="req">*</span>Programming Language:</b> <select id="lang" name="lang" > <option>Select...</option> <option>C</option> <option>C++</option> <option>Java</option> </select> <br /> </label> <label for="code"><b><span class="req">*</span>Code:</b> <textarea id="code" name="code" wrap="off" class="f-code" rows="20" cols="50" ></textarea> <br /> </label> <div class="f-submit-wrap"> <input type="submit" value="Submit" class="f-submit" /><br /> </div> </fieldset> </form> ''' %(problem_id,) sess = Session() try: from buzhug import Base from datetime import date,datetime submit = Base('database/submit').open() now = datetime(1,1,1) record_id = submit.insert(user_id = sess.user_id, problem_id = int(_problem_id),lang = _lang, code = unicode(_code,'utf-8'),stime = now.today(), status=6) vPool['Main'] = \ '''<p>Success! Your Submit Record Id is %d</p> <p>You will be notified when the result comes out.<br> You can also get the result in <a href="status">status page</a></p> '''%(record_id,) + "<br/>" * 9 if not hasattr(sess,'just_submit'): sess.just_submit = [(record_id,_problem_id,'Waiting')] else: sess.just_submit.append((record_id,_problem_id,'Waiting')) except AttributeError,e: vPool['Main'] = "<p>Not Login</p>" + "<br/>" *11 except NameError,e: pass ShowPage()
Python
# vim:fileencoding=utf-8 Include("Page.py") vPool['Head'] = "Running Status" vPool['SectionName'] = "Problems" vPool['SectionLink'] = 'browse' vPool['PageName'] = "Runs Status" vPool['moreMeta'] = '<META HTTP-EQUIV="REFRESH" CONTENT=20>\n' sess = Session() try: argument = THIS.path.split('?',1)[1] #print argument if argument == "pre": sess.page = sess.page - 1 elif argument == "next": sess.page = sess.page + 1 elif argument == "first" : sess.page = 1 else: sess.page #no change #print sess.page except (NameError,AttributeError,IndexError): sess.page = 1 from database import submit_to_tr from buzhug import Base from datetime import date,datetime submit = Base('database/submit').open() num_per_page = 20 #current put it here begin = len(submit)- num_per_page * sess.page if begin < 0: begin = 0 end = begin + num_per_page if end > len(submit): end = len(submit) lastest_record = list(submit)[begin:] lastest_record.reverse() vPool['Main'] = ''' <table class="table1" > <!--thead> <tr> <th colspan="9">Runns Status</th> </tr> </thead--> <tbody> <tr> <th>ID</th> <th>User ID</th> <th>Problem ID</th> <th>Status</th> <th>Language</th> <th>Code</th> <!--<th>Time</th>--> <!--<th>Memory</th>--> <th>Submit Time</th> </tr> ''' +\ "\n".join([submit_to_tr(rec) for rec in lastest_record]) +\ ''' </tbody> </table> [<a href="status?first">First Page</a>] [<a href="status?pre">Previous Page</a>] [<a href="status?next">Next Page</a>] ''' #except AttributeError,e: # pass ShowPage()
Python
# vim:fileencoding=utf-8 from buzhug import Base from datetime import date,datetime from database import problem_to_tr Include("Page.py") def show_all(): '''show all problem sets''' problem = Base('database/problem').open() vPool['Main'] = ''' <p>Currently, we only have a few test problems.</p> <table class="table1" > <!--thead> <tr> <th colspan="9">Problems</th> </tr> </thead--> <tbody> <tr> <th>Problem ID</th> <th>Title</th> <th>Ratio (AC/SUBMIT)</th> <!--<th>Added Date</th>--> </tr> %s </tbody> </table> <!--[<a href="browse?first">First Page</a>] [<a href="browse?pre">Previous Page</a>] [<a href="browse?next">Next Page</a>]--> ''' % '\n'.join([problem_to_tr(rec) for rec in problem]) vPool['Head'] = "Browse The Problem Sets" vPool['SectionName'] = "Problems" vPool['SectionLink'] = 'browse' vPool['PageName'] = "Browse" try: desc = file("ProblemSet/%s/desc.txt" %_pid).read() vPool['Main'] = ''' <pre>%s</pre> <br/> <div><a href="submit?pid=%s">Submit Your Answer</a> &nbsp;&nbsp;&nbsp;<a href="discuss?pid=%s">Discuss This Problem</a></div> ''' %(desc,_pid,_pid) except (TypeError,ValueError,IndexError,NameError): #print "TYPE ERROR" show_all() except IOError: vPool['Main'] = ''' <p>No Such Problem.</p> ''' ShowPage()
Python
# vim:fileencoding=utf-8 from buzhug import Base if not locals().has_key('_sid'): print "Tell Me Which Submission You Want to see." else: submit = Base('database/submit').open() record = submit[int(_sid)] lang = ["unknow","shBrushUnknow.js"] if record.lang in ['C','C++']: lang = ["cpp","shBrushCpp.js"] #print record.lang if record.lang in ['Java']: lang = ['java',"shBrushJava.js"] print '''\ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <!-- Copyright: Filia Tao (gudu2005@gmail.com) Chengjian (@) License: Released Under the GPL 2 http://www.gnu.org/copyleft/gpl.html --> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>View Source And Complier Error</title> <link type="text/css" rel="stylesheet" href="js/highlighter/SyntaxHighlighter.css"></link> <script type="text/javascript" src="js/highlighter/shCore.js"></script> <script type="text/javascript" src="js/highlighter/%s"></script> </head> <body> <h2>The Source Code </h2><br/> <textarea id="sourcecode" name="sourcecode" class="%s"> %s </textarea> <script type="text/javascript"> dp.SyntaxHighlighter.HighlightAll('sourcecode'); </script> <h3 name="error">Complier Error Infomation</h3><br/> <pre> %s </pre> </body> </html> ''' %(lang[1],lang[0],record.code.encode('utf-8'),record.more.encode('utf-8'))
Python
# vim:fileencoding=utf-8 # from database import SameNameError Include('Page.py') vPool['moreJS'] ='''<script type="text/javascript" src="js/validation.js"></script> <script type="text/javascript"> // 密码两此相同 ( from http://ajaxcn.org/comments/start/2006-05-22/1 ,thanks macrochen Validation.add("validate-identical", "The value must be same as password filed.", function(v){ return !Validation.get('IsEmpty').test(v) && v == $F("password"); }); //长度 4-15 Validation.add('validate-length','Your input is too long or too short.',function (v){ return !Validation.get('IsEmpty').test(v) && v.length>=4 && v.length<=15; }); Event.observe(window,'load',function(ev){var valid = new Validation('register', {immediate : true});}); </script> ''' vPool['moreCSS'] = ''' <style> .validation-advice { font-size: 8pt; color : #3366FF; } </style> ''' vPool['Head'] = "Register" vPool['SectionName'] = "Member" vPool['SectionLink'] = '#' vPool['PageName'] = "Register" vPool['Main'] = ''' <form action="#" id="register" name="register" method="post" class="f-wrap-1"> <fieldset> <!--h3>Form title here</h3--> <label for="user_id" ><b>User Id:</b> <input id="user_id" name="user_id" type="text" class="f-name required validate-alphpnum" /><br /> </label> <label for="nick_name"><b>Nick Name:</b> <input id="nick_name" name="nick_name" type="text" class="f-name" /><br /> </label> <label for="password"><b>Password:</b> <input type="password" id="password" name="password" class="required validate-length"/><br/> </label> <label for="con_password"><b>Confirm Password:</b> <input type="password" id="con_password" name="con_password" class="required validate-identical"/><br/> </label> <label for="email"><b>E-Mail:</b> <input id="email" name="email" class="required validate-email"/><br/> </label> <div class="f-submit-wrap"> <input type="submit" value="Submit" class="f-submit" /><br /> </div> </fieldset> </form> ''' try: from buzhug import Base from datetime import date users = Base('database/user').open() result_set = users.select(['user_id'],user_id=_user_id) if len(result_set) > 0: raise SameNameError,{'field':'user_id','value':_user_id} new_user = users.insert(user_id=_user_id,password=_password,nick_name=unicode(_nick_name,'utf-8'),email=_email) vPool['Main'] = "<p>Success, Thank you for register.</p>" + "<br/>"*11 except IndexError,e: vPool['Main'] = "<p>Failed. " + e.message + "</p>"+ "<br/>"*11 except SameNameError,e: vPool['Main'] = "<p>Failed. " + e.message + "</p>"+ "<br/>"*11 except NameError,e: pass #print type(e) #print e.message ShowPage()
Python
# vim:fileencoding=utf-8 import os cmd = "bash judge/run.sh /deal/result.exe " os.system("dir")
Python
# vim:fileencoding=utf-8 #简化引用对象名 from Cheetah.Template import Template as ctTpl vPool = {} vPool['moreMeta'] = "" vPool['moreJS'] = "" vPool['moreCSS'] = "" vPool['Head'] = "Welcome To Filia's Judge Online" vPool['status'] = ''' Click Here to <a href="login">Login</a> or <a href="register">register</a> ''' vPool['SubmitStatus'] = "" vPool['SectionName'] = "Main" vPool['PageName'] = "Welcome" vPool['SectionLink'] = '#' vPool['Main'] = ''' <p> 这个站点是一个在线裁判系统.<br/> 采用Python开发,基于<a target="_blank" href="http://karrigell.sourceforge.net/">Karrigell</a>框架.<br/> 页面基于HTML/CSS模板系统<a target="_blank" href="http://www.mollio.org">mollio</a>.<br/> 更对信息请点击<a href="ppt/">这里</a><br/> </p><br/><br/><br/><br/><br/><br/><br/><br/><br/> ''' def ShowPage(): sess = Session() try: vPool['status'] = '''Welcome %s.<a href="logout">[logout]</a>&nbsp;<a href="member">[member]</a>''' %(sess.user_id,) # vPool['SubmitStatus'] = '\n'.join(['''<li>Problem ID:%s&nbsp;<span class="result" id="result_%d">%s</span></li>''' %(item[1],item[0],item[2]) for item in sess.just_submit]) # vPool['SubmitStatus'] = vPool['SubmitStatus'] + \ # ''' # <script type="text/javascript" src="js/utils.js"></script> # <script type="text/javascript"> # function update_all() # { # update = []; # %s # update.each( function(id){ # fetch_result(id,"result_"+id); # }); # } # Event.observe(window, 'load',update_all, false); # </script> # ''' %('\n'.join(["update.push(%d);" %(item[0]) for item in sess.just_submit])) except Exception,e: #print e pass page = open("template/index.html","r").read() txp = ctTpl(page, searchList=[vPool]) print txp def check_problem(): #just if the problem exsits return True
Python
# vim:fileencoding=utf-8 Include("Page.py") vPool['Head'] = "Solve Problems" vPool['SectionName'] = "Problems" vPool['SectionLink'] = 'browse' vPool['PageName'] = "Solve Record" sess = Session(); try: uid = sess.user_id except AttributeError: uid = "" try: uid = uid = THIS.path.split('?',1)[1] except (ValueError,IndexError): pass if uid == "": vPool['Main'] = "<p>Tell Me Who's Solve Record you Want to see</p>" + "<br/>" *11 else: from database import submit_to_tr from buzhug import Base from datetime import date,datetime submit = Base('database/submit').open() rs = [item.problem_id for item in submit.select(['problem_id'],user_id = uid,status = 0)] rs = set(rs) if len(rs) == 0: vPool['Main'] = "<div>No Resolved Problems for this user <b>%s</b></div>" %uid else: vPool['Head'] = "Solved Problems For %s" %uid group_records = [[]] * ((len(rs)-1)/8 + 1) i = 0 for record in rs : group_records[i/8].append(record) i = i + 1 vPool['Main'] = "<br/> \n".join(["&nbsp;&nbsp;".join(["<a href='browse?pid=%d'>%d</a>" %(item,item) for item in gitem]) for gitem in group_records]) vPool['Main'] = "<div>" + vPool['Main'] + "</div>" ShowPage()
Python
# vim:fileencoding=utf-8 session=Session() session.close() raise HTTP_REDIRECTION, "index"
Python
# vim:fileencoding=utf-8 Include("Page.py") ShowPage();
Python
# vim:fileencoding=utf-8 Include("Page.py") vPool['Head'] = "Login" vPool['SectionName'] = "Member" vPool['SectionLink'] = '#' vPool['PageName'] = "Login" vPool['Main'] = ''' <form action="#" method="post" class="f-wrap-1"> <fieldset> <!--h3>Form title here</h3--> <label for="user_id"><b>User Id:</b> <input id="user_id" name="user_id" type="text" class="f-name" /><br /> </label> <label for="password"><b>Password:</b> <input type="password" id="password" name="password"/><br/> </label> <div class="f-submit-wrap"> <input type="submit" value="Submit" class="f-submit" /><br /> </div> </fieldset> </form> <br/><br/><br/><br/><br/><br/> ''' #always trys to do login ,if an NameError exception is catched #the login page is shown to the user try: from buzhug import Base from datetime import date users = Base('database/user').open() the_user = users.select(user_id = _user_id)[0] #print the_user if the_user.password == _password: vPool['Main'] = "<p>Sucesss. You have login as %s </p>" %(the_user.user_id,) + "<br/>" *11 session=Session() session.user_id = _user_id raise HTTP_REDIRECTION, "index" else: vPool['Main'] = "<p>Failed. Please Check Your UserId and Password </p>" + "<br/>" *11 except IndexError,e: #user not exists vPool['Main'] = "<p>Failed. User %s doesn't exists</p>" %(_user_id,) + "<br/>" *11 except NameError,e: pass ShowPage()
Python
# vim:fileencoding=utf-8 from buzhug import Base from datetime import date,datetime import string,os,time import filecmp subcode = Base('database/submit').open() sleep_time = 5 ret ="" while True: unjudged = subcode.select_for_update(status = 6) if len(unjudged) == 0: print "No Unjudged Submit in database, sleep for %d second" %sleep_time time.sleep(sleep_time) continue for record in unjudged : try: print "Begin Test For SubmitId:%d ProblemID:%d " %(record.__id__,record.problem_id) temp=record.code type=record.lang if(type=="C"): dealing=open('dealCode.c','w') dealing.write(temp.decode('utf-8')) dealing.close() cmd='gcc dealCode.c -o result.exe -O -ansi -fno-asm -Wall -lm -static ' else: if(type=="C++"):#c++ dealing=open('dealCode.cpp','w') dealing.write(temp.encode('utf-8')) dealing.close() cmd='g++ dealCode.cpp -o result.exe -O -ansi -fno-asm -Wall -lm -static ' if(type=="Java"):#java dealing=open('Main.java','w') dealing.write(temp.decode('utf-8')) dealing.close() cmd='javac -g:none Main.java ' print cmd #f = os.system(cmd,) #print f.read() compile_ret = os.system(cmd + " 2>error 1>tmp") if compile_ret != 0: compile_output = file("error").read() ret={"ExitCode":1,"Desc":"COMPLIER ERROR","More":compile_output} print ret else: if type=="JAVA": cmd="java Main <ProblemSet/%d/data.in 1>b.out 2>error " %record.problem_id #subcode.update(record,codelen=len(file("deal/Main.class").read())) else: cmd='result.exe <ProblemSet/%d/data.in 1>b.out 2>error' %record.problem_id #subcode.update(record,codelen=len(file("result.exe").read())) #print len(file("result.exe").read()) print cmd run_ret = os.system(cmd) print run_ret #if run_ret != 0: # ret={"ExitCode":2,"Desc":"INNER ERROR"} # print ret #else: if filecmp.cmp("b.out","ProblemSet/%d/data.out" %(record.problem_id)): ret={"ExitCode":0,"Desc":"ACCEPT"} else: ret={"ExitCode":4,"Desc":"WRONG ANSWER"} print ret print "End Test For SubmitId:%d ProblemID:%d " %(record.__id__,record.problem_id) print "**********************************************************" if not ret.has_key("More"): subcode.update(record,status=ret['ExitCode']) else: subcode.update(record,status=ret['ExitCode'],more = unicode(ret['More'],"utf-8")) except Exception,e: subcode.update(record,status=5) print e
Python
# vim:fileencoding=utf-8 from buzhug import Base from datetime import date,datetime from database import contest_to_tr from database import contest_detail_to_div contests = Base('database/contest').open() Include("Page.py") vPool['Head'] = "Contests" vPool['SectionName'] = "Contests" vPool['SectionLink'] = '#' vPool['PageName'] = "Contests" if locals().has_key('_cid'): #print contests[int(_cid)] vPool['Main'] = contest_detail_to_div(contests[int(_cid)]) vPool['moreCSS'] = ''' <style type="text/css"> div.contest h2.name {text-align:center} div.contest div.time {text-align:center} div.contest div.status {text-align:center} div.contest div.problems {text-align:center;padding-left:30%} div.contest div.problems ol li {text-align:left;} </style> ''' else: vPool['Main'] = ''' <table class="table1"> <tr> <th>Name</th><th>Start Time</th><th>End Time</th><th>Status</th> </tr> %s </table> ''' %"\n".join([contest_to_tr(rec) for rec in contests]) ShowPage()
Python
# vim:fileencoding=utf-8 from buzhug import Base from datetime import date,datetime def build_problem(): try: print "Build the problem Database........" problem = Base('database/problem') problem.create(('problem_id',str),('title',unicode),('time_limit',int),('memory_limit',int),("source",unicode)) print "Done." except IOError: print "Error. problem Database Already Exists" problem = Base('database/problem').open() print "Data in problem " for record in problem : print record.title.encode('utf-8') print "Done" def build_relation(): #problem and contest relationship try: contest = Base('database/contest') problem = Base('database/problem') print "Build the relation Database........" relation = Base('database/relation') relation.create(('contest',contest),('problem',problem)) print "Done." except IOError: print "Error. relation Database Already Exists" print "OR contest ,problem database not exists" relation = Base('database/relation').open() print "Data in relation " for record in relation : print record.contest.name.encode('utf-8'),record.problem.title.encode('utf-8') print "Done" def build_contest(): try: print "Build the Contest Database........" contest = Base('database/contest') contest.create(('name',unicode),('start',datetime),('end',datetime),('status',int),('holder',str)) print "Done." except IOError: print "Error. Contest Database Already Exists" print "Set String Format" contest.set_string_format(unicode,'utf-8') print "Done" contest = Base('database/contest').open() print "Data in contest " #print len(users) for record in contest : print record.name.encode('utf-8') print "Done" def build_user(): try: print "Build the User Database........" users = Base('database/user') users.create(('user_id',str),('password',str),('nick_name',unicode),('email',str)) print "Done." except IOError: print "Error. User Database Already Exists" print "Set String Format" users.set_string_format(unicode,'utf-8') print "Done" users = Base('database/user').open() print "Data in user " print len(users) for record in users : #print "id:" + record.id, print "user_id:" + record.user_id print "nick_name:" + record.nick_name.encode('gb2312') # why gb2312 #users.delete(record) print "Done" def build_submit(): try: print "Build the Submit Record Database........" submit = Base('database/submit') submit.create(('user_id',str),('problem_id',int),('lang',str),('code',unicode),('status',int),('more',unicode),('codelen',int),('time',int),('memory',int),('stime',datetime)) print "Done." except IOError: print "Error. Submit Database Already Exists" print "Set String Format" submit.set_string_format(unicode,'utf-8') submit.set_string_format(date,'%Y-%m-%d') submit.set_string_format(datetime,'%Y-%m-%d %H:%M:%S') print "Done" print "Data in submit " submit = Base('database/submit').open() for record in submit : print record.__id__,record.problem_id,record.lang,record.status print "Done" def build_article(): try: print "Build the Article Database........" article = Base('database/article') article.create(('problem_id',int),('thread_id',int),('user_id',str),('reply',int),('title',unicode),('content',unicode),('ptime',datetime)) print "Done." except IOError: print "Error. Article Database Already Exists" print "Set String Format" article.set_string_format(unicode,'utf-8') article.set_string_format(date,'%Y-%m-%d') article.set_string_format(datetime,'%Y-%m-%d %H:%M:%S') print "Done" print "Data in article " article = Base('database/article').open() for record in article : print record.problem_id,record.thread_id,record.reply print "Done" def get_max(db,field): fs = [getattr(record,field) for record in db] if len(fs) == 0: return 0 else: return max(fs) class SameNameError(Exception): '''Raise This Exception Where try to insert to database with a same name''' def __init__(self,dict): Exception.__init__(self) self.field = dict['field'] self.value = dict['value'] self.message = "Already Exisits an Entry with %s = %s " %(self.field,self.value) def problem_to_tr(rec): '''Convert an problem record to a tr''' ret = ['<tr>'] ret.append('<td>%s</td>' %rec.problem_id) ret.append('<td><a href="browse?pid=%s">%s</a></td>' %(rec.problem_id,rec.title.encode('utf-8'))) submit = Base('database/submit').open() submit_num = len(submit.select(problem_id= int(rec.problem_id))) ac_num = len(submit.select(problem_id= int(rec.problem_id),status = 0)) try: rat = ac_num*100.0/submit_num except ZeroDivisionError: rat = 0.00 ret.append('<td>%2.2f (%d/%d)</td>' %(rat,ac_num,submit_num)) ret.append('</tr>\n') return '\n'.join(ret) #SUBMIT_STATUS. status_desc = ["ACCEPT","COMPLIER ERROR","RUNTIME ERROR","TIME OUT","WRONG ANSWER","INNER ERROR","WAIT FOR JUDGE"] def submit_to_tr(rec): '''Convert an submit record to a tr ''' # @param rec submit record # @return a string contains an <tr> with the infomation of the record # ret = ["<tr>"] ret.append("<td>%d</td>" % rec.__id__) ret.append("<td><a href='member?%s'>%s</a></td>" % (rec.user_id,rec.user_id)) ret.append("<td><a href='browse?pid=%d'>%d</a></td>" % (rec.problem_id,rec.problem_id)) if rec.status == 1: ret.append("<td><a href='more?sid=%d' target='_blank'>%s</a></td>" % (rec.__id__,status_desc[rec.status])) else: ret.append("<td>%s</td>" % status_desc[rec.status]) ret.append("<td>%s</td>" % rec.lang) ret.append("<td>%dB</td>" % len(rec.code)) #or rec.codelen #ret.append("<td>%s</td>" % rec.time) #ret.append("<td>%s</td>" % rec.memory) ret.append("<td>%s</td>" % str(rec.stime)) ret.append("</tr>") return "\n".join(ret) def thread_to_tr(rec): '''Convert the information about an thread into a tr''' ret = ["<tr>"] ret.append("<td><a href='discuss?tid=%d'>%s</a></td>" % (rec.thread_id,rec.title.encode('utf-8'))) ret.append("<td>%s</td>" % rec.user_id) ret.append("<td>%d</td>" % rec.reply) ret.append("<td>%s</td>" % str(rec.last_reply)) ret.append("</tr>") return "\n".join(ret) def article_to_div(rec): '''Convert the information about an thread into a tr''' if rec.reply < 0: atype = "reply" else: atype = "topic" ret = ["<div class='%s'>" %atype] ret.append("<div class='title'>%s</div>" % rec.title.encode('utf-8')) ret.append("<span class='authortime'><a href='member?%s'>%s</a>&nbsp;&nbsp;%s</span><br/>" % (rec.user_id,rec.user_id,str(rec.ptime))) ret.append("<pre>%s</pre><br/>" % rec.content.encode('utf-8')) ret.append("</div>") return "\n".join(ret) def article_to_textarea(rec): '''Convert the information about an thread into a tr''' if rec.reply < 0: atype = "reply" else: atype = "topic" ret = ["<div class='%s'>" %atype] ret.append("<div class='title'>%s</div>" % rec.title.encode('utf-8')) ret.append("%s&nbsp;&nbsp;" % rec.user_id) ret.append("%s<br/>" % str(rec.ptime)) ret.append("<textarea readonly wrap=off rows='20' cols='100'>%s</textarea><br/>" % rec.content.encode('utf-8')) ret.append("</div>") return "\n".join(ret) def user_to_html(user,option = {}): '''Convert an user record to an form (for update info) or an table (for view info)''' # @param user an record of user # @param option an dictionary with possible key-value ['update':true/false,'showemail':true/false] if not option.has_key('update'): option['update'] = False if not option.has_key('showemail'): option['showemail'] = False from Cheetah.Template import Template as ctTpl if option['update']: ret = '''<form> </form> ''' page = open("template/index.html","r").read() txp = ctTpl(page, searchList=[vPool]) contest_status = ["Running","Scheduled","Ended"] def contest_to_tr(rec): ret = ["<tr>"] ret.append("<td><a href='contest?cid=%d'>%s</td>" %(rec.__id__,rec.name.encode('utf-8'))) ret.append("<td>%s</td>" %rec.start) ret.append("<td>%s</td>" %rec.end) ret.append("<td>%s</td>" %contest_status[rec.status]) ret.append("</tr>") return "\n".join(ret) def contest_detail_to_div(rec): curr = datetime(1,1,1).now() if curr > rec.end: status = contest_status[2] elif curr <rec.start: status = contest_status[1] else: status = contest_status[0] ret = ["<div class='contest'>"] ret.append("<h2 class='name'>%s</h2>" %rec.name.encode('utf-8')) ret.append("<div class='time'>Start:%s &nbsp; End:%s</div>" %(rec.start,rec.end)) ret.append("<div class='status'>Current:%s &nbsp; Status:%s</div> " %(datetime(1,1,1).now(),status)) ret.append("<div class='problems'>") ret.append("<ol>") relation = Base('database/relation').open() problems = [item.problem for item in relation if item.contest.__id__ == rec.__id__] for problem in problems: ret.append("<li><a href='browse?pid=%s'>%s</a></li>" %(problem.problem_id,problem.title.encode('utf-8'))) ret.append("</ol>") ret.append("</div>") ret.append("</div>") return '\n'.join(ret) def add_problems_contest(): problems = Base('database/problem').open() relation = Base('database/relation').open() cont= Base('database/contest').open()[0] #relation.insert(problem=problems[0],contest=cont) relation.insert(problem=problems[1],contest=cont) relation.insert(problem=problems[2],contest=cont) relation.insert(problem=problems[3],contest=cont) relation.insert(problem=problems[4],contest=cont) relation.insert(problem=problems[5],contest=cont) def add_problems(): problem = Base('database/problem').open() problem.insert(problem_id = "1002",title=unicode("Dividing","utf-8"),time_limit=1000,memory_limit=10000) problem.insert(problem_id = "1003",title=unicode("Simple Addition","utf-8"),time_limit=1000,memory_limit=10000) problem.insert(problem_id = "1004",title=unicode("Is There Any Prefix ?","utf-8"),time_limit=1000,memory_limit=10000) problem.insert(problem_id = "1005",title=unicode("Smith Number","utf-8"),time_limit=1000,memory_limit=10000) problem.insert(problem_id = "1006",title=unicode("洗牌","utf-8"),time_limit=1000,memory_limit=10000) # contest = Base('database/contest').open() # current = datetime(1,1,1).now() # end_time = datetime(current.year,current.month,current.day,current.hour+2,current.minute) # contest.insert(name=unicode("My First Contest",'utf-8'),start=current,end = end_time,status=0) if __name__ == "__main__": build_submit() build_user() build_article() build_contest() build_problem() build_relation() problem = Base('database/problem').open() if len(problem)<=0: print "add some problems" add_problems()
Python
import string import random lletras = [c for c in string.printable if c in string.letters] random.shuffle(lletras) letras = ''.join(lletras) lnumeros = [d for d in string.digits] random.shuffle(lnumeros) numeros = ''.join(lnumeros) random.shuffle(lletras) random.shuffle(lnumeros) letrasnumeros = (''.join(lletras) + ''.join(lnumeros)) * 2 comandos = [ [ # Defino el usuario y grupo inicial ['DU', 'usuario1'], ['CG', 'grupo1'], # Creo algunos directorios en el raiz ['MD', 'dir_1'], ['MD', 'dir_2'], ['MD', 'dir_3'], # Creo algunos directorios dentro de dir_1 ['CD', 'dir_1'], ['MD', 'dir_1_1'], ['MD', 'dir_1_2'], # Creo algunos directorios dentro de dir_2 ['CD', '/dir_2'], ['MD', 'dir_2_1'], ['MD', 'dir_2_2'], # Creo algunos directorios dentro de dir_3 ['CD', '..'], ['CD', 'dir_3'], ['MD', 'dir_3_1'], # Creo algunos archivos ['CD', '/dir_1/dir_1_2'], ['CF', 'arch1.txt'], ['CD', '/dir_2/dir_2_1'], ['CF', 'arch2.txt'], ['CD', '/dir_3'], ['CF', 'arch3.txt'], # Guardo contenido en los archivos ['WF', '/dir_1/dir_1_2/arch1.txt', letras], ['CD', '/dir_2/dir_2_1'], ['WF', 'arch2.txt', numeros], ['WF', '/dir_3/arch3.txt', letrasnumeros], ], [ # Defino el usuario y grupo inicial ['DU', 'usuario2'], ['CG', 'grupo2'], # Creo algunos directorios en el raiz ['MD', 'dir_1'], ['MD', 'dir_2'], ['MD', 'dir_3'], # Creo algunos directorios dentro de dir_1 ['CD', 'dir_1'], ['MD', 'dir_1_1'], # Creo algunos directorios dentro de dir_2 ['CD', '/dir_2'], ['MD', 'dir_2_1'], ['MD', 'dir_2_2'], ['MD', 'dir_2_3'], # Defino el usuario y grupo ['DU', 'usuario1'], ['CG', 'grupo1'], # Creo algunos directorios dentro de dir_3 ['CD', '..'], ['CD', 'dir_3'], ['MD', 'dir_3_1'], ['CD', 'dir_3_1'], ['MD', 'dir_3_1_1'], # Creo algunos archivos ['CD', '/dir_1'], ['CF', 'arch1.txt'], ['CD', '/dir_2/dir_2_3'], ['CF', 'arch2.txt'], ['DU', 'usuario2'], ['CG', 'grupo2'], ['CD', '/dir_3/dir_3_1/dir_3_1_1'], ['CF', 'arch3.txt'], # Guardo contenido en los archivos ['WF', '/dir_1/arch1.txt', numeros], ['CD', '/dir_2/dir_2_3'], ['DU', 'usuario1'], ['CG', 'grupo1'], ['WF', 'arch2.txt', letrasnumeros], ['WF', '/dir_3/dir_3_1/dir_3_1_1/arch3.txt', letras], ] ] for i in range(len(comandos)): f = open('datos_tp3_%s.txt' % (i + 1), 'w') f.write("\n".join(["|".join(cmd) for cmd in comandos[i]])) f.close()
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # # estructuras.py # TODO # # Ver que si se está en la raíz, el directorio de trabajo se toma como "None" o "/" # from datetime import datetime class Error(Exception): """Clase base para excepciones""" pass class SistemaArchivosError(Error): """Clase base para errores del Sistema de Archivos""" pass class DirError(SistemaArchivosError): """Erorres derivados del manejo de directorios""" def __init__(self, accion, mensaje): self.accion = accion # Accion respectiva a directorios en la que ocurre el error self.mensaje = mensaje # Mensaje descriptivo class SistemaArchivos: """Control del sistema de archivos""" #============= # "Globales" #============= MAX_APUNTADORES_DIRECTOS = 10 MAX_LONGITUD_DATOS = None #Longitud de los datos que puede guardar un nodo NodoDatos #PERMISOS_POR_DEFECTO = '' #Corresponden a los NodosI usuario = None grupo = None directorioDeTrabajo = None #============= # Composición... (Bueno, casi) #============= listaInicialDeNodosI = [] #En realidad, guardamos los números enteros correspondientes al id() de cada nodo listaRestoDeNodosI = [] #============= # Acciones externas #============= def LeerArchivo(self): raise NotImplementedError def ObtenerInfo(self): raise NotImplementedError #============= # Operaciones #============= def MD(self, nombreDirectorio): """Crea un directorio""" #Si el directorio actual de trabajo es None, se crea en la lista de los principales... #Esto es para evitar confusiones con nombres de archivo / directorio, e IDs. #~ if nombreDirectorio is None: #~ raise DirError('MD', 'No se ha especificado un nombre de directorio.') nuevoNodo = NodoI(nombreDirectorio, self.usuario, self.grupo, True) if self.directorioDeTrabajo is None: #El nuevo nodo va en la lista de los principales self.listaInicialDeNodosI.append(nuevoNodo) else: # Si el directorio de trabajo es otro, asignarlo a la lista del montón, y referenciarlo en el directorio de trabajo raise NotImplementedError def RD(self): """Elimina directorio""" raise NotImplementedError def CD(self, nombreDirectorio): """Cambia Directorio de trabajo""" if nombreDirectorio == '/': #Si se quiere cambiar a la raíz, tomamos el directorio de trabajo como None self.directorioDeTrabajo = None raise NotImplementedError def CF(self): """Crea archivo""" raise NotImplementedError def DF(self): """Elimina archivo""" raise NotImplementedError def WF(self): """Escribe archivo""" raise NotImplementedError def DU(self): """Definir usuario""" raise NotImplementedError def CG(self): """Crear / Definir grupo""" raise NotImplementedError def AG(self): """Asignar grupo a un archivo / directorio""" raise NotImplementedError class NodoApuntador: apuntadoresDirectos = [] class NodoDatos: datos = None #USAR... id(objeto) -> Int class NodoI: """Estructura usada como cabecera de directorios / archivos """ PERMISOS_POR_DEFECTO = '111101101' # drwxrwxrwx mtime = None atime = None L1 = None L2 = None L3 = None def __init__(self, nombre, usuario, grupo, esDirectorio): self.name = nombre self.size = 0 #Esto debe ser dinámicamente actualizado, pero para datos, no directorios self.user = usuario #Si es None, cualquiera tiene control total self.group = grupo #Si es None, cualquiera tiene control total self.mode = "1" + self.PERMISOS_POR_DEFECTO if esDirectorio else "0" + self.PERMISOS_POR_DEFECTO #Determina si es directorio self.ctime = datetime.today() #mtime #atime self.apuntadoresDirectos = [] #No puede tener más de 10 elementos #L1 #L2 #L3 def __repr__(self): return "<Nombre: %s>" % self.name if __name__ == '__main__': #Sólo pruebas provisorias NodoPrueba = NodoI('', 'Gabriel', 'SO', True) print NodoPrueba.ctime #NodoPrueba.atime = print NodoPrueba print NodoPrueba.atime print NodoPrueba.mode asd = SistemaArchivos() asd.CD()
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # # estructuras.py # TODO # # Ver que si se está en la raíz, el directorio de trabajo se toma como "None" o "/" # from datetime import datetime class Error(Exception): """Clase base para excepciones""" pass class SistemaArchivosError(Error): """Clase base para errores del Sistema de Archivos""" pass class DirError(SistemaArchivosError): """Erorres derivados del manejo de directorios""" def __init__(self, accion, mensaje): self.accion = accion # Accion respectiva a directorios en la que ocurre el error self.mensaje = mensaje # Mensaje descriptivo class SistemaArchivos: """Control del sistema de archivos""" #============= # "Globales" #============= MAX_APUNTADORES_DIRECTOS = 10 MAX_LONGITUD_DATOS = None #Longitud de los datos que puede guardar un nodo NodoDatos #PERMISOS_POR_DEFECTO = '' #Corresponden a los NodosI usuario = None grupo = None directorioDeTrabajo = None #============= # Composición... (Bueno, casi) #============= listaInicialDeNodosI = [] #En realidad, guardamos los números enteros correspondientes al id() de cada nodo listaRestoDeNodosI = [] #============= # Acciones externas #============= def LeerArchivo(self): raise NotImplementedError def ObtenerInfo(self): raise NotImplementedError #============= # Operaciones #============= def MD(self, nombreDirectorio): """Crea un directorio""" #Si el directorio actual de trabajo es None, se crea en la lista de los principales... #Esto es para evitar confusiones con nombres de archivo / directorio, e IDs. #~ if nombreDirectorio is None: #~ raise DirError('MD', 'No se ha especificado un nombre de directorio.') nuevoNodo = NodoI(nombreDirectorio, self.usuario, self.grupo, True) if self.directorioDeTrabajo is None: #El nuevo nodo va en la lista de los principales self.listaInicialDeNodosI.append(nuevoNodo) else: # Si el directorio de trabajo es otro, asignarlo a la lista del montón, y referenciarlo en el directorio de trabajo raise NotImplementedError def RD(self): """Elimina directorio""" raise NotImplementedError def CD(self, nombreDirectorio): """Cambia Directorio de trabajo""" if nombreDirectorio == '/': #Si se quiere cambiar a la raíz, tomamos el directorio de trabajo como None self.directorioDeTrabajo = None raise NotImplementedError def CF(self): """Crea archivo""" raise NotImplementedError def DF(self): """Elimina archivo""" raise NotImplementedError def WF(self): """Escribe archivo""" raise NotImplementedError def DU(self): """Definir usuario""" raise NotImplementedError def CG(self): """Crear / Definir grupo""" raise NotImplementedError def AG(self): """Asignar grupo a un archivo / directorio""" raise NotImplementedError class NodoApuntador: apuntadoresDirectos = [] class NodoDatos: datos = None #USAR... id(objeto) -> Int class NodoI: """Estructura usada como cabecera de directorios / archivos """ PERMISOS_POR_DEFECTO = '111101101' # drwxrwxrwx mtime = None atime = None L1 = None L2 = None L3 = None def __init__(self, nombre, usuario, grupo, esDirectorio): self.name = nombre self.size = 0 #Esto debe ser dinámicamente actualizado, pero para datos, no directorios self.user = usuario #Si es None, cualquiera tiene control total self.group = grupo #Si es None, cualquiera tiene control total self.mode = "1" + self.PERMISOS_POR_DEFECTO if esDirectorio else "0" + self.PERMISOS_POR_DEFECTO #Determina si es directorio self.ctime = datetime.today() #mtime #atime self.apuntadoresDirectos = [] #No puede tener más de 10 elementos #L1 #L2 #L3 def __repr__(self): return "<Nombre: %s>" % self.name if __name__ == '__main__': #Sólo pruebas provisorias NodoPrueba = NodoI('', 'Gabriel', 'SO', True) print NodoPrueba.ctime #NodoPrueba.atime = print NodoPrueba print NodoPrueba.atime print NodoPrueba.mode asd = SistemaArchivos() asd.CD()
Python
import wsgiref.handlers from google.appengine.ext import webapp import unittest from datetime import datetime import frontpage import gallery from pixeltoy import model from pixeltoy import colorlib from pixeltoy import datelib class PixelToyTest(unittest.TestCase): def testMakeMainPageOnLocalhost(self): handler = frontpage.MainPage() page = handler.make_page(host='localhost') self.failIf('google-analytics' in page) def testMakeMainPageInProduction(self): handler = frontpage.MainPage() page = handler.make_page(host='pixeltoypixeltoy.appspot.com') self.failUnless('google-analytics' in page) def testMakeSpectrum(self): colors = colorlib._make_spectrum_rgb() self.assertEquals(17, len(colors)) self.assertEquals((255,0,0), colors[0]) def testPaletteSize(self): (w,h) = colorlib.palette_size self.assertEquals(w * h, len(colorlib.color_names)) def noDuplicateColors(self): self.assertEquals(len(set(colorlib.color_names)), len(colorlib.color_names)) def testStartingColor(self): self.assertEquals('000000', colorlib.color_names[0]) self.failIf(colorlib.starting_color == None) self.assertEquals('0000ff', colorlib.color_names[colorlib.starting_color]) def testApplyStroke(self): pixels = model.make_empty_pixels() self.assertEquals(0, ord(pixels.pixels[0])) pixels.apply_stroke("c1_0.0_2.0_0.1") self.assertEquals(1, ord(pixels.pixels[0])) self.assertEquals(0, ord(pixels.pixels[1])) self.assertEquals(1, ord(pixels.pixels[2])) self.assertEquals(1, ord(pixels.pixels[model.grid_size.width])) def testToSnapshot(self): pixels = model.make_empty_pixels() pixels.to_snapshot() def testParseIsodate(self): date = datelib.from_isodate("2001-02-03T04:05:06.000007Z") self.assertEquals(2001, date.year) self.assertEquals(2, date.month) self.assertEquals(3, date.day) self.assertEquals(4, date.hour) self.assertEquals(5, date.minute) self.assertEquals(6, date.second) self.assertEquals(7, date.microsecond) self.assertEquals(None, date.tzinfo) date_string = datelib.to_isodate(date) self.assertEquals("2001-02-03T04:05:06.000007Z", date_string) def testRoundtripFromCurrentTimeToIsodate(self): now = datetime.utcnow() now_string = datelib.to_isodate(now) after = datelib.from_isodate(now_string) self.assertEquals(now, after) after_string = datelib.to_isodate(after) self.assertEquals(now_string, after_string) class SelfTestPage(webapp.RequestHandler): def get(self): self.response.headers['Content-Type'] = 'text/plain' runner = unittest.TextTestRunner(stream=self.response.out) module = __import__(__name__) tests = unittest.defaultTestLoader.loadTestsFromModule(module) runner.run(tests) def main(): application = webapp.WSGIApplication([('/selftest', SelfTestPage)], debug=True) wsgiref.handlers.CGIHandler().run(application) if __name__ == "__main__": main()
Python
#!/usr/bin/env python # png.py - PNG encoder in pure Python # Copyright (C) 2006 Johann C. Rocholl <johann@browsershots.org> # # Permission is hereby granted, free of charge, to any person # obtaining a copy of this software and associated documentation files # (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Software, # and to permit persons to whom the Software is furnished to do so, # subject to the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # Contributors (alphabetical): # Nicko van Someren <nicko@nicko.org> # # Changelog (recent first): # 2006-06-17 Nicko: Reworked into a class, faster interlacing. # 2006-06-17 Johann: Very simple prototype PNG decoder. # 2006-06-17 Nicko: Test suite with various image generators. # 2006-06-17 Nicko: Alpha-channel, grey-scale, 16-bit/plane support. # 2006-06-15 Johann: Scanline iterator interface for large input files. # 2006-06-09 Johann: Very simple prototype PNG encoder. """ Pure Python PNG Reader/Writer This is an implementation of a subset of the PNG specification at http://www.w3.org/TR/2003/REC-PNG-20031110 in pure Python. It reads and writes PNG files with 8/16/24/32/48/64 bits per pixel (greyscale, RGB, RGBA, with 8 or 16 bits per layer), with a number of options. For help, type "import png; help(png)" in your python interpreter. This file can also be used as a command-line utility to convert PNM files to PNG. The interface is similar to that of the pnmtopng program from the netpbm package. Type "python png.py --help" at the shell prompt for usage and a list of options. """ __revision__ = '$Rev$' __date__ = '$Date$' __author__ = '$Author$' import sys import zlib import struct import math from array import array _adam7 = ((0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2)) def interleave_planes(ipixels, apixels, ipsize, apsize): """ Interleave color planes, e.g. RGB + A = RGBA. Return an array of pixels consisting of the ipsize bytes of data from each pixel in ipixels followed by the apsize bytes of data from each pixel in apixels, for an image of size width x height. """ itotal = len(ipixels) atotal = len(apixels) newtotal = itotal + atotal newpsize = ipsize + apsize # Set up the output buffer out = array('B') # It's annoying that there is no cheap way to set the array size :-( out.extend(ipixels) out.extend(apixels) # Interleave in the pixel data for i in range(ipsize): out[i:newtotal:newpsize] = ipixels[i:itotal:ipsize] for i in range(apsize): out[i+ipsize:newtotal:newpsize] = apixels[i:atotal:apsize] return out class Error(Exception): pass class Writer: """ PNG encoder in pure Python. """ def __init__(self, width, height, transparent=None, background=None, gamma=None, greyscale=False, has_alpha=False, bytes_per_sample=1, compression=None, interlaced=False, chunk_limit=2**20): """ Create a PNG encoder object. Arguments: width, height - size of the image in pixels transparent - create a tRNS chunk background - create a bKGD chunk gamma - create a gAMA chunk greyscale - input data is greyscale, not RGB has_alpha - input data has alpha channel (RGBA) bytes_per_sample - 8-bit or 16-bit input data compression - zlib compression level (1-9) chunk_limit - write multiple IDAT chunks to save memory If specified, the transparent and background parameters must be a tuple with three integer values for red, green, blue, or a simple integer (or singleton tuple) for a greyscale image. If specified, the gamma parameter must be a float value. """ if width <= 0 or height <= 0: raise ValueError("width and height must be greater than zero") if has_alpha and transparent is not None: raise ValueError( "transparent color not allowed with alpha channel") if bytes_per_sample < 1 or bytes_per_sample > 2: raise ValueError("bytes per sample must be 1 or 2") if transparent is not None: if greyscale: if type(transparent) is not int: raise ValueError( "transparent color for greyscale must be integer") else: if not (len(transparent) == 3 and type(transparent[0]) is int and type(transparent[1]) is int and type(transparent[2]) is int): raise ValueError( "transparent color must be a triple of integers") if background is not None: if greyscale: if type(background) is not int: raise ValueError( "background color for greyscale must be integer") else: if not (len(background) == 3 and type(background[0]) is int and type(background[1]) is int and type(background[2]) is int): raise ValueError( "background color must be a triple of integers") self.width = width self.height = height self.transparent = transparent self.background = background self.gamma = gamma self.greyscale = greyscale self.has_alpha = has_alpha self.bytes_per_sample = bytes_per_sample self.compression = compression self.chunk_limit = chunk_limit self.interlaced = interlaced if self.greyscale: self.color_depth = 1 if self.has_alpha: self.color_type = 4 self.psize = self.bytes_per_sample * 2 else: self.color_type = 0 self.psize = self.bytes_per_sample else: self.color_depth = 3 if self.has_alpha: self.color_type = 6 self.psize = self.bytes_per_sample * 4 else: self.color_type = 2 self.psize = self.bytes_per_sample * 3 def write_chunk(self, outfile, tag, data): """ Write a PNG chunk to the output file, including length and checksum. """ # http://www.w3.org/TR/PNG/#5Chunk-layout outfile.write(struct.pack("!I", len(data))) outfile.write(tag) outfile.write(data) checksum = zlib.crc32(tag) checksum = zlib.crc32(data, checksum) outfile.write(struct.pack("!I", checksum)) def write(self, outfile, scanlines): """ Write a PNG image to the output file. """ # http://www.w3.org/TR/PNG/#5PNG-file-signature outfile.write(struct.pack("8B", 137, 80, 78, 71, 13, 10, 26, 10)) # http://www.w3.org/TR/PNG/#11IHDR if self.interlaced: interlaced = 1 else: interlaced = 0 self.write_chunk(outfile, 'IHDR', struct.pack("!2I5B", self.width, self.height, self.bytes_per_sample * 8, self.color_type, 0, 0, interlaced)) # http://www.w3.org/TR/PNG/#11tRNS if self.transparent is not None: if self.greyscale: self.write_chunk(outfile, 'tRNS', struct.pack("!1H", *self.transparent)) else: self.write_chunk(outfile, 'tRNS', struct.pack("!3H", *self.transparent)) # http://www.w3.org/TR/PNG/#11bKGD if self.background is not None: if self.greyscale: self.write_chunk(outfile, 'bKGD', struct.pack("!1H", *self.background)) else: self.write_chunk(outfile, 'bKGD', struct.pack("!3H", *self.background)) # http://www.w3.org/TR/PNG/#11gAMA if self.gamma is not None: self.write_chunk(outfile, 'gAMA', struct.pack("!L", int(self.gamma * 100000))) # http://www.w3.org/TR/PNG/#11IDAT if self.compression is not None: compressor = zlib.compressobj(self.compression) else: compressor = zlib.compressobj() data = array('B') for scanline in scanlines: data.append(0) data.extend(scanline) if len(data) > self.chunk_limit: compressed = compressor.compress(data.tostring()) if len(compressed): # print >> sys.stderr, len(data), len(compressed) self.write_chunk(outfile, 'IDAT', compressed) data = array('B') if len(data): compressed = compressor.compress(data.tostring()) else: compressed = '' flushed = compressor.flush() if len(compressed) or len(flushed): # print >> sys.stderr, len(data), len(compressed), len(flushed) self.write_chunk(outfile, 'IDAT', compressed + flushed) # http://www.w3.org/TR/PNG/#11IEND self.write_chunk(outfile, 'IEND', '') def write_array(self, outfile, pixels): """ Encode a pixel array to PNG and write output file. """ if self.interlaced: self.write(outfile, self.array_scanlines_interlace(pixels)) else: self.write(outfile, self.array_scanlines(pixels)) def convert_ppm(self, ppmfile, outfile): """ Convert a PPM file containing raw pixel data into a PNG file with the parameters set in the writer object. """ if self.interlaced: pixels = array('B') pixels.fromfile(ppmfile, self.bytes_per_sample * self.color_depth * self.width * self.height) self.write(outfile, self.array_scanlines_interlace(pixels)) else: self.write(outfile, self.file_scanlines(ppmfile)) def convert_ppm_and_pgm(self, ppmfile, pgmfile, outfile): """ Convert a PPM and PGM file containing raw pixel data into a PNG outfile with the parameters set in the writer object. """ pixels = array('B') pixels.fromfile(ppmfile, self.bytes_per_sample * self.color_depth * self.width * self.height) apixels = array('B') apixels.fromfile(pgmfile, self.bytes_per_sample * self.width * self.height) pixels = interleave_planes(pixels, apixels, self.bytes_per_sample * self.color_depth, self.bytes_per_sample) if self.interlaced: self.write(outfile, self.array_scanlines_interlace(pixels)) else: self.write(outfile, self.array_scanlines(pixels)) def file_scanlines(self, infile): """ Generator for scanlines from an input file. """ row_bytes = self.psize * self.width for y in range(self.height): scanline = array('B') scanline.fromfile(infile, row_bytes) yield scanline def array_scanlines(self, pixels): """ Generator for scanlines from an array. """ row_bytes = self.width * self.psize stop = 0 for y in range(self.height): start = stop stop = start + row_bytes yield pixels[start:stop] def old_array_scanlines_interlace(self, pixels): """ Generator for interlaced scanlines from an array. http://www.w3.org/TR/PNG/#8InterlaceMethods """ row_bytes = self.psize * self.width for xstart, ystart, xstep, ystep in _adam7: for y in range(ystart, self.height, ystep): if xstart < self.width: if xstep == 1: offset = y*row_bytes yield pixels[offset:offset+row_bytes] else: row = array('B') offset = y*row_bytes + xstart* self.psize skip = self.psize * xstep for x in range(xstart, self.width, xstep): row.extend(pixels[offset:offset + self.psize]) offset += skip yield row def array_scanlines_interlace(self, pixels): """ Generator for interlaced scanlines from an array. http://www.w3.org/TR/PNG/#8InterlaceMethods """ row_bytes = self.psize * self.width for xstart, ystart, xstep, ystep in _adam7: for y in range(ystart, self.height, ystep): if xstart >= self.width: continue if xstep == 1: offset = y * row_bytes yield pixels[offset:offset+row_bytes] else: row = array('B') # Note we want the ceiling of (self.width - xstart) / xtep row_len = self.psize * ( (self.width - xstart + xstep - 1) / xstep) # There's no easier way to set the length of an array row.extend(pixels[0:row_len]) offset = y * row_bytes + xstart * self.psize end_offset = (y+1) * row_bytes skip = self.psize * xstep for i in range(self.psize): row[i:row_len:self.psize] = \ pixels[offset+i:end_offset:skip] yield row class _readable: """ A simple file-like interface for strings and arrays. """ def __init__(self, buf): self.buf = buf self.offset = 0 def read(self, n): r = buf[offset:offset+n] if isinstance(r, array): r = r.tostring() offset += n return r class Reader: """ PNG decoder in pure Python. """ def __init__(self, _guess=None, **kw): """ Create a PNG decoder object. The constructor expects exactly one keyword argument. If you supply a positional argument instead, it will guess the input type. You can choose among the following arguments: filename - name of PNG input file file - object with a read() method pixels - array or string with PNG data """ if ((_guess is not None and len(kw) != 0) or (_guess is None and len(kw) != 1)): raise TypeError("Reader() takes exactly 1 argument") if _guess is not None: if isinstance(_guess, array): kw["pixels"] = _guess elif isinstance(_guess, str): kw["filename"] = _guess elif isinstance(_guess, file): kw["file"] = _guess if "filename" in kw: self.file = file(kw["filename"]) elif "file" in kw: self.file = kw["file"] elif "pixels" in kw: self.file = _readable(kw["pixels"]) else: raise TypeError("expecting filename, file or pixels array") def read_chunk(self): """ Read a PNG chunk from the input file, return tag name and data. """ # http://www.w3.org/TR/PNG/#5Chunk-layout try: data_bytes, tag = struct.unpack('!I4s', self.file.read(8)) except struct.error: raise ValueError('Chunk too short for header') data = self.file.read(data_bytes) if len(data) != data_bytes: raise ValueError('Chunk %s too short for required %i data octets' % (tag, data_bytes)) checksum = self.file.read(4) if len(checksum) != 4: raise ValueError('Chunk %s too short for checksum', tag) verify = zlib.crc32(tag) verify = zlib.crc32(data, verify) verify = struct.pack('!i', verify) if checksum != verify: # print repr(checksum) (a,) = struct.unpack('!I', checksum) (b,) = struct.unpack('!I', verify) raise ValueError("Checksum error in %s chunk: 0x%X != 0x%X" % (tag, a, b)) return tag, data def _reconstruct_sub(self, offset, xstep, ystep): """ Reverse sub filter. """ pixels = self.pixels a_offset = offset offset += self.psize * xstep if xstep == 1: for index in range(self.psize, self.row_bytes): x = pixels[offset] a = pixels[a_offset] pixels[offset] = (x + a) & 0xff offset += 1 a_offset += 1 else: byte_step = self.psize * xstep for index in range(byte_step, self.row_bytes, byte_step): for i in range(self.psize): x = pixels[offset + i] a = pixels[a_offset + i] pixels[offset + i] = (x + a) & 0xff offset += self.psize * xstep a_offset += self.psize * xstep def _reconstruct_up(self, offset, xstep, ystep): """ Reverse up filter. """ pixels = self.pixels b_offset = offset - (self.row_bytes * ystep) if xstep == 1: for index in range(self.row_bytes): x = pixels[offset] b = pixels[b_offset] pixels[offset] = (x + b) & 0xff offset += 1 b_offset += 1 else: for index in range(0, self.row_bytes, xstep * self.psize): for i in range(self.psize): x = pixels[offset + i] b = pixels[b_offset + i] pixels[offset + i] = (x + b) & 0xff offset += self.psize * xstep b_offset += self.psize * xstep def _reconstruct_average(self, offset, xstep, ystep): """ Reverse average filter. """ pixels = self.pixels a_offset = offset - (self.psize * xstep) b_offset = offset - (self.row_bytes * ystep) if xstep == 1: for index in range(self.row_bytes): x = pixels[offset] if index < self.psize: a = 0 else: a = pixels[a_offset] if b_offset < 0: b = 0 else: b = pixels[b_offset] pixels[offset] = (x + ((a + b) >> 1)) & 0xff offset += 1 a_offset += 1 b_offset += 1 else: for index in range(0, self.row_bytes, self.psize * xstep): for i in range(self.psize): x = pixels[offset+i] if index < self.psize: a = 0 else: a = pixels[a_offset + i] if b_offset < 0: b = 0 else: b = pixels[b_offset + i] pixels[offset + i] = (x + ((a + b) >> 1)) & 0xff offset += self.psize * xstep a_offset += self.psize * xstep b_offset += self.psize * xstep def _reconstruct_paeth(self, offset, xstep, ystep): """ Reverse Paeth filter. """ pixels = self.pixels a_offset = offset - (self.psize * xstep) b_offset = offset - (self.row_bytes * ystep) c_offset = b_offset - (self.psize * xstep) # There's enough inside this loop that it's probably not worth # optimising for xstep == 1 for index in range(0, self.row_bytes, self.psize * xstep): for i in range(self.psize): x = pixels[offset+i] if index < self.psize: a = c = 0 b = pixels[b_offset+i] else: a = pixels[a_offset+i] b = pixels[b_offset+i] c = pixels[c_offset+i] p = a + b - c pa = abs(p - a) pb = abs(p - b) pc = abs(p - c) if pa <= pb and pa <= pc: pr = a elif pb <= pc: pr = b else: pr = c pixels[offset+i] = (x + pr) & 0xff offset += self.psize * xstep a_offset += self.psize * xstep b_offset += self.psize * xstep c_offset += self.psize * xstep # N.B. PNG files with 'up', 'average' or 'paeth' filters on the # first line of a pass are legal. The code above for 'average' # deals with this case explicitly. For up we map to the null # filter and for paeth we map to the sub filter. def reconstruct_line(self, filter_type, first_line, offset, xstep, ystep): """ Reverse the filtering for a scanline. """ # print >> sys.stderr, "Filter type %s, first_line=%s" % ( # filter_type, first_line) filter_type += (first_line << 8) if filter_type == 1 or filter_type == 0x101 or filter_type == 0x104: self._reconstruct_sub(offset, xstep, ystep) elif filter_type == 2: self._reconstruct_up(offset, xstep, ystep) elif filter_type == 3 or filter_type == 0x103: self._reconstruct_average(offset, xstep, ystep) elif filter_type == 4: self._reconstruct_paeth(offset, xstep, ystep) return def deinterlace(self, scanlines): """ Read pixel data and remove interlacing. """ # print >> sys.stderr, ("Reading interlaced, w=%s, r=%s, planes=%s," + # " bpp=%s") % (self.width, self.height, self.planes, self.bps) a = array('B') self.pixels = a # Make the array big enough temp = scanlines[0:self.width*self.height*self.psize] a.extend(temp) source_offset = 0 for xstart, ystart, xstep, ystep in _adam7: # print >> sys.stderr, "Adam7: start=%s,%s step=%s,%s" % ( # xstart, ystart, xstep, ystep) filter_first_line = 1 for y in range(ystart, self.height, ystep): if xstart >= self.width: continue filter_type = scanlines[source_offset] source_offset += 1 if xstep == 1: offset = y * self.row_bytes a[offset:offset+self.row_bytes] = \ scanlines[source_offset:source_offset + self.row_bytes] source_offset += self.row_bytes else: # Note we want the ceiling of (width - xstart) / xtep row_len = self.psize * ( (self.width - xstart + xstep - 1) / xstep) offset = y * self.row_bytes + xstart * self.psize end_offset = (y+1) * self.row_bytes skip = self.psize * xstep for i in range(self.psize): a[offset+i:end_offset:skip] = \ scanlines[source_offset + i: source_offset + row_len: self.psize] source_offset += row_len if filter_type: self.reconstruct_line(filter_type, filter_first_line, offset, xstep, ystep) filter_first_line = 0 return a def read_flat(self, scanlines): """ Read pixel data without de-interlacing. """ a = array('B') self.pixels = a offset = 0 source_offset = 0 filter_first_line = 1 for y in range(self.height): filter_type = scanlines[source_offset] source_offset += 1 a.extend(scanlines[source_offset: source_offset + self.row_bytes]) if filter_type: self.reconstruct_line(filter_type, filter_first_line, offset, 1, 1) filter_first_line = 0 offset += self.row_bytes source_offset += self.row_bytes return a def read(self): """ Read a simple PNG file, return width, height, pixels and image metadata This function is a very early prototype with limited flexibility and excessive use of memory. """ signature = self.file.read(8) if (signature != struct.pack("8B", 137, 80, 78, 71, 13, 10, 26, 10)): raise Error("PNG file has invalid header") compressed = [] image_metadata = {} while True: try: tag, data = self.read_chunk() except ValueError, e: raise Error('Chunk error: ' + e.args[0]) # print >> sys.stderr, tag, len(data) if tag == 'IHDR': # http://www.w3.org/TR/PNG/#11IHDR (width, height, bits_per_sample, color_type, compression_method, filter_method, interlaced) = struct.unpack("!2I5B", data) bps = bits_per_sample / 8 if bps == 0: raise Error("unsupported pixel depth") if bps > 2 or bits_per_sample != (bps * 8): raise Error("invalid pixel depth") if color_type == 0: greyscale = True has_alpha = False planes = 1 elif color_type == 2: greyscale = False has_alpha = False planes = 3 elif color_type == 4: greyscale = True has_alpha = True planes = 2 elif color_type == 6: greyscale = False has_alpha = True planes = 4 else: raise Error("unknown PNG colour type %s" % color_type) if compression_method != 0: raise Error("unknown compression method") if filter_method != 0: raise Error("unknown filter method") self.bps = bps self.planes = planes self.psize = bps * planes self.width = width self.height = height self.row_bytes = width * self.psize elif tag == 'IDAT': # http://www.w3.org/TR/PNG/#11IDAT compressed.append(data) elif tag == 'bKGD': if greyscale: image_metadata["background"] = struct.unpack("!1H", data) else: image_metadata["background"] = struct.unpack("!3H", data) elif tag == 'tRNS': if greyscale: image_metadata["transparent"] = struct.unpack("!1H", data) else: image_metadata["transparent"] = struct.unpack("!3H", data) elif tag == 'gAMA': image_metadata["gamma"] = ( struct.unpack("!L", data)[0]) / 100000.0 elif tag == 'IEND': # http://www.w3.org/TR/PNG/#11IEND break scanlines = array('B', zlib.decompress(''.join(compressed))) if interlaced: pixels = self.deinterlace(scanlines) else: pixels = self.read_flat(scanlines) image_metadata["greyscale"] = greyscale image_metadata["has_alpha"] = has_alpha image_metadata["bytes_per_sample"] = bps image_metadata["interlaced"] = interlaced return width, height, pixels, image_metadata def test_suite(options): """ Run regression test and write PNG file to stdout. """ # Below is a big stack of test image generators def test_gradient_horizontal_lr(x, y): return x def test_gradient_horizontal_rl(x, y): return 1-x def test_gradient_vertical_tb(x, y): return y def test_gradient_vertical_bt(x, y): return 1-y def test_radial_tl(x, y): return max(1-math.sqrt(x*x+y*y), 0.0) def test_radial_center(x, y): return test_radial_tl(x-0.5, y-0.5) def test_radial_tr(x, y): return test_radial_tl(1-x, y) def test_radial_bl(x, y): return test_radial_tl(x, 1-y) def test_radial_br(x, y): return test_radial_tl(1-x, 1-y) def test_stripe(x, n): return 1.0*(int(x*n) & 1) def test_stripe_h_2(x, y): return test_stripe(x, 2) def test_stripe_h_4(x, y): return test_stripe(x, 4) def test_stripe_h_10(x, y): return test_stripe(x, 10) def test_stripe_v_2(x, y): return test_stripe(y, 2) def test_stripe_v_4(x, y): return test_stripe(y, 4) def test_stripe_v_10(x, y): return test_stripe(y, 10) def test_stripe_lr_10(x, y): return test_stripe(x+y, 10) def test_stripe_rl_10(x, y): return test_stripe(x-y, 10) def test_checker(x, y, n): return 1.0*((int(x*n) & 1) ^ (int(y*n) & 1)) def test_checker_8(x, y): return test_checker(x, y, 8) def test_checker_15(x, y): return test_checker(x, y, 15) def test_zero(x, y): return 0 def test_one(x, y): return 1 test_patterns = { "GLR": test_gradient_horizontal_lr, "GRL": test_gradient_horizontal_rl, "GTB": test_gradient_vertical_tb, "GBT": test_gradient_vertical_bt, "RTL": test_radial_tl, "RTR": test_radial_tr, "RBL": test_radial_bl, "RBR": test_radial_br, "RCTR": test_radial_center, "HS2": test_stripe_h_2, "HS4": test_stripe_h_4, "HS10": test_stripe_h_10, "VS2": test_stripe_v_2, "VS4": test_stripe_v_4, "VS10": test_stripe_v_10, "LRS": test_stripe_lr_10, "RLS": test_stripe_rl_10, "CK8": test_checker_8, "CK15": test_checker_15, "ZERO": test_zero, "ONE": test_one, } def test_pattern(width, height, depth, pattern): """ Create a single plane (monochrome) test pattern. """ a = array('B') fw = float(width) fh = float(height) pfun = test_patterns[pattern] if depth == 1: for y in range(height): for x in range(width): a.append(int(pfun(float(x)/fw, float(y)/fh) * 255)) elif depth == 2: for y in range(height): for x in range(width): v = int(pfun(float(x)/fw, float(y)/fh) * 65535) a.append(v >> 8) a.append(v & 0xff) return a def test_rgba(size=256, depth=1, red="GTB", green="GLR", blue="RTL", alpha=None): """ Create a test image. """ r = test_pattern(size, size, depth, red) g = test_pattern(size, size, depth, green) b = test_pattern(size, size, depth, blue) if alpha: a = test_pattern(size, size, depth, alpha) i = interleave_planes(r, g, depth, depth) i = interleave_planes(i, b, 2 * depth, depth) if alpha: i = interleave_planes(i, a, 3 * depth, depth) return i # The body of test_suite() size = 256 if options.test_size: size = options.test_size depth = 1 if options.test_deep: depth = 2 kwargs = {} if options.test_red: kwargs["red"] = options.test_red if options.test_green: kwargs["green"] = options.test_green if options.test_blue: kwargs["blue"] = options.test_blue if options.test_alpha: kwargs["alpha"] = options.test_alpha pixels = test_rgba(size, depth, **kwargs) writer = Writer(size, size, bytes_per_sample=depth, transparent=options.transparent, background=options.background, gamma=options.gamma, has_alpha=options.test_alpha, compression=options.compression, interlaced=options.interlace) writer.write_array(sys.stdout, pixels) def read_pnm_header(infile, supported='P6'): """ Read a PNM header, return width and height of the image in pixels. """ header = [] while len(header) < 4: line = infile.readline() sharp = line.find('#') if sharp > -1: line = line[:sharp] header.extend(line.split()) if len(header) == 3 and header[0] == 'P4': break # PBM doesn't have maxval if header[0] not in supported: raise NotImplementedError('file format %s not supported' % header[0]) if header[0] != 'P4' and header[3] != '255': raise NotImplementedError('maxval %s not supported' % header[3]) return int(header[1]), int(header[2]) def color_triple(color): """ Convert a command line color value to a RGB triple of integers. FIXME: Somewhere we need support for greyscale backgrounds etc. """ if color.startswith('#') and len(color) == 4: return (int(color[1], 16), int(color[2], 16), int(color[3], 16)) if color.startswith('#') and len(color) == 7: return (int(color[1:3], 16), int(color[3:5], 16), int(color[5:7], 16)) elif color.startswith('#') and len(color) == 13: return (int(color[1:5], 16), int(color[5:9], 16), int(color[9:13], 16)) def _main(): """ Run the PNG encoder with options from the command line. """ # Parse command line arguments from optparse import OptionParser version = '%prog ' + __revision__.strip('$').replace('Rev: ', 'r') parser = OptionParser(version=version) parser.set_usage("%prog [options] [pnmfile]") parser.add_option("-i", "--interlace", default=False, action="store_true", help="create an interlaced PNG file (Adam7)") parser.add_option("-t", "--transparent", action="store", type="string", metavar="color", help="mark the specified color as transparent") parser.add_option("-b", "--background", action="store", type="string", metavar="color", help="save the specified background color") parser.add_option("-a", "--alpha", action="store", type="string", metavar="pgmfile", help="alpha channel transparency (RGBA)") parser.add_option("-g", "--gamma", action="store", type="float", metavar="value", help="save the specified gamma value") parser.add_option("-c", "--compression", action="store", type="int", metavar="level", help="zlib compression level (0-9)") parser.add_option("-T", "--test", default=False, action="store_true", help="create a test image") parser.add_option("-R", "--test-red", action="store", type="string", metavar="pattern", help="test pattern for the red image layer") parser.add_option("-G", "--test-green", action="store", type="string", metavar="pattern", help="test pattern for the green image layer") parser.add_option("-B", "--test-blue", action="store", type="string", metavar="pattern", help="test pattern for the blue image layer") parser.add_option("-A", "--test-alpha", action="store", type="string", metavar="pattern", help="test pattern for the alpha image layer") parser.add_option("-D", "--test-deep", default=False, action="store_true", help="use test patterns with 16 bits per layer") parser.add_option("-S", "--test-size", action="store", type="int", metavar="size", help="width and height of the test image") (options, args) = parser.parse_args() # Convert options if options.transparent is not None: options.transparent = color_triple(options.transparent) if options.background is not None: options.background = color_triple(options.background) # Run regression tests if options.test: return test_suite(options) # Prepare input and output files if len(args) == 0: ppmfilename = '-' ppmfile = sys.stdin elif len(args) == 1: ppmfilename = args[0] ppmfile = open(ppmfilename, 'rb') else: parser.error("more than one input file") outfile = sys.stdout # Encode PNM to PNG width, height = read_pnm_header(ppmfile) writer = Writer(width, height, interlaced=options.interlace, transparent=options.transparent, background=options.background, has_alpha=options.alpha is not None, gamma=options.gamma, compression=options.compression) if options.alpha is not None: pgmfile = open(options.alpha, 'rb') awidth, aheight = read_pnm_header(pgmfile, 'P5') if (awidth, aheight) != (width, height): raise ValueError("alpha channel image size mismatch" + " (%s has %sx%s but %s has %sx%s)" % (ppmfilename, width, height, options.alpha, awidth, aheight)) writer.convert_ppm_and_pgm(ppmfile, pgmfile, outfile) else: writer.convert_ppm(ppmfile, outfile) if __name__ == '__main__': _main()
Python
import wsgiref.handlers from google.appengine.ext import webapp from pixeltoy import model class GetSnapshotImage(webapp.RequestHandler): def get(self): try: id = int(self.request.get('id')) except ValueError: return snapshot = model.Snapshot.get_by_id(ids=id) if snapshot is None: return self.response.headers['Content-Type'] = 'image/png' self.response.out.write(snapshot.data) def main(): application = webapp.WSGIApplication([('/snapshot', GetSnapshotImage)], debug=True) wsgiref.handlers.CGIHandler().run(application) if __name__ == "__main__": main()
Python
import wsgiref.handlers from google.appengine.ext import webapp from google.appengine.ext import db from google.appengine.api import users from datetime import datetime import logging import string import StringIO import urllib from pixeltoy import datelib from pixeltoy import header from pixeltoy import model from pixeltoy import tracker gallery_size = 30 gallery_template = string.Template(''' <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <link rel="stylesheet" type="text/css" href="files/site.css"/> </head> <body> $header <p>Visitors drew these pictures with <a href="/">PixelToy</a>.</p> $next_link <a href="/">Return to PixelToy</a></p> <div id="gallery"> $snapshots </div> <p style="clear: both"> $next_link <a href="/">Return to PixelToy</a></p> <p><a href="http://feeds.feedburner.com/PixeltoyGallery" rel="alternate" type="application/rss+xml" ><img src="http://www.feedburner.com/fb/images/pub/feed-icon16x16.png" alt="" style="vertical-align:middle;border:0"/></a>&nbsp;<a href="http://feeds.feedburner.com/PixeltoyGallery" rel="alternate" type="application/rss+xml">Subscribe in a reader</a></p> <p><a href="/about">More about PixelToy</a></p> $tracker </body> </html> ''') next_link_template = string.Template(''' <a href="/gallery?before=${before_date}">Next Page</a> - ''') snapshot_template = string.Template(''' <div class="snapshot"> <img src="/snapshot?id=${snapshot_id}" width="$width" height="$height"> $hide </div> ''') hide_button_template = string.Template(''' <form action="/hide" method="post"> <input type=hidden name="id" value="$snapshot_id"/> <input type=hidden name="return_date" value="$current_page_date"/> <input type=submit value='Hide'/> </form> ''') unhide_button_template = string.Template(''' <form action="/unhide" method="post"> <input type=hidden name="id" value="$snapshot_id"/><input type=submit value='Unhide'/> </form> ''') gallery_atom_template = string.Template('''<?xml version="1.0" encoding="utf-8"?> <feed xmlns="http://www.w3.org/2005/Atom"> <id>$host_url/-gallery-feed</id> <title>PixelToy Gallery</title> <author><name>Visitors to PixelToy</name></author> <link rel="self" href="$host_url/feed"/> <link rel="alternate" href="$host_url/"/> <updated>$date_updated</updated> $snapshots </feed> ''') snapshot_atom_template = string.Template(''' <entry> <id>$host_url/-snapshot-${snapshot_id}</id> <title>PixelToy Snapshot</title> <updated>$date_created</updated> <content type="xhtml"> <div xmlns="http://www.w3.org/1999/xhtml"> <img src="$host_url/snapshot?id=${snapshot_id}" width="$width" height="$height" xmlns="http://www.w3.org/1999/xhtml" /> </div> </content> </entry> ''') def ShowGallery(want_hidden=False): return GalleryPage('text/html', gallery_template, snapshot_template, want_hidden) def ShowGalleryAtom(): return GalleryPage('text/xml', gallery_atom_template, snapshot_atom_template, want_hidden=False) def ShowHidden(): return ShowGallery(want_hidden=True) class GalleryPage(webapp.RequestHandler): def __init__(self, content_type, gallery_template, snapshot_template, want_hidden): webapp.RequestHandler.__init__(self) self.content_type = content_type self.gallery_template = gallery_template self.snapshot_template = snapshot_template self.want_hidden = want_hidden def get(self): host=self.request.environ['SERVER_NAME'] before_date = datetime.utcnow() if self.request.GET.has_key('before'): try: before_date = datelib.from_isodate(self.request.GET['before']) except datelib.ParseError: pass most_recent = model.Snapshot.all().order("-date_created").fetch(1) if len(most_recent) == 0: self.response.headers['Content-Type'] = "text/plain" self.response.out.write("No snapshots yet") return date_updated = most_recent[0].date_created all_snapshots = \ model.Snapshot.all().order("-date_created").filter("date_created <", before_date) \ .filter("is_hidden =", self.want_hidden) \ .fetch(gallery_size * 2) if self.want_hidden: wanted_snapshots_plus = [s for s in all_snapshots if s.hidden!=None] else: wanted_snapshots_plus = [s for s in all_snapshots if s.hidden==None] wanted_snapshots = wanted_snapshots_plus[:gallery_size] if len(wanted_snapshots) < len(wanted_snapshots_plus): next_link_date = wanted_snapshots[-1].date_created else: next_link_date = None self.response.headers['Content-Type'] = self.content_type self.response.out.write(self.make_page(host, wanted_snapshots, date_updated, before_date, next_link_date)) def make_page(self, host, snapshots, date_updated, current_page_date, next_link_date): if next_link_date is None: next_link = '' else: before_date = urllib.quote(datelib.to_isodate(next_link_date)) next_link = next_link_template.substitute(before_date=before_date) snapshots = self.make_snapshot_rows(snapshots, current_page_date) return self.gallery_template.substitute(date_updated=datelib.to_isodate(date_updated), snapshots=snapshots, tracker=tracker.make_tracker(host), host_and_port=self.request.host, host_url=self.request.host_url, header=header.make_header_html('/gallery'), next_link=next_link) def make_snapshot_rows(self, snapshots, current_page_date): logged_in = users.get_current_user() out = StringIO.StringIO() for snapshot in snapshots: snapshot_id = snapshot.key().id() if logged_in and snapshot.can_hide and not self.want_hidden: hide = hide_button_template.substitute(snapshot_id=snapshot_id, current_page_date=datelib.to_isodate(current_page_date)) elif self.want_hidden: hide = unhide_button_template.substitute(snapshot_id=snapshot_id) else: hide = "" out.write(self.snapshot_template.substitute( snapshot_id=snapshot_id, width=snapshot.width, height=snapshot.height, date_created=datelib.to_isodate(snapshot.date_created), host_and_port=self.request.host, host_url=self.request.host_url, hide=hide)) return out.getvalue() def show_error_page(response, message): response.headers['Content-Type'] = "text/plain" response.set_status(400) response.out.write(message) class HideSnapshot(webapp.RequestHandler): def post(self): user = users.get_current_user() if not user: show_error_page(self.response, "Not logged in!") return id_string = self.request.get('id') if id_string is None: show_error_page(self.response, "No id!") return try: id = int(id_string) except ValueError: logging.warning("HideSnapshot got bad id string: %s", repr(id_string)) show_error_page(self.response, "Bad id!") return return_date = datetime.utcnow() if self.request.POST.has_key('return_date'): try: return_date = datelib.from_isodate(self.request.POST['return_date']) except datelib.ParseError: pass def transaction(id): snapshot = model.Snapshot.get_by_id(ids=id) if snapshot is None or not snapshot.can_hide: return False action = model.SnapshotAction(parent=snapshot, action_type=db.Category('hide_snapshot'), done_by=user) action.put() snapshot.hidden = action snapshot.is_hidden = True snapshot.put() return True ok = db.run_in_transaction(transaction, id) if not ok: show_error_page(self.response, "Transaction failed!") return self.redirect("/gallery?before=" + urllib.quote(datelib.to_isodate(return_date))) class UnhideSnapshot(webapp.RequestHandler): def post(self): user = users.get_current_user() if not user: return try: id = int(self.request.get('id')) except ValueError: return def transaction(id): snapshot = model.Snapshot.get_by_id(ids=id) if snapshot is None: return snapshot.hidden = None snapshot.can_hide = False snapshot.is_hidden = False snapshot.put() db.run_in_transaction(transaction, id) self.redirect("/hidden") def main(): application = webapp.WSGIApplication([('/gallery', ShowGallery), ('/feed', ShowGalleryAtom), ('/hide', HideSnapshot), ('/hidden', ShowHidden), ('/unhide', UnhideSnapshot)], debug=True) wsgiref.handlers.CGIHandler().run(application) if __name__ == "__main__": main()
Python
import wsgiref.handlers from google.appengine.ext import webapp from google.appengine.ext import db import string import StringIO from pixeltoy import colorlib from pixeltoy import model from pixeltoy import tracker from pixeltoy import header page_template = string.Template(''' <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <link rel="stylesheet" type="text/css" href="files/site.css"/> <script type="text/javascript" src="files/jquery-1.2.3.min.js"></script> <script type="text/javascript" src="files/pixeltoy.js"></script> <style type="text/css"> $colors_css </style> <head> <body> $header <div id='border'> <div id='title'>PixelToy!</div> <table><tr><td> <table id='pixels'> $pixel_rows </table> </td><td id='rightside'> <table id='palette'> $palette </table> </td></tr> <tr><td> <form action="take_snapshot" method="post" id="takesnapshot"> <input type="submit" value="Take Snapshot"> <a href="/gallery">See Gallery</a> </form> </td></tr> </table> </div> $tracker </body> </html> ''') color_css_template = string.Template( '.$colorclass { background-color: #$colorname; border-color: #$colorname; }\n') pixel_template = string.Template('<td id="_${x}.${y}" class="$colorclass"></td>') color_template = string.Template(''' <td id='$colorclass' class="$colorclass$selected"></td> ''') def get_color_class(color_index): return "c%s" % color_index def make_pixel_rows(pixel_record): pixel_it = iter(pixel_record.pixels) out = StringIO.StringIO() for y in range(0, pixel_record.height): out.write("<tr>") for x in range(0, pixel_record.width): color_index = ord(pixel_it.next()) out.write(pixel_template.substitute(x=x, y=y, colorclass=get_color_class(color_index))) out.write("</tr>\n") return out.getvalue() class MainPage(webapp.RequestHandler): def get(self): self.response.headers['Content-Type'] = 'text/html' self.response.out.write(self.make_page(host=self.request.environ['SERVER_NAME'])) def make_page(self, host): grid = model.get_pixels() return page_template.substitute( header = header.make_header_html('/'), colors_css = self.make_colors_css(grid), pixel_rows = make_pixel_rows(grid), palette = self.make_palette(grid), tracker = tracker.make_tracker(host)) def make_colors_css(self, grid): out = StringIO.StringIO() for i in xrange(0,len(grid.colors)): out.write(color_css_template.substitute(colorclass = get_color_class(i), colorname = grid.colors[i])) return out.getvalue() def make_palette(self, grid): out = StringIO.StringIO() palette_width = colorlib.palette_size[0] for index in xrange(0, len(grid.colors)): if index % palette_width == 0: out.write("<tr>") colorclass = 'c%d' % index if index == colorlib.starting_color: selected = ' selected-color' else: selected = '' out.write(color_template.substitute(colorclass = colorclass, selected = selected)) if index % palette_width == palette_width - 1: out.write("</tr>") if len(grid.colors) % palette_width != 0: out.write("</tr>") return out.getvalue() class ApplyStroke(webapp.RequestHandler): def post(self): def transaction(data): pixels = model.get_pixels() pixels.apply_stroke(data) pixels.put() return pixels pixels = db.run_in_transaction(transaction, self.request.get('data')) self.response.headers['Content-Type'] = 'text/plain' out = self.response.out.write(make_pixel_rows(pixels)) class GetPixels(webapp.RequestHandler): def get(self): pixels = model.get_pixels() self.response.headers['Content-Type'] = 'text/plain' out = self.response.out.write(make_pixel_rows(pixels)) class TakeSnapshot(webapp.RequestHandler): def post(self): pixels = model.get_pixels() pixels.to_snapshot().put() self.redirect("/gallery") def main(): application = webapp.WSGIApplication([('/', MainPage), ('/stroke', ApplyStroke), ('/pixels', GetPixels), ('/take_snapshot', TakeSnapshot)], debug=True) wsgiref.handlers.CGIHandler().run(application) if __name__ == "__main__": main()
Python
print "Content-Type: text/plain" print print "ok"
Python
from google.appengine.api import users import string not_signed_in_template = string.Template(''' <div id='header'><a href="$login_url">Sign in</a></div> ''') signed_in_template = string.Template(''' <div id='header'>$nickname | <a href="$logout_url">Sign out</a></p></div> ''') def make_header_html(login_dest_url): user = users.get_current_user() if user: return signed_in_template.substitute( nickname=user.nickname(), logout_url=users.create_logout_url(login_dest_url)) else: return not_signed_in_template.substitute( login_url=users.create_login_url(login_dest_url))
Python
import array import math starting_color = None color_names = [] snapshot_pixel_size = 8 color_rgb_chunks = {} palette_size = (4,20) def _make_spectrum_rgb(): "Creates a list of (r,g,b) triplets for colors in a spectrum from red to violet" corners = [(1,0,0), (1,1,0), (0,1,0), (0,1,1), (0,0,1), (1,0,1), (1,0,0)] ranges = { (0,0): [0x00] * 4, (1,1): [0xff] * 4, (0,1): [0x00, 0x66, 0x99, 0xff], (1,0): [0xff, 0x99, 0x66, 0x00] } result = [] for (start, end) in zip(corners[:-1], corners[1:]): ranges_rgb = [ ranges[i] for i in zip(start, end)] result.extend(zip(*ranges_rgb)[0:-1]) return [x for x in result if x!=(0x00,0xff,0x66)] def _init_colors(): def add_color(red, green, blue): name = '%02x%02x%02x' % (red, green, blue) color_names.append(name) color_rgb_chunks[name] = array.array('B', (red,green,blue) * snapshot_pixel_size) brightness_scale = [0x00, 0x33, 0x66, 0x99, 0xcc, 0xff] def scale_down(value, brightness): for index in xrange(0, len(brightness_scale)): if value == brightness_scale[index]: new_index = index * brightness / 6 return brightness_scale[new_index] raise ValueException def scale_up(value, brightness): for index in xrange(0, len(brightness_scale)): if value == brightness_scale[index]: new_index = 5 - int(math.ceil((5 - index) * brightness / 6.0)) return brightness_scale[new_index] raise ValueException def add_grey(v): add_color(v,v,v) lo = 0x00 hi = 0x33 add_grey(0x00) add_grey(0xff) add_color(hi,hi,lo) add_color(hi,lo,hi) add_grey(0x33) add_grey(0xcc) add_color(hi,lo,lo) add_color(lo,lo,hi) add_grey(0x66) add_grey(0x99) add_color(lo,hi,lo) add_color(lo,hi,hi) for (r,g,b) in _make_spectrum_rgb(): add_color(scale_up(r,3), scale_up(g,3), scale_up(b,3)) for brite in [6,5,4]: add_color(scale_down(r,brite), scale_down(g,brite), scale_down(b,brite)) for i in xrange(0, len(color_names)): if color_names[i] == '0000ff': global starting_color starting_color = i _init_colors()
Python
import string tracker_template = string.Template(''' <script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script> <script type="text/javascript"> var pageTracker = _gat._getTracker("UA-309109-3"); pageTracker._initData(); pageTracker._trackPageview(); </script> ''') def make_tracker(host): if host == 'localhost': return '' else: return tracker_template.substitute()
Python
from google.appengine.ext import db import array import logging import png import StringIO from pixeltoy import colorlib class Props(object): pass grid_size = Props() grid_size.width = 32 grid_size.height = 32 snapshot_pixel_size = colorlib.snapshot_pixel_size class Pixels(db.Model): """A grid of pixels where each pixel is an index into a color list.""" width = db.IntegerProperty(required=True) height = db.IntegerProperty(required=True) colors = db.StringListProperty() pixels = db.BlobProperty() def apply_stroke(self, data_as_string): data = data_as_string.split('_') try: color_index = int(data[0][1:]) bytes = list(self.pixels) for coord in data[1:]: (x_str,y_str) = coord.split(".") x = int(x_str) y = int(y_str) if (x >= 0 and x < self.width and y >= 0 and y < self.height): bytes[x + y * self.width] = chr(color_index) self.pixels = ''.join(bytes) except ValueError: logging.warn("unable to apply stroke: '%s'" % data_as_string) raise Pixels.pixels.validate(self.pixels) def to_snapshot(self): rgb = array.array('B') for y in xrange(0, self.height): line = array.array('B') for x in xrange(0, self.width): color_index = self.pixels[y * self.width + x] color_name = self.colors[ord(color_index)] line.extend(colorlib.color_rgb_chunks[color_name]) for i in xrange (0, snapshot_pixel_size): rgb.extend(line) png_data = StringIO.StringIO() snapshot_width = self.width * snapshot_pixel_size snapshot_height = self.height * snapshot_pixel_size writer = png.Writer(width=snapshot_width, height=snapshot_height) writer.write_array(png_data, rgb) return Snapshot(width=snapshot_width, height=snapshot_height, data=png_data.getvalue()) class SnapshotAction(db.Model): action_type = db.CategoryProperty(required=True) date_done = db.DateTimeProperty(required=True, auto_now_add=True) done_by = db.UserProperty() class Snapshot(db.Model): """A snapshot of pixeltoy, converted to a PNG""" name = db.StringProperty(required=True, default="Untitled") date_created = db.DateTimeProperty(required=True, auto_now_add=True) width = db.IntegerProperty(required=True) height = db.IntegerProperty(required=True) data = db.BlobProperty() hidden = db.ReferenceProperty(reference_class=SnapshotAction, default=None) is_hidden = db.BooleanProperty(default=False) can_hide = db.BooleanProperty(default=True, required=True) def make_empty_pixels(width=grid_size.width, height=grid_size.height): return Pixels(key_name='singleton', width = width, height = height, colors = colorlib.color_names, pixels = chr(0) * (grid_size.width * grid_size.height)) def get_pixels(): result = Pixels.get_by_key_name('singleton') if result is None: return make_empty_pixels() else: return result
Python
import re from datetime import datetime iso_format = re.compile(r"(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d).(\d\d\d\d\d\d)Z$") class ParseError(Exception): pass def to_isodate(a_datetime): return a_datetime.isoformat() + 'Z' def from_isodate(date_string): m = iso_format.search(date_string) if not m: raise ParseError() (year, month, day, hour, minute, second, fraction) = m.groups() return datetime(int(year), int(month), int(day), int(hour), int(minute), int(second), int(fraction), None)
Python
import logging import wsgiref.handlers from google.appengine.ext import webapp from google.appengine.api import users from google.appengine.ext import db from pixeltoy import model def show_error_page(response, message): response.headers['Content-Type'] = "text/plain" response.set_status(400) response.out.write(message) def fix_one(snapshot_id): logging.warn("fixing: %d" % snapshot_id) def transaction(id): snapshot = model.Snapshot.get_by_id(ids=id) if snapshot is None: return False snapshot.is_hidden = (snapshot.hidden != None) snapshot.put() return True return db.run_in_transaction(transaction, snapshot_id) class FixHidden(webapp.RequestHandler): def get(self): self.response.headers['Content-Type'] = 'text/html' self.response.out.write('<form method="POST"><input type="Submit"></form>') def post(self): user = users.get_current_user() if not user: self.show_error_page("not logged in") return snapshots = model.Snapshot.gql("where date_created <= DATE(2008,4,29)").fetch(1000) logging.warn("checking %d snapshots for fix" % len(snapshots)) fix_count = 0 for snap in snapshots: id = snap.key().id() old_value = snap.is_hidden # if not type(old_value) is bool: if fix_one(id): fix_count += 1 else: logging.warn("transaction failed for %s" % id) # else: # logging.warn("no need for fix: %d, %s" % (id, repr(old_value))) self.response.headers['Content-Type'] = 'text/plain' self.response.out.write("Fixed: %d" % fix_count) def main(): application = webapp.WSGIApplication([('/fix_hidden', FixHidden)], debug=True) wsgiref.handlers.CGIHandler().run(application) if __name__ == "__main__": main()
Python
import os import inspect import glob # try to import an environment first try: Import('env') except: exec open("../build/build-env.py") env = Environment() # on mac we have to tell the linker to link against the C++ library if env['PLATFORM'] == "darwin": env.Append(LINKFLAGS = "-lstdc++") # find all .cus & .cpps in the current directory sources = [] directories = [name for name in os.listdir('.') if os.path.isdir(name)] extensions = ['*.cu', '*.cpp'] for dir in directories: for ext in extensions: regexp = os.path.join(dir, ext) #sources.extend(env.Glob(regexp, strings = True)) sources.extend(glob.glob(regexp)) # compile examples for src in sources: env.Program(src)
Python
from scipy.sparse import coo_matrix from scipy.io import mmwrite from numpy.random import permutation M = N = 10 for nnz in [0, 1, 2, 5, 8, 10, 15, 20, 30, 50, 80, 100]: P = permutation(M * N)[:nnz] I = P / N J = P % N V = permutation(nnz) + 1 A = coo_matrix( (V,(I,J)) , shape=(M,N)) filename = '%03d_nonzeros.mtx' % (nnz,) mmwrite(filename, A)
Python
import os import inspect import glob # try to import an environment first try: Import('env') except: exec open("../build/build-env.py") env = Environment() # on mac we have to tell the linker to link against the C++ library if env['PLATFORM'] == "darwin": env.Append(LINKFLAGS = "-lstdc++") # find all .cus & .cpps in the current directory sources = [] directories = ['.', 'cuda'] extensions = ['*.cu', '*.cpp'] for dir in directories: for ext in extensions: regexp = os.path.join(dir, ext) #sources.extend(env.Glob(regexp, strings = True)) sources.extend(glob.glob(regexp)) # add the directory containing this file to the include path this_file = inspect.currentframe().f_code.co_filename this_dir = os.path.dirname(this_file) env.Append(CPPPATH = [this_dir]) # by default, we want to build the full unit test suite tester = env.Program('tester', sources) Default(tester) # add targets to build individual tests core_sources = ['testframework.cu', 'unittest_tester.cu'] for test in glob.glob('*.cu'): if test not in core_sources: name, ext = os.path.splitext(test) env.Program('test_'+name, core_sources+[test])
Python
import os import glob from warnings import warn cusp_abspath = os.path.abspath("../../cusp/") # try to import an environment first try: Import('env') except: exec open("../../build/build-env.py") env = Environment() # this function builds a trivial source file from a Cusp header def trivial_source_from_header(source, target, env): src_abspath = str(source[0]) src_relpath = os.path.relpath(src_abspath, cusp_abspath) include = os.path.join('cusp', src_relpath) target_filename = str(target[0]) fid = open(target_filename, 'w') fid.write('#include <' + include + '>\n') fid.close() # CUFile builds a trivial .cu file from a Cusp header cu_from_header_builder = Builder(action = trivial_source_from_header, suffix = '.cu', src_suffix = '.h') env.Append(BUILDERS = {'CUFile' : cu_from_header_builder}) # CPPFile builds a trivial .cpp file from a Cusp header cpp_from_header_builder = Builder(action = trivial_source_from_header, suffix = '.cpp', src_suffix = '.h') env.Append(BUILDERS = {'CPPFile' : cpp_from_header_builder}) # find all user-includable .h files in the cusp tree and generate trivial source files #including them extensions = ['.h'] folders = ['', # main folder 'gallery/', 'graph/', 'io/', 'krylov/', 'precond/', 'relaxation/'] sources = [] for folder in folders: for ext in extensions: pattern = os.path.join(os.path.join(cusp_abspath, folder), "*" + ext) for fullpath in glob.glob(pattern): headerfilename = os.path.basename(fullpath) cu = env.CUFile(headerfilename.replace('.h', '.cu'), fullpath) cpp = env.CPPFile(headerfilename.replace('.h', '_cpp.cpp'), fullpath) sources.append(cu) #sources.append(cpp) # TODO: re-enable this # insure that all files #include <cusp/detail/config.h> fid = open(fullpath) if '#include <cusp/detail/config.h>' not in fid.read(): warn('Header <cusp/' + folder + headerfilename + '> does not include <cusp/detail/config.h>') # and the file with main() sources.append('main.cu') tester = env.Program('tester', sources)
Python
import os import inspect import glob # try to import an environment first try: Import('env') except: exec open("../../build/build-env.py") env = Environment() # on mac we have to tell the linker to link against the C++ library if env['PLATFORM'] == "darwin": env.Append(LINKFLAGS = "-lstdc++") # find all .cus & .cpps in the current directory sources = [] directories = ['.'] extensions = ['*.cu', '*.cpp'] for dir in directories: for ext in extensions: regexp = os.path.join(dir, ext) #sources.extend(env.Glob(regexp, strings = True)) sources.extend(glob.glob(regexp)) # compile examples for src in sources: env.Program(src)
Python
import os import inspect import glob # try to import an environment first try: Import('env') except: exec open("../../build/build-env.py") env = Environment() # on mac we have to tell the linker to link against the C++ library if env['PLATFORM'] == "darwin": env.Append(LINKFLAGS = "-lstdc++") # find all .cus & .cpps in the current directory sources = [] directories = ['.'] extensions = ['*.cu', '*.cpp'] for dir in directories: for ext in extensions: regexp = os.path.join(dir, ext) #sources.extend(env.Glob(regexp, strings = True)) sources.extend(glob.glob(regexp)) # compile examples for src in sources: env.Program(src)
Python
import os import inspect import glob # try to import an environment first try: Import('env') except: exec open("../../build/build-env.py") env = Environment() # on mac we have to tell the linker to link against the C++ library if env['PLATFORM'] == "darwin": env.Append(LINKFLAGS = "-lstdc++") # find all .cus & .cpps in the current directory sources = [] directories = ['.'] extensions = ['*.cu', '*.cpp'] for dir in directories: for ext in extensions: regexp = os.path.join(dir, ext) #sources.extend(env.Glob(regexp, strings = True)) sources.extend(glob.glob(regexp)) # compile examples for src in sources: env.Program(src)
Python
import os import inspect import glob # try to import an environment first try: Import('env') except: exec open("../../build/build-env.py") env = Environment() # on mac we have to tell the linker to link against the C++ library if env['PLATFORM'] == "darwin": env.Append(LINKFLAGS = "-lstdc++") # find all .cus & .cpps in the current directory sources = [] directories = ['.'] extensions = ['*.cu', '*.cpp'] for dir in directories: for ext in extensions: regexp = os.path.join(dir, ext) #sources.extend(env.Glob(regexp, strings = True)) sources.extend(glob.glob(regexp)) # compile examples for src in sources: env.Program(src)
Python
import os import inspect import glob # try to import an environment first try: Import('env') except: exec open("../../build/build-env.py") env = Environment() # on mac we have to tell the linker to link against the C++ library if env['PLATFORM'] == "darwin": env.Append(LINKFLAGS = "-lstdc++") # find all .cus & .cpps in the current directory sources = [] directories = ['.'] extensions = ['*.cu', '*.cpp'] for dir in directories: for ext in extensions: regexp = os.path.join(dir, ext) #sources.extend(env.Glob(regexp, strings = True)) sources.extend(glob.glob(regexp)) # compile examples for src in sources: env.Program(src)
Python
#!/usr/bin/env python import os,csv device_id = '0' # index of the device to use binary_filename = '../spmv' # command used to run the tests output_file = 'benchmark_output.log' # file where results are stored # The unstructured matrices are available online: # http://www.nvidia.com/content/NV_Research/matrices.zip mats = [] unstructured_path = '~/scratch/Matrices/williams/mm/' unstructured_mats = [('Dense','dense2.mtx'), ('Protein','pdb1HYS.mtx'), ('FEM/Spheres','consph.mtx'), ('FEM/Cantilever','cant.mtx'), ('Wind Tunnel','pwtk.mtx'), ('FEM/Harbor','rma10.mtx'), ('QCD','qcd5_4.mtx'), ('FEM/Ship','shipsec1.mtx'), ('Economics','mac_econ_fwd500.mtx'), ('Epidemiology','mc2depi.mtx'), ('FEM/Accelerator','cop20k_A.mtx'), ('Circuit','scircuit.mtx'), ('Webbase','webbase-1M.mtx'), ('LP','rail4284.mtx') ] unstructured_mats = [ mat + (unstructured_path,) for mat in unstructured_mats] structured_path = '~/scratch/Matrices/stencil/' structured_mats = [('Laplacian_3pt_stencil', '3pt_1000000.mtx'), ('Laplacian_5pt_stencil', '5pt_1000x1000.mtx'), ('Laplacian_7pt_stencil', '7pt_100x100x100.mtx'), ('Laplacian_9pt_stencil', '9pt_1000x1000.mtx'), ('Laplacian_27pt_stencil', '27pt_100x100x100.mtx')] structured_mats = [ mat + (structured_path,) for mat in structured_mats] # assemble suite of matrices trials = unstructured_mats + structured_mats def run_tests(value_type): # remove previous result (if present) open(output_file,'w').close() # run benchmark for each file for matrix,filename,path in trials: matrix_filename = path + filename # setup the command to execute cmd = binary_filename cmd += ' ' + matrix_filename # e.g. pwtk.mtx cmd += ' --device=' + device_id # e.g. 0 or 1 cmd += ' --value_type=' + value_type # e.g. float or double # execute the benchmark on this file os.system(cmd) # process output_file matrices = {} results = {} kernels = set() # fid = open(output_file) for line in fid.readlines(): tokens = dict( [tuple(part.split('=')) for part in line.split()] ) if 'file' in tokens: file = os.path.split(tokens['file'])[1] matrices[file] = tokens results[file] = {} else: kernel = tokens['kernel'] results[file][kernel] = tokens kernels.add(tokens['kernel']) ## put CPU results before GPU results #kernels = ['csr_serial'] + sorted(kernels - set(['csr_serial'])) kernels = sorted(kernels) # write out CSV formatted results def write_csv(field): fid = open('bench_' + value_type + '_' + field + '.csv','w') writer = csv.writer(fid) writer.writerow(['matrix','file','rows','cols','nonzeros'] + kernels) for (matrix,file,path) in trials: line = [matrix, file, matrices[file]['rows'], matrices[file]['cols'], matrices[file]['nonzeros']] matrix_results = results[file] for kernel in kernels: if kernel in matrix_results: line.append( matrix_results[kernel][field] ) else: line.append(' ') writer.writerow( line ) fid.close() write_csv('gflops') #GFLOP/s write_csv('gbytes') #GBytes/s run_tests('float') run_tests('double')
Python
import os import inspect import glob # try to import an environment first try: Import('env') except: exec open("../../build/build-env.py") env = Environment() # on mac we have to tell the linker to link against the C++ library if env['PLATFORM'] == "darwin": env.Append(LINKFLAGS = "-lstdc++") # find all .cus & .cpps in the current directory sources = [] directories = ['.'] extensions = ['*.cu', '*.cpp'] for dir in directories: for ext in extensions: regexp = os.path.join(dir, ext) #sources.extend(env.Glob(regexp, strings = True)) sources.extend(glob.glob(regexp)) # compile examples for src in sources: env.Program(src)
Python
import os import inspect import glob # try to import an environment first try: Import('env') except: exec open("../../build/build-env.py") env = Environment() # on mac we have to tell the linker to link against the C++ library if env['PLATFORM'] == "darwin": env.Append(LINKFLAGS = "-lstdc++") # find all .cus & .cpps in the current directory sources = [] directories = ['.'] extensions = ['*.cu', '*.cpp'] for dir in directories: for ext in extensions: regexp = os.path.join(dir, ext) #sources.extend(env.Glob(regexp, strings = True)) sources.extend(glob.glob(regexp)) # compile examples for src in sources: env.Program(src)
Python
import os import inspect import glob # try to import an environment first try: Import('env') except: exec open("../../build/build-env.py") env = Environment() # on mac we have to tell the linker to link against the C++ library if env['PLATFORM'] == "darwin": env.Append(LINKFLAGS = "-lstdc++") # find all .cus & .cpps in the current directory sources = [] directories = ['.'] extensions = ['*.cu', '*.cpp'] for dir in directories: for ext in extensions: regexp = os.path.join(dir, ext) #sources.extend(env.Glob(regexp, strings = True)) sources.extend(glob.glob(regexp)) # compile examples for src in sources: env.Program(src)
Python
import unittest class Test(unittest.TestCase): def testPrueba(self): a=2 b=2 c= a+b self.assertEqual(c, 4) if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testPrueba'] unittest.main()
Python
import unittest from disc import Disc from fileSystem import FileSystem from directoryEntry import DirectoryEntry class Test(unittest.TestCase): def testDirectoryRoot(self): disc= Disc(12) fs= FileSystem(disc) root = fs.currentDirectory self.assertFalse(disc==None) self.assertFalse(fs==None) self.assertFalse(root==None) self.assertIsInstance(root, DirectoryEntry, msg=None) def testmkdir(self): disc= Disc(12) fs= FileSystem(disc) fs.mkdir("sistemasOperativos") currentDirectory=fs.currentDirectory existe=currentDirectory.existInDirectory("sistemasOperativos") self.assertTrue(existe) def testls(self): disc= Disc(12) fs= FileSystem(disc) fs.mkdir("home") fs.mkdir("leo") listOfDirectory=fs.ls() self.assertTrue(["home", "leo"]==listOfDirectory) def testrmdir(self): disc= Disc(12) fs= FileSystem(disc) fs.mkdir("user") newDirectoryIdInode = fs.currentDirectory.getInodeId("user") self.assertFalse(disc.freeInodes.isFree(newDirectoryIdInode)) fs.rmDir("user") self.assertTrue(disc.freeInodes.isFree(newDirectoryIdInode)) def testChangeDirBack(self): disc= Disc(12) fs= FileSystem(disc) fs.mkdir("var") fs.mkdir("river plate") print "esta es la lista del directorio /:" print fs.currentDirectory.directoryList currentDirBeforeChangeDirBack = fs.currentDirectory self.assertTrue(currentDirBeforeChangeDirBack.name=="/") print fs.currentDirectory.getInodeId("var"), fs.currentDirectory.currentDir fs.changeDir("var") print "esta es la lista del directorio var:" print fs.currentDirectory.directoryList currentDirAfterChangeDir= fs.currentDirectory self.assertTrue(currentDirAfterChangeDir.name=="var") fs.changeDirBack() currentDirAfterChangedirBack=fs.currentDirectory print currentDirAfterChangedirBack.name self.assertTrue(currentDirAfterChangedirBack.name=="/") self.assertEqual(currentDirAfterChangedirBack, currentDirBeforeChangeDirBack) def testChangeDir(self): disc= Disc(12) fs= FileSystem(disc) fs.mkdir("tmp") currentDirBeforeChangeDir = fs.currentDirectory self.assertTrue(currentDirBeforeChangeDir.name=="/") fs.changeDir("tmp") currentDirAfterChangeDir= fs.currentDirectory self.assertTrue(currentDirAfterChangeDir.name=="tmp") if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main()
Python
import unittest from disc import Disc from fileSystem import FileSystem class Test(unittest.TestCase): def testCreateArchive(self): disc= Disc(16) fs= FileSystem(disc) fs.createArchive("tp.txt", 2) currentDirectory= fs.currentDirectory IdinodoArchive= currentDirectory.getInodeId("tp.txt") inodoArchive= disc.inodos[IdinodoArchive] existe=currentDirectory.existInDirectory("tp.txt") num =len (inodoArchive.directions) self.assertTrue(num==2) self.assertTrue(existe) def testDeleteArchive(self): disc= Disc(16) fs= FileSystem(disc) fs.createArchive("tp.txt", 2) currentDirectory= fs.currentDirectory existe=currentDirectory.existInDirectory("tp.txt") self.assertTrue(existe) fs.deleteArchive("tp.txt") noExiste=currentDirectory.existInDirectory("tp.txt") self.assertFalse(noExiste) def testCopy(self): disc= Disc(12) fs= FileSystem(disc) fs.mkdir("var") fs.createArchive("tp.txt", 2) print fs.currentDirectory.directoryList existeEnRoot = fs.currentDirectory.existInDirectory("tp.txt") print existeEnRoot self.assertTrue(existeEnRoot) fs.copy("tp.txt", ["var"]) print fs.currentDirectory.directoryList print fs.currentDirectory.name existeEnVar = fs.currentDirectory.existInDirectory("tp.txt") self.assertTrue(existeEnVar) fs.returnToRootDirectory() existeEnRoot = fs.currentDirectory.existInDirectory("tp.txt") self.assertTrue(existeEnRoot) def testMove(self): disc= Disc(12) fs= FileSystem(disc) fs.mkdir("var") fs.createArchive("tp.txt", 2) print fs.currentDirectory.directoryList existeEnRoot = fs.currentDirectory.existInDirectory("tp.txt") print existeEnRoot self.assertTrue(existeEnRoot) fs.changeDir("var") fs.mkdir("leo") fs.returnToRootDirectory() print "esto es del move" print fs.currentDirectory.directoryList print fs.currentDirectory.name fs.move("tp.txt", ["var", "leo"]) fs.changeDir("var") fs.changeDir("leo") print "la carpeta leo debe tener tp.txt:" print fs.currentDirectory.directoryList print fs.currentDirectory.name existeEnLeo = fs.currentDirectory.existInDirectory("tp.txt") print existeEnLeo self.assertTrue(existeEnLeo) fs.returnToRootDirectory() existeEnRoot = fs.currentDirectory.existInDirectory("tp.txt") print "no debe estar en root" print existeEnRoot self.assertFalse(existeEnRoot) if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testcreateArchive'] unittest.main()
Python
from datetime import datetime class Inode: def __init__(self,inodeId): ''' La variable directiones, solo almacena 3 direciones de bloques de disco. Porque nuestra estructura de Inode esta definida asi. las claves para acceder a los campos son 1, 2 y 3. ''' self.date = None self.id= inodeId self.directions= {} self.aditionalDirection= None def setDate(self): self.date = datetime.today() def setDirection(self, direction, numBlock): self.directions[direction]=numBlock def getDirection(self, num): return self.directions[num] def __repr__(self): return '[date: %s, id: %s, directions: %s]' % (self.date, self.id, self.directions)
Python
from freeBlocksTable import FreeBlocksTable from freeInodesTable import FreeInodesTable class Disc: def __init__(self, size): self.dataBlocks = [] self.size = size self.freeblocks = FreeBlocksTable() self.freeInodes = FreeInodesTable() self.inodos={} def read(self, numBlock): return self.dataBlocks[numBlock] def write(self, numBlock,data): self.dataBlocks.insert(numBlock, data) def delete(self, numBlock): self.freeblocks.add(numBlock)
Python
class FreeInodesTable: def __init__(self): self.table={} def setAsFree(self,iNodeId): self.table[iNodeId]=True def findFreeInode(self): if not self.isEmpty(): for i in self.table: if self.table[i]==True: self.table[i]= False return i else: print "Error, no hay mas espacio en disco" return Exception def isEmpty(self): for i in self.table: if self.table[i]==True: return False return True def isFree(self, iNodeId): for i in self.table: if i == iNodeId: return self.table[i]==True else: print "Error, no hay mas espacio en disco" return Exception def setAsOcupate(self,iNodeId): self.table[iNodeId]=False
Python
from directoryEntry import DirectoryEntry from iNode import Inode class FileSystem: def __init__(self, disc): self.disc = disc self.formatDisc() self.currentDirectory = self.rootDir("/") def formatDisc(self): self.disc.freeblocks.initialize(self.disc.size) self.createInodesAndCreateFreeInodesTable() def createInodesAndCreateFreeInodesTable(self): # La cantidad de Inodos se determina dividiendo la cantidad de bloques para datos # del disco y la cantidad de direcciones de un inodo(en este caso 3). cantInodes = self.disc.size // 3 cont = 1 while cont<= cantInodes: self.disc.inodos[cont] = Inode(cont) self.disc.freeInodes.setAsFree(cont) cont=cont+1 def mkdir(self, name): newInode = self.setFreeInode() newInode.setDate() self.disc.freeInodes.setAsOcupate(newInode.id) newDirectoryEntry = DirectoryEntry(newInode.id, self.currentDirectory.currentDir,name) numBlock = self.disc.freeblocks.findFreeBlock() newInode.setDirection(1,numBlock) self.disc.inodos[newInode.id]=newInode self.disc.write(numBlock,newDirectoryEntry) self.currentDirectory.addEntry(name,newInode.id) def rootDir(self, name): newInode = self.setInodeOne() newInode.setDate() self.disc.freeInodes.setAsOcupate(newInode.id) newDirectoryEntry = DirectoryEntry(newInode.id,newInode.id,name) numBlock = self.disc.freeblocks.findFreeBlock() newInode.setDirection(1,numBlock) self.disc.write(numBlock,newDirectoryEntry) return newDirectoryEntry def setInodeOne(self): return self.disc.inodos[1] def setFreeInode(self): numINode = self.disc.freeInodes.findFreeInode() return self.disc.inodos[numINode] def rmDir(self, name): if self.currentDirectory.existInDirectory(name): iNodeId = self.currentDirectory.getInodeId(name) inode = self.disc.inodos[iNodeId] numBlock= inode.getDirection(1) self.disc.freeInodes.setAsFree(iNodeId) self.disc.freeblocks.setAsFree(numBlock) else: print "No existe el directorio que se quiere borrar" return Exception def ls(self): return self.currentDirectory.directoryList.values() def changeDirBack(self): iNodeFatherId = self.currentDirectory.fatherId iNodeFather = self.disc.inodos[iNodeFatherId] numBlockFather = iNodeFather.getDirection(1) self.currentDirectory = self.disc.read(numBlockFather) def changeDir(self, name): if self.currentDirectory.existInDirectory(name): iNodeId = self.currentDirectory.getInodeId(name) print iNodeId, self.currentDirectory.currentDir iNode = self.disc.inodos[iNodeId] numBlock = iNode.getDirection(1) self.currentDirectory = self.disc.read(numBlock) else: print "No existe el directorio al cual se quiere acceder" return Exception def createArchive(self, name, size): #el size que pasamos es la cantidad de bloques que ocupa el archivo por una cuestion #de simplicidad, ademas asumimos que los archivos no ocupan mas de 3 bloques newInode = self.setFreeInode() newInode.setDate() cont = 1 while cont <= size: numBlock = self.disc.freeblocks.findFreeBlock() newInode.setDirection(cont,numBlock) self.disc.write(numBlock,'aca hay datos :D') cont = cont+1 self.disc.inodos[newInode.id]=newInode self.currentDirectory.addEntry(name,newInode.id) def deleteArchive(self, name): if self.currentDirectory.existInDirectory(name): iNodeId = self.currentDirectory.getInodeId(name) iNode = self.disc.inodos[iNodeId] blocks = iNode.directions for i in blocks: block = blocks[i] self.disc.freeblocks.setAsFree(block) self.disc.freeInodes.setAsFree(iNodeId) self.currentDirectory.directoryList.pop(iNodeId) else: print "No existe el archivo que se quiere borrar" return Exception def copy(self, name, pathDestination): archiveIdInode=self.currentDirectory.getInodeId(name) directoryEntryDestination = self.navigate(pathDestination) directoryEntryDestination.addEntry(name,archiveIdInode) def move(self, name, pathDestination): archiveIdInode = self.currentDirectory.getInodeId(name) self.currentDirectory.deleteEntry(archiveIdInode) directoryEntryDestination = self.navigate(pathDestination) directoryEntryDestination.addEntry(name,archiveIdInode) def navigate(self, pathList): #el path esta representado por una lista de strings que van conteniendo los nombres de las carpetas. #Como sabemos que el directorio raiz esta en el iNodo 1, buscamos a partir de ahi #esta funcion retorna la entrada de directorio a la cual se quiere acceder actualEntry = self.returnRootDirectoryEntry() for i in pathList: actualEntry = self.findDirectoryEntry(i, actualEntry) return actualEntry def returnRootDirectoryEntry(self): iNodo = self.disc.inodos[1] numBlock = iNodo.directions[1] return self.disc.read(numBlock) def returnToRootDirectory(self): iNodo = self.disc.inodos[1] numBlock = iNodo.directions[1] self.currentDirectory = self.disc.read(numBlock) def findDirectoryEntry(self, name, actualEntry): if actualEntry.existInDirectory(name): iNodeId = actualEntry.getInodeId(name) iNode = self.disc.inodos[iNodeId] numBlock = iNode.directions[1] return self.disc.read(numBlock) else: print "No existe el directorio al cual se quiere acceder" return Exception
Python