rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
r = self.read_var
r = self._read_var
def read_config(self,file): """ Read config parameters from open file passed in argument and return a Config instance. """ c = Config() self.parser.readfp(file) r = self.read_var c.project_name = r('MAIN', 'project_name') c.project_short = r('MAIN', 'project_short') c.db_type ...
raise ConfigFileReadErrorException("Can't read option '%s' from %s" % (name,self.config_file))
raise ConfigFileReadErrorException("Can't read option '%s' from section %s of file %s" % (name, section, self.config_file))
def _read_var(self, section, name): if not self.parser.has_section(section) : raise ConfigFileReadErrorException("File '%s' is missing or does not" " contain a '%s' section" % (self.config_file,section))
config = ConfigReader().read_config(open(config_file)) config.config_file = config_file
config_reader = ConfigReader() config_reader.config_file = config_file config = config_reader.read_config(open(config_file))
def _read_var(self, section, name): if not self.parser.has_section(section) : raise ConfigFileReadErrorException("File '%s' is missing or does not" " contain a '%s' section" % (self.config_file,section))
config.print_debug()
print str(config)
def _read_var(self, section, name): if not self.parser.has_section(section) : raise ConfigFileReadErrorException("File '%s' is missing or does not" " contain a '%s' section" % (self.config_file,section))
widgets.data(string.join(page.data)),
widgets.data(page.data),
def method(self, uri): if not sessions.session: return '|blknopermission|' elif sessions.session.user.can_edit(page_code=uri.code)==0: return '|blknopermission|'
box = box + '<tr><th class="label">|strusername|</td><td><input type=text name=username size=12></input></td></tr>\n' box = box + '<tr><th class="label">|strpassword|</td><td><input type=password name=password size=12></input></td></tr>\n'
box = box + '<tr><td class="label">|strusername|</td><td><input type=text name=username size=12></input></td></tr>\n' box = box + '<tr><td class="label">|strpassword|</td><td><input type=password name=password size=12></input></td></tr>\n'
def login(self, uri, user): if user: log(3, 'Creating active user box') box = '<table class="navbox"><tr><th>|stractive_user|</th></tr>\n' box = box + '<form name="logout" action="data/session/logout">\n' box = box + '<input name=username type=hidden value="' + user.username + '">\n' box = box + '<tr><td align=center>|...
else: box = box + '|strpassword|'
def user(self, uri, build_user): if not build_user: return '|blknopermission|' elif build_user.can_edit(username=uri.username)==0: return '|blknopermission|'
raise ConfigFileReadErrorException("File '" + CONF_FILE + "' is missing or does not contain a '" + section + "' section")
raise ConfigFileReadErrorException("File '" + self.config_file + "' is missing or does not contain a '" + section + "' section")
def read_var(self, section, name): if not self.config.has_section(section) : raise ConfigFileReadErrorException("File '" + CONF_FILE + "' is missing or does not contain a '" + section + "' section")
raise ConfigFileReadErrorException("Can't read option '" + name + "' from " + CONF_FILE)
raise ConfigFileReadErrorException("Can't read option '" + name + "' from " + self.config_file)
def read_var(self, section, name): if not self.config.has_section(section) : raise ConfigFileReadErrorException("File '" + CONF_FILE + "' is missing or does not contain a '" + section + "' section")
def execute(sql,params=None) :
def execute(self, sql, params=None) :
def execute(sql,params=None) : if config.log_sql : log(3, sql+' '+str(params)) cursor = self.connection.cursor() cursor.execute(sql,params) return cursor
logmessage = time.ctime(time.time()) + ' ' + message try: log_file = open(config.log_file, 'a+') log_file.write(logmessage + "\n") log_file.close except IOError: pass
def write(self, level, message): db.log(level, message) if config.log_level >= level: logmessage = time.ctime(time.time()) + ' ' + message try: log_file = open(config.log_file, 'a+') log_file.write(logmessage + "\n") log_file.close except IOError: pass
print 'Making target: ' + name
def make(self, name='all'): """ Runs the makefile specified target (defaulting to all) and records errors, results and other status flags against the document.
print 'back to ' + name
def make(self, name='all'): """ Runs the makefile specified target (defaulting to all) and records errors, results and other status flags against the document.
doc.errors.add(ERR_MAKE_EXIT_STATUS)
self.doc.errors.add(ERR_MAKE_EXIT_STATUS)
def make(self, name='all'): """ Runs the makefile specified target (defaulting to all) and records errors, results and other status flags against the document.
'cache-dir': (str, '/var/cache/scrollserver',
'cache-dir': (str, '/var/cache/scrollserver/',
def showHelp(): """ List all of the options and their help strings from 'configOptions'. """ sections = configOptions.keys() # Do the sections and the options alphabetically. sections.sort() for section in sections: print 'Options for %s:' % section options = configOptions[section].keys() options.sort() for option in o...
sql = "SELECT `code` FROM `%s` WHERE LOWER(`name`) == LOWER('%s')" % (tableName, domain)
sql = "SELECT `code` FROM `%s` WHERE LOWER(`name`) = LOWER('%s')" % (tableName, domain)
def check(self, data): param = self.getParam('param') paramValue = data.get(param, '') vtype = self.getParam('vtype') tableName = self.getParam('tableName')
sql = "SELECT `code` FROM `%s` WHERE LOWER(`name`) == LOWER('%s@%s')" % (tableName, user, domain)
sql = "SELECT `code` FROM `%s` WHERE LOWER(`name`) = LOWER('%s@%s')" % (tableName, user, domain)
def check(self, data): param = self.getParam('param') paramValue = data.get(param, '') vtype = self.getParam('vtype') tableName = self.getParam('tableName')
obj, running = self.modules.get(name) if not running: obj.start() hashArg = str(obj.hashArg(data, *args, **keywords)) code, codeEx = self.__cacheGet(name+hashArg) if code == None: hitCache = '' logging.getLogger().info("%s running" % name) code, codeEx = obj.check(data, *args, **keywords) self.__cacheSet(name+hashArg,...
def check(self, name, data, *args, **keywords): """Called from config file. We should cache results here.""" startTime = time.time() if not self.modules.has_key(name): raise Exception("Module named \"%s\" was not defined" % name) try: obj, running = self.modules.get(name) if not running: obj.start() hashArg = str(obj.h...
prefix = obj.getParam('saveResultPrefix', '')
def check(self, name, data, *args, **keywords): """Called from config file. We should cache results here.""" startTime = time.time() if not self.modules.has_key(name): raise Exception("Module named \"%s\" was not defined" % name) try: obj, running = self.modules.get(name) if not running: obj.start() hashArg = str(obj.h...
if self.cacheExpire.has_key(key) and self.cacheExpire[key] < time.time():
if self.cacheExpire.has_key(key) and self.cacheExpire[key] >= time.time():
def __cacheGet(self, key): if key == 0: return None, None retVal = None, None self.cacheLock.acquire() #logging.getLogger().debug("__cacheGet for %s" % key) try: if self.cacheExpire.has_key(key) and self.cacheExpire[key] < time.time(): retVal = self.cacheValue[key] except Exception, e: self.cacheLock.release() raise e ...
return Verification.CHECK_FAILED, "%s verification HELO failed: %s" % (param, retmsg)
if code >= 500: return Verification.CHECK_FAILED, "%s verification HELO failed with code %s: %s" % (param, code, retmsg) else: return Verification.CHECK_UNKNOWN, "%s verification HELO failed with code %s: %s" % (param, code, retmsg)
def checkMailhost(self, mailhost, domain, user): """Check if something listening for incomming SMTP connection for mailhost. For details about status that can occur during communication see RFC 2821, section 4.3.2"""
return Verification.CHECK_FAILED, "%s verification MAIL failed: %s" % (param, retmsg)
if code >= 500: return Verification.CHECK_FAILED, "%s verification HELO failed with code %s: %s" % (param, code, retmsg) else: return Verification.CHECK_UNKNOWN, "%s verification HELO failed with code %s: %s" % (param, code, retmsg)
def checkMailhost(self, mailhost, domain, user): """Check if something listening for incomming SMTP connection for mailhost. For details about status that can occur during communication see RFC 2821, section 4.3.2"""
return Verification.CHECK_FAILED, "%s verification RCPT failed: %s" % (param, retmsg)
if code >= 500: return Verification.CHECK_FAILED, "%s verification HELO failed with code %s: %s" % (param, code, retmsg) else: return Verification.CHECK_UNKNOWN, "%s verification HELO failed with code %s: %s" % (param, code, retmsg)
def checkMailhost(self, mailhost, domain, user): """Check if something listening for incomming SMTP connection for mailhost. For details about status that can occur during communication see RFC 2821, section 4.3.2"""
return Verification.UNKNOWN_FAILED, "address verification failed: %s" % msg
return Verification.CHECK_UNKNOWN, "address verification failed: %s" % msg
def checkMailhost(self, mailhost, domain, user): """Check if something listening for incomming SMTP connection for mailhost. For details about status that can occur during communication see RFC 2821, section 4.3.2"""
self.cacheExp[key] = time.time() + exp
self.cacheExp[key] = exp
def set(self, key, val, exp = 0): self.lock.acquire() try: if self.memMaxSize > 0 and len(self.cacheUse) >= self.memMaxSize: self.__clearCache() self.cacheVal[key] = val if self.memExpire > 0: if exp == 0: exp = self.memExpire self.cacheExp[key] = time.time() + exp if self.memMaxSize > 0: self.cacheUse[key] = time.time...
self.cacheVal.set(key, val, self.memExpire)
self.cacheVal.set(key, val, time.time() + self.memExpire)
def set(self, key, val = True, exp = 0): """Set data in cache.""" self.lock.acquire() try: if self.memCache: self.cacheVal.set(key, val, self.memExpire) if self.__useDb(): sql = "SELECT COUNT(*) FROM %s" % self.table sql += " WHERE %s" % self.__getWhere(key) conn = self.getDbConnection() cursor = conn.cursor() try: cur...
keywords = re.findall("%(\(.*?\))", text) replace = []
keywords = re.findall("(%\(.*?\))", text)
def safeSubstitute(text, dict, unknown = 'UNKNOWN'): """Replace keywords in text with data from dictionary. If there is not matching key in dictionary, use unknown.""" import re retVal = text keywords = re.findall("%(\(.*?\))", text) replace = [] for keyword in keywords: if not dict.has_key(keyword[1:-1]): replace.appe...
if not dict.has_key(keyword[1:-1]): replace.append(".\(%s\)." % keyword[1:-1]) for repl in replace: retVal = re.sub(repl, unknown, retVal) return retVal % dict
if dict.has_key(keyword[2:-1]): retVal = retVal.replace(keyword, dict[keyword[2:-1]]) else: retVal = retVal.replace(keyword, 'UNKNOWN') return retVal
def safeSubstitute(text, dict, unknown = 'UNKNOWN'): """Replace keywords in text with data from dictionary. If there is not matching key in dictionary, use unknown.""" import re retVal = text keywords = re.findall("%(\(.*?\))", text) replace = [] for keyword in keywords: if not dict.has_key(keyword[1:-1]): replace.appe...
if board.castling & WHITE_OO:
if board.castling & WHITE_OO and board.data[0][7] != None:
def genKing (cord, board): for dx, dy in kingPlaces: x, y = cord.x+dx, cord.y+dy if not (0 <= x <= 7 and 0 <= y <= 7): continue if not board.data[y][x] or board.data[y][x].color != board.color: yield x,y if board.color == WHITE: if board.castling & WHITE_OO: if _isclear (board, (5,6), (0,)) and \ not genMovesPointingA...
if board.castling & WHITE_OOO:
if board.castling & WHITE_OOO and board.data[0][0] != None:
def genKing (cord, board): for dx, dy in kingPlaces: x, y = cord.x+dx, cord.y+dy if not (0 <= x <= 7 and 0 <= y <= 7): continue if not board.data[y][x] or board.data[y][x].color != board.color: yield x,y if board.color == WHITE: if board.castling & WHITE_OO: if _isclear (board, (5,6), (0,)) and \ not genMovesPointingA...
if board.castling & BLACK_OO:
if board.castling & BLACK_OO and board.data[7][7] != None:
def genKing (cord, board): for dx, dy in kingPlaces: x, y = cord.x+dx, cord.y+dy if not (0 <= x <= 7 and 0 <= y <= 7): continue if not board.data[y][x] or board.data[y][x].color != board.color: yield x,y if board.color == WHITE: if board.castling & WHITE_OO: if _isclear (board, (5,6), (0,)) and \ not genMovesPointingA...
if board.castling & BLACK_OOO:
if board.castling & BLACK_OOO and board.data[7][0] != None:
def genKing (cord, board): for dx, dy in kingPlaces: x, y = cord.x+dx, cord.y+dy if not (0 <= x <= 7 and 0 <= y <= 7): continue if not board.data[y][x] or board.data[y][x].color != board.color: yield x,y if board.color == WHITE: if board.castling & WHITE_OO: if _isclear (board, (5,6), (0,)) and \ not genMovesPointingA...
q = board.data[cord1.y][cord0.x]
q = board.data[cord0.y][cord1.x]
def move (self, move, mvlist=False): board = self.clone() board.movelist = None cord0, cord1 = move.cords p = board[cord0] if p.sign == KING: if cord0.y == 0: if cord0.x - cord1.x == 2: board._move(a1, d1) elif cord0.x - cord1.x == -2: board._move(h1, f1) else: if cord0.x - cord1.x == 2: board._move(a8, d8) elif cord...
board.data[cord1.y][cord0.x] = None
board.data[cord0.y][cord1.x] = None
def move (self, move, mvlist=False): board = self.clone() board.movelist = None cord0, cord1 = move.cords p = board[cord0] if p.sign == KING: if cord0.y == 0: if cord0.x - cord1.x == 2: board._move(a1, d1) elif cord0.x - cord1.x == -2: board._move(h1, f1) else: if cord0.x - cord1.x == 2: board._move(a8, d8) elif cord...
history = game.history
if isinstance (game, Game): history = game.history else: history = game
def save (file, game): """Saves game to file in fen format""" history = game.history pieces = history[-1].data sign = lambda p: p.color == WHITE and reprSign[p.sign][0] or reprSign[p.sign][0].lower() for i in range(len(pieces))[::-1]: row = pieces[i] empty = 0 for j in range(len(row)): piece = row[j] if piece == None...
moves.append(self.parseMove(m, board))
parsedMove = self.parseMove(m, board)
def parseLine (self, line): #self.lock.acquire() parts = multiWs.split(line.strip()) if self.features["sigint"]: self.engine.sigint() # Illegal Move if parts[0].lower().find("illegal") >= 0: if parts[-2] == "sd" and parts[-1].isdigit(): self.sd = False self.setDepth (int(parts[-1])) return # A Move if self.history: ...
print boards, moves, parts
print boards, moves, parts, m, parsedMove
def parseLine (self, line): #self.lock.acquire() parts = multiWs.split(line.strip()) if self.features["sigint"]: self.engine.sigint() # Illegal Move if parts[0].lower().find("illegal") >= 0: if parts[-2] == "sd" and parts[-1].isdigit(): self.sd = False self.setDepth (int(parts[-1])) return # A Move if self.history: ...
rlist, _, _ = select.select([self.fd], [], [], timeout-time())
t = timeout-time() if t < 0: t = 0 rlist, _, _ = select.select([self.fd], [], [], t)
def readline (self, timeout=-1): if timeout < 0: timeout = time()+600 i = self.buffer.find("\n") if i >= 0: line = self.buffer[:i] self.buffer = self.buffer[i+1:] if line: return line while True: while True: try: rlist, _, _ = select.select([self.fd], [], [], timeout-time()) except select.error, error: if error.args[...
if no == WHITE: player.updateTime (self.chessclock.p0time/10., self.chessclock.p1time/10.) else: player.updateTime (self.chessclock.p1time/10., self.chessclock.p0time/10.)
if self.chessclock: if no == WHITE: player.updateTime (self.chessclock.p0time/10., self.chessclock.p1time/10.) else: player.updateTime (self.chessclock.p1time/10., self.chessclock.p0time/10.)
def _run (self): self.running = True while self.running: player, no = { WHITE: (self.player1, 0), BLACK: (self.player2, 1)} [self.history.curCol()] if self.chessclock: self.chessclock.player = no if player.__type__ == LOCAL: self.gmwidg.setTabReady(True) else: self.gmwidg.setTabReady(False) if no == WHITE: player.up...
if step < 0: if self.shown != 0: self.lastMove = self.history.moves[self.shown-1] else: self.lastMove = None self.runAnimation(first = True) if step > 0: if self.shown != 0: self.lastMove = self.history.moves[self.shown-1] else: self.lastMove = None
if self.lastMove: paintBox = self.cord2Rect(self.lastMove.cord0) paintBox = join(paintBox, self.cord2Rect(self.lastMove.cord1)) self.lastMove = None self.redraw_canvas(rect(paintBox)) if self.shown != 0: self.lastMove = self.history.moves[self.shown-1] else: self.lastMove = None self.runAnimation(redrawMisc = True)
def do(): if step < 0: if self.shown != 0: self.lastMove = self.history.moves[self.shown-1] else: self.lastMove = None self.runAnimation(first = True) if step > 0: if self.shown != 0: self.lastMove = self.history.moves[self.shown-1] else: self.lastMove = None self.animationID = idle_add(self.runAnimation)
def runAnimation (self, first=False):
def runAnimation (self, redrawMisc=False):
def runAnimation (self, first=False): mod = min(1.0, (time()-self.animationStart)/ANIMATION_TIME) board = self.history[self.shown]
if first: for cord in (self.selected, self.hover, self.active): if cord: paintBox = join(paintBox, self.cord2Rect(cord)) for arrow in (self.redarrow, self.greenarrow, self.bluearrow): if arrow: paintBox = join(paintBox, self.cord2Rect(arrow[0])) paintBox = join(paintBox, self.cord2Rect(arrow[1])) if self.lastMove: pain...
self.redraw_canvas(rect(paintBox))
def runAnimation (self, first=False): mod = min(1.0, (time()-self.animationStart)/ANIMATION_TIME) board = self.history[self.shown]
sd = 1
sd = 4
def nextedIterator (*items): for item in items: for i in item: try: if not i in used: used.add(i) yield i except: print items, item, i raise
elif validator.isCheck(board2, board2.color):
elif validator.isCheck(board2, 1-board2.color):
def toSAN (board, board2, move, fan=False): """ Returns a Short/Abbreviated Algebraic Notation string of a move The board should be prior to the move, board2 past. If not board2, toSAN will not test mate """ c0, c1 = move.cords if board[c0].sign == KING: if c0.x - c1.x == 2: return "O-O-O" elif c0.x - c1.x == -2: retu...
if validator.isCheck(board2, board2.color):
if validator.isCheck(board2, 1-board2.color):
def toSAN (board, board2, move, fan=False): """ Returns a Short/Abbreviated Algebraic Notation string of a move The board should be prior to the move, board2 past. If not board2, toSAN will not test mate """ c0, c1 = move.cords if board[c0].sign == KING: if c0.x - c1.x == 2: return "O-O-O" elif c0.x - c1.x == -2: retu...
def reset (self): pass
def reset (self): pass #TODO
hpad, vpad = 7, 1
def draw(self, context): self.dark = self.get_style().dark[gtk.STATE_NORMAL] self.light = self.get_style().light[gtk.STATE_NORMAL] hpad, vpad = 7, 1 #FIXME: The clock will always redraw everything, #while the next line is outcommented #Problem is that saving the redrawingAll in self, #will make natural redraws, as whe...
w = layout1.get_pixel_size()[0] + layout0.get_pixel_size()[0] self.set_size_request(w+hpad*4, self.get_size_request()[1])
w = max(layout1.get_pixel_size()[0], layout0.get_pixel_size()[0])*2 self.set_size_request(w, self.get_size_request()[1])
def draw(self, context): self.dark = self.get_style().dark[gtk.STATE_NORMAL] self.light = self.get_style().light[gtk.STATE_NORMAL] hpad, vpad = 7, 1 #FIXME: The clock will always redraw everything, #while the next line is outcommented #Problem is that saving the redrawingAll in self, #will make natural redraws, as whe...
float(rect.width)/2 * self.player, 0, float(rect.width)/2, rect.height)
rect.width/2. * self.player, 0, rect.width/2., rect.height)
def draw(self, context): self.dark = self.get_style().dark[gtk.STATE_NORMAL] self.light = self.get_style().light[gtk.STATE_NORMAL] hpad, vpad = 7, 1 #FIXME: The clock will always redraw everything, #while the next line is outcommented #Problem is that saving the redrawingAll in self, #will make natural redraws, as whe...
context.move_to(hpad,vpad)
y = rect.height/2. - layout0.get_extents()[0][3]/2/pango.SCALE \ - layout0.get_extents()[0][1]/pango.SCALE context.move_to(0,y)
def draw(self, context): self.dark = self.get_style().dark[gtk.STATE_NORMAL] self.light = self.get_style().light[gtk.STATE_NORMAL] hpad, vpad = 7, 1 #FIXME: The clock will always redraw everything, #while the next line is outcommented #Problem is that saving the redrawingAll in self, #will make natural redraws, as whe...
context.move_to(float(rect.width)/2+hpad,vpad)
y = rect.height/2. - layout1.get_extents()[0][3]/2/pango.SCALE \ - layout1.get_extents()[0][1]/pango.SCALE context.move_to(rect.width/2.,y)
def draw(self, context): self.dark = self.get_style().dark[gtk.STATE_NORMAL] self.light = self.get_style().light[gtk.STATE_NORMAL] hpad, vpad = 7, 1 #FIXME: The clock will always redraw everything, #while the next line is outcommented #Problem is that saving the redrawingAll in self, #will make natural redraws, as whe...
promotion = "q" if len(self.view.history) > 0 and self.view.history[-1][cord0] != None and \ self.view.history[-1][cord0].sign == "p" and cord1.y in [0,7]:
promotion = QUEEN if self.view.history[-1][cord0].sign == PAWN and cord1.y in (0,7):
def emit_move_signal (self, cord0, cord1): promotion = "q" if len(self.view.history) > 0 and self.view.history[-1][cord0] != None and \ self.view.history[-1][cord0].sign == "p" and cord1.y in [0,7]: res = int(self.promotionDialog.run()) self.promotionDialog.hide() if res == int(gtk.RESPONSE_DELETE_EVENT): return promot...
print >> self.engine, "new"
def setBoard (self, history): assert self.ready, "Still waiting for done=1" if self.features["setboard"]: io = StringIO() epd.save(io, history) fen = io.getvalue() print >> self.engine, "force" print >> self.engine, "setboard", fen else: print >> self.engine, "new" # Kludge to set black to move, avoiding the troubleso...
print >> self.engine, "force" if history.curCol() == "black": print >> self.engine, "a2a3"
def setBoard (self, history): assert self.ready, "Still waiting for done=1" if self.features["setboard"]: io = StringIO() epd.save(io, history) fen = io.getvalue() print >> self.engine, "force" print >> self.engine, "setboard", fen else: print >> self.engine, "new" # Kludge to set black to move, avoiding the troubleso...
elif board[cord1].sign == PAWN and abs(cord0.y - cord1.y) == 2:
if board[cord1].sign == PAWN and abs(cord0.y - cord1.y) == 2:
def move (self, move, mvlist=False):
def getBestOpening (history):
def getBestOpening (board):
def getBestOpening (history): score = 0 move = None for m, w, d, l in getOpenings(history): s = (w+d/3.0)*random.random() if not move or s > score: move = m score = s return move
for m, w, d, l in getOpenings(history):
for m, w, d, l in getOpenings(board):
def getBestOpening (history): score = 0 move = None for m, w, d, l in getOpenings(history): s = (w+d/3.0)*random.random() if not move or s > score: move = m score = s return move
omove = getBestOpening(history) if omove: return parseSAN(history,omove)
omove = getBestOpening(history[-1]) if omove: return parseSAN(history[-1],omove)
def makeMove (self, history): if self.analyzing: self.analyzingBoard = len(history) pool.start(self.runAnalyze, history) return None omove = getBestOpening(history) if omove: return parseSAN(history,omove)
mvs, score = alphaBeta(self, history, self.depth, -9999, 9999)
mvs, score = alphaBeta(self, history[-1], self.depth, -9999, 9999)
def makeMove (self, history): if self.analyzing: self.analyzingBoard = len(history) pool.start(self.runAnalyze, history) return None omove = getBestOpening(history) if omove: return parseSAN(history,omove)
mvs, score = alphaBeta(self, history, d+1, -9999, 9999)
mvs, score = alphaBeta(self, history[-1], d+1, -9999, 9999)
def makeMove (self, history): if self.analyzing: self.analyzingBoard = len(history) pool.start(self.runAnalyze, history) return None omove = getBestOpening(history) if omove: return parseSAN(history,omove)
his2 = history.clone() mvs, score = alphaBeta(self, his2, 1, -9999, 9999)
mvs, score = alphaBeta(self, history[-1], 1, -9999, 9999)
def runAnalyze (self, history): self.analyzeLock.acquire() del self.analyzeMoves[:] his2 = history.clone() mvs, score = alphaBeta(self, his2, 1, -9999, 9999) self.analyzeMoves = mvs if mvs: self.emit("analyze", mvs) # TODO: When PyChess is put in its own process, # this should be turned into a loop, seaking deeper and ...
mvs, score = alphaBeta(self, his2, 2, -9999, 9999)
mvs, score = alphaBeta(self, history[-1], 2, -9999, 9999)
def runAnalyze (self, history): self.analyzeLock.acquire() del self.analyzeMoves[:] his2 = history.clone() mvs, score = alphaBeta(self, his2, 1, -9999, 9999) self.analyzeMoves = mvs if mvs: self.emit("analyze", mvs) # TODO: When PyChess is put in its own process, # this should be turned into a loop, seaking deeper and ...
def moves (history):
def moves (board):
def moves (history): #if history.movelist[-1] == None: for m in findMoves2(history): yield m #else: # for cord0, cord1s in history.movelist[-1].iteritems(): # for cord1 in cord1s: # try: # yield movePool.pop(history,cord0,cord1) # except: # pass
for m in findMoves2(history):
for m in findMoves2(board):
def moves (history): #if history.movelist[-1] == None: for m in findMoves2(history): yield m #else: # for cord0, cord1s in history.movelist[-1].iteritems(): # for cord1 in cord1s: # try: # yield movePool.pop(history,cord0,cord1) # except: # pass
if ra or self.player == 0: time0 = self.names[0],self.formatTime(self.getDeciSeconds(0)) layout0 = self.create_pango_layout(" %s: %s " % (time0)) layout0.set_font_description(pango.FontDescription("Sans Serif 17")) if ra or self.player == 1: time1 = self.names[1],self.formatTime(self.getDeciSeconds(1)) layout1 = self....
def draw(self, context): self.dark = self.get_style().dark[gtk.STATE_NORMAL] self.light = self.get_style().light[gtk.STATE_NORMAL] drawClock = True #TODO: move to gconf #FIXME: The clock will always redraw everything, #while the next line is outcommented #Problem is that saving the redrawingAll in self, #will make na...
cr.rectangle(lw/2, y-lw/2, width-lw/2, self.moveHeight+lw/2)
cr.rectangle(lw/2, y-lw/2, width-lw, self.moveHeight+lw)
def draw (self, cr): for score in self.scores: if abs(score) > self.maxScore: self.maxScore = abs(score) width = self.get_allocation().width height = (len(self.scores)-1)*self.moveHeight cr.set_source_rgb (0, 0, 0) cr.rectangle(0,0,width,height) cr.fill() cr.set_source_rgb (1, 1, 1) cr.move_to(0, 0) for i, score in ...
self.names = ["White","Black"]
self.names = [_("White"),_("Black")]
def __init__(self): super(ChessClock, self).__init__() self.connect("expose_event", self.expose) self.names = ["White","Black"] self.setTime(0)
for level, stock in ((_("Beginner"), "stock_weather-few-clouds"), (_("Intermediate"), "stock_weather-cloudy"), (_("Expert"), "stock_weather-storm")): image = it.load_icon(stock, 16, gtk.ICON_LOOKUP_USE_BUILTIN)
for level, stock, altstock in icons: try: image = it.load_icon(stock, 16, gtk.ICON_LOOKUP_USE_BUILTIN) except gobject.GError: image = it.load_icon(altstock, 16, gtk.ICON_LOOKUP_USE_BUILTIN)
def createCombo (combo, data): ls = gtk.ListStore(gtk.gdk.Pixbuf, str) for icon, label in data: ls.append([icon, label]) combo.clear() combo.set_model(ls) crp = gtk.CellRendererPixbuf() crp.set_property('xalign',0) combo.pack_start(crp, False) combo.add_attribute(crp, 'pixbuf', 0) crt = gtk.CellRendererText() crt.set_p...
if board.enpassant.y == 5 and board.color == WHITE or \ board.enpassant.y == 2 and board.color == BLACK:
if (board.enpassant.y == 5 and board.color == WHITE and cord.y = 4) or \ (board.enpassant.y == 2 and board.color == BLACK and cord.y = 3) :
def genPawn (cord, board): direction = board.color == WHITE and 1 or -1 x, y = cord.x, cord.y if not board.data[y+direction][x]: yield x, y+direction row = board.color == WHITE and 1 or 6 if y == row: if not board.data[y+direction*2][x] and \ not board.data[y+direction][x]: yield x, y+direction*2 for side in (1,-1):...
engine, args = random.choice(anaengines[:-1])
if len(anaengines) > 1: engine, args = random.choice(anaengines[:-1]) else: engine, args = anaengines[0]
def runNewGameDialog (hideFC=True): makeNewGameDialogReady () if hideFC: window["ngfcalignment"].hide() else: window["ngfcalignment"].show() res = window["newgamedialog"].run() window["newgamedialog"].hide() if res != gtk.RESPONSE_OK: return if window["useTimeCB"].get_active(): window["ccalign"].show() clock = windo...
elif parts[0].lower().find("illegal") >= 0:
if parts[0].lower().find("illegal") >= 0:
def parseLine (self, line): #self.lock.acquire() parts = multiWs.split(line.strip()) if self.features["sigint"]: self.engine.sigint() # Illegal Move elif parts[0].lower().find("illegal") >= 0: if parts[-2] == "sd" and parts[-1].isdigit(): self.sd = False self.setDepth (int(parts[-1])) # A Move elif self.history: if ...
return
def parseLine (self, line): #self.lock.acquire() parts = multiWs.split(line.strip()) if self.features["sigint"]: self.engine.sigint() # Illegal Move elif parts[0].lower().find("illegal") >= 0: if parts[-2] == "sd" and parts[-1].isdigit(): self.sd = False self.setDepth (int(parts[-1])) # A Move elif self.history: if ...
elif self.history:
if self.history:
def parseLine (self, line): #self.lock.acquire() parts = multiWs.split(line.strip()) if self.features["sigint"]: self.engine.sigint() # Illegal Move elif parts[0].lower().find("illegal") >= 0: if parts[-2] == "sd" and parts[-1].isdigit(): self.sd = False self.setDepth (int(parts[-1])) # A Move elif self.history: if ...
elif len(parts) >= 5 and self.forced and isdigits(parts[1:4]):
if len(parts) >= 5 and self.forced and isdigits(parts[1:4]):
def parseLine (self, line): #self.lock.acquire() parts = multiWs.split(line.strip()) if self.features["sigint"]: self.engine.sigint() # Illegal Move elif parts[0].lower().find("illegal") >= 0: if parts[-2] == "sd" and parts[-1].isdigit(): self.sd = False self.setDepth (int(parts[-1])) # A Move elif self.history: if ...
elif parts[0] == "offer" and parts[1] == "draw":
if parts[0] == "offer" and parts[1] == "draw":
def parseLine (self, line): #self.lock.acquire() parts = multiWs.split(line.strip()) if self.features["sigint"]: self.engine.sigint() # Illegal Move elif parts[0].lower().find("illegal") >= 0: if parts[-2] == "sd" and parts[-1].isdigit(): self.sd = False self.setDepth (int(parts[-1])) # A Move elif self.history: if ...
elif line.find("resign") >= 0:
if line.find("resign") >= 0:
def parseLine (self, line): #self.lock.acquire() parts = multiWs.split(line.strip()) if self.features["sigint"]: self.engine.sigint() # Illegal Move elif parts[0].lower().find("illegal") >= 0: if parts[-2] == "sd" and parts[-1].isdigit(): self.sd = False self.setDepth (int(parts[-1])) # A Move elif self.history: if ...
elif parts[0] in ("tellusererror", "Error"):
if parts[0] in ("tellusererror", "Error"):
def parseLine (self, line): #self.lock.acquire() parts = multiWs.split(line.strip()) if self.features["sigint"]: self.engine.sigint() # Illegal Move elif parts[0].lower().find("illegal") >= 0: if parts[-2] == "sd" and parts[-1].isdigit(): self.sd = False self.setDepth (int(parts[-1])) # A Move elif self.history: if ...
elif parts[0][:4] == "tell" and \
if parts[0][:4] == "tell" and \
def parseLine (self, line): #self.lock.acquire() parts = multiWs.split(line.strip()) if self.features["sigint"]: self.engine.sigint() # Illegal Move elif parts[0].lower().find("illegal") >= 0: if parts[-2] == "sd" and parts[-1].isdigit(): self.sd = False self.setDepth (int(parts[-1])) # A Move elif self.history: if ...
pass
return
def parseLine (self, line): #self.lock.acquire() parts = multiWs.split(line.strip()) if self.features["sigint"]: self.engine.sigint() # Illegal Move elif parts[0].lower().find("illegal") >= 0: if parts[-2] == "sd" and parts[-1].isdigit(): self.sd = False self.setDepth (int(parts[-1])) # A Move elif self.history: if ...
elif parts[0].lower() in ("illegal", "error"):
if parts[0].lower() in ("illegal", "error"):
def parseLine (self, line): #self.lock.acquire() parts = multiWs.split(line.strip()) if self.features["sigint"]: self.engine.sigint() # Illegal Move elif parts[0].lower().find("illegal") >= 0: if parts[-2] == "sd" and parts[-1].isdigit(): self.sd = False self.setDepth (int(parts[-1])) # A Move elif self.history: if ...
elif parts.count("feature") > 0: for i, pair in enumerate(parts[j+1:]):
if parts[0] == "feature": for i, pair in enumerate(parts[1:]):
def parseLine (self, line): #self.lock.acquire() parts = multiWs.split(line.strip()) if self.features["sigint"]: self.engine.sigint() # Illegal Move elif parts[0].lower().find("illegal") >= 0: if parts[-2] == "sd" and parts[-1].isdigit(): self.sd = False self.setDepth (int(parts[-1])) # A Move elif self.history: if ...
rest = value[1:]+" "+" ".join(parts[2+i+j:])
rest = value[1:]+" "+" ".join(parts[2+i:])
def parseLine (self, line): #self.lock.acquire() parts = multiWs.split(line.strip()) if self.features["sigint"]: self.engine.sigint() # Illegal Move elif parts[0].lower().find("illegal") >= 0: if parts[-2] == "sd" and parts[-1].isdigit(): self.sd = False self.setDepth (int(parts[-1])) # A Move elif self.history: if ...
ra = self.redrawingAll
ra = True
def draw(self, context): self.dark = self.get_style().dark[gtk.STATE_NORMAL] self.light = self.get_style().light[gtk.STATE_NORMAL] hpad, vpad = 7, 1 ra = self.redrawingAll if ra or self.player == 0: time0 = self.names[0],self.formatTime(self.getDeciSeconds(0)) layout0 = self.create_pango_layout("%s: %s" % (time0)) la...
elif len(history) >= 2:
elif len(history) >= 2 and y in (2,5):
def genPawn (cord, history): board = history[-1] direction = history.curCol() == "white" and 1 or -1 x, y = cord.x, cord.y if not board.data[y+direction][x]: yield x, y+direction row = history.curCol() == "white" and 1 or 6 if y == row: if not board.data[y+direction*2][x] and \ not board.data[y+direction][x]: yield x...
a1 = Cord('a1') h1 = Cord('h1') a8 = Cord('a8') h8 = Cord('h8')
a1 = Cord('a1'); d1 = Cord('d1') h1 = Cord('h1'); f1 = Cord('f1') a8 = Cord('a8'); d8 = Cord('d8') h8 = Cord('h8'); f8 = Cord('f8')
def rm (var, opp): if var & opp: return var ^ opp return var
self.myhash ^= zobrit[piece.color][piece.sign][x][y]
try: self.myhash ^= zobrit[piece.color][piece.sign][x][y] except: print [piece.color,piece.sign,x,y] def _move (self, cord0, cord1): p = self[cord0] self.myhash = self.myhash ^ zobrit[p.color][p.sign][cord0.x][cord0.y] self.myhash = self.myhash ^ zobrit[p.color][p.sign][cord1.x][cord1.y] self[cord1] = p self[cord0] = ...
def __init__ (self, array): self.data = array self.enpassant = None self.movelist = None self.color = WHITE self.castling = WHITE_OO | WHITE_OOO | BLACK_OO | BLACK_OOO self.status = RUNNING self.fifty = 0 self.myhash = 0 for y, row in enumerate(self.data): for x, piece in enumerate(row): if not piece: continue self.myh...
board.myhash = self.myhash ^ zobrit[p.color][p.sign][cord0.x][cord0.y] board.myhash = self.myhash ^ zobrit[p.color][p.sign][cord1.x][cord1.y]
if not p: print move,"\n",board raise Exception
def move (self, move, mvlist=False): board = self.clone() board.movelist = None cord0, cord1 = move.cords p = board[cord0] board.myhash = self.myhash ^ zobrit[p.color][p.sign][cord0.x][cord0.y] board.myhash = self.myhash ^ zobrit[p.color][p.sign][cord1.x][cord1.y] if p.sign == KING: r = cord0.y if cord0.x - cord1.x =...
r = cord0.y if cord0.x - cord1.x == -2: board.data[r][5] = board.data[r][7] board.data[r][7] = None elif cord0.x - cord1.x == 2: board.data[r][3] = board.data[r][0] board.data[r][0] = None
if cord0.y == 0: if cord0.x - cord1.x == 2: board._move(a1, d1) elif cord0.x - cord1.x == -2: board._move(h1, f1) else: if cord0.x - cord1.x == 2: board._move(a8, d8) elif cord0.x - cord1.x == -2: board._move(h8, f8)
def move (self, move, mvlist=False): board = self.clone() board.movelist = None cord0, cord1 = move.cords p = board[cord0] board.myhash = self.myhash ^ zobrit[p.color][p.sign][cord0.x][cord0.y] board.myhash = self.myhash ^ zobrit[p.color][p.sign][cord1.x][cord1.y] if p.sign == KING: r = cord0.y if cord0.x - cord1.x =...
board.data[cord1.x][cord0.y] = None board[cord1] = p board[cord0] = None
q = board.data[cord1.y][cord0.x] if q: board.myhash = board.myhash ^ zobrit[q.color][q.sign][cord1.x][cord0.y] board.data[cord1.y][cord0.x] = None elif p.sign == PAWN and cord1.y in (0,7): q = board[cord0] board.myhash = board.myhash ^ zobrit[q.color][q.sign][cord0.x][cord0.y] board[cord0] = Piece(q.color, move.promot...
def move (self, move, mvlist=False): board = self.clone() board.movelist = None cord0, cord1 = move.cords p = board[cord0] board.myhash = self.myhash ^ zobrit[p.color][p.sign][cord0.x][cord0.y] board.myhash = self.myhash ^ zobrit[p.color][p.sign][cord1.x][cord1.y] if p.sign == KING: r = cord0.y if cord0.x - cord1.x =...
self.enpassant = Cord(cord0.x, (cord0.y+cord1.y)/2) else: self.enpassant = None
board.enpassant = Cord(cord0.x, (cord0.y+cord1.y)/2) else: board.enpassant = None
def move (self, move, mvlist=False): board = self.clone() board.movelist = None cord0, cord1 = move.cords p = board[cord0] board.myhash = self.myhash ^ zobrit[p.color][p.sign][cord0.x][cord0.y] board.myhash = self.myhash ^ zobrit[p.color][p.sign][cord1.x][cord1.y] if p.sign == KING: r = cord0.y if cord0.x - cord1.x =...
continue
break
def parseLine (self, line): #self.lock.acquire() parts = multiWs.split(line.strip()) if self.features["sigint"]: self.engine.sigint() # Illegal Move if parts[0].lower().find("illegal") >= 0: if parts[-2] == "sd" and parts[-1].isdigit(): self.sd = False self.setDepth (int(parts[-1])) return # A Move if self.history: ...
scroll.set_usize(width, height)
scroll.set_size_request(width, height)
def newMessage (log, task, message, type): if not task in task2book: view = gtk.TextView () view.set_editable(False) vp = gtk.Viewport() vp.set_shadow_type(gtk.SHADOW_NONE) vp.add(view) scroll = gtk.ScrolledWindow() scroll.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC) scroll.set_usize(width, height) scroll.a...
ANIMATION_TIME = 15
ANIMATION_TIME = .15
def rect (r): x, y = [int(floor(v)) for v in r[:2]] w = int(ceil(r[2])) if len(r) == 4: h = int(ceil(r[3])) else: h = w return gtk.gdk.Rectangle (x, y, w, h)
if self.shown != 0: self.lastMove = self.history.moves[self.shown-1] else: self.lastMove = None
if step > 0: if self.shown != 0: self.lastMove = self.history.moves[self.shown-1] else: self.lastMove = None
def do(): self.runAnimation(first = True) if self.shown != 0: self.lastMove = self.history.moves[self.shown-1] else: self.lastMove = None self.animationID = idle_add(self.runAnimation)
text = " "
text = u" "
def _update(self, redraw=True): """ This is called after this widget has been updated by set_text or set_style. """
return (0, 0, w, h), [ (0, 0, w, h) ]
return (0, 0, sw, sh), [ (0, 0, sw, sh) ]
def compute_clip(source): """ This computes and returns the clipping rectangle of the source render. """ global old_blits global old_forced new_blits = [ ] forced = [ ] source.clip_to(0, 0, new_blits, forced) bl0 = old_blits[:] bl1 = new_blits[:] # Backup blits. old_blits = new_blits # Changes between the two list...
return (0, 0, w, h), [ (0, 0, w, h) ]
return (0, 0, sw, sh), [ (0, 0, sw, sh) ] if w * h >= sa: return (0, 0, sw, sh), [ (0, 0, sw, sh) ]
def compute_clip(source): """ This computes and returns the clipping rectangle of the source render. """ global old_blits global old_forced new_blits = [ ] forced = [ ] source.clip_to(0, 0, new_blits, forced) bl0 = old_blits[:] bl1 = new_blits[:] # Backup blits. old_blits = new_blits # Changes between the two list...
with(None)
renpy.exports.with(None)
def display_say(who, what, who_style='say_label', what_style='say_dialogue', window_style='say_window', who_prefix='', who_suffix=': ', what_prefix='', what_suffix='', interact=True, slow=True, slow_speed=None, slow_abortable=True, image=False, afm=True, ctc=None, ctc_position="nestled", all_at_once=False, what_propert...
path, position = treeview.get_dest_row_at_pos(x, y)
if not treeview.get_dest_row_at_pos(x, y)==None: path, position = treeview.get_dest_row_at_pos(x, y) else: path = last_visible(None, model, treeview) position = gtk.TREE_VIEW_DROP_AFTER
def drag_data_received_data(treeview, context, x, y, selection, info, etime): model = treeview.get_model() data = selection.data global src_iter temp_dict = {} if data[:4]=="http": data = string.split(data, "?") data[1] = string.split(data[1], "&") for row in data[1]: key, content = string.split(row, "=") content = str...
if position == gtk.TREE_VIEW_DROP_BEFORE:
if src_iter==iter: pass elif position == gtk.TREE_VIEW_DROP_BEFORE:
def drag_data_received_data(treeview, context, x, y, selection, info, etime): model = treeview.get_model() data = selection.data global src_iter temp_dict = {} if data[:4]=="http": data = string.split(data, "?") data[1] = string.split(data[1], "&") for row in data[1]: key, content = string.split(row, "=") content = str...