code
stringlengths
1
1.72M
language
stringclasses
1 value
#!/usr/bin/env python import time t = time.time() u = time.gmtime(t) s = time.strftime('%a, %e %b %Y %T GMT', u) print 'Content-Type: text/javascript' print 'Cache-Control: no-cache' print 'Date: ' + s print 'Expires: ' + s print '' print 'var timeskew = new Date().getTime() - ' + str(t*1000) + ';'
Python
# Adapted for numpy/ma/cdms2 by convertcdms.py import _vcs import vcs,cdtime,queries import numpy class PPE(Exception): def __init__ (self, parameter,type): self.parameter=parameter self.type=type def __str__(self): return 'Projection Parameter Error: Parameter "'+self.parameter+'" is not settable for projection type:'+str(self.type) ## def checkPythonOnly(name): ## if name in []: ## return 1 ## else: ## return 0 def color2vcs(col): if isinstance(col,str): r,g,b=vcs.colors.str2rgb(col) if r is None : r,g,b=[0,0,0] # black by default # Now calls the function that matches the closest color in the the colormap color=matchVcsColor(r/2.55,g/2.55,b/2.55) else: color = col return color def matchVcsColor(r,g,b): rmsmin=100000000. color=None for i in range(256): r2,g2,b2=_vcs.getcolorcell(i) rms=numpy.sqrt((r2-r)**2+(g2-g)**2+(b2-b)**2) if rms<rmsmin : rmsmin=rms color=i return color def checkElements(self,name,value,function): if not isinstance(value,list): raise ValueError,'Error type for %s, you must pass a list' % name for i in range(len(value)): try: value[i] = function(self,name,value[i]) except Exception,err: raise ValueError, '%s failed while checking validity of element: %s\nError message was: %s' % (name, repr(value[i]),err) return value def checkContType(self,name,value): checkName(self,name,value) checkInt(self,name,value,minvalue=0) return value def checkLine(self,name,value): checkName(self,name,value) if not isinstance(value,(str,vcs.line.Tl)): raise ValueError, name+' must be an line primitive or the name of an exiting one.' if isinstance(value,str): if not value in _vcs.listelements('line'): raise ValueError, name+' is not an existing line primitive' value=self.x.getline(value) return value ## def checkIsoline(self,name,value): ## checkName(self,name,value) ## if not isinstance(value,(str,vcs.isoline.Gi)): ## raise ValueError, name+' must be an isoline graphic method or the name of an exiting one.' ## if isinstance(value,str): ## if not value in self.x.listelements('isoline'): ## raise ValueError, name+' is not an existing isoline graphic method' ## value=self.x.getisoline(value) ## return value ## def checkIsofill(self,name,value): ## checkName(self,name,value) ## if not isinstance(value,(str,vcs.isofill.Gfi)): ## raise ValueError, name+' must be an isofill graphic method or the name of an exiting one.' ## if isinstance(value,str): ## if not value in self.x.listelements('isofill'): ## raise ValueError, name+' is not an existing isofill graphic method' ## value=self.x.getisofill(value) ## return value def isNumber(value,min=None,max=None): """ Checks if value is a Number, optionaly can check if min<value<max """ try: value=value.tolist() # converts MA/MV/numpy except: pass if not isinstance(value,(int,long,float,numpy.floating)): return False if min is not None and value<min: return -1 if max is not None and value>max: return -2 return True def checkNumber(self,name,value,minvalue=None,maxvalue=None): checkName(self,name,value) try: value=value.tolist() # converts MA/MV/numpy except: pass n=isNumber(value,min=minvalue,max=maxvalue) if n is False: raise ValueError, name+' must be a number' if n==-1: raise ValueError, name+' values must be at least '+str(minvalue) if n==-2: raise ValueError, name+' values must be at most '+str(maxvalue) return value def checkInt(self,name,value,minvalue=None,maxvalue=None): checkName(self,name,value) n=checkNumber(self,name,value,minvalue=minvalue,maxvalue=maxvalue) if not isinstance(n,int): raise ValueError, name+' must be an integer' return n def checkListOfNumbers(self,name,value,minvalue=None,maxvalue=None,minelements=None,maxelements=None,ints=False): checkName(self,name,value) if not isinstance(value,(list,tuple)): raise ValueError, name+' must be a list or tuple' n=len(value) if minelements is not None and n<minelements: raise ValueError, name+' must have at least '+str(minelements)+' elements' if maxelements is not None and n>maxelements: raise ValueError, name+' must have at most '+str(maxelements)+' elements' for v in value: if ints: checkInt(self,name,v,minvalue=minvalue,maxvalue=maxvalue) else: checkNumber(self,name,v,minvalue=minvalue,maxvalue=maxvalue) return list(value) def checkFont(self,name,value): if (value == None): pass elif isNumber(value,min=1): value=int(value) # try to see if font exists nm = _vcs.getfontname(value) elif isinstance(value,str): value = _vcs.getfontnumber(value) else: nms = _vcs.listelements("font") raise ValueError, 'Error for attribute %s: The font attribute values must be a valid font number or a valid font name. valid names are: %s' % (name,', '.join(nms)) return value def checkMarker(self,name,value): checkName(self,name,value) if ((value in (None, 'dot', 'plus', 'star', 'circle', 'cross', 'diamond', 'triangle_up', 'triangle_down', 'triangle_down', 'triangle_left', 'triangle_right', 'square', 'diamond_fill','triangle_up_fill','triangle_down_fill','triangle_left_fill','triangle_right_fill','square_fill','hurricane','w00','w01','w02','w03','w04','w05','w06','w07', 'w08','w09','w10','w11','w12','w13','w14','w15','w16','w17','w18','w19','w20','w21','w22','w23','w24','w25','w26','w27','w28','w29','w30','w31','w32','w33','w34','w35','w36', 'w37','w38','w39','w40','w41','w42','w43','w44','w45','w46','w47','w48','w49','w50','w51','w52','w53','w54','w55','w56','w57','w58','w59','w60','w61','w62','w63','w64','w65', 'w66','w67','w68','w69','w70','w71','w72','w73','w74','w75','w76','w77','w78','w79','w80','w81','w82','w83','w84','w85','w86','w87','w88','w89','w90','w91','w92','w93','w94', 'w95','w96','w97','w98','w99','w200','w201','w202', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ,15, 16, 17, 18, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114,115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202 )) or (queries.ismarker(value)==1)): if value in (None, 0): value=None elif value in ('dot', 1): value='dot' elif value in ('plus', 2): value='plus' elif value in ('star', 3): value='star' elif value in ('circlet', 4): value='circle' elif value in ('cross', 5): value='cross' elif value in ('diamond', 6): value='diamond' elif value in ('triangle_up', 7): value='triangle_up' elif value in ('triangle_down', 8): value='triangle_down' elif value in ('triangle_left', 9): value='triangle_left' elif value in ('triangle_right', 10): value='triangle_right' elif value in ('square', 11): value='square' elif value in ('diamond_fill', 12): value='diamond_fill' elif value in ('triangle_up_fill', 13): value='triangle_up_fill' elif value in ('triangle_down_fill', 14): value='triangle_down_fill' elif value in ('triangle_left_fill', 15): value='triangle_left_fill' elif value in ('triangle_right_fill', 16): value='triangle_right_fill' elif value in ('square_fill', 17): value='square_fill' elif value in ('hurricane', 18): value='hurricane' elif value in ('w00', 100): value='w00' elif value in ('w01', 101): value='w01' elif value in ('w02', 102): value='w02' elif value in ('w03', 103): value='w03' elif value in ('w04', 104): value='w04' elif value in ('w05', 105): value='w05' elif value in ('w06', 106): value='w06' elif value in ('w07', 107): value='w07' elif value in ('w08', 108): value='w08' elif value in ('w09', 109): value='w09' elif value in ('w10', 110): value='w10' elif value in ('w11', 111): value='w11' elif value in ('w12', 112): value='w12' elif value in ('w13', 113): value='w13' elif value in ('w14', 114): value='w14' elif value in ('w15', 115): value='w15' elif value in ('w16', 116): value='w16' elif value in ('w17', 117): value='w17' elif value in ('w18', 118): value='w18' elif value in ('w19', 119): value='w19' elif value in ('w20', 120): value='w20' elif value in ('w21', 121): value='w21' elif value in ('w22', 122): value='w22' elif value in ('w23', 123): value='w23' elif value in ('w24', 124): value='w24' elif value in ('w25', 125): value='w25' elif value in ('w26', 126): value='w26' elif value in ('w27', 127): value='w27' elif value in ('w28', 128): value='w28' elif value in ('w29', 129): value='w29' elif value in ('w30', 130): value='w30' elif value in ('w31', 131): value='w31' elif value in ('w32', 132): value='w32' elif value in ('w33', 133): value='w33' elif value in ('w34', 134): value='w34' elif value in ('w35', 135): value='w35' elif value in ('w36', 136): value='w36' elif value in ('w37', 137): value='w37' elif value in ('w38', 138): value='w38' elif value in ('w39', 139): value='w39' elif value in ('w40', 140): value='w40' elif value in ('w41', 141): value='w41' elif value in ('w42', 142): value='w42' elif value in ('w43', 143): value='w43' elif value in ('w44', 144): value='w44' elif value in ('w45', 145): value='w45' elif value in ('w46', 146): value='w46' elif value in ('w47', 147): value='w47' elif value in ('w48', 148): value='w48' elif value in ('w49', 149): value='w49' elif value in ('w50', 150): value='w50' elif value in ('w51', 151): value='w51' elif value in ('w52', 152): value='w52' elif value in ('w53', 153): value='w53' elif value in ('w54', 154): value='w54' elif value in ('w55', 155): value='w55' elif value in ('w56', 156): value='w56' elif value in ('w57', 157): value='w57' elif value in ('w58', 158): value='w58' elif value in ('w59', 159): value='w59' elif value in ('w60', 160): value='w60' elif value in ('w61', 161): value='w61' elif value in ('w62', 162): value='w62' elif value in ('w63', 163): value='w63' elif value in ('w64', 164): value='w64' elif value in ('w65', 165): value='w65' elif value in ('w66', 166): value='w66' elif value in ('w67', 167): value='w67' elif value in ('w68', 168): value='w68' elif value in ('w69', 169): value='w69' elif value in ('w70', 170): value='w70' elif value in ('w71', 171): value='w71' elif value in ('w72', 172): value='w72' elif value in ('w73', 173): value='w73' elif value in ('w74', 174): value='w74' elif value in ('w75', 175): value='w75' elif value in ('w76', 176): value='w76' elif value in ('w77', 177): value='w77' elif value in ('w78', 178): value='w78' elif value in ('w79', 179): value='w79' elif value in ('w80', 180): value='w80' elif value in ('w81', 181): value='w81' elif value in ('w82', 182): value='w82' elif value in ('w83', 183): value='w83' elif value in ('w84', 184): value='w84' elif value in ('w85', 185): value='w85' elif value in ('w86', 186): value='w86' elif value in ('w87', 187): value='w87' elif value in ('w88', 188): value='w88' elif value in ('w89', 189): value='w89' elif value in ('w90', 190): value='w90' elif value in ('w91', 191): value='w91' elif value in ('w92', 192): value='w92' elif value in ('w93', 193): value='w93' elif value in ('w94', 194): value='w94' elif value in ('w95', 195): value='w95' elif value in ('w96', 196): value='w96' elif value in ('w97', 197): value='w97' elif value in ('w98', 198): value='w98' elif value in ('w99', 199): value='w99' elif value in ('w200',200): value='w200' elif value in ('w201', 201): value='w201' elif value in ('w202', 202): value='w202' elif (queries.ismarker(value)==1): value=value.name else: error=""" value can either be (None, "dot", "plus", "star", "circle", "cross", "diamond", "triangle_up", "triangle_down", "triangle_left", "triangle_right","square","diamond_fill","triangle_up_fill","triangle_down_fill","triangle_left_fill","triangle_right_fill","square_fill","hurricane","w00","w01","w02","w03", "w04","w05","w06","w07","w08","w09","w10","w11","w12","w13","w14","w15","w16","w17","w18","w19","w20","w21","w22","w23","w24","w25","w26","w27","w28","w29","w30","w31","w32", "w33","w34","w35","w36","w37","w38","w39","w40","w41","w42","w43","w44","w45","w46","w47","w48","w49","w50","w51","w52","w53","w54","w55","w56","w57","w58","w59","w60","w61", "w62","w63","w64","w65","w66","w67","w68","w69","w70","w71","w72","w73","w74","w75","w76","w77","w78","w79","w80","w81","w82","w83","w84","w85","w86","w87","w88","w89","w90", "w91","w92","w93","w94","w95","w96","w97","w98","w99","w200","w201","w202") or (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ,15, 16, 17, 18, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202 ) or a marker object.""" raise ValueError, 'The '+ name + error return value def checkMarkersList(self,name,value): checkName(self,name,value) if isinstance(value,int): value=list(value) value=checkListTuple(self,name,value) hvalue = [] for v in value: hvalue.append(checkMarker(self,name,v)) return hvalue def checkListElements(self,name,value,function): checkName(self,name,value) if not isinstance(value,(list,tuple)): raise ValueError, "Attribute %s must be a list" % name for v in value: try: v = function(self,name,v) except Exception,err: raise ValueError, "element %s of attribute %s list failed type compliance\n error was: %s" % (repr(v),name,err) return value def isListorTuple(value): if isinstance(value,(list,tuple)): return 1 return 0 def checkName(self, name, value): if hasattr(self,'name'): if (self.name == '__removed_from_VCS__'): raise ValueError, 'This instance has been removed from VCS.' if (self.name == 'default'): raise ValueError, 'You cannot modify the default' def checkname(self,name,value): checkName(self,name,value) if isinstance(value,str): if value!='__removed_from_VCS__': self.rename(self.name, value) return value else: self._name=value return None else: raise ValueError, 'The name attribute must be a string.' def checkString(self,name,value): checkName(self,name,value) if isinstance(value,str): return value else: raise ValueError, 'The '+name+' attribute must be a string.' def checkCallable(self,name,value): checkName(self,name,value) if callable(value): return value else: raise ValueError, 'The '+name+' attribute must be callable.' ## def checkFillAreaStyle(self,name,value): ## checkName(self,name,value) ## if not isinstance(value,str): ## raise ValueError,'The fillarea attribute must be a string' ## if not value.lower() in ['solid','hatch','pattern']: ## raise ValueError, 'The fillarea attribute must be either solid, hatch, or pattern.' ## return value def checkFillAreaStyle(self,name,value): checkName(self,name,value) if ((value in ('solid', 'hatch', 'pattern', 'hallow', 0, 1, 2, 3)) or (queries.isfillarea(value)==1)): if value in ('solid', 0): value='solid' elif value in ('hatch', 1): value='hatch' elif value in ('pattern', 2): value='pattern' elif value in ('hallow', 3): value='hallow' elif (queries.isfillarea(value)==1): value=value.name else: raise ValueError, 'The '+name+' attribute must be either solid, hatch, or pattern.' return value def checkAxisConvert(self,name,value): checkName(self,name,value) if isinstance(value,str) and (value.lower() in ('linear', 'log10', 'ln','exp','area_wt')): return value.lower() else: raise ValueError, 'The '+name+' attribute must be either: linear, log10, ln, exp, or area_wt' def checkBoxfillType(self,name,value): checkName(self,name,value) if isinstance(value,str) and (value.lower() in ('linear', 'log10', 'custom')): return value.lower() else: raise ValueError, 'The '+name+' attribute must be either: linear, log10 or custom' def checkIntFloat(self,name,value): try: value=value.tolist() # converts MA/MV/numpy except: pass if isinstance(value,(int,float,numpy.floating)): return float(value) else: raise ValueError, 'The '+name+' attribute must be either an integer or a float value.' ## def checkInt(self,name,value): ## checkName(self,name,value) ## if isinstance(value,int): ## return value ## else: ## raise ValueError, 'The '+name+' attribute must be either an integer or a float value.' def checkOnOff(self,name,value,return_string=0): checkName(self,name,value) if value is None: value = 0 elif isinstance(value,str): if value.lower() in ['on','1','y','yes']: value = 1 elif value.lower() in ['off','0','n','no']: value = 0 else: raise ValueError, "The "+name+" attribute must be either 1/0, 'on'/'off', 'y'/'n' or 'yes'/'no'" elif isNumber(value): if value==0. or value==1.: value = int(value) else: raise ValueError, "The "+name+" attribute must be either 1/0, 'on'/'off', 'y'/'n' or 'yes'/'no'" else: raise ValueError, "The "+name+" attribute must be either 1/0, 'on'/'off', 'y'/'n' or 'yes'/'no'" if return_string: if value: return 'y' else: return 'n' elif return_string!=0: if value: return 'on' else: return 'off' else: return value def checkYesNo(self,name,value): checkName(self,name,value) if value is None: value = 'n' elif isinstance(value,str): if value.lower() in ['on','1','y','yes']: value = 'y' elif value.lower() in ['off','0','n','no']: value = 'n' else: raise ValueError, "The "+name+" attribute must be either 1/0, 'on'/'off', 'y'/'n' or 'yes'/'no'" elif isNumber(value): if value==0.: value='n' elif value==1.: value = 'y' else: raise ValueError, "The "+name+" attribute must be either 1/0, 'on'/'off', 'y'/'n' or 'yes'/'no'" else: raise ValueError, "The "+name+" attribute must be either 1/0, 'on'/'off', 'y'/'n' or 'yes'/'no'" return value def checkWrap(self,name,value): checkName(self,name,value) if isinstance(value,tuple) : value=list(value) if value is None: value = [0,0] if isinstance(value,list): return value else: raise ValueError, 'The '+name+' attribute must be either None or a list.' def checkListTuple(self,name,value): checkName(self,name,value) if isinstance(value,list) or isinstance(value,tuple): return list(value) else: raise ValueError, 'The '+name+' attribute must be either a list or a tuple.' def checkColor(self,name,value): checkName(self,name,value) if isinstance(value,str): value = color2vcs(value) if isinstance(value,int) and value in range(0,256): return value else: raise ValueError, 'The '+name+' attribute must be an integer value within the range 0 to 255.' def checkColorList(self,name,value): checkName(self,name,value) value=checkListTuple(self,name,value) for v in value:checkColor(self,name+'_list_value',v) return value def checkIsolineLevels(self,name,value): checkName(self,name,value) value=checkListTuple(self,name,value) hvalue=[] for v in value: if isinstance(v,(list,tuple)): if (len(v) == 2): hvalue.append(list(v)) else: for j in range(len(v)): hvalue.append([v[j],0]) elif isNumber(v): hvalue.append([float(v),0]) return hvalue def checkIndex(self,name,value): checkName(self,name,value) if ((value not in range(1,21)) and (queries.isfillarea(value)==0)): raise ValueError, 'The '+name+' values must be in the range 1 to 18 or provide one or more fillarea objects.' elif (queries.isfillarea(value)==1): value=value.name return value def checkIndicesList(self,name,value): checkName(self,name,value) value=checkListTuple(self,name,value) hvalue=[] for v in value: v=checkIndex(self,name,v) hvalue.append(v) return hvalue def checkVectorType(self,name,value): checkName(self,name,value) if value in ('arrows', 0): hvalue = 'arrows' elif value in ('barbs', 1): hvalue = 'barbs' elif value in ('solidarrows', 2): hvalue = 'solidarrows' else: raise ValueError, 'The '+name+' can either be ("arrows", "barbs", "solidarrows") or (0, 1, 2).' return hvalue def checkVectorAlignment(self,name,value): checkName(self,name,value) if value in ('head', 0): hvalue = 'head' elif value in ('center', 1): hvalue = 'center' elif value in ('tail', 2): hvalue = 'tail' else: raise ValueError, 'The '+name+' can either be ("head", "center", "tail") or (0, 1, 2).' return hvalue def checkLineType(self,name,value): checkName(self,name,value) if value in ('solid', 0): hvalue = 'solid' elif value in ('dash', 1): hvalue = 'dash' elif value in ('dot', 2): hvalue = 'dot' elif value in ('dash-dot', 3): hvalue = 'dash-dot' elif value in ('long-dash', 4): hvalue = 'long-dash' elif (queries.isline(value)==1): hvalue = value.name else: raise ValueError, 'The '+name+' can either be ("solid", "dash", "dot", "dash-dot", "long-dash"), (0, 1, 2, 3, 4), or a line object.' return hvalue def checkLinesList(self,name,value): checkName(self,name,value) if isinstance(value,int): value=list(value) value=checkListTuple(self,name,value) hvalue = [] for v in value: hvalue.append(checkLineType(self,name,v)) return hvalue def checkTextTable(self,name,value): checkName(self,name,value) if isinstance(value,str): if not value in self.parent.parent.listelements("texttable"): raise "Error : not a valid texttable" elif not isinstance(value,vcs.texttable.Tt): raise "Error you must pass a texttable objector a texttable name" else: return value.name return value def checkTextOrientation(self,name,value): checkName(self,name,value) if isinstance(value,str): if not value in self.parent.parent.listelements("textorientation"): raise "Error : not a valid textorientation" elif not isinstance(value,vcs.textorientation.To): raise "Error you must pass a textorientation objector a textorientation name" else: return value.name return value def checkTextsList(self,name,value): checkName(self,name,value) if isinstance(value,int): value=list(value) value=checkListTuple(self,name,value) hvalue = [] for v in value: if v in range(1,10): hvalue.append(v) elif ((queries.istexttable(v)==1) and (queries.istextorientation(v)==0)): name='__Tt__.'+ v.name hvalue.append(name) elif ((queries.istexttable(v)==0) and (queries.istextorientation(v)==1)): name='__To__.'+ v.name hvalue.append(name) elif (queries.istextcombined(v)==1): name=v.Tt_name + '__' + v.To_name hvalue.append(name) return hvalue def checkLegend(self,name,value): checkName(self,name,value) if isinstance(value,dict): return value elif isNumber(value): try: value= value.tolist() except: pass return {value:repr(value)} elif isinstance(value,(list,tuple)): ret={} for v in value: ret[v]=repr(v) return ret elif value is None: return None else: raise ValueError, 'The '+name+' attribute should be a dictionary !' ## def checkListTupleDictionaryNone(self,name,value): ## checkName(self,name,value) ## if isinstance(value,int) or isinstance(value,float) \ ## or isinstance(value,list) or isinstance(value,tuple) or isinstance(value,dict): ## if isinstance(value,int) or isinstance(value,float): ## value=list((value,)) ## elif isinstance(value,list) or isinstance(value,tuple): ## value=list(value) ## if isinstance(value,list): ## d={} ## for i in range(len(value)): ## d[value[i]]=repr(value[i]) ## else: ## d=value ## return d ## elif value is None: ## return value ## else: ## raise ValueError, 'The '+name+' attribute must be a List, Tuple, Dictionary, or None' def checkExt(self,name,value): checkName(self,name,value) if isinstance(value,str): if (value in ('n', 'y')): if ( ((value == 'n') and (getattr(self,'_'+name) == 'n')) or ((value == 'y') and (getattr(self,'_'+name) == 'y')) ): # do nothing return else: return 1 else: raise ValueError, 'The ext_1 attribute must be either n or y.' else: raise ValueError, 'The '+name+' attribute must be a string' def checkProjection(self,name,value): checkName(self,name,value) if isinstance(value,vcs.projection.Proj): value=value.name if isinstance(value,str): if (_vcs.checkProj(value)): return value else: raise ValueError, 'The '+value+' projection does not exist' def checkStringDictionary(self,name,value): checkName(self,name,value) if isinstance(value,str) or isinstance(value,dict): return value else: raise ValueError, 'The '+name+' attribute must be either a string or a dictionary' def deg2DMS(val): """ converts degrees to DDDMMMSSS.ss format""" ival=int(val) out=float(ival) ftmp=val-out out=out*1000000. itmp=int(ftmp*60.) out=out+float(itmp)*1000. ftmp=ftmp-float(itmp)/60. itmp=ftmp*3600. out=out+float(itmp) ftmp=ftmp-float(itmp)/3600. out=out+ftmp return out def DMS2deg(val): """converts DDDMMMSSS to degrees""" if val>1.e19: return val ival=int(val) s=str(ival).zfill(9) deg=float(s[:3]) mn=float(s[3:6]) sec=float(s[6:9]) r=val-ival ## print deg,mn,sec,r return deg+mn/60.+sec/3600.+r/3600. def checkProjParameters(self,name,value): if not (isinstance(value,list) or isinstance(value,tuple)): raise ValueError, "Error Projection Parameters must be a list or tuple" if not(len(value))==15: raise ValueError, "Error Projection Parameters must be of length 15 (see doc)" for i in range(2,6): if abs(value[i])<10000: if (not(i==3 and (self.type in [9,15,20,22,30])) and (not(i==4 and (self.type==20 or (self.type==22 and value[12]==1) or self.type==30))) ): ## print i,value[i] value[i]=deg2DMS(value[i]) for i in range(8,12): if self.type in [20,30] and abs(value[i])<10000 : ## print i,value[i] value[i]=deg2DMS(value[i]) return value def checkCalendar(self,name,value): checkName(self,name,value) if not isinstance(value,(int,long)): raise ValueError,'cdtime calendar value must be an integer' if not value in [cdtime.Calendar360,cdtime.ClimCalendar,cdtime.ClimLeapCalendar,cdtime.DefaultCalendar, cdtime.GregorianCalendar,cdtime.JulianCalendar,cdtime.MixedCalendar,cdtime.NoLeapCalendar, cdtime.StandardCalendar]: raise ValueError,str(value)+' is not a valid cdtime calendar value' return value def checkTimeUnits(self,name,value): checkName(self,name,value) if not isinstance(value,str): raise ValueError, 'time units must be a string' a=cdtime.reltime(1,'days since 1900') try: a.torel(value) except: raise ValueError, value+' is invalid time units' sp=value.split('since')[1] b=cdtime.s2c(sp) if b==cdtime.comptime(0,1): raise ValueError, sp+' is invalid date' return value def checkDatawc(self,name,value): checkName(self,name,value) if isNumber(value): value = float(value), 0 elif isinstance(value,str): t=cdtime.s2c(value) if t!=cdtime.comptime(0,1): t=t.torel(self.datawc_timeunits,self.datawc_calendar) value = float(t.value), 1 else: raise ValueError, 'The '+name+' attribute must be either an integer or a float value or a date/time.' elif type(value) in [type(cdtime.comptime(1900)),type(cdtime.reltime(0,'days since 1900'))]: value = value.torel(self.datawc_timeunits,self.datawc_calendar).value, 1 else: raise ValueError, 'The '+name+' attribute must be either an integer or a float value or a date/time.' return value def checkInStringsListInt(self,name,value,values): """ checks the line type""" checkName(self,name,value) val=[] str1=name + ' can either be (' str2=' or (' i=0 for v in values: if not v=='': # skips the invalid/non-contiguous values str2=str2+str(i)+', ' if isinstance(v,list) or isinstance(v,tuple): str1=str1+"'"+v[0]+"', " for v2 in v: val.append(v2) else: val.append(v) str1=str1+"'"+v+"', " i=i+1 err=str1[:-2]+')'+str2[:-2]+')' if isinstance(value,str): value=value.lower() if not value in val: raise ValueError, err i=0 for v in values: if isinstance(v,list) or isinstance(v,tuple): if value in v: return i elif value==v: return i i=i+1 elif isNumber(value) and int(value)==value: if not int(value) in range(len(values)): raise ValueError, err else: return int(value) else: raise ValueError, err def checkProjType(self,name,value): """set the projection type """ checkName(self,name,value) if isinstance(value,str): value=value.lower() if value in ['utm','state plane']: raise ValueError, "Projection Type: "+value+" not supported yet" if -3<=value<0: return value if self._type==-3 and (value=='polar' or value==6 or value=="polar (non gctp)"): return -3 if self._type==-1 and (value=='robinson' or value=='robinson (non gctp)' or value==21): return -1 if self._type==-2 and (value=='mollweide' or value=='mollweide (non gctp)' or value==25): return -2 checkedvalue= checkInStringsListInt(self,name,value, ["linear", "utm", "state plane", ["albers equal area","albers"], ["lambert","lambert conformal c","lambert conformal conic"], "mercator", ["polar","polar stereographic"], "polyconic", ["equid conic a","equid conic","equid conic b"], "transverse mercator", "stereographic", "lambert azimuthal", "azimuthal", "gnomonic", "orthographic", ["gen. vert. near per","gen vert near per",], "sinusoidal", "equirectangular", ["miller","miller cylindrical"], "van der grinten", ["hotin","hotin oblique", "hotin oblique merc","hotin oblique merc a","hotin oblique merc b", "hotin oblique mercator","hotin oblique mercator a","hotin oblique mercator b",], "robinson", ["space oblique","space oblique merc","space oblique merc a","space oblique merc b",], ["alaska","alaska conformal"], ["interrupted goode","goode"], "mollweide", ["interrupted mollweide","interrupt mollweide",], "hammer", ["wagner iv","wagner 4","wagner4"], ["wagner vii","wagner 7","wagner7"], ["oblated","oblated equal area"], ] ) self._type=checkedvalue p=self.parameters if self._type in [3,4]: self.smajor=p[0] self.sminor=p[1] self.standardparallel1=DMS2deg(p[2]) self.standardparallel2=DMS2deg(p[3]) self.centralmeridian=DMS2deg(p[4]) self.originlatitude=DMS2deg(p[5]) self.falseeasting=p[6] self.falsenorthing=p[7] elif self._type==5: self.smajor=p[0] self.sminor=p[1] self.centralmeridian=DMS2deg(p[4]) self.truescale=DMS2deg(p[5]) self.falseeasting=p[6] self.falsenorthing=p[7] elif self._type==6: self.smajor=p[0] self.sminor=p[1] self.centerlongitude=DMS2deg(p[4]) self.truescale=DMS2deg(p[5]) self.falseeasting=p[6] self.falsenorthing=p[7] elif self._type==7: self.smajor=p[0] self.sminor=p[1] self.centralmeridian=DMS2deg(p[4]) self.originlatitude=DMS2deg(p[5]) self.falseeasting=p[6] self.falsenorthing=p[7] elif self._type==8: self.smajor=p[0] self.sminor=p[1] self.centralmeridian=DMS2deg(p[4]) self.originlatitude=DMS2deg(p[5]) self.falseeasting=p[6] self.falsenorthing=p[7] if (p[8]==0 or p[8]>9.9E19): self.subtype=0 self.standardparallel=DMS2deg(p[2]) else: self.subtype=1 self.standardparallel1=DMS2deg(p[2]) self.standardparallel2=DMS2deg(p[3]) elif self._type==9: self.smajor=p[0] self.sminor=p[1] self.factor=p[2] self.centralmeridian=DMS2deg(p[4]) self.originlatitude=DMS2deg(p[5]) self.falseeasting=p[6] self.falsenorthing=p[7] elif self._type in [10,11,12,13,14]: self.sphere=p[0] self.centerlongitude=DMS2deg(p[4]) self.centerlatitude=DMS2deg(p[5]) self.falseeasting=p[6] self.falsenorthing=p[7] elif self._type==15: self.sphere=p[0] self.height=p[2] self.centerlongitude=DMS2deg(p[4]) self.centerlatitude=DMS2deg(p[5]) self.falseeasting=p[6] self.falsenorthing=p[7] elif self._type in [16,18,21,25,27,28,29]: self.sphere=p[0] self.centralmeridian=DMS2deg(p[4]) self.falseeasting=p[6] self.falsenorthing=p[7] elif self._type==17: self.sphere=p[0] self.centralmeridian=DMS2deg(p[4]) self.truescale=DMS2deg(p[5]) self.falseeasting=p[6] self.falsenorthing=p[7] elif self._type==19: self.sphere=p[0] self.centralmeridian=DMS2deg(p[4]) self.originlatitude=DMS2deg(p[5]) self.falseeasting=p[6] self.falsenorthing=p[7] elif self._type==20: self.smajor=p[0] self.sminor=p[1] self.factor=p[2] self.originlatitude=DMS2deg(p[5]) self.falseeasting=p[6] self.falsenorthing=p[7] if (p[12]==0 or p[12]>9.9E19): self.subtype=0 self.longitude1=DMS2deg(p[8]) self.latitude1=DMS2deg(p[9]) self.longitude2=DMS2deg(p[10]) self.latitude2=DMS2deg(p[11]) else: self.subtype=1 self.azimuthalangle=DMS2deg(p[3]) self.azimuthallongitude=DMS2deg(p[4]) elif self._type==22: self.smajor=p[0] self.sminor=p[1] self.falseeasting=p[6] self.falsenorthing=p[7] if (p[12]==0 or p[12]>9.9E19): self.subtype=0 self.orbitinclination=DMS2deg(p[3]) self.orbitlongitude=DMS2deg(p[4]) self.satelliterevolutionperiod=p[8] self.landsatcompensationratio=p[9] self.pathflag=p[10] else: self.subtype=1 self.satellite=p[2] self.path=p[3] elif self._type==23: self.smajor=p[0] self.sminor=p[1] self.falseeasting=p[6] self.falsenorthing=p[7] elif self._type in [24,26]: self.sphere=p[0] elif self._type==30: self.sphere=p[0] self.shapem=p[2] self.shapen=p[3] self.centerlongitude=DMS2deg(p[4]) self.centerlatitude=DMS2deg(p[5]) self.falseeasting=p[6] self.falsenorthing=p[7] return checkedvalue def getProjType(self): """get the projection type """ dic={0:"linear", 1:"utm", 2:"state plane", 3:"albers equal area", 4:"lambert conformal c", 5:"mercator", 6:"polar stereographic", 7:"polyconic", 8:"equid conic", 9:"transverse mercator", 10:"stereographic", 11:"lambert azimuthal", 12:"azimutal", 13:"gnomonic", 14:"orthographic", 15:"gen. vert. near per", 16:"sinusoidal", 17:"equirectangular", 18:"miller cylindrical", 19:"van der grinten", 20:"hotin oblique merc", 21:"robinson", 22:"space oblique merc", 23:"alaska conformal", 24:"interrupted goode", 25:"mollweide", 26:"interrupt mollweide", 27:"hammer", 28:"wagner iv", 29:"wagner vii", 30:"oblated equal area", } value=self._type if 0<=value<=30: return dic[value] elif value==-1: return "robinson (non gctp)" elif value==-2: return "mollweide (non gctp)" elif value==-3: return "polar (non gctp)" def setProjParameter(self,name,value): """ Set an individual paramater for a projection """ checkName(self,name,value) param=self.parameters ok={ 'smajor':[[3,4,5,6,7,8,9,20,22,23],0,[]], 'sminor':[[3,4,5,6,7,8,9,20,22,23],1,[]], 'sphere':[[10,11,12,13,14,15,16,17,18,19,21,24,25,26,27,28,29,30],0,[]], 'centralmeridian':[[3,4,5,7,8,9,16,17,18,19,21,25,27,28,29],4,[]], 'centerlongitude':[[6,10,11,12,13,14,15,30],4,[]], 'standardparallel1':[[3,4,8],2,[]], 'standardparallel2':[[3,4,8],3,[]], 'originlatitude':[[3,4,7,8,9,19,20],5,[]], 'falseeasting':[[3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,25,27,28,29,30],6,[]], 'falsenorthing':[[3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,25,27,28,29,30],7,[]], 'truescale':[[5,6,17,],5,[]], 'standardparallel':[[8,],2,[]], 'factor':[[9,20,],2,[]], 'centerlatitude':[[10,11,12,13,14,15,30],5,[]], 'height':[[15,],2,[]], 'azimuthalangle':[[20,],3,[]], 'azimuthallongitude':[[20,],4,[]], 'orbitinclination':[[22,],3,[]], 'orbitlongitude':[[22,],4,[]], 'satelliterevolutionperiod':[[22,],8,[]], 'landsatcompensationratio':[[22,],9,[]], 'pathflag':[[22,],10,[]], 'path':[[22,],3,[]], 'satellite':[[22,],2,[]], 'shapem':[[30,],2,[]], 'shapen':[[30,],3,[]], 'subtype':[[8,20,22,],12,[]], 'longitude1':[[20,],8,[]], 'latitude1':[[20,],9,[]], 'longitude2':[[20,],10,[]], 'latitude2':[[20,],11,[]], 'angle':[[30,],8,[]], } for nm in ok.keys(): vals=ok[nm] oktypes=vals[0] position=vals[1] nms=vals[2] nms.insert(0,nm) if name in nms: if not self._type in oktypes: raise PPE(name,self._type) param[position]=value ## Subtype is parameter 8 not 12 for projection type 8 if nm=='subtype' and self._type==8: param[position]=1.e20 param[8]=value ## Now raise error when wrong subtype if nm in ['longitude1','longitude2','latitude1','latitude2', 'satelliterevolutionperiod','landsatcompensationratio', 'pathflag','orbitinclination'] and self.parameters[12]==1: raise PPE(name,str(self.type)+' subtype 1') if nm in ['azimuthalangle','azimuthallongitude','satellite','path',] and (self.parameters[12]==0. or self.parameters[12]==1.e20): raise PPE(name,str(self.type)+' subtype 0') if nm=='standardparallel' and self.parameters[8]==1: raise PPE(name,str(self.type)+' subtype 1') if nm in ['standardparallel1','standardparallel2'] and (self.parameters[8]==0 or self.parameters[8]==1.e20) and self.type==8: raise PPE(name,str(self.type)+' subtype 0') self.parameters=param return value raise PPE(name,'Unknow error...')
Python
import vcs, cdms2, cdutil import time,os, sys # Open data file: filepath = os.path.join(sys.prefix, 'sample_data/clt.nc') cdmsfile = cdms2.open( filepath ) # Extract a 3 dimensional data set and get a subset of the time dimension #data = cdmsfile('clt', longitude=(-180, 180), latitude = (-180., 180.)) data = cdmsfile('clt', longitude=(60, 100), latitude = (0., 40.)) # for india # Initial VCS. v = vcs.init() # Now get the line 'continents' object. lc = v.getline('continents') # Change line attribute values lc.color=30#light blue #244 # light blue #250 dark blue lc.width=1 #lc.list() cf_asd = v.getboxfill( 'ASD' ) cf_asd.datawc(1e20,1e20,1e20,1e20) # change to default region #cf_asd.datawc(0,0,80,80) cf_asd.level_1=1e20 # change to default minimum level cf_asd.level_2=1e20 # change to default maximum level cf_asd.color_1=240 # change 1st color index value cf_asd.color_2=240 # change 2nd color index value cf_asd.yticlabels1={0:'0',5:'5',10:'10',15:'15',20:'20',25:'25',30:'30',35:'35',40:'40'} # our own template # Assign the variable "t_asd" to the persistent 'ASD' template. t_asd = v.gettemplate( 'ASD' ) t_asd.data.priority = 1 t_asd.legend.priority = 0 t_asd.max.priority = 0 t_asd.min.priority = 0 t_asd.mean.priority = 0 #t_asd.source.priority = 1 t_asd.title.priority = 0 t_asd.units.priority = 0 t_asd.crdate.priority = 0 t_asd.crtime.priority = 0 t_asd.dataname.priority = 0 t_asd.zunits.priority = 0 t_asd.tunits.priority = 0 t_asd.xname.priority = 0 t_asd.yname.priority = 0 t_asd.xvalue.priority = 0 t_asd.yvalue.priority = 0 t_asd.tvalue.priority = 0 t_asd.zvalue.priority = 0 t_asd.box1.priority = 0 t_asd.xlabel2.priority = 1 t_asd.xtic2.priority = 0 # set the right y-axis (second y axis) to be blank (priority=0) t_asd.ylabel2.priority = 0 t_asd.ytic2.priority = 0 # set the top x-axis (secind y axis) to be blank t_asd.xlabel1.priority = 0 t_asd.xtic1.priority = 0 # set the right y-axis (second y axis) to be blank (priority=0) t_asd.ylabel1.priority = 1 #t_asd.ymintic1.priority = 1 t_asd.ytic1.priority = 0 t_asd.scalefont(0.1) # lat and long text font size #t_asd.ylabel1.list() v.plot( data, t_asd ,cf_asd,bg=0) v.update() arr=[] t=[] c=[] s=[] for i in range(0,31): arr.append(0) t.append(0) c.append(0) s.append(0) # plotting marker m=v.createmarker() mytmpl=v.createtemplate() m.viewport=[mytmpl.data.x1,mytmpl.data.x2,mytmpl.data.y1,mytmpl.data.y2] # this sets the area used for drawing m.worldcoordinate=[60.,100.,0,40] #use m.viewport and m.wordcoordinate to define you're area t[0]=None t[1]=113 c[0]=None c[1]=85 s[0]=5 s[1]=5 s[2]=5 s[3]=5 s[4]=8 s[5]=5 s[6]=5 s[7]=5 s[8]=10 s[9]=12 s[10]=15 s[11]=15 s[12]=15 s[13]=25 s[14]=10 s[15]=10 s[16]=10 s[17]=8 s[18]=15 s[19]=15 s[20]=10 s[21]=5 s[22]=5 s[23]=5 s[24]=5 s[25]=5 s[26]=5 s[27]=5 s[28]=5 s[29]=10 s[30]=8 m.type=[130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159] m.color=[241,] size=[] for i in range(0,31): size.append(s[i]) m.size=size m.x=[[64],[66],[68],[70],[73],[76],[78],[81],[83],[86],[89],[92],[95],[64],[62],[64],[68],[70],[73],[75],[78],[82],[84],[86],[89],[92],[95],[97],[74],[79],] m.y=[[35],[35],[35],[35],[35],[35],[35],[35],[35],[35],[35],[35],[35],[15],[10],[10],[10],[10],[10],[6],[12],[10],[10],[10],[10],[10],[10],[10],[25],[25],] v.update() v.plot(m,bg=0) #v.svg("/home/arulalan/marker1",width=30,height=30,units="cm") raw_input()
Python
import vcs, cdms2, cdutil import time,os, sys # Open data file: filepath = os.path.join(sys.prefix, 'sample_data/clt.nc') cdmsfile = cdms2.open( filepath ) # Extract a 3 dimensional data set and get a subset of the time dimension #data = cdmsfile('clt', longitude=(-180, 180), latitude = (-180., 180.)) data = cdmsfile('clt', longitude=(60, 100), latitude = (0., 40.)) # for india # Initial VCS. v = vcs.init() # Now get the line 'continents' object. lc = v.getline('continents') # Change line attribute values lc.color=30#light blue #244 # light blue #250 dark blue lc.width=1 #lc.list() cf_asd = v.getboxfill( 'ASD' ) cf_asd.datawc(1e20,1e20,1e20,1e20) # change to default region #cf_asd.datawc(0,0,80,80) cf_asd.level_1=1e20 # change to default minimum level cf_asd.level_2=1e20 # change to default maximum level cf_asd.color_1=240 # change 1st color index value cf_asd.color_2=240 # change 2nd color index value cf_asd.yticlabels1={0:'0',5:'5',10:'10',15:'15',20:'20',25:'25',30:'30',35:'35',40:'40'} # our own template # Assign the variable "t_asd" to the persistent 'ASD' template. t_asd = v.gettemplate( 'ASD' ) t_asd.data.priority = 1 t_asd.legend.priority = 0 t_asd.max.priority = 0 t_asd.min.priority = 0 t_asd.mean.priority = 0 #t_asd.source.priority = 1 t_asd.title.priority = 0 t_asd.units.priority = 0 t_asd.crdate.priority = 0 t_asd.crtime.priority = 0 t_asd.dataname.priority = 0 t_asd.zunits.priority = 0 t_asd.tunits.priority = 0 t_asd.xname.priority = 0 t_asd.yname.priority = 0 t_asd.xvalue.priority = 0 t_asd.yvalue.priority = 0 t_asd.tvalue.priority = 0 t_asd.zvalue.priority = 0 t_asd.box1.priority = 0 t_asd.xlabel2.priority = 1 t_asd.xtic2.priority = 0 # set the right y-axis (second y axis) to be blank (priority=0) t_asd.ylabel2.priority = 0 t_asd.ytic2.priority = 0 # set the top x-axis (secind y axis) to be blank t_asd.xlabel1.priority = 0 t_asd.xtic1.priority = 0 # set the right y-axis (second y axis) to be blank (priority=0) t_asd.ylabel1.priority = 1 #t_asd.ymintic1.priority = 1 t_asd.ytic1.priority = 0 t_asd.scalefont(0.1) # lat and long text font size #t_asd.ylabel1.list() v.plot( data, t_asd ,cf_asd,bg=0) v.update() arr=[] t=[] c=[] s=[] for i in range(0,31): arr.append(0) t.append(0) c.append(0) s.append(0) # plotting marker m=v.createmarker() mytmpl=v.createtemplate() m.viewport=[mytmpl.data.x1,mytmpl.data.x2,mytmpl.data.y1,mytmpl.data.y2] # this sets the area used for drawing m.worldcoordinate=[60.,100.,0,40] #use m.viewport and m.wordcoordinate to define you're area t[0]=None t[1]=113 c[0]=None c[1]=85 s[0]=10 s[1]=10 s[2]=10 s[3]=10 s[4]=25 s[5]=35 s[6]=10 s[7]=8 s[8]=10 s[9]=12 s[10]=15 s[11]=15 s[12]=15 s[13]=25 s[14]=10 s[15]=10 s[16]=10 s[17]=8 s[18]=10 s[19]=5 s[20]=15 s[21]=5 s[22]=5 s[23]=5 s[24]=5 s[25]=5 s[26]=5 s[27]=5 s[28]=5 s[29]=20 s[30]=5 m.type=[100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129] m.color=[242,] size=[] for i in range(0,31): size.append(s[i]) m.size=size m.x=[[64],[66],[68],[70],[72],[75],[77],[81],[83],[86],[89],[92],[95],[98],[62],[66],[68],[72],[73],[75],[78],[82],[83],[86],[89],[92],[95],[97],[74],[79],] m.y=[[35],[35],[35],[35],[35],[35],[35],[35],[35],[35],[35],[35],[35],[35],[10],[10],[10],[10],[10],[8],[12],[10],[10],[10],[10],[10],[10],[10],[25],[25],] v.update() v.plot(m,bg=0) v.svg("/home/arulalan/marker",width=30,height=30,units="cm") raw_input()
Python
import vcs, cdms2, cdutil import time,os, sys # Open data file: filepath = os.path.join(sys.prefix, 'sample_data/clt.nc') cdmsfile = cdms2.open( filepath ) # Extract a 3 dimensional data set and get a subset of the time dimension #data = cdmsfile('clt', longitude=(-180, 180), latitude = (-180., 180.)) data = cdmsfile('clt', longitude=(60, 100), latitude = (0., 40.)) # for india # Initial VCS. v = vcs.init() # Now get the line 'continents' object. lc = v.getline('continents') # Change line attribute values lc.color=30#light blue #244 # light blue #250 dark blue lc.width=1 #lc.list() cf_asd = v.getboxfill( 'ASD' ) cf_asd.datawc(1e20,1e20,1e20,1e20) # change to default region #cf_asd.datawc(0,0,80,80) cf_asd.level_1=1e20 # change to default minimum level cf_asd.level_2=1e20 # change to default maximum level cf_asd.color_1=240 # change 1st color index value cf_asd.color_2=240 # change 2nd color index value cf_asd.yticlabels1={0:'0',5:'5',10:'10',15:'15',20:'20',25:'25',30:'30',35:'35',40:'40'} # our own template # Assign the variable "t_asd" to the persistent 'ASD' template. t_asd = v.gettemplate( 'ASD' ) t_asd.data.priority = 1 t_asd.legend.priority = 0 t_asd.max.priority = 0 t_asd.min.priority = 0 t_asd.mean.priority = 0 #t_asd.source.priority = 1 t_asd.title.priority = 0 t_asd.units.priority = 0 t_asd.crdate.priority = 0 t_asd.crtime.priority = 0 t_asd.dataname.priority = 0 t_asd.zunits.priority = 0 t_asd.tunits.priority = 0 t_asd.xname.priority = 0 t_asd.yname.priority = 0 t_asd.xvalue.priority = 0 t_asd.yvalue.priority = 0 t_asd.tvalue.priority = 0 t_asd.zvalue.priority = 0 t_asd.box1.priority = 0 t_asd.xlabel2.priority = 1 t_asd.xtic2.priority = 0 # set the right y-axis (second y axis) to be blank (priority=0) t_asd.ylabel2.priority = 0 t_asd.ytic2.priority = 0 # set the top x-axis (secind y axis) to be blank t_asd.xlabel1.priority = 0 t_asd.xtic1.priority = 0 # set the right y-axis (second y axis) to be blank (priority=0) t_asd.ylabel1.priority = 1 #t_asd.ymintic1.priority = 1 t_asd.ytic1.priority = 0 t_asd.scalefont(0.1) # lat and long text font size #t_asd.ylabel1.list() v.plot( data, t_asd ,cf_asd,bg=0) v.update() arr=[] t=[] c=[] s=[] for i in range(0,14): arr.append(0) t.append(0) c.append(0) s.append(0) # plotting marker m=v.createmarker() mytmpl=v.createtemplate() m.viewport=[mytmpl.data.x1,mytmpl.data.x2,mytmpl.data.y1,mytmpl.data.y2] # this sets the area used for drawing m.worldcoordinate=[60.,100.,0,40] #use m.viewport and m.wordcoordinate to define you're area t[0]=None t[1]=113 c[0]=None c[1]=85 s[0]=10 s[1]=10 s[2]=10 s[3]=10 s[4]=10 s[5]=10 s[6]=10 s[7]=10 s[8]=10 s[9]=20 s[10]=20 s[11]=10 s[12]=20 s[13]=10 m.type=[190,191,192,193,194,195,196,197,198,199,200,201,202] m.color=[241,241,241,241,241,241,241,241,241,241,242,242,242] size=[] for i in range(0,14): size.append(s[i]) m.size=size m.x=[[64],[68],[76],[70],[77],[65],[78],[81],[88],[86],[89],[92],[95]]#,[64],[62],[64],[68],[70],[73],[75],[78],[82],[84],[86],[89],[92],[95],[97],[74],[79],] m.y=[[33],[35],[35],[15],[25],[18],[18],[35],[5],[35],[15],[35],[35]]#,[15],[10],[10],[10],[15],[10],[6],[12],[10],[10],[10],[10],[10],[10],[10],[25],[25],] v.update() v.plot(m,bg=0) #v.svg("/home/arulalan/marker3",width=30,height=30,units="cm") raw_input()7
Python
import vcs, cdms2, cdutil import time,os, sys # Open data file: filepath = os.path.join(sys.prefix, 'sample_data/clt.nc') cdmsfile = cdms2.open( filepath ) # Extract a 3 dimensional data set and get a subset of the time dimension #data = cdmsfile('clt', longitude=(-180, 180), latitude = (-180., 180.)) data = cdmsfile('clt', longitude=(60, 100), latitude = (0., 40.)) # for india # Initial VCS. v = vcs.init() # Now get the line 'continents' object. lc = v.getline('continents') # Change line attribute values lc.color=30#light blue #244 # light blue #250 dark blue lc.width=1 #lc.list() cf_asd = v.getboxfill( 'ASD' ) cf_asd.datawc(1e20,1e20,1e20,1e20) # change to default region #cf_asd.datawc(0,0,80,80) cf_asd.level_1=1e20 # change to default minimum level cf_asd.level_2=1e20 # change to default maximum level cf_asd.color_1=240 # change 1st color index value cf_asd.color_2=240 # change 2nd color index value cf_asd.yticlabels1={0:'0',5:'5',10:'10',15:'15',20:'20',25:'25',30:'30',35:'35',40:'40'} # our own template # Assign the variable "t_asd" to the persistent 'ASD' template. t_asd = v.gettemplate( 'ASD' ) t_asd.data.priority = 1 t_asd.legend.priority = 0 t_asd.max.priority = 0 t_asd.min.priority = 0 t_asd.mean.priority = 0 #t_asd.source.priority = 1 t_asd.title.priority = 0 t_asd.units.priority = 0 t_asd.crdate.priority = 0 t_asd.crtime.priority = 0 t_asd.dataname.priority = 0 t_asd.zunits.priority = 0 t_asd.tunits.priority = 0 t_asd.xname.priority = 0 t_asd.yname.priority = 0 t_asd.xvalue.priority = 0 t_asd.yvalue.priority = 0 t_asd.tvalue.priority = 0 t_asd.zvalue.priority = 0 t_asd.box1.priority = 0 t_asd.xlabel2.priority = 1 t_asd.xtic2.priority = 0 # set the right y-axis (second y axis) to be blank (priority=0) t_asd.ylabel2.priority = 0 t_asd.ytic2.priority = 0 # set the top x-axis (secind y axis) to be blank t_asd.xlabel1.priority = 0 t_asd.xtic1.priority = 0 # set the right y-axis (second y axis) to be blank (priority=0) t_asd.ylabel1.priority = 1 #t_asd.ymintic1.priority = 1 t_asd.ytic1.priority = 0 t_asd.scalefont(0.1) # lat and long text font size #t_asd.ylabel1.list() v.plot( data, t_asd ,cf_asd,bg=0) v.update() arr=[] t=[] c=[] s=[] for i in range(0,31): arr.append(0) t.append(0) c.append(0) s.append(0) # plotting marker m=v.createmarker() mytmpl=v.createtemplate() m.viewport=[mytmpl.data.x1,mytmpl.data.x2,mytmpl.data.y1,mytmpl.data.y2] # this sets the area used for drawing m.worldcoordinate=[60.,100.,0,40] #use m.viewport and m.wordcoordinate to define you're area t[0]=None t[1]=113 c[0]=None c[1]=85 s[0]=5 s[1]=5 s[2]=5 s[3]=5 s[4]=5 s[5]=5 s[6]=5 s[7]=5 s[8]=5 s[9]=5 s[10]=5 s[11]=5 s[12]=5 s[13]=8 s[14]=5 s[15]=5 s[16]=10 s[17]=12 s[18]=15 s[19]=15 s[20]=10 s[21]=8 s[22]=8 s[23]=8 s[24]=8 s[25]=8 s[26]=8 s[27]=8 s[28]=10 s[29]=10 s[30]=10 m.type=[160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189] m.color=[242,] size=[] for i in range(0,31): size.append(s[i]) m.size=size m.x=[[64],[66],[68],[70],[72],[76],[78],[81],[83],[86],[89],[92],[95],[64],[62],[64],[68],[70],[73],[75],[78],[82],[84],[86],[89],[92],[95],[97],[74],[79],] m.y=[[35],[35],[35],[35],[35],[35],[35],[35],[35],[35],[35],[35],[35],[15],[10],[10],[10],[15],[10],[6],[12],[10],[10],[10],[10],[10],[10],[10],[25],[25],] v.update() v.plot(m,bg=0) #v.svg("/home/arulalan/marker2",width=30,height=30,units="cm") raw_input()7
Python
""" FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == This is the integration file for Python. """ import cgi import os import re import string def escape(text, replace=string.replace): """Converts the special characters '<', '>', and '&'. RFC 1866 specifies that these characters be represented in HTML as &lt; &gt; and &amp; respectively. In Python 1.5 we use the new string.replace() function for speed. """ text = replace(text, '&', '&amp;') # must be done 1st text = replace(text, '<', '&lt;') text = replace(text, '>', '&gt;') text = replace(text, '"', '&quot;') text = replace(text, "'", '&#39;') return text # The FCKeditor class class FCKeditor(object): def __init__(self, instanceName): self.InstanceName = instanceName self.BasePath = '/fckeditor/' self.Width = '100%' self.Height = '200' self.ToolbarSet = 'Default' self.Value = ''; self.Config = {} def Create(self): return self.CreateHtml() def CreateHtml(self): HtmlValue = escape(self.Value) Html = "" if (self.IsCompatible()): File = "fckeditor.html" Link = "%seditor/%s?InstanceName=%s" % ( self.BasePath, File, self.InstanceName ) if (self.ToolbarSet is not None): Link += "&amp;Toolbar=%s" % self.ToolbarSet # Render the linked hidden field Html += "<input type=\"hidden\" id=\"%s\" name=\"%s\" value=\"%s\" style=\"display:none\" />" % ( self.InstanceName, self.InstanceName, HtmlValue ) # Render the configurations hidden field Html += "<input type=\"hidden\" id=\"%s___Config\" value=\"%s\" style=\"display:none\" />" % ( self.InstanceName, self.GetConfigFieldString() ) # Render the editor iframe Html += "<iframe id=\"%s\__Frame\" src=\"%s\" width=\"%s\" height=\"%s\" frameborder=\"0\" scrolling=\"no\"></iframe>" % ( self.InstanceName, Link, self.Width, self.Height ) else: if (self.Width.find("%%") < 0): WidthCSS = "%spx" % self.Width else: WidthCSS = self.Width if (self.Height.find("%%") < 0): HeightCSS = "%spx" % self.Height else: HeightCSS = self.Height Html += "<textarea name=\"%s\" rows=\"4\" cols=\"40\" style=\"width: %s; height: %s;\" wrap=\"virtual\">%s</textarea>" % ( self.InstanceName, WidthCSS, HeightCSS, HtmlValue ) return Html def IsCompatible(self): if (os.environ.has_key("HTTP_USER_AGENT")): sAgent = os.environ.get("HTTP_USER_AGENT", "") else: sAgent = "" if (sAgent.find("MSIE") >= 0) and (sAgent.find("mac") < 0) and (sAgent.find("Opera") < 0): i = sAgent.find("MSIE") iVersion = float(sAgent[i+5:i+5+3]) if (iVersion >= 5.5): return True return False elif (sAgent.find("Gecko/") >= 0): i = sAgent.find("Gecko/") iVersion = int(sAgent[i+6:i+6+8]) if (iVersion >= 20030210): return True return False elif (sAgent.find("Opera/") >= 0): i = sAgent.find("Opera/") iVersion = float(sAgent[i+6:i+6+4]) if (iVersion >= 9.5): return True return False elif (sAgent.find("AppleWebKit/") >= 0): p = re.compile('AppleWebKit\/(\d+)', re.IGNORECASE) m = p.search(sAgent) if (m.group(1) >= 522): return True return False else: return False def GetConfigFieldString(self): sParams = "" bFirst = True for sKey in self.Config.keys(): sValue = self.Config[sKey] if (not bFirst): sParams += "&amp;" else: bFirst = False if (sValue): k = escape(sKey) v = escape(sValue) if (sValue == "true"): sParams += "%s=true" % k elif (sValue == "false"): sParams += "%s=false" % k else: sParams += "%s=%s" % (k, v) return sParams
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector for Python (CGI and WSGI). """ import os try: # Windows needs stdio set for binary mode for file upload to work. import msvcrt msvcrt.setmode (0, os.O_BINARY) # stdin = 0 msvcrt.setmode (1, os.O_BINARY) # stdout = 1 except ImportError: pass from fckutil import * from fckoutput import * import config as Config class GetFoldersCommandMixin (object): def getFolders(self, resourceType, currentFolder): """ Purpose: command to recieve a list of folders """ # Map the virtual path to our local server serverPath = mapServerFolder(self.userFilesFolder,currentFolder) s = """<Folders>""" # Open the folders node for someObject in os.listdir(serverPath): someObjectPath = mapServerFolder(serverPath, someObject) if os.path.isdir(someObjectPath): s += """<Folder name="%s" />""" % ( convertToXmlAttribute(someObject) ) s += """</Folders>""" # Close the folders node return s class GetFoldersAndFilesCommandMixin (object): def getFoldersAndFiles(self, resourceType, currentFolder): """ Purpose: command to recieve a list of folders and files """ # Map the virtual path to our local server serverPath = mapServerFolder(self.userFilesFolder,currentFolder) # Open the folders / files node folders = """<Folders>""" files = """<Files>""" for someObject in os.listdir(serverPath): someObjectPath = mapServerFolder(serverPath, someObject) if os.path.isdir(someObjectPath): folders += """<Folder name="%s" />""" % ( convertToXmlAttribute(someObject) ) elif os.path.isfile(someObjectPath): size = os.path.getsize(someObjectPath) if size > 0: size = round(size/1024) if size < 1: size = 1 files += """<File name="%s" size="%d" />""" % ( convertToXmlAttribute(someObject), size ) # Close the folders / files node folders += """</Folders>""" files += """</Files>""" return folders + files class CreateFolderCommandMixin (object): def createFolder(self, resourceType, currentFolder): """ Purpose: command to create a new folder """ errorNo = 0; errorMsg =''; if self.request.has_key("NewFolderName"): newFolder = self.request.get("NewFolderName", None) newFolder = sanitizeFolderName (newFolder) try: newFolderPath = mapServerFolder(self.userFilesFolder, combinePaths(currentFolder, newFolder)) self.createServerFolder(newFolderPath) except Exception, e: errorMsg = str(e).decode('iso-8859-1').encode('utf-8') # warning with encodigns!!! if hasattr(e,'errno'): if e.errno==17: #file already exists errorNo=0 elif e.errno==13: # permission denied errorNo = 103 elif e.errno==36 or e.errno==2 or e.errno==22: # filename too long / no such file / invalid name errorNo = 102 else: errorNo = 110 else: errorNo = 102 return self.sendErrorNode ( errorNo, errorMsg ) def createServerFolder(self, folderPath): "Purpose: physically creates a folder on the server" # No need to check if the parent exists, just create all hierachy try: permissions = Config.ChmodOnFolderCreate if not permissions: os.makedirs(folderPath) except AttributeError: #ChmodOnFolderCreate undefined permissions = 0755 if permissions: oldumask = os.umask(0) os.makedirs(folderPath,mode=0755) os.umask( oldumask ) class UploadFileCommandMixin (object): def uploadFile(self, resourceType, currentFolder): """ Purpose: command to upload files to server (same as FileUpload) """ errorNo = 0 if self.request.has_key("NewFile"): # newFile has all the contents we need newFile = self.request.get("NewFile", "") # Get the file name newFileName = newFile.filename newFileName = sanitizeFileName( newFileName ) newFileNameOnly = removeExtension(newFileName) newFileExtension = getExtension(newFileName).lower() allowedExtensions = Config.AllowedExtensions[resourceType] deniedExtensions = Config.DeniedExtensions[resourceType] if (allowedExtensions): # Check for allowed isAllowed = False if (newFileExtension in allowedExtensions): isAllowed = True elif (deniedExtensions): # Check for denied isAllowed = True if (newFileExtension in deniedExtensions): isAllowed = False else: # No extension limitations isAllowed = True if (isAllowed): # Upload to operating system # Map the virtual path to the local server path currentFolderPath = mapServerFolder(self.userFilesFolder, currentFolder) i = 0 while (True): newFilePath = os.path.join (currentFolderPath,newFileName) if os.path.exists(newFilePath): i += 1 newFileName = "%s(%d).%s" % ( newFileNameOnly, i, newFileExtension ) errorNo= 201 # file renamed else: # Read file contents and write to the desired path (similar to php's move_uploaded_file) fout = file(newFilePath, 'wb') while (True): chunk = newFile.file.read(100000) if not chunk: break fout.write (chunk) fout.close() if os.path.exists ( newFilePath ): doChmod = False try: doChmod = Config.ChmodOnUpload permissions = Config.ChmodOnUpload except AttributeError: #ChmodOnUpload undefined doChmod = True permissions = 0755 if ( doChmod ): oldumask = os.umask(0) os.chmod( newFilePath, permissions ) os.umask( oldumask ) newFileUrl = combinePaths(self.webUserFilesFolder, currentFolder) + newFileName return self.sendUploadResults( errorNo , newFileUrl, newFileName ) else: return self.sendUploadResults( errorNo = 202, customMsg = "" ) else: return self.sendUploadResults( errorNo = 202, customMsg = "No File" )
Python
#!/usr/bin/env python """ * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Configuration file for the File Manager Connector for Python """ # INSTALLATION NOTE: You must set up your server environment accordingly to run # python scripts. This connector requires Python 2.4 or greater. # # Supported operation modes: # * WSGI (recommended): You'll need apache + mod_python + modpython_gateway # or any web server capable of the WSGI python standard # * Plain Old CGI: Any server capable of running standard python scripts # (although mod_python is recommended for performance) # This was the previous connector version operation mode # # If you're using Apache web server, replace the htaccess.txt to to .htaccess, # and set the proper options and paths. # For WSGI and mod_python, you may need to download modpython_gateway from: # http://projects.amor.org/misc/svn/modpython_gateway.py and copy it in this # directory. # SECURITY: You must explicitly enable this "connector". (Set it to "True"). # WARNING: don't just set "ConfigIsEnabled = True", you must be sure that only # authenticated users can access this file or use some kind of session checking. Enabled = False # Path to user files relative to the document root. UserFilesPath = '/userfiles/' # Fill the following value it you prefer to specify the absolute path for the # user files directory. Useful if you are using a virtual directory, symbolic # link or alias. Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'. # Attention: The above 'UserFilesPath' must point to the same directory. # WARNING: GetRootPath may not work in virtual or mod_python configurations, and # may not be thread safe. Use this configuration parameter instead. UserFilesAbsolutePath = '' # Due to security issues with Apache modules, it is recommended to leave the # following setting enabled. ForceSingleExtension = True # What the user can do with this connector ConfigAllowedCommands = [ 'QuickUpload', 'FileUpload', 'GetFolders', 'GetFoldersAndFiles', 'CreateFolder' ] # Allowed Resource Types ConfigAllowedTypes = ['File', 'Image', 'Flash', 'Media'] # After file is uploaded, sometimes it is required to change its permissions # so that it was possible to access it at the later time. # If possible, it is recommended to set more restrictive permissions, like 0755. # Set to 0 to disable this feature. # Note: not needed on Windows-based servers. ChmodOnUpload = 0755 # See comments above. # Used when creating folders that does not exist. ChmodOnFolderCreate = 0755 # Do not touch this 3 lines, see "Configuration settings for each Resource Type" AllowedExtensions = {}; DeniedExtensions = {}; FileTypesPath = {}; FileTypesAbsolutePath = {}; QuickUploadPath = {}; QuickUploadAbsolutePath = {}; # Configuration settings for each Resource Type # # - AllowedExtensions: the possible extensions that can be allowed. # If it is empty then any file type can be uploaded. # - DeniedExtensions: The extensions that won't be allowed. # If it is empty then no restrictions are done here. # # For a file to be uploaded it has to fulfill both the AllowedExtensions # and DeniedExtensions (that's it: not being denied) conditions. # # - FileTypesPath: the virtual folder relative to the document root where # these resources will be located. # Attention: It must start and end with a slash: '/' # # - FileTypesAbsolutePath: the physical path to the above folder. It must be # an absolute path. # If it's an empty string then it will be autocalculated. # Useful if you are using a virtual directory, symbolic link or alias. # Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'. # Attention: The above 'FileTypesPath' must point to the same directory. # Attention: It must end with a slash: '/' # # # - QuickUploadPath: the virtual folder relative to the document root where # these resources will be uploaded using the Upload tab in the resources # dialogs. # Attention: It must start and end with a slash: '/' # # - QuickUploadAbsolutePath: the physical path to the above folder. It must be # an absolute path. # If it's an empty string then it will be autocalculated. # Useful if you are using a virtual directory, symbolic link or alias. # Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'. # Attention: The above 'QuickUploadPath' must point to the same directory. # Attention: It must end with a slash: '/' AllowedExtensions['File'] = ['7z','aiff','asf','avi','bmp','csv','doc','fla','flv','gif','gz','gzip','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','ods','odt','pdf','png','ppt','pxd','qt','ram','rar','rm','rmi','rmvb','rtf','sdc','sitd','swf','sxc','sxw','tar','tgz','tif','tiff','txt','vsd','wav','wma','wmv','xls','xml','zip'] DeniedExtensions['File'] = [] FileTypesPath['File'] = UserFilesPath + 'file/' FileTypesAbsolutePath['File'] = (not UserFilesAbsolutePath == '') and (UserFilesAbsolutePath + 'file/') or '' QuickUploadPath['File'] = FileTypesPath['File'] QuickUploadAbsolutePath['File'] = FileTypesAbsolutePath['File'] AllowedExtensions['Image'] = ['bmp','gif','jpeg','jpg','png'] DeniedExtensions['Image'] = [] FileTypesPath['Image'] = UserFilesPath + 'image/' FileTypesAbsolutePath['Image'] = (not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'image/' or '' QuickUploadPath['Image'] = FileTypesPath['Image'] QuickUploadAbsolutePath['Image']= FileTypesAbsolutePath['Image'] AllowedExtensions['Flash'] = ['swf','flv'] DeniedExtensions['Flash'] = [] FileTypesPath['Flash'] = UserFilesPath + 'flash/' FileTypesAbsolutePath['Flash'] = ( not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'flash/' or '' QuickUploadPath['Flash'] = FileTypesPath['Flash'] QuickUploadAbsolutePath['Flash']= FileTypesAbsolutePath['Flash'] AllowedExtensions['Media'] = ['aiff','asf','avi','bmp','fla', 'flv','gif','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','png','qt','ram','rm','rmi','rmvb','swf','tif','tiff','wav','wma','wmv'] DeniedExtensions['Media'] = [] FileTypesPath['Media'] = UserFilesPath + 'media/' FileTypesAbsolutePath['Media'] = ( not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'media/' or '' QuickUploadPath['Media'] = FileTypesPath['Media'] QuickUploadAbsolutePath['Media']= FileTypesAbsolutePath['Media']
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Utility functions for the File Manager Connector for Python """ import string, re import os import config as Config # Generic manipulation functions def removeExtension(fileName): index = fileName.rindex(".") newFileName = fileName[0:index] return newFileName def getExtension(fileName): index = fileName.rindex(".") + 1 fileExtension = fileName[index:] return fileExtension def removeFromStart(string, char): return string.lstrip(char) def removeFromEnd(string, char): return string.rstrip(char) # Path functions def combinePaths( basePath, folder ): return removeFromEnd( basePath, '/' ) + '/' + removeFromStart( folder, '/' ) def getFileName(filename): " Purpose: helper function to extrapolate the filename " for splitChar in ["/", "\\"]: array = filename.split(splitChar) if (len(array) > 1): filename = array[-1] return filename def sanitizeFolderName( newFolderName ): "Do a cleanup of the folder name to avoid possible problems" # Remove . \ / | : ? * " < > and control characters return re.sub( '\\.|\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[\x00-\x1f\x7f-\x9f]', '_', newFolderName ) def sanitizeFileName( newFileName ): "Do a cleanup of the file name to avoid possible problems" # Replace dots in the name with underscores (only one dot can be there... security issue). if ( Config.ForceSingleExtension ): # remove dots newFileName = re.sub ( '\\.(?![^.]*$)', '_', newFileName ) ; newFileName = newFileName.replace('\\','/') # convert windows to unix path newFileName = os.path.basename (newFileName) # strip directories # Remove \ / | : ? * return re.sub ( '\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[\x00-\x1f\x7f-\x9f]/', '_', newFileName ) def getCurrentFolder(currentFolder): if not currentFolder: currentFolder = '/' # Check the current folder syntax (must begin and end with a slash). if (currentFolder[-1] <> "/"): currentFolder += "/" if (currentFolder[0] <> "/"): currentFolder = "/" + currentFolder # Ensure the folder path has no double-slashes while '//' in currentFolder: currentFolder = currentFolder.replace('//','/') # Check for invalid folder paths (..) if '..' in currentFolder or '\\' in currentFolder: return None # Check for invalid folder paths (..) if re.search( '(/\\.)|(//)|([\\\\:\\*\\?\\""\\<\\>\\|]|[\x00-\x1F]|[\x7f-\x9f])', currentFolder ): return None return currentFolder def mapServerPath( environ, url): " Emulate the asp Server.mapPath function. Given an url path return the physical directory that it corresponds to " # This isn't correct but for the moment there's no other solution # If this script is under a virtual directory or symlink it will detect the problem and stop return combinePaths( getRootPath(environ), url ) def mapServerFolder(resourceTypePath, folderPath): return combinePaths ( resourceTypePath , folderPath ) def getRootPath(environ): "Purpose: returns the root path on the server" # WARNING: this may not be thread safe, and doesn't work w/ VirtualServer/mod_python # Use Config.UserFilesAbsolutePath instead if environ.has_key('DOCUMENT_ROOT'): return environ['DOCUMENT_ROOT'] else: realPath = os.path.realpath( './' ) selfPath = environ['SCRIPT_FILENAME'] selfPath = selfPath [ : selfPath.rfind( '/' ) ] selfPath = selfPath.replace( '/', os.path.sep) position = realPath.find(selfPath) # This can check only that this script isn't run from a virtual dir # But it avoids the problems that arise if it isn't checked raise realPath if ( position < 0 or position <> len(realPath) - len(selfPath) or realPath[ : position ]==''): raise Exception('Sorry, can\'t map "UserFilesPath" to a physical path. You must set the "UserFilesAbsolutePath" value in "editor/filemanager/connectors/py/config.py".') return realPath[ : position ]
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector/QuickUpload for Python (WSGI wrapper). See config.py for configuration settings """ from connector import FCKeditorConnector from upload import FCKeditorQuickUpload import cgitb from cStringIO import StringIO # Running from WSGI capable server (recomended) def App(environ, start_response): "WSGI entry point. Run the connector" if environ['SCRIPT_NAME'].endswith("connector.py"): conn = FCKeditorConnector(environ) elif environ['SCRIPT_NAME'].endswith("upload.py"): conn = FCKeditorQuickUpload(environ) else: start_response ("200 Ok", [('Content-Type','text/html')]) yield "Unknown page requested: " yield environ['SCRIPT_NAME'] return try: # run the connector data = conn.doResponse() # Start WSGI response: start_response ("200 Ok", conn.headers) # Send response text yield data except: start_response("500 Internal Server Error",[("Content-type","text/html")]) file = StringIO() cgitb.Hook(file = file).handle() yield file.getvalue()
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector for Python (CGI and WSGI). """ import os try: # Windows needs stdio set for binary mode for file upload to work. import msvcrt msvcrt.setmode (0, os.O_BINARY) # stdin = 0 msvcrt.setmode (1, os.O_BINARY) # stdout = 1 except ImportError: pass from fckutil import * from fckoutput import * import config as Config class GetFoldersCommandMixin (object): def getFolders(self, resourceType, currentFolder): """ Purpose: command to recieve a list of folders """ # Map the virtual path to our local server serverPath = mapServerFolder(self.userFilesFolder,currentFolder) s = """<Folders>""" # Open the folders node for someObject in os.listdir(serverPath): someObjectPath = mapServerFolder(serverPath, someObject) if os.path.isdir(someObjectPath): s += """<Folder name="%s" />""" % ( convertToXmlAttribute(someObject) ) s += """</Folders>""" # Close the folders node return s class GetFoldersAndFilesCommandMixin (object): def getFoldersAndFiles(self, resourceType, currentFolder): """ Purpose: command to recieve a list of folders and files """ # Map the virtual path to our local server serverPath = mapServerFolder(self.userFilesFolder,currentFolder) # Open the folders / files node folders = """<Folders>""" files = """<Files>""" for someObject in os.listdir(serverPath): someObjectPath = mapServerFolder(serverPath, someObject) if os.path.isdir(someObjectPath): folders += """<Folder name="%s" />""" % ( convertToXmlAttribute(someObject) ) elif os.path.isfile(someObjectPath): size = os.path.getsize(someObjectPath) if size > 0: size = round(size/1024) if size < 1: size = 1 files += """<File name="%s" size="%d" />""" % ( convertToXmlAttribute(someObject), size ) # Close the folders / files node folders += """</Folders>""" files += """</Files>""" return folders + files class CreateFolderCommandMixin (object): def createFolder(self, resourceType, currentFolder): """ Purpose: command to create a new folder """ errorNo = 0; errorMsg =''; if self.request.has_key("NewFolderName"): newFolder = self.request.get("NewFolderName", None) newFolder = sanitizeFolderName (newFolder) try: newFolderPath = mapServerFolder(self.userFilesFolder, combinePaths(currentFolder, newFolder)) self.createServerFolder(newFolderPath) except Exception, e: errorMsg = str(e).decode('iso-8859-1').encode('utf-8') # warning with encodigns!!! if hasattr(e,'errno'): if e.errno==17: #file already exists errorNo=0 elif e.errno==13: # permission denied errorNo = 103 elif e.errno==36 or e.errno==2 or e.errno==22: # filename too long / no such file / invalid name errorNo = 102 else: errorNo = 110 else: errorNo = 102 return self.sendErrorNode ( errorNo, errorMsg ) def createServerFolder(self, folderPath): "Purpose: physically creates a folder on the server" # No need to check if the parent exists, just create all hierachy try: permissions = Config.ChmodOnFolderCreate if not permissions: os.makedirs(folderPath) except AttributeError: #ChmodOnFolderCreate undefined permissions = 0755 if permissions: oldumask = os.umask(0) os.makedirs(folderPath,mode=0755) os.umask( oldumask ) class UploadFileCommandMixin (object): def uploadFile(self, resourceType, currentFolder): """ Purpose: command to upload files to server (same as FileUpload) """ errorNo = 0 if self.request.has_key("NewFile"): # newFile has all the contents we need newFile = self.request.get("NewFile", "") # Get the file name newFileName = newFile.filename newFileName = sanitizeFileName( newFileName ) newFileNameOnly = removeExtension(newFileName) newFileExtension = getExtension(newFileName).lower() allowedExtensions = Config.AllowedExtensions[resourceType] deniedExtensions = Config.DeniedExtensions[resourceType] if (allowedExtensions): # Check for allowed isAllowed = False if (newFileExtension in allowedExtensions): isAllowed = True elif (deniedExtensions): # Check for denied isAllowed = True if (newFileExtension in deniedExtensions): isAllowed = False else: # No extension limitations isAllowed = True if (isAllowed): # Upload to operating system # Map the virtual path to the local server path currentFolderPath = mapServerFolder(self.userFilesFolder, currentFolder) i = 0 while (True): newFilePath = os.path.join (currentFolderPath,newFileName) if os.path.exists(newFilePath): i += 1 newFileName = "%s(%d).%s" % ( newFileNameOnly, i, newFileExtension ) errorNo= 201 # file renamed else: # Read file contents and write to the desired path (similar to php's move_uploaded_file) fout = file(newFilePath, 'wb') while (True): chunk = newFile.file.read(100000) if not chunk: break fout.write (chunk) fout.close() if os.path.exists ( newFilePath ): doChmod = False try: doChmod = Config.ChmodOnUpload permissions = Config.ChmodOnUpload except AttributeError: #ChmodOnUpload undefined doChmod = True permissions = 0755 if ( doChmod ): oldumask = os.umask(0) os.chmod( newFilePath, permissions ) os.umask( oldumask ) newFileUrl = combinePaths(self.webUserFilesFolder, currentFolder) + newFileName return self.sendUploadResults( errorNo , newFileUrl, newFileName ) else: return self.sendUploadResults( errorNo = 202, customMsg = "" ) else: return self.sendUploadResults( errorNo = 202, customMsg = "No File" )
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == This is the "File Uploader" for Python """ import os from fckutil import * from fckcommands import * # default command's implementation from fckconnector import FCKeditorConnectorBase # import base connector import config as Config class FCKeditorQuickUpload( FCKeditorConnectorBase, UploadFileCommandMixin, BaseHttpMixin, BaseHtmlMixin): def doResponse(self): "Main function. Process the request, set headers and return a string as response." # Check if this connector is disabled if not(Config.Enabled): return self.sendUploadResults(1, "This file uploader is disabled. Please check the \"editor/filemanager/connectors/py/config.py\"") command = 'QuickUpload' # The file type (from the QueryString, by default 'File'). resourceType = self.request.get('Type','File') currentFolder = "/" # Check for invalid paths if currentFolder is None: return self.sendUploadResults(102, '', '', "") # Check if it is an allowed command if ( not command in Config.ConfigAllowedCommands ): return self.sendUploadResults( 1, '', '', 'The %s command isn\'t allowed' % command ) if ( not resourceType in Config.ConfigAllowedTypes ): return self.sendUploadResults( 1, '', '', 'Invalid type specified' ) # Setup paths self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType] self.webUserFilesFolder = Config.QuickUploadPath[resourceType] if not self.userFilesFolder: # no absolute path given (dangerous...) self.userFilesFolder = mapServerPath(self.environ, self.webUserFilesFolder) # Ensure that the directory exists. if not os.path.exists(self.userFilesFolder): try: self.createServerFoldercreateServerFolder( self.userFilesFolder ) except: return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ") # File upload doesn't have to return XML, so intercept here return self.uploadFile(resourceType, currentFolder) # Running from command line (plain old CGI) if __name__ == '__main__': try: # Create a Connector Instance conn = FCKeditorQuickUpload() data = conn.doResponse() for header in conn.headers: if not header is None: print '%s: %s' % header print print data except: print "Content-Type: text/plain" print import cgi cgi.print_exception()
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Base Connector for Python (CGI and WSGI). See config.py for configuration settings """ import cgi, os from fckutil import * from fckcommands import * # default command's implementation from fckoutput import * # base http, xml and html output mixins import config as Config class FCKeditorConnectorBase( object ): "The base connector class. Subclass it to extend functionality (see Zope example)" def __init__(self, environ=None): "Constructor: Here you should parse request fields, initialize variables, etc." self.request = FCKeditorRequest(environ) # Parse request self.headers = [] # Clean Headers if environ: self.environ = environ else: self.environ = os.environ # local functions def setHeader(self, key, value): self.headers.append ((key, value)) return class FCKeditorRequest(object): "A wrapper around the request object" def __init__(self, environ): if environ: # WSGI self.request = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ, keep_blank_values=1) self.environ = environ else: # plain old cgi self.environ = os.environ self.request = cgi.FieldStorage() if 'REQUEST_METHOD' in self.environ and 'QUERY_STRING' in self.environ: if self.environ['REQUEST_METHOD'].upper()=='POST': # we are in a POST, but GET query_string exists # cgi parses by default POST data, so parse GET QUERY_STRING too self.get_request = cgi.FieldStorage(fp=None, environ={ 'REQUEST_METHOD':'GET', 'QUERY_STRING':self.environ['QUERY_STRING'], }, ) else: self.get_request={} def has_key(self, key): return self.request.has_key(key) or self.get_request.has_key(key) def get(self, key, default=None): if key in self.request.keys(): field = self.request[key] elif key in self.get_request.keys(): field = self.get_request[key] else: return default if hasattr(field,"filename") and field.filename: #file upload, do not convert return value return field else: return field.value
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector for Python (CGI and WSGI). See config.py for configuration settings """ import os from fckutil import * from fckcommands import * # default command's implementation from fckoutput import * # base http, xml and html output mixins from fckconnector import FCKeditorConnectorBase # import base connector import config as Config class FCKeditorConnector( FCKeditorConnectorBase, GetFoldersCommandMixin, GetFoldersAndFilesCommandMixin, CreateFolderCommandMixin, UploadFileCommandMixin, BaseHttpMixin, BaseXmlMixin, BaseHtmlMixin ): "The Standard connector class." def doResponse(self): "Main function. Process the request, set headers and return a string as response." s = "" # Check if this connector is disabled if not(Config.Enabled): return self.sendError(1, "This connector is disabled. Please check the connector configurations in \"editor/filemanager/connectors/py/config.py\" and try again.") # Make sure we have valid inputs for key in ("Command","Type","CurrentFolder"): if not self.request.has_key (key): return # Get command, resource type and current folder command = self.request.get("Command") resourceType = self.request.get("Type") currentFolder = getCurrentFolder(self.request.get("CurrentFolder")) # Check for invalid paths if currentFolder is None: if (command == "FileUpload"): return self.sendUploadResults( errorNo = 102, customMsg = "" ) else: return self.sendError(102, "") # Check if it is an allowed command if ( not command in Config.ConfigAllowedCommands ): return self.sendError( 1, 'The %s command isn\'t allowed' % command ) if ( not resourceType in Config.ConfigAllowedTypes ): return self.sendError( 1, 'Invalid type specified' ) # Setup paths if command == "QuickUpload": self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType] self.webUserFilesFolder = Config.QuickUploadPath[resourceType] else: self.userFilesFolder = Config.FileTypesAbsolutePath[resourceType] self.webUserFilesFolder = Config.FileTypesPath[resourceType] if not self.userFilesFolder: # no absolute path given (dangerous...) self.userFilesFolder = mapServerPath(self.environ, self.webUserFilesFolder) # Ensure that the directory exists. if not os.path.exists(self.userFilesFolder): try: self.createServerFolder( self.userFilesFolder ) except: return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ") # File upload doesn't have to return XML, so intercept here if (command == "FileUpload"): return self.uploadFile(resourceType, currentFolder) # Create Url url = combinePaths( self.webUserFilesFolder, currentFolder ) # Begin XML s += self.createXmlHeader(command, resourceType, currentFolder, url) # Execute the command selector = {"GetFolders": self.getFolders, "GetFoldersAndFiles": self.getFoldersAndFiles, "CreateFolder": self.createFolder, } s += selector[command](resourceType, currentFolder) s += self.createXmlFooter() return s # Running from command line (plain old CGI) if __name__ == '__main__': try: # Create a Connector Instance conn = FCKeditorConnector() data = conn.doResponse() for header in conn.headers: print '%s: %s' % header print print data except: print "Content-Type: text/plain" print import cgi cgi.print_exception()
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector for Python and Zope. This code was not tested at all. It just was ported from pre 2.5 release, so for further reference see \editor\filemanager\browser\default\connectors\py\connector.py in previous releases. """ from fckutil import * from connector import * import config as Config class FCKeditorConnectorZope(FCKeditorConnector): """ Zope versiof FCKeditorConnector """ # Allow access (Zope) __allow_access_to_unprotected_subobjects__ = 1 def __init__(self, context=None): """ Constructor """ FCKeditorConnector.__init__(self, environ=None) # call superclass constructor # Instance Attributes self.context = context self.request = FCKeditorRequest(context) def getZopeRootContext(self): if self.zopeRootContext is None: self.zopeRootContext = self.context.getPhysicalRoot() return self.zopeRootContext def getZopeUploadContext(self): if self.zopeUploadContext is None: folderNames = self.userFilesFolder.split("/") c = self.getZopeRootContext() for folderName in folderNames: if (folderName <> ""): c = c[folderName] self.zopeUploadContext = c return self.zopeUploadContext def setHeader(self, key, value): self.context.REQUEST.RESPONSE.setHeader(key, value) def getFolders(self, resourceType, currentFolder): # Open the folders node s = "" s += """<Folders>""" zopeFolder = self.findZopeFolder(resourceType, currentFolder) for (name, o) in zopeFolder.objectItems(["Folder"]): s += """<Folder name="%s" />""" % ( convertToXmlAttribute(name) ) # Close the folders node s += """</Folders>""" return s def getZopeFoldersAndFiles(self, resourceType, currentFolder): folders = self.getZopeFolders(resourceType, currentFolder) files = self.getZopeFiles(resourceType, currentFolder) s = folders + files return s def getZopeFiles(self, resourceType, currentFolder): # Open the files node s = "" s += """<Files>""" zopeFolder = self.findZopeFolder(resourceType, currentFolder) for (name, o) in zopeFolder.objectItems(["File","Image"]): s += """<File name="%s" size="%s" />""" % ( convertToXmlAttribute(name), ((o.get_size() / 1024) + 1) ) # Close the files node s += """</Files>""" return s def findZopeFolder(self, resourceType, folderName): # returns the context of the resource / folder zopeFolder = self.getZopeUploadContext() folderName = self.removeFromStart(folderName, "/") folderName = self.removeFromEnd(folderName, "/") if (resourceType <> ""): try: zopeFolder = zopeFolder[resourceType] except: zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=resourceType, title=resourceType) zopeFolder = zopeFolder[resourceType] if (folderName <> ""): folderNames = folderName.split("/") for folderName in folderNames: zopeFolder = zopeFolder[folderName] return zopeFolder def createFolder(self, resourceType, currentFolder): # Find out where we are zopeFolder = self.findZopeFolder(resourceType, currentFolder) errorNo = 0 errorMsg = "" if self.request.has_key("NewFolderName"): newFolder = self.request.get("NewFolderName", None) zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=newFolder, title=newFolder) else: errorNo = 102 return self.sendErrorNode ( errorNo, errorMsg ) def uploadFile(self, resourceType, currentFolder, count=None): zopeFolder = self.findZopeFolder(resourceType, currentFolder) file = self.request.get("NewFile", None) fileName = self.getFileName(file.filename) fileNameOnly = self.removeExtension(fileName) fileExtension = self.getExtension(fileName).lower() if (count): nid = "%s.%s.%s" % (fileNameOnly, count, fileExtension) else: nid = fileName title = nid try: zopeFolder.manage_addProduct['OFSP'].manage_addFile( id=nid, title=title, file=file.read() ) except: if (count): count += 1 else: count = 1 return self.zopeFileUpload(resourceType, currentFolder, count) return self.sendUploadResults( 0 ) class FCKeditorRequest(object): "A wrapper around the request object" def __init__(self, context=None): r = context.REQUEST self.request = r def has_key(self, key): return self.request.has_key(key) def get(self, key, default=None): return self.request.get(key, default) """ Running from zope, you will need to modify this connector. If you have uploaded the FCKeditor into Zope (like me), you need to move this connector out of Zope, and replace the "connector" with an alias as below. The key to it is to pass the Zope context in, as we then have a like to the Zope context. ## Script (Python) "connector.py" ##bind container=container ##bind context=context ##bind namespace= ##bind script=script ##bind subpath=traverse_subpath ##parameters=*args, **kws ##title=ALIAS ## import Products.zope as connector return connector.FCKeditorConnectorZope(context=context).doResponse() """
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector for Python (CGI and WSGI). """ from time import gmtime, strftime import string def escape(text, replace=string.replace): """ Converts the special characters '<', '>', and '&'. RFC 1866 specifies that these characters be represented in HTML as &lt; &gt; and &amp; respectively. In Python 1.5 we use the new string.replace() function for speed. """ text = replace(text, '&', '&amp;') # must be done 1st text = replace(text, '<', '&lt;') text = replace(text, '>', '&gt;') text = replace(text, '"', '&quot;') return text def convertToXmlAttribute(value): if (value is None): value = "" return escape(value) class BaseHttpMixin(object): def setHttpHeaders(self, content_type='text/xml'): "Purpose: to prepare the headers for the xml to return" # Prevent the browser from caching the result. # Date in the past self.setHeader('Expires','Mon, 26 Jul 1997 05:00:00 GMT') # always modified self.setHeader('Last-Modified',strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime())) # HTTP/1.1 self.setHeader('Cache-Control','no-store, no-cache, must-revalidate') self.setHeader('Cache-Control','post-check=0, pre-check=0') # HTTP/1.0 self.setHeader('Pragma','no-cache') # Set the response format. self.setHeader( 'Content-Type', content_type + '; charset=utf-8' ) return class BaseXmlMixin(object): def createXmlHeader(self, command, resourceType, currentFolder, url): "Purpose: returns the xml header" self.setHttpHeaders() # Create the XML document header s = """<?xml version="1.0" encoding="utf-8" ?>""" # Create the main connector node s += """<Connector command="%s" resourceType="%s">""" % ( command, resourceType ) # Add the current folder node s += """<CurrentFolder path="%s" url="%s" />""" % ( convertToXmlAttribute(currentFolder), convertToXmlAttribute(url), ) return s def createXmlFooter(self): "Purpose: returns the xml footer" return """</Connector>""" def sendError(self, number, text): "Purpose: in the event of an error, return an xml based error" self.setHttpHeaders() return ("""<?xml version="1.0" encoding="utf-8" ?>""" + """<Connector>""" + self.sendErrorNode (number, text) + """</Connector>""" ) def sendErrorNode(self, number, text): if number != 1: return """<Error number="%s" />""" % (number) else: return """<Error number="%s" text="%s" />""" % (number, convertToXmlAttribute(text)) class BaseHtmlMixin(object): def sendUploadResults( self, errorNo = 0, fileUrl = '', fileName = '', customMsg = '' ): self.setHttpHeaders("text/html") "This is the function that sends the results of the uploading process" "Minified version of the document.domain automatic fix script (#1919)." "The original script can be found at _dev/domain_fix_template.js" return """<script type="text/javascript"> (function(){var d=document.domain;while (true){try{var A=window.parent.document.domain;break;}catch(e) {};d=d.replace(/.*?(?:\.|$)/,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})(); window.parent.OnUploadCompleted(%(errorNumber)s,"%(fileUrl)s","%(fileName)s","%(customMsg)s"); </script>""" % { 'errorNumber': errorNo, 'fileUrl': fileUrl.replace ('"', '\\"'), 'fileName': fileName.replace ( '"', '\\"' ) , 'customMsg': customMsg.replace ( '"', '\\"' ), }
Python
#!/usr/bin/env python """ * FCKeditor - The text editor for Internet - http://www.fckeditor.net * Copyright (C) 2003-2009 Frederico Caldeira Knabben * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Configuration file for the File Manager Connector for Python """ # INSTALLATION NOTE: You must set up your server environment accordingly to run # python scripts. This connector requires Python 2.4 or greater. # # Supported operation modes: # * WSGI (recommended): You'll need apache + mod_python + modpython_gateway # or any web server capable of the WSGI python standard # * Plain Old CGI: Any server capable of running standard python scripts # (although mod_python is recommended for performance) # This was the previous connector version operation mode # # If you're using Apache web server, replace the htaccess.txt to to .htaccess, # and set the proper options and paths. # For WSGI and mod_python, you may need to download modpython_gateway from: # http://projects.amor.org/misc/svn/modpython_gateway.py and copy it in this # directory. # SECURITY: You must explicitly enable this "connector". (Set it to "True"). # WARNING: don't just set "ConfigIsEnabled = True", you must be sure that only # authenticated users can access this file or use some kind of session checking. Enabled = False # Path to user files relative to the document root. UserFilesPath = '/userfiles/' # Fill the following value it you prefer to specify the absolute path for the # user files directory. Useful if you are using a virtual directory, symbolic # link or alias. Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'. # Attention: The above 'UserFilesPath' must point to the same directory. # WARNING: GetRootPath may not work in virtual or mod_python configurations, and # may not be thread safe. Use this configuration parameter instead. UserFilesAbsolutePath = '' # Due to security issues with Apache modules, it is recommended to leave the # following setting enabled. ForceSingleExtension = True # What the user can do with this connector ConfigAllowedCommands = [ 'QuickUpload', 'FileUpload', 'GetFolders', 'GetFoldersAndFiles', 'CreateFolder' ] # Allowed Resource Types ConfigAllowedTypes = ['File', 'Image', 'Flash', 'Media'] # After file is uploaded, sometimes it is required to change its permissions # so that it was possible to access it at the later time. # If possible, it is recommended to set more restrictive permissions, like 0755. # Set to 0 to disable this feature. # Note: not needed on Windows-based servers. ChmodOnUpload = 0755 # See comments above. # Used when creating folders that does not exist. ChmodOnFolderCreate = 0755 # Do not touch this 3 lines, see "Configuration settings for each Resource Type" AllowedExtensions = {}; DeniedExtensions = {}; FileTypesPath = {}; FileTypesAbsolutePath = {}; QuickUploadPath = {}; QuickUploadAbsolutePath = {}; # Configuration settings for each Resource Type # # - AllowedExtensions: the possible extensions that can be allowed. # If it is empty then any file type can be uploaded. # - DeniedExtensions: The extensions that won't be allowed. # If it is empty then no restrictions are done here. # # For a file to be uploaded it has to fulfill both the AllowedExtensions # and DeniedExtensions (that's it: not being denied) conditions. # # - FileTypesPath: the virtual folder relative to the document root where # these resources will be located. # Attention: It must start and end with a slash: '/' # # - FileTypesAbsolutePath: the physical path to the above folder. It must be # an absolute path. # If it's an empty string then it will be autocalculated. # Useful if you are using a virtual directory, symbolic link or alias. # Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'. # Attention: The above 'FileTypesPath' must point to the same directory. # Attention: It must end with a slash: '/' # # # - QuickUploadPath: the virtual folder relative to the document root where # these resources will be uploaded using the Upload tab in the resources # dialogs. # Attention: It must start and end with a slash: '/' # # - QuickUploadAbsolutePath: the physical path to the above folder. It must be # an absolute path. # If it's an empty string then it will be autocalculated. # Useful if you are using a virtual directory, symbolic link or alias. # Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'. # Attention: The above 'QuickUploadPath' must point to the same directory. # Attention: It must end with a slash: '/' AllowedExtensions['File'] = ['7z','aiff','asf','avi','bmp','csv','doc','fla','flv','gif','gz','gzip','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','ods','odt','pdf','png','ppt','pxd','qt','ram','rar','rm','rmi','rmvb','rtf','sdc','sitd','swf','sxc','sxw','tar','tgz','tif','tiff','txt','vsd','wav','wma','wmv','xls','xml','zip'] DeniedExtensions['File'] = [] FileTypesPath['File'] = UserFilesPath + 'file/' FileTypesAbsolutePath['File'] = (not UserFilesAbsolutePath == '') and (UserFilesAbsolutePath + 'file/') or '' QuickUploadPath['File'] = FileTypesPath['File'] QuickUploadAbsolutePath['File'] = FileTypesAbsolutePath['File'] AllowedExtensions['Image'] = ['bmp','gif','jpeg','jpg','png'] DeniedExtensions['Image'] = [] FileTypesPath['Image'] = UserFilesPath + 'image/' FileTypesAbsolutePath['Image'] = (not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'image/' or '' QuickUploadPath['Image'] = FileTypesPath['Image'] QuickUploadAbsolutePath['Image']= FileTypesAbsolutePath['Image'] AllowedExtensions['Flash'] = ['swf','flv'] DeniedExtensions['Flash'] = [] FileTypesPath['Flash'] = UserFilesPath + 'flash/' FileTypesAbsolutePath['Flash'] = ( not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'flash/' or '' QuickUploadPath['Flash'] = FileTypesPath['Flash'] QuickUploadAbsolutePath['Flash']= FileTypesAbsolutePath['Flash'] AllowedExtensions['Media'] = ['aiff','asf','avi','bmp','fla', 'flv','gif','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','png','qt','ram','rm','rmi','rmvb','swf','tif','tiff','wav','wma','wmv'] DeniedExtensions['Media'] = [] FileTypesPath['Media'] = UserFilesPath + 'media/' FileTypesAbsolutePath['Media'] = ( not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'media/' or '' QuickUploadPath['Media'] = FileTypesPath['Media'] QuickUploadAbsolutePath['Media']= FileTypesAbsolutePath['Media']
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Base Connector for Python (CGI and WSGI). See config.py for configuration settings """ import cgi, os from fckutil import * from fckcommands import * # default command's implementation from fckoutput import * # base http, xml and html output mixins import config as Config class FCKeditorConnectorBase( object ): "The base connector class. Subclass it to extend functionality (see Zope example)" def __init__(self, environ=None): "Constructor: Here you should parse request fields, initialize variables, etc." self.request = FCKeditorRequest(environ) # Parse request self.headers = [] # Clean Headers if environ: self.environ = environ else: self.environ = os.environ # local functions def setHeader(self, key, value): self.headers.append ((key, value)) return class FCKeditorRequest(object): "A wrapper around the request object" def __init__(self, environ): if environ: # WSGI self.request = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ, keep_blank_values=1) self.environ = environ else: # plain old cgi self.environ = os.environ self.request = cgi.FieldStorage() if 'REQUEST_METHOD' in self.environ and 'QUERY_STRING' in self.environ: if self.environ['REQUEST_METHOD'].upper()=='POST': # we are in a POST, but GET query_string exists # cgi parses by default POST data, so parse GET QUERY_STRING too self.get_request = cgi.FieldStorage(fp=None, environ={ 'REQUEST_METHOD':'GET', 'QUERY_STRING':self.environ['QUERY_STRING'], }, ) else: self.get_request={} def has_key(self, key): return self.request.has_key(key) or self.get_request.has_key(key) def get(self, key, default=None): if key in self.request.keys(): field = self.request[key] elif key in self.get_request.keys(): field = self.get_request[key] else: return default if hasattr(field,"filename") and field.filename: #file upload, do not convert return value return field else: return field.value
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector for Python (CGI and WSGI). See config.py for configuration settings """ import os from fckutil import * from fckcommands import * # default command's implementation from fckoutput import * # base http, xml and html output mixins from fckconnector import FCKeditorConnectorBase # import base connector import config as Config class FCKeditorConnector( FCKeditorConnectorBase, GetFoldersCommandMixin, GetFoldersAndFilesCommandMixin, CreateFolderCommandMixin, UploadFileCommandMixin, BaseHttpMixin, BaseXmlMixin, BaseHtmlMixin ): "The Standard connector class." def doResponse(self): "Main function. Process the request, set headers and return a string as response." s = "" # Check if this connector is disabled if not(Config.Enabled): return self.sendError(1, "This connector is disabled. Please check the connector configurations in \"editor/filemanager/connectors/py/config.py\" and try again.") # Make sure we have valid inputs for key in ("Command","Type","CurrentFolder"): if not self.request.has_key (key): return # Get command, resource type and current folder command = self.request.get("Command") resourceType = self.request.get("Type") currentFolder = getCurrentFolder(self.request.get("CurrentFolder")) # Check for invalid paths if currentFolder is None: if (command == "FileUpload"): return self.sendUploadResults( errorNo = 102, customMsg = "" ) else: return self.sendError(102, "") # Check if it is an allowed command if ( not command in Config.ConfigAllowedCommands ): return self.sendError( 1, 'The %s command isn\'t allowed' % command ) if ( not resourceType in Config.ConfigAllowedTypes ): return self.sendError( 1, 'Invalid type specified' ) # Setup paths if command == "QuickUpload": self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType] self.webUserFilesFolder = Config.QuickUploadPath[resourceType] else: self.userFilesFolder = Config.FileTypesAbsolutePath[resourceType] self.webUserFilesFolder = Config.FileTypesPath[resourceType] if not self.userFilesFolder: # no absolute path given (dangerous...) self.userFilesFolder = mapServerPath(self.environ, self.webUserFilesFolder) # Ensure that the directory exists. if not os.path.exists(self.userFilesFolder): try: self.createServerFolder( self.userFilesFolder ) except: return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ") # File upload doesn't have to return XML, so intercept here if (command == "FileUpload"): return self.uploadFile(resourceType, currentFolder) # Create Url url = combinePaths( self.webUserFilesFolder, currentFolder ) # Begin XML s += self.createXmlHeader(command, resourceType, currentFolder, url) # Execute the command selector = {"GetFolders": self.getFolders, "GetFoldersAndFiles": self.getFoldersAndFiles, "CreateFolder": self.createFolder, } s += selector[command](resourceType, currentFolder) s += self.createXmlFooter() return s # Running from command line (plain old CGI) if __name__ == '__main__': try: # Create a Connector Instance conn = FCKeditorConnector() data = conn.doResponse() for header in conn.headers: print '%s: %s' % header print print data except: print "Content-Type: text/plain" print import cgi cgi.print_exception()
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Utility functions for the File Manager Connector for Python """ import string, re import os import config as Config # Generic manipulation functions def removeExtension(fileName): index = fileName.rindex(".") newFileName = fileName[0:index] return newFileName def getExtension(fileName): index = fileName.rindex(".") + 1 fileExtension = fileName[index:] return fileExtension def removeFromStart(string, char): return string.lstrip(char) def removeFromEnd(string, char): return string.rstrip(char) # Path functions def combinePaths( basePath, folder ): return removeFromEnd( basePath, '/' ) + '/' + removeFromStart( folder, '/' ) def getFileName(filename): " Purpose: helper function to extrapolate the filename " for splitChar in ["/", "\\"]: array = filename.split(splitChar) if (len(array) > 1): filename = array[-1] return filename def sanitizeFolderName( newFolderName ): "Do a cleanup of the folder name to avoid possible problems" # Remove . \ / | : ? * " < > and control characters return re.sub( '\\.|\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[\x00-\x1f\x7f-\x9f]', '_', newFolderName ) def sanitizeFileName( newFileName ): "Do a cleanup of the file name to avoid possible problems" # Replace dots in the name with underscores (only one dot can be there... security issue). if ( Config.ForceSingleExtension ): # remove dots newFileName = re.sub ( '\\.(?![^.]*$)', '_', newFileName ) ; newFileName = newFileName.replace('\\','/') # convert windows to unix path newFileName = os.path.basename (newFileName) # strip directories # Remove \ / | : ? * return re.sub ( '\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[\x00-\x1f\x7f-\x9f]/', '_', newFileName ) def getCurrentFolder(currentFolder): if not currentFolder: currentFolder = '/' # Check the current folder syntax (must begin and end with a slash). if (currentFolder[-1] <> "/"): currentFolder += "/" if (currentFolder[0] <> "/"): currentFolder = "/" + currentFolder # Ensure the folder path has no double-slashes while '//' in currentFolder: currentFolder = currentFolder.replace('//','/') # Check for invalid folder paths (..) if '..' in currentFolder or '\\' in currentFolder: return None # Check for invalid folder paths (..) if re.search( '(/\\.)|(//)|([\\\\:\\*\\?\\""\\<\\>\\|]|[\x00-\x1F]|[\x7f-\x9f])', currentFolder ): return None return currentFolder def mapServerPath( environ, url): " Emulate the asp Server.mapPath function. Given an url path return the physical directory that it corresponds to " # This isn't correct but for the moment there's no other solution # If this script is under a virtual directory or symlink it will detect the problem and stop return combinePaths( getRootPath(environ), url ) def mapServerFolder(resourceTypePath, folderPath): return combinePaths ( resourceTypePath , folderPath ) def getRootPath(environ): "Purpose: returns the root path on the server" # WARNING: this may not be thread safe, and doesn't work w/ VirtualServer/mod_python # Use Config.UserFilesAbsolutePath instead if environ.has_key('DOCUMENT_ROOT'): return environ['DOCUMENT_ROOT'] else: realPath = os.path.realpath( './' ) selfPath = environ['SCRIPT_FILENAME'] selfPath = selfPath [ : selfPath.rfind( '/' ) ] selfPath = selfPath.replace( '/', os.path.sep) position = realPath.find(selfPath) # This can check only that this script isn't run from a virtual dir # But it avoids the problems that arise if it isn't checked raise realPath if ( position < 0 or position <> len(realPath) - len(selfPath) or realPath[ : position ]==''): raise Exception('Sorry, can\'t map "UserFilesPath" to a physical path. You must set the "UserFilesAbsolutePath" value in "editor/filemanager/connectors/py/config.py".') return realPath[ : position ]
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector for Python (CGI and WSGI). """ from time import gmtime, strftime import string def escape(text, replace=string.replace): """ Converts the special characters '<', '>', and '&'. RFC 1866 specifies that these characters be represented in HTML as &lt; &gt; and &amp; respectively. In Python 1.5 we use the new string.replace() function for speed. """ text = replace(text, '&', '&amp;') # must be done 1st text = replace(text, '<', '&lt;') text = replace(text, '>', '&gt;') text = replace(text, '"', '&quot;') return text def convertToXmlAttribute(value): if (value is None): value = "" return escape(value) class BaseHttpMixin(object): def setHttpHeaders(self, content_type='text/xml'): "Purpose: to prepare the headers for the xml to return" # Prevent the browser from caching the result. # Date in the past self.setHeader('Expires','Mon, 26 Jul 1997 05:00:00 GMT') # always modified self.setHeader('Last-Modified',strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime())) # HTTP/1.1 self.setHeader('Cache-Control','no-store, no-cache, must-revalidate') self.setHeader('Cache-Control','post-check=0, pre-check=0') # HTTP/1.0 self.setHeader('Pragma','no-cache') # Set the response format. self.setHeader( 'Content-Type', content_type + '; charset=utf-8' ) return class BaseXmlMixin(object): def createXmlHeader(self, command, resourceType, currentFolder, url): "Purpose: returns the xml header" self.setHttpHeaders() # Create the XML document header s = """<?xml version="1.0" encoding="utf-8" ?>""" # Create the main connector node s += """<Connector command="%s" resourceType="%s">""" % ( command, resourceType ) # Add the current folder node s += """<CurrentFolder path="%s" url="%s" />""" % ( convertToXmlAttribute(currentFolder), convertToXmlAttribute(url), ) return s def createXmlFooter(self): "Purpose: returns the xml footer" return """</Connector>""" def sendError(self, number, text): "Purpose: in the event of an error, return an xml based error" self.setHttpHeaders() return ("""<?xml version="1.0" encoding="utf-8" ?>""" + """<Connector>""" + self.sendErrorNode (number, text) + """</Connector>""" ) def sendErrorNode(self, number, text): if number != 1: return """<Error number="%s" />""" % (number) else: return """<Error number="%s" text="%s" />""" % (number, convertToXmlAttribute(text)) class BaseHtmlMixin(object): def sendUploadResults( self, errorNo = 0, fileUrl = '', fileName = '', customMsg = '' ): self.setHttpHeaders("text/html") "This is the function that sends the results of the uploading process" "Minified version of the document.domain automatic fix script (#1919)." "The original script can be found at _dev/domain_fix_template.js" return """<script type="text/javascript"> (function(){var d=document.domain;while (true){try{var A=window.parent.document.domain;break;}catch(e) {};d=d.replace(/.*?(?:\.|$)/,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})(); window.parent.OnUploadCompleted(%(errorNumber)s,"%(fileUrl)s","%(fileName)s","%(customMsg)s"); </script>""" % { 'errorNumber': errorNo, 'fileUrl': fileUrl.replace ('"', '\\"'), 'fileName': fileName.replace ( '"', '\\"' ) , 'customMsg': customMsg.replace ( '"', '\\"' ), }
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector/QuickUpload for Python (WSGI wrapper). See config.py for configuration settings """ from connector import FCKeditorConnector from upload import FCKeditorQuickUpload import cgitb from cStringIO import StringIO # Running from WSGI capable server (recomended) def App(environ, start_response): "WSGI entry point. Run the connector" if environ['SCRIPT_NAME'].endswith("connector.py"): conn = FCKeditorConnector(environ) elif environ['SCRIPT_NAME'].endswith("upload.py"): conn = FCKeditorQuickUpload(environ) else: start_response ("200 Ok", [('Content-Type','text/html')]) yield "Unknown page requested: " yield environ['SCRIPT_NAME'] return try: # run the connector data = conn.doResponse() # Start WSGI response: start_response ("200 Ok", conn.headers) # Send response text yield data except: start_response("500 Internal Server Error",[("Content-type","text/html")]) file = StringIO() cgitb.Hook(file = file).handle() yield file.getvalue()
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == This is the "File Uploader" for Python """ import os from fckutil import * from fckcommands import * # default command's implementation from fckconnector import FCKeditorConnectorBase # import base connector import config as Config class FCKeditorQuickUpload( FCKeditorConnectorBase, UploadFileCommandMixin, BaseHttpMixin, BaseHtmlMixin): def doResponse(self): "Main function. Process the request, set headers and return a string as response." # Check if this connector is disabled if not(Config.Enabled): return self.sendUploadResults(1, "This file uploader is disabled. Please check the \"editor/filemanager/connectors/py/config.py\"") command = 'QuickUpload' # The file type (from the QueryString, by default 'File'). resourceType = self.request.get('Type','File') currentFolder = "/" # Check for invalid paths if currentFolder is None: return self.sendUploadResults(102, '', '', "") # Check if it is an allowed command if ( not command in Config.ConfigAllowedCommands ): return self.sendUploadResults( 1, '', '', 'The %s command isn\'t allowed' % command ) if ( not resourceType in Config.ConfigAllowedTypes ): return self.sendUploadResults( 1, '', '', 'Invalid type specified' ) # Setup paths self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType] self.webUserFilesFolder = Config.QuickUploadPath[resourceType] if not self.userFilesFolder: # no absolute path given (dangerous...) self.userFilesFolder = mapServerPath(self.environ, self.webUserFilesFolder) # Ensure that the directory exists. if not os.path.exists(self.userFilesFolder): try: self.createServerFoldercreateServerFolder( self.userFilesFolder ) except: return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ") # File upload doesn't have to return XML, so intercept here return self.uploadFile(resourceType, currentFolder) # Running from command line (plain old CGI) if __name__ == '__main__': try: # Create a Connector Instance conn = FCKeditorQuickUpload() data = conn.doResponse() for header in conn.headers: if not header is None: print '%s: %s' % header print print data except: print "Content-Type: text/plain" print import cgi cgi.print_exception()
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector for Python and Zope. This code was not tested at all. It just was ported from pre 2.5 release, so for further reference see \editor\filemanager\browser\default\connectors\py\connector.py in previous releases. """ from fckutil import * from connector import * import config as Config class FCKeditorConnectorZope(FCKeditorConnector): """ Zope versiof FCKeditorConnector """ # Allow access (Zope) __allow_access_to_unprotected_subobjects__ = 1 def __init__(self, context=None): """ Constructor """ FCKeditorConnector.__init__(self, environ=None) # call superclass constructor # Instance Attributes self.context = context self.request = FCKeditorRequest(context) def getZopeRootContext(self): if self.zopeRootContext is None: self.zopeRootContext = self.context.getPhysicalRoot() return self.zopeRootContext def getZopeUploadContext(self): if self.zopeUploadContext is None: folderNames = self.userFilesFolder.split("/") c = self.getZopeRootContext() for folderName in folderNames: if (folderName <> ""): c = c[folderName] self.zopeUploadContext = c return self.zopeUploadContext def setHeader(self, key, value): self.context.REQUEST.RESPONSE.setHeader(key, value) def getFolders(self, resourceType, currentFolder): # Open the folders node s = "" s += """<Folders>""" zopeFolder = self.findZopeFolder(resourceType, currentFolder) for (name, o) in zopeFolder.objectItems(["Folder"]): s += """<Folder name="%s" />""" % ( convertToXmlAttribute(name) ) # Close the folders node s += """</Folders>""" return s def getZopeFoldersAndFiles(self, resourceType, currentFolder): folders = self.getZopeFolders(resourceType, currentFolder) files = self.getZopeFiles(resourceType, currentFolder) s = folders + files return s def getZopeFiles(self, resourceType, currentFolder): # Open the files node s = "" s += """<Files>""" zopeFolder = self.findZopeFolder(resourceType, currentFolder) for (name, o) in zopeFolder.objectItems(["File","Image"]): s += """<File name="%s" size="%s" />""" % ( convertToXmlAttribute(name), ((o.get_size() / 1024) + 1) ) # Close the files node s += """</Files>""" return s def findZopeFolder(self, resourceType, folderName): # returns the context of the resource / folder zopeFolder = self.getZopeUploadContext() folderName = self.removeFromStart(folderName, "/") folderName = self.removeFromEnd(folderName, "/") if (resourceType <> ""): try: zopeFolder = zopeFolder[resourceType] except: zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=resourceType, title=resourceType) zopeFolder = zopeFolder[resourceType] if (folderName <> ""): folderNames = folderName.split("/") for folderName in folderNames: zopeFolder = zopeFolder[folderName] return zopeFolder def createFolder(self, resourceType, currentFolder): # Find out where we are zopeFolder = self.findZopeFolder(resourceType, currentFolder) errorNo = 0 errorMsg = "" if self.request.has_key("NewFolderName"): newFolder = self.request.get("NewFolderName", None) zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=newFolder, title=newFolder) else: errorNo = 102 return self.sendErrorNode ( errorNo, errorMsg ) def uploadFile(self, resourceType, currentFolder, count=None): zopeFolder = self.findZopeFolder(resourceType, currentFolder) file = self.request.get("NewFile", None) fileName = self.getFileName(file.filename) fileNameOnly = self.removeExtension(fileName) fileExtension = self.getExtension(fileName).lower() if (count): nid = "%s.%s.%s" % (fileNameOnly, count, fileExtension) else: nid = fileName title = nid try: zopeFolder.manage_addProduct['OFSP'].manage_addFile( id=nid, title=title, file=file.read() ) except: if (count): count += 1 else: count = 1 return self.zopeFileUpload(resourceType, currentFolder, count) return self.sendUploadResults( 0 ) class FCKeditorRequest(object): "A wrapper around the request object" def __init__(self, context=None): r = context.REQUEST self.request = r def has_key(self, key): return self.request.has_key(key) def get(self, key, default=None): return self.request.get(key, default) """ Running from zope, you will need to modify this connector. If you have uploaded the FCKeditor into Zope (like me), you need to move this connector out of Zope, and replace the "connector" with an alias as below. The key to it is to pass the Zope context in, as we then have a like to the Zope context. ## Script (Python) "connector.py" ##bind container=container ##bind context=context ##bind namespace= ##bind script=script ##bind subpath=traverse_subpath ##parameters=*args, **kws ##title=ALIAS ## import Products.zope as connector return connector.FCKeditorConnectorZope(context=context).doResponse() """
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Sample page. """ import cgi import os # Ensure that the fckeditor.py is included in your classpath import fckeditor # Tell the browser to render html print "Content-Type: text/html" print "" # Document header print """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>FCKeditor - Sample</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="robots" content="noindex, nofollow"> <link href="../sample.css" rel="stylesheet" type="text/css" /> </head> <body> <h1>FCKeditor - Python - Sample 1</h1> This sample displays a normal HTML form with an FCKeditor with full features enabled. <hr> <form action="sampleposteddata.py" method="post" target="_blank"> """ # This is the real work try: sBasePath = os.environ.get("SCRIPT_NAME") sBasePath = sBasePath[0:sBasePath.find("_samples")] oFCKeditor = fckeditor.FCKeditor('FCKeditor1') oFCKeditor.BasePath = sBasePath oFCKeditor.Value = """<p>This is some <strong>sample text</strong>. You are using <a href="http://www.fckeditor.net/">FCKeditor</a>.</p>""" print oFCKeditor.Create() except Exception, e: print e print """ <br> <input type="submit" value="Submit"> </form> """ # For testing your environments #print "<hr>" #for key in os.environ.keys(): # print "%s: %s<br>" % (key, os.environ.get(key, "")) #print "<hr>" # Document footer print """ </body> </html> """
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == This page lists the data posted by a form. """ import cgi import os # Tell the browser to render html print "Content-Type: text/html" print "" try: # Create a cgi object form = cgi.FieldStorage() except Exception, e: print e # Document header print """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>FCKeditor - Samples - Posted Data</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="robots" content="noindex, nofollow"> <link href="../sample.css" rel="stylesheet" type="text/css" /> </head> <body> """ # This is the real work print """ <h1>FCKeditor - Samples - Posted Data</h1> This page lists all data posted by the form. <hr> <table border="1" cellspacing="0" id="outputSample"> <colgroup><col width="80"><col></colgroup> <thead> <tr> <th>Field Name</th> <th>Value</th> </tr> </thead> """ for key in form.keys(): try: value = form[key].value print """ <tr> <th>%s</th> <td><pre>%s</pre></td> </tr> """ % (cgi.escape(key), cgi.escape(value)) except Exception, e: print e print "</table>" # For testing your environments #print "<hr>" #for key in os.environ.keys(): # print "%s: %s<br>" % (key, os.environ.get(key, "")) #print "<hr>" # Document footer print """ </body> </html> """
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Sample page. """ import cgi import os # Ensure that the fckeditor.py is included in your classpath import fckeditor # Tell the browser to render html print "Content-Type: text/html" print "" # Document header print """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>FCKeditor - Sample</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="robots" content="noindex, nofollow"> <link href="../sample.css" rel="stylesheet" type="text/css" /> </head> <body> <h1>FCKeditor - Python - Sample 1</h1> This sample displays a normal HTML form with an FCKeditor with full features enabled. <hr> <form action="sampleposteddata.py" method="post" target="_blank"> """ # This is the real work try: sBasePath = os.environ.get("SCRIPT_NAME") sBasePath = sBasePath[0:sBasePath.find("_samples")] oFCKeditor = fckeditor.FCKeditor('FCKeditor1') oFCKeditor.BasePath = sBasePath oFCKeditor.Value = """<p>This is some <strong>sample text</strong>. You are using <a href="http://www.fckeditor.net/">FCKeditor</a>.</p>""" print oFCKeditor.Create() except Exception, e: print e print """ <br> <input type="submit" value="Submit"> </form> """ # For testing your environments #print "<hr>" #for key in os.environ.keys(): # print "%s: %s<br>" % (key, os.environ.get(key, "")) #print "<hr>" # Document footer print """ </body> </html> """
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2009 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == This page lists the data posted by a form. """ import cgi import os # Tell the browser to render html print "Content-Type: text/html" print "" try: # Create a cgi object form = cgi.FieldStorage() except Exception, e: print e # Document header print """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>FCKeditor - Samples - Posted Data</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="robots" content="noindex, nofollow"> <link href="../sample.css" rel="stylesheet" type="text/css" /> </head> <body> """ # This is the real work print """ <h1>FCKeditor - Samples - Posted Data</h1> This page lists all data posted by the form. <hr> <table border="1" cellspacing="0" id="outputSample"> <colgroup><col width="80"><col></colgroup> <thead> <tr> <th>Field Name</th> <th>Value</th> </tr> </thead> """ for key in form.keys(): try: value = form[key].value print """ <tr> <th>%s</th> <td><pre>%s</pre></td> </tr> """ % (cgi.escape(key), cgi.escape(value)) except Exception, e: print e print "</table>" # For testing your environments #print "<hr>" #for key in os.environ.keys(): # print "%s: %s<br>" % (key, os.environ.get(key, "")) #print "<hr>" # Document footer print """ </body> </html> """
Python
''' Module which brings history information about files from Mercurial. @author: Rodrigo Damazio ''' import re import subprocess REVISION_REGEX = re.compile(r'(?P<hash>[0-9a-f]{12}):.*') def _GetOutputLines(args): ''' Runs an external process and returns its output as a list of lines. @param args: the arguments to run ''' process = subprocess.Popen(args, stdout=subprocess.PIPE, universal_newlines = True, shell = False) output = process.communicate()[0] return output.splitlines() def FillMercurialRevisions(filename, parsed_file): ''' Fills the revs attribute of all strings in the given parsed file with a list of revisions that touched the lines corresponding to that string. @param filename: the name of the file to get history for @param parsed_file: the parsed file to modify ''' # Take output of hg annotate to get revision of each line output_lines = _GetOutputLines(['hg', 'annotate', '-c', filename]) # Create a map of line -> revision (key is list index, line 0 doesn't exist) line_revs = ['dummy'] for line in output_lines: rev_match = REVISION_REGEX.match(line) if not rev_match: raise 'Unexpected line of output from hg: %s' % line rev_hash = rev_match.group('hash') line_revs.append(rev_hash) for str in parsed_file.itervalues(): # Get the lines that correspond to each string start_line = str['startLine'] end_line = str['endLine'] # Get the revisions that touched those lines revs = [] for line_number in range(start_line, end_line + 1): revs.append(line_revs[line_number]) # Merge with any revisions that were already there # (for explict revision specification) if 'revs' in str: revs += str['revs'] # Assign the revisions to the string str['revs'] = frozenset(revs) def DoesRevisionSuperceed(filename, rev1, rev2): ''' Tells whether a revision superceeds another. This essentially means that the older revision is an ancestor of the newer one. This also returns True if the two revisions are the same. @param rev1: the revision that may be superceeding the other @param rev2: the revision that may be superceeded @return: True if rev1 superceeds rev2 or they're the same ''' if rev1 == rev2: return True # TODO: Add filename args = ['hg', 'log', '-r', 'ancestors(%s)' % rev1, '--template', '{node|short}\n', filename] output_lines = _GetOutputLines(args) return rev2 in output_lines def NewestRevision(filename, rev1, rev2): ''' Returns which of two revisions is closest to the head of the repository. If none of them is the ancestor of the other, then we return either one. @param rev1: the first revision @param rev2: the second revision ''' if DoesRevisionSuperceed(filename, rev1, rev2): return rev1 return rev2
Python
''' Module which compares languague files to the master file and detects issues. @author: Rodrigo Damazio ''' import os from mytracks.parser import StringsParser import mytracks.history class Validator(object): def __init__(self, languages): ''' Builds a strings file validator. Params: @param languages: a dictionary mapping each language to its corresponding directory ''' self._langs = {} self._master = None self._language_paths = languages parser = StringsParser() for lang, lang_dir in languages.iteritems(): filename = os.path.join(lang_dir, 'strings.xml') parsed_file = parser.Parse(filename) mytracks.history.FillMercurialRevisions(filename, parsed_file) if lang == 'en': self._master = parsed_file else: self._langs[lang] = parsed_file self._Reset() def Validate(self): ''' Computes whether all the data in the files for the given languages is valid. ''' self._Reset() self._ValidateMissingKeys() self._ValidateOutdatedKeys() def valid(self): return (len(self._missing_in_master) == 0 and len(self._missing_in_lang) == 0 and len(self._outdated_in_lang) == 0) def missing_in_master(self): return self._missing_in_master def missing_in_lang(self): return self._missing_in_lang def outdated_in_lang(self): return self._outdated_in_lang def _Reset(self): # These are maps from language to string name list self._missing_in_master = {} self._missing_in_lang = {} self._outdated_in_lang = {} def _ValidateMissingKeys(self): ''' Computes whether there are missing keys on either side. ''' master_keys = frozenset(self._master.iterkeys()) for lang, file in self._langs.iteritems(): keys = frozenset(file.iterkeys()) missing_in_master = keys - master_keys missing_in_lang = master_keys - keys if len(missing_in_master) > 0: self._missing_in_master[lang] = missing_in_master if len(missing_in_lang) > 0: self._missing_in_lang[lang] = missing_in_lang def _ValidateOutdatedKeys(self): ''' Computers whether any of the language keys are outdated with relation to the master keys. ''' for lang, file in self._langs.iteritems(): outdated = [] for key, str in file.iteritems(): # Get all revisions that touched master and language files for this # string. master_str = self._master[key] master_revs = master_str['revs'] lang_revs = str['revs'] if not master_revs or not lang_revs: print 'WARNING: No revision for %s in %s' % (key, lang) continue master_file = os.path.join(self._language_paths['en'], 'strings.xml') lang_file = os.path.join(self._language_paths[lang], 'strings.xml') # Assume that the repository has a single head (TODO: check that), # and as such there is always one revision which superceeds all others. master_rev = reduce( lambda r1, r2: mytracks.history.NewestRevision(master_file, r1, r2), master_revs) lang_rev = reduce( lambda r1, r2: mytracks.history.NewestRevision(lang_file, r1, r2), lang_revs) # If the master version is newer than the lang version if mytracks.history.DoesRevisionSuperceed(lang_file, master_rev, lang_rev): outdated.append(key) if len(outdated) > 0: self._outdated_in_lang[lang] = outdated
Python
#!/usr/bin/python ''' Entry point for My Tracks i18n tool. @author: Rodrigo Damazio ''' import mytracks.files import mytracks.translate import mytracks.validate import sys def Usage(): print 'Usage: %s <command> [<language> ...]\n' % sys.argv[0] print 'Commands are:' print ' cleanup' print ' translate' print ' validate' sys.exit(1) def Translate(languages): ''' Asks the user to interactively translate any missing or oudated strings from the files for the given languages. @param languages: the languages to translate ''' validator = mytracks.validate.Validator(languages) validator.Validate() missing = validator.missing_in_lang() outdated = validator.outdated_in_lang() for lang in languages: untranslated = missing[lang] + outdated[lang] if len(untranslated) == 0: continue translator = mytracks.translate.Translator(lang) translator.Translate(untranslated) def Validate(languages): ''' Computes and displays errors in the string files for the given languages. @param languages: the languages to compute for ''' validator = mytracks.validate.Validator(languages) validator.Validate() error_count = 0 if (validator.valid()): print 'All files OK' else: for lang, missing in validator.missing_in_master().iteritems(): print 'Missing in master, present in %s: %s:' % (lang, str(missing)) error_count = error_count + len(missing) for lang, missing in validator.missing_in_lang().iteritems(): print 'Missing in %s, present in master: %s:' % (lang, str(missing)) error_count = error_count + len(missing) for lang, outdated in validator.outdated_in_lang().iteritems(): print 'Outdated in %s: %s:' % (lang, str(outdated)) error_count = error_count + len(outdated) return error_count if __name__ == '__main__': argv = sys.argv argc = len(argv) if argc < 2: Usage() languages = mytracks.files.GetAllLanguageFiles() if argc == 3: langs = set(argv[2:]) if not langs.issubset(languages): raise 'Language(s) not found' # Filter just to the languages specified languages = dict((lang, lang_file) for lang, lang_file in languages.iteritems() if lang in langs or lang == 'en' ) cmd = argv[1] if cmd == 'translate': Translate(languages) elif cmd == 'validate': error_count = Validate(languages) else: Usage() error_count = 0 print '%d errors found.' % error_count
Python
''' Module for dealing with resource files (but not their contents). @author: Rodrigo Damazio ''' import os.path from glob import glob import re MYTRACKS_RES_DIR = 'MyTracks/res' ANDROID_MASTER_VALUES = 'values' ANDROID_VALUES_MASK = 'values-*' def GetMyTracksDir(): ''' Returns the directory in which the MyTracks directory is located. ''' path = os.getcwd() while not os.path.isdir(os.path.join(path, MYTRACKS_RES_DIR)): if path == '/': raise 'Not in My Tracks project' # Go up one level path = os.path.split(path)[0] return path def GetAllLanguageFiles(): ''' Returns a mapping from all found languages to their respective directories. ''' mytracks_path = GetMyTracksDir() res_dir = os.path.join(mytracks_path, MYTRACKS_RES_DIR, ANDROID_VALUES_MASK) language_dirs = glob(res_dir) master_dir = os.path.join(mytracks_path, MYTRACKS_RES_DIR, ANDROID_MASTER_VALUES) if len(language_dirs) == 0: raise 'No languages found!' if not os.path.isdir(master_dir): raise 'Couldn\'t find master file' language_tuples = [(re.findall(r'.*values-([A-Za-z-]+)', dir)[0],dir) for dir in language_dirs] language_tuples.append(('en', master_dir)) return dict(language_tuples)
Python
''' Module which parses a string XML file. @author: Rodrigo Damazio ''' from xml.parsers.expat import ParserCreate import re #import xml.etree.ElementTree as ET class StringsParser(object): ''' Parser for string XML files. This object is not thread-safe and should be used for parsing a single file at a time, only. ''' def Parse(self, file): ''' Parses the given file and returns a dictionary mapping keys to an object with attributes for that key, such as the value, start/end line and explicit revisions. In addition to the standard XML format of the strings file, this parser supports an annotation inside comments, in one of these formats: <!-- KEEP_PARENT name="bla" --> <!-- KEEP_PARENT name="bla" rev="123456789012" --> Such an annotation indicates that we're explicitly inheriting form the master file (and the optional revision says that this decision is compatible with the master file up to that revision). @param file: the name of the file to parse ''' self._Reset() # Unfortunately expat is the only parser that will give us line numbers self._xml_parser = ParserCreate() self._xml_parser.StartElementHandler = self._StartElementHandler self._xml_parser.EndElementHandler = self._EndElementHandler self._xml_parser.CharacterDataHandler = self._CharacterDataHandler self._xml_parser.CommentHandler = self._CommentHandler file_obj = open(file) self._xml_parser.ParseFile(file_obj) file_obj.close() return self._all_strings def _Reset(self): self._currentString = None self._currentStringName = None self._currentStringValue = None self._all_strings = {} def _StartElementHandler(self, name, attrs): if name != 'string': return if 'name' not in attrs: return assert not self._currentString assert not self._currentStringName self._currentString = { 'startLine' : self._xml_parser.CurrentLineNumber, } if 'rev' in attrs: self._currentString['revs'] = [attrs['rev']] self._currentStringName = attrs['name'] self._currentStringValue = '' def _EndElementHandler(self, name): if name != 'string': return assert self._currentString assert self._currentStringName self._currentString['value'] = self._currentStringValue self._currentString['endLine'] = self._xml_parser.CurrentLineNumber self._all_strings[self._currentStringName] = self._currentString self._currentString = None self._currentStringName = None self._currentStringValue = None def _CharacterDataHandler(self, data): if not self._currentString: return self._currentStringValue += data _KEEP_PARENT_REGEX = re.compile(r'\s*KEEP_PARENT\s+' r'name\s*=\s*[\'"]?(?P<name>[a-z0-9_]+)[\'"]?' r'(?:\s+rev=[\'"]?(?P<rev>[0-9a-f]{12})[\'"]?)?\s*', re.MULTILINE | re.DOTALL) def _CommentHandler(self, data): keep_parent_match = self._KEEP_PARENT_REGEX.match(data) if not keep_parent_match: return name = keep_parent_match.group('name') self._all_strings[name] = { 'keepParent' : True, 'startLine' : self._xml_parser.CurrentLineNumber, 'endLine' : self._xml_parser.CurrentLineNumber } rev = keep_parent_match.group('rev') if rev: self._all_strings[name]['revs'] = [rev]
Python
''' Module which prompts the user for translations and saves them. TODO: implement @author: Rodrigo Damazio ''' class Translator(object): ''' classdocs ''' def __init__(self, language): ''' Constructor ''' self._language = language def Translate(self, string_names): print string_names
Python
#!/usr/bin/python2.6 # # Simple http server to emulate api.playfoursquare.com import logging import shutil import sys import urlparse import SimpleHTTPServer import BaseHTTPServer class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): """Handle playfoursquare.com requests, for testing.""" def do_GET(self): logging.warn('do_GET: %s, %s', self.command, self.path) url = urlparse.urlparse(self.path) logging.warn('do_GET: %s', url) query = urlparse.parse_qs(url.query) query_keys = [pair[0] for pair in query] response = self.handle_url(url) if response != None: self.send_200() shutil.copyfileobj(response, self.wfile) self.wfile.close() do_POST = do_GET def handle_url(self, url): path = None if url.path == '/v1/venue': path = '../captures/api/v1/venue.xml' elif url.path == '/v1/addvenue': path = '../captures/api/v1/venue.xml' elif url.path == '/v1/venues': path = '../captures/api/v1/venues.xml' elif url.path == '/v1/user': path = '../captures/api/v1/user.xml' elif url.path == '/v1/checkcity': path = '../captures/api/v1/checkcity.xml' elif url.path == '/v1/checkins': path = '../captures/api/v1/checkins.xml' elif url.path == '/v1/cities': path = '../captures/api/v1/cities.xml' elif url.path == '/v1/switchcity': path = '../captures/api/v1/switchcity.xml' elif url.path == '/v1/tips': path = '../captures/api/v1/tips.xml' elif url.path == '/v1/checkin': path = '../captures/api/v1/checkin.xml' elif url.path == '/history/12345.rss': path = '../captures/api/v1/feed.xml' if path is None: self.send_error(404) else: logging.warn('Using: %s' % path) return open(path) def send_200(self): self.send_response(200) self.send_header('Content-type', 'text/xml') self.end_headers() def main(): if len(sys.argv) > 1: port = int(sys.argv[1]) else: port = 8080 server_address = ('0.0.0.0', port) httpd = BaseHTTPServer.HTTPServer(server_address, RequestHandler) sa = httpd.socket.getsockname() print "Serving HTTP on", sa[0], "port", sa[1], "..." httpd.serve_forever() if __name__ == '__main__': main()
Python
#!/usr/bin/python import os import subprocess import sys BASEDIR = '../main/src/com/joelapenna/foursquare' TYPESDIR = '../captures/types/v1' captures = sys.argv[1:] if not captures: captures = os.listdir(TYPESDIR) for f in captures: basename = f.split('.')[0] javaname = ''.join([c.capitalize() for c in basename.split('_')]) fullpath = os.path.join(TYPESDIR, f) typepath = os.path.join(BASEDIR, 'types', javaname + '.java') parserpath = os.path.join(BASEDIR, 'parsers', javaname + 'Parser.java') cmd = 'python gen_class.py %s > %s' % (fullpath, typepath) print cmd subprocess.call(cmd, stdout=sys.stdout, shell=True) cmd = 'python gen_parser.py %s > %s' % (fullpath, parserpath) print cmd subprocess.call(cmd, stdout=sys.stdout, shell=True)
Python
#!/usr/bin/python """ Pull a oAuth protected page from foursquare. Expects ~/.oget to contain (one on each line): CONSUMER_KEY CONSUMER_KEY_SECRET USERNAME PASSWORD Don't forget to chmod 600 the file! """ import httplib import os import re import sys import urllib import urllib2 import urlparse import user from xml.dom import pulldom from xml.dom import minidom import oauth """From: http://groups.google.com/group/foursquare-api/web/oauth @consumer = OAuth::Consumer.new("consumer_token","consumer_secret", { :site => "http://foursquare.com", :scheme => :header, :http_method => :post, :request_token_path => "/oauth/request_token", :access_token_path => "/oauth/access_token", :authorize_path => "/oauth/authorize" }) """ SERVER = 'api.foursquare.com:80' CONTENT_TYPE_HEADER = {'Content-Type' :'application/x-www-form-urlencoded'} SIGNATURE_METHOD = oauth.OAuthSignatureMethod_HMAC_SHA1() AUTHEXCHANGE_URL = 'http://api.foursquare.com/v1/authexchange' def parse_auth_response(auth_response): return ( re.search('<oauth_token>(.*)</oauth_token>', auth_response).groups()[0], re.search('<oauth_token_secret>(.*)</oauth_token_secret>', auth_response).groups()[0] ) def create_signed_oauth_request(username, password, consumer): oauth_request = oauth.OAuthRequest.from_consumer_and_token( consumer, http_method='POST', http_url=AUTHEXCHANGE_URL, parameters=dict(fs_username=username, fs_password=password)) oauth_request.sign_request(SIGNATURE_METHOD, consumer, None) return oauth_request def main(): url = urlparse.urlparse(sys.argv[1]) # Nevermind that the query can have repeated keys. parameters = dict(urlparse.parse_qsl(url.query)) password_file = open(os.path.join(user.home, '.oget')) lines = [line.strip() for line in password_file.readlines()] if len(lines) == 4: cons_key, cons_key_secret, username, password = lines access_token = None else: cons_key, cons_key_secret, username, password, token, secret = lines access_token = oauth.OAuthToken(token, secret) consumer = oauth.OAuthConsumer(cons_key, cons_key_secret) if not access_token: oauth_request = create_signed_oauth_request(username, password, consumer) connection = httplib.HTTPConnection(SERVER) headers = {'Content-Type' :'application/x-www-form-urlencoded'} connection.request(oauth_request.http_method, AUTHEXCHANGE_URL, body=oauth_request.to_postdata(), headers=headers) auth_response = connection.getresponse().read() token = parse_auth_response(auth_response) access_token = oauth.OAuthToken(*token) open(os.path.join(user.home, '.oget'), 'w').write('\n'.join(( cons_key, cons_key_secret, username, password, token[0], token[1]))) oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer, access_token, http_method='POST', http_url=url.geturl(), parameters=parameters) oauth_request.sign_request(SIGNATURE_METHOD, consumer, access_token) connection = httplib.HTTPConnection(SERVER) connection.request(oauth_request.http_method, oauth_request.to_url(), body=oauth_request.to_postdata(), headers=CONTENT_TYPE_HEADER) print connection.getresponse().read() #print minidom.parse(connection.getresponse()).toprettyxml(indent=' ') if __name__ == '__main__': main()
Python
#!/usr/bin/python import datetime import sys import textwrap import common from xml.dom import pulldom PARSER = """\ /** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.parsers; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareError; import com.joelapenna.foursquare.error.FoursquareParseException; import com.joelapenna.foursquare.types.%(type_name)s; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * Auto-generated: %(timestamp)s * * @author Joe LaPenna (joe@joelapenna.com) * @param <T> */ public class %(type_name)sParser extends AbstractParser<%(type_name)s> { private static final Logger LOG = Logger.getLogger(%(type_name)sParser.class.getCanonicalName()); private static final boolean DEBUG = Foursquare.PARSER_DEBUG; @Override public %(type_name)s parseInner(XmlPullParser parser) throws XmlPullParserException, IOException, FoursquareError, FoursquareParseException { parser.require(XmlPullParser.START_TAG, null, null); %(type_name)s %(top_node_name)s = new %(type_name)s(); while (parser.nextTag() == XmlPullParser.START_TAG) { String name = parser.getName(); %(stanzas)s } else { // Consume something we don't understand. if (DEBUG) LOG.log(Level.FINE, "Found tag that we don't recognize: " + name); skipSubTree(parser); } } return %(top_node_name)s; } }""" BOOLEAN_STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(Boolean.valueOf(parser.nextText())); """ GROUP_STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(new GroupParser(new %(sub_parser_camel_case)s()).parse(parser)); """ COMPLEX_STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(new %(parser_name)s().parse(parser)); """ STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(parser.nextText()); """ def main(): type_name, top_node_name, attributes = common.WalkNodesForAttributes( sys.argv[1]) GenerateClass(type_name, top_node_name, attributes) def GenerateClass(type_name, top_node_name, attributes): """generate it. type_name: the type of object the parser returns top_node_name: the name of the object the parser returns. per common.WalkNodsForAttributes """ stanzas = [] for name in sorted(attributes): typ, children = attributes[name] replacements = Replacements(top_node_name, name, typ, children) if typ == common.BOOLEAN: stanzas.append(BOOLEAN_STANZA % replacements) elif typ == common.GROUP: stanzas.append(GROUP_STANZA % replacements) elif typ in common.COMPLEX: stanzas.append(COMPLEX_STANZA % replacements) else: stanzas.append(STANZA % replacements) if stanzas: # pop off the extranious } else for the first conditional stanza. stanzas[0] = stanzas[0].replace('} else ', '', 1) replacements = Replacements(top_node_name, name, typ, [None]) replacements['stanzas'] = '\n'.join(stanzas).strip() print PARSER % replacements def Replacements(top_node_name, name, typ, children): # CameCaseClassName type_name = ''.join([word.capitalize() for word in top_node_name.split('_')]) # CamelCaseClassName camel_name = ''.join([word.capitalize() for word in name.split('_')]) # camelCaseLocalName attribute_name = camel_name.lower().capitalize() # mFieldName field_name = 'm' + camel_name if children[0]: sub_parser_camel_case = children[0] + 'Parser' else: sub_parser_camel_case = (camel_name[:-1] + 'Parser') return { 'type_name': type_name, 'name': name, 'top_node_name': top_node_name, 'camel_name': camel_name, 'parser_name': typ + 'Parser', 'attribute_name': attribute_name, 'field_name': field_name, 'typ': typ, 'timestamp': datetime.datetime.now(), 'sub_parser_camel_case': sub_parser_camel_case, 'sub_type': children[0] } if __name__ == '__main__': main()
Python
#!/usr/bin/python import logging from xml.dom import minidom from xml.dom import pulldom BOOLEAN = "boolean" STRING = "String" GROUP = "Group" # Interfaces that all FoursquareTypes implement. DEFAULT_INTERFACES = ['FoursquareType'] # Interfaces that specific FoursqureTypes implement. INTERFACES = { } DEFAULT_CLASS_IMPORTS = [ ] CLASS_IMPORTS = { # 'Checkin': DEFAULT_CLASS_IMPORTS + [ # 'import com.joelapenna.foursquare.filters.VenueFilterable' # ], # 'Venue': DEFAULT_CLASS_IMPORTS + [ # 'import com.joelapenna.foursquare.filters.VenueFilterable' # ], # 'Tip': DEFAULT_CLASS_IMPORTS + [ # 'import com.joelapenna.foursquare.filters.VenueFilterable' # ], } COMPLEX = [ 'Group', 'Badge', 'Beenhere', 'Checkin', 'CheckinResponse', 'City', 'Credentials', 'Data', 'Mayor', 'Rank', 'Score', 'Scoring', 'Settings', 'Stats', 'Tags', 'Tip', 'User', 'Venue', ] TYPES = COMPLEX + ['boolean'] def WalkNodesForAttributes(path): """Parse the xml file getting all attributes. <venue> <attribute>value</attribute> </venue> Returns: type_name - The java-style name the top node will have. "Venue" top_node_name - unadultured name of the xml stanza, probably the type of java class we're creating. "venue" attributes - {'attribute': 'value'} """ doc = pulldom.parse(path) type_name = None top_node_name = None attributes = {} level = 0 for event, node in doc: # For skipping parts of a tree. if level > 0: if event == pulldom.END_ELEMENT: level-=1 logging.warn('(%s) Skip end: %s' % (str(level), node)) continue elif event == pulldom.START_ELEMENT: logging.warn('(%s) Skipping: %s' % (str(level), node)) level+=1 continue if event == pulldom.START_ELEMENT: logging.warn('Parsing: ' + node.tagName) # Get the type name to use. if type_name is None: type_name = ''.join([word.capitalize() for word in node.tagName.split('_')]) top_node_name = node.tagName logging.warn('Found Top Node Name: ' + top_node_name) continue typ = node.getAttribute('type') child = node.getAttribute('child') # We don't want to walk complex types. if typ in COMPLEX: logging.warn('Found Complex: ' + node.tagName) level = 1 elif typ not in TYPES: logging.warn('Found String: ' + typ) typ = STRING else: logging.warn('Found Type: ' + typ) logging.warn('Adding: ' + str((node, typ))) attributes.setdefault(node.tagName, (typ, [child])) logging.warn('Attr: ' + str((type_name, top_node_name, attributes))) return type_name, top_node_name, attributes
Python
#!/usr/bin/python2.6 # # Simple http server to emulate api.playfoursquare.com import logging import shutil import sys import urlparse import SimpleHTTPServer import BaseHTTPServer class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): """Handle playfoursquare.com requests, for testing.""" def do_GET(self): logging.warn('do_GET: %s, %s', self.command, self.path) url = urlparse.urlparse(self.path) logging.warn('do_GET: %s', url) query = urlparse.parse_qs(url.query) query_keys = [pair[0] for pair in query] response = self.handle_url(url) if response != None: self.send_200() shutil.copyfileobj(response, self.wfile) self.wfile.close() do_POST = do_GET def handle_url(self, url): path = None if url.path == '/v1/venue': path = '../captures/api/v1/venue.xml' elif url.path == '/v1/addvenue': path = '../captures/api/v1/venue.xml' elif url.path == '/v1/venues': path = '../captures/api/v1/venues.xml' elif url.path == '/v1/user': path = '../captures/api/v1/user.xml' elif url.path == '/v1/checkcity': path = '../captures/api/v1/checkcity.xml' elif url.path == '/v1/checkins': path = '../captures/api/v1/checkins.xml' elif url.path == '/v1/cities': path = '../captures/api/v1/cities.xml' elif url.path == '/v1/switchcity': path = '../captures/api/v1/switchcity.xml' elif url.path == '/v1/tips': path = '../captures/api/v1/tips.xml' elif url.path == '/v1/checkin': path = '../captures/api/v1/checkin.xml' elif url.path == '/history/12345.rss': path = '../captures/api/v1/feed.xml' if path is None: self.send_error(404) else: logging.warn('Using: %s' % path) return open(path) def send_200(self): self.send_response(200) self.send_header('Content-type', 'text/xml') self.end_headers() def main(): if len(sys.argv) > 1: port = int(sys.argv[1]) else: port = 8080 server_address = ('0.0.0.0', port) httpd = BaseHTTPServer.HTTPServer(server_address, RequestHandler) sa = httpd.socket.getsockname() print "Serving HTTP on", sa[0], "port", sa[1], "..." httpd.serve_forever() if __name__ == '__main__': main()
Python
#!/usr/bin/python import os import subprocess import sys BASEDIR = '../main/src/com/joelapenna/foursquare' TYPESDIR = '../captures/types/v1' captures = sys.argv[1:] if not captures: captures = os.listdir(TYPESDIR) for f in captures: basename = f.split('.')[0] javaname = ''.join([c.capitalize() for c in basename.split('_')]) fullpath = os.path.join(TYPESDIR, f) typepath = os.path.join(BASEDIR, 'types', javaname + '.java') parserpath = os.path.join(BASEDIR, 'parsers', javaname + 'Parser.java') cmd = 'python gen_class.py %s > %s' % (fullpath, typepath) print cmd subprocess.call(cmd, stdout=sys.stdout, shell=True) cmd = 'python gen_parser.py %s > %s' % (fullpath, parserpath) print cmd subprocess.call(cmd, stdout=sys.stdout, shell=True)
Python
#!/usr/bin/python """ Pull a oAuth protected page from foursquare. Expects ~/.oget to contain (one on each line): CONSUMER_KEY CONSUMER_KEY_SECRET USERNAME PASSWORD Don't forget to chmod 600 the file! """ import httplib import os import re import sys import urllib import urllib2 import urlparse import user from xml.dom import pulldom from xml.dom import minidom import oauth """From: http://groups.google.com/group/foursquare-api/web/oauth @consumer = OAuth::Consumer.new("consumer_token","consumer_secret", { :site => "http://foursquare.com", :scheme => :header, :http_method => :post, :request_token_path => "/oauth/request_token", :access_token_path => "/oauth/access_token", :authorize_path => "/oauth/authorize" }) """ SERVER = 'api.foursquare.com:80' CONTENT_TYPE_HEADER = {'Content-Type' :'application/x-www-form-urlencoded'} SIGNATURE_METHOD = oauth.OAuthSignatureMethod_HMAC_SHA1() AUTHEXCHANGE_URL = 'http://api.foursquare.com/v1/authexchange' def parse_auth_response(auth_response): return ( re.search('<oauth_token>(.*)</oauth_token>', auth_response).groups()[0], re.search('<oauth_token_secret>(.*)</oauth_token_secret>', auth_response).groups()[0] ) def create_signed_oauth_request(username, password, consumer): oauth_request = oauth.OAuthRequest.from_consumer_and_token( consumer, http_method='POST', http_url=AUTHEXCHANGE_URL, parameters=dict(fs_username=username, fs_password=password)) oauth_request.sign_request(SIGNATURE_METHOD, consumer, None) return oauth_request def main(): url = urlparse.urlparse(sys.argv[1]) # Nevermind that the query can have repeated keys. parameters = dict(urlparse.parse_qsl(url.query)) password_file = open(os.path.join(user.home, '.oget')) lines = [line.strip() for line in password_file.readlines()] if len(lines) == 4: cons_key, cons_key_secret, username, password = lines access_token = None else: cons_key, cons_key_secret, username, password, token, secret = lines access_token = oauth.OAuthToken(token, secret) consumer = oauth.OAuthConsumer(cons_key, cons_key_secret) if not access_token: oauth_request = create_signed_oauth_request(username, password, consumer) connection = httplib.HTTPConnection(SERVER) headers = {'Content-Type' :'application/x-www-form-urlencoded'} connection.request(oauth_request.http_method, AUTHEXCHANGE_URL, body=oauth_request.to_postdata(), headers=headers) auth_response = connection.getresponse().read() token = parse_auth_response(auth_response) access_token = oauth.OAuthToken(*token) open(os.path.join(user.home, '.oget'), 'w').write('\n'.join(( cons_key, cons_key_secret, username, password, token[0], token[1]))) oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer, access_token, http_method='POST', http_url=url.geturl(), parameters=parameters) oauth_request.sign_request(SIGNATURE_METHOD, consumer, access_token) connection = httplib.HTTPConnection(SERVER) connection.request(oauth_request.http_method, oauth_request.to_url(), body=oauth_request.to_postdata(), headers=CONTENT_TYPE_HEADER) print connection.getresponse().read() #print minidom.parse(connection.getresponse()).toprettyxml(indent=' ') if __name__ == '__main__': main()
Python
#!/usr/bin/python import datetime import sys import textwrap import common from xml.dom import pulldom PARSER = """\ /** * Copyright 2009 Joe LaPenna */ package com.joelapenna.foursquare.parsers; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareError; import com.joelapenna.foursquare.error.FoursquareParseException; import com.joelapenna.foursquare.types.%(type_name)s; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; /** * Auto-generated: %(timestamp)s * * @author Joe LaPenna (joe@joelapenna.com) * @param <T> */ public class %(type_name)sParser extends AbstractParser<%(type_name)s> { private static final Logger LOG = Logger.getLogger(%(type_name)sParser.class.getCanonicalName()); private static final boolean DEBUG = Foursquare.PARSER_DEBUG; @Override public %(type_name)s parseInner(XmlPullParser parser) throws XmlPullParserException, IOException, FoursquareError, FoursquareParseException { parser.require(XmlPullParser.START_TAG, null, null); %(type_name)s %(top_node_name)s = new %(type_name)s(); while (parser.nextTag() == XmlPullParser.START_TAG) { String name = parser.getName(); %(stanzas)s } else { // Consume something we don't understand. if (DEBUG) LOG.log(Level.FINE, "Found tag that we don't recognize: " + name); skipSubTree(parser); } } return %(top_node_name)s; } }""" BOOLEAN_STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(Boolean.valueOf(parser.nextText())); """ GROUP_STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(new GroupParser(new %(sub_parser_camel_case)s()).parse(parser)); """ COMPLEX_STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(new %(parser_name)s().parse(parser)); """ STANZA = """\ } else if ("%(name)s".equals(name)) { %(top_node_name)s.set%(camel_name)s(parser.nextText()); """ def main(): type_name, top_node_name, attributes = common.WalkNodesForAttributes( sys.argv[1]) GenerateClass(type_name, top_node_name, attributes) def GenerateClass(type_name, top_node_name, attributes): """generate it. type_name: the type of object the parser returns top_node_name: the name of the object the parser returns. per common.WalkNodsForAttributes """ stanzas = [] for name in sorted(attributes): typ, children = attributes[name] replacements = Replacements(top_node_name, name, typ, children) if typ == common.BOOLEAN: stanzas.append(BOOLEAN_STANZA % replacements) elif typ == common.GROUP: stanzas.append(GROUP_STANZA % replacements) elif typ in common.COMPLEX: stanzas.append(COMPLEX_STANZA % replacements) else: stanzas.append(STANZA % replacements) if stanzas: # pop off the extranious } else for the first conditional stanza. stanzas[0] = stanzas[0].replace('} else ', '', 1) replacements = Replacements(top_node_name, name, typ, [None]) replacements['stanzas'] = '\n'.join(stanzas).strip() print PARSER % replacements def Replacements(top_node_name, name, typ, children): # CameCaseClassName type_name = ''.join([word.capitalize() for word in top_node_name.split('_')]) # CamelCaseClassName camel_name = ''.join([word.capitalize() for word in name.split('_')]) # camelCaseLocalName attribute_name = camel_name.lower().capitalize() # mFieldName field_name = 'm' + camel_name if children[0]: sub_parser_camel_case = children[0] + 'Parser' else: sub_parser_camel_case = (camel_name[:-1] + 'Parser') return { 'type_name': type_name, 'name': name, 'top_node_name': top_node_name, 'camel_name': camel_name, 'parser_name': typ + 'Parser', 'attribute_name': attribute_name, 'field_name': field_name, 'typ': typ, 'timestamp': datetime.datetime.now(), 'sub_parser_camel_case': sub_parser_camel_case, 'sub_type': children[0] } if __name__ == '__main__': main()
Python
#!/usr/bin/python import logging from xml.dom import minidom from xml.dom import pulldom BOOLEAN = "boolean" STRING = "String" GROUP = "Group" # Interfaces that all FoursquareTypes implement. DEFAULT_INTERFACES = ['FoursquareType'] # Interfaces that specific FoursqureTypes implement. INTERFACES = { } DEFAULT_CLASS_IMPORTS = [ ] CLASS_IMPORTS = { # 'Checkin': DEFAULT_CLASS_IMPORTS + [ # 'import com.joelapenna.foursquare.filters.VenueFilterable' # ], # 'Venue': DEFAULT_CLASS_IMPORTS + [ # 'import com.joelapenna.foursquare.filters.VenueFilterable' # ], # 'Tip': DEFAULT_CLASS_IMPORTS + [ # 'import com.joelapenna.foursquare.filters.VenueFilterable' # ], } COMPLEX = [ 'Group', 'Badge', 'Beenhere', 'Checkin', 'CheckinResponse', 'City', 'Credentials', 'Data', 'Mayor', 'Rank', 'Score', 'Scoring', 'Settings', 'Stats', 'Tags', 'Tip', 'User', 'Venue', ] TYPES = COMPLEX + ['boolean'] def WalkNodesForAttributes(path): """Parse the xml file getting all attributes. <venue> <attribute>value</attribute> </venue> Returns: type_name - The java-style name the top node will have. "Venue" top_node_name - unadultured name of the xml stanza, probably the type of java class we're creating. "venue" attributes - {'attribute': 'value'} """ doc = pulldom.parse(path) type_name = None top_node_name = None attributes = {} level = 0 for event, node in doc: # For skipping parts of a tree. if level > 0: if event == pulldom.END_ELEMENT: level-=1 logging.warn('(%s) Skip end: %s' % (str(level), node)) continue elif event == pulldom.START_ELEMENT: logging.warn('(%s) Skipping: %s' % (str(level), node)) level+=1 continue if event == pulldom.START_ELEMENT: logging.warn('Parsing: ' + node.tagName) # Get the type name to use. if type_name is None: type_name = ''.join([word.capitalize() for word in node.tagName.split('_')]) top_node_name = node.tagName logging.warn('Found Top Node Name: ' + top_node_name) continue typ = node.getAttribute('type') child = node.getAttribute('child') # We don't want to walk complex types. if typ in COMPLEX: logging.warn('Found Complex: ' + node.tagName) level = 1 elif typ not in TYPES: logging.warn('Found String: ' + typ) typ = STRING else: logging.warn('Found Type: ' + typ) logging.warn('Adding: ' + str((node, typ))) attributes.setdefault(node.tagName, (typ, [child])) logging.warn('Attr: ' + str((type_name, top_node_name, attributes))) return type_name, top_node_name, attributes
Python
#==================================================================== # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # ==================================================================== # # This software consists of voluntary contributions made by many # individuals on behalf of the Apache Software Foundation. For more # information on the Apache Software Foundation, please see # <http://www.apache.org/>. # import os import re import tempfile import shutil ignore_pattern = re.compile('^(.svn|target|bin|classes)') java_pattern = re.compile('^.*\.java') annot_pattern = re.compile('import org\.apache\.http\.annotation\.') def process_dir(dir): files = os.listdir(dir) for file in files: f = os.path.join(dir, file) if os.path.isdir(f): if not ignore_pattern.match(file): process_dir(f) else: if java_pattern.match(file): process_source(f) def process_source(filename): tmp = tempfile.mkstemp() tmpfd = tmp[0] tmpfile = tmp[1] try: changed = False dst = os.fdopen(tmpfd, 'w') try: src = open(filename) try: for line in src: if annot_pattern.match(line): changed = True line = line.replace('import org.apache.http.annotation.', 'import net.jcip.annotations.') dst.write(line) finally: src.close() finally: dst.close(); if changed: shutil.move(tmpfile, filename) else: os.remove(tmpfile) except: os.remove(tmpfile) process_dir('.')
Python
#!/usr/bin/python #for test webpy in visualhost import sys sys.path.insert(0, "/usr/local/bin/python") sys.path.insert(0, "/www/fancyhan.host/ifancc_com/htdocs/115") sys.path.insert(0, "/www/fancyhan.host/ifancc_com/modules") import web from web.contrib.template import render_mako from netcrack import netdisk render = render_mako( directories=['templates'], module_directory="templates", input_encoding='utf-8', output_encoding='utf-8', ) class main: def GET(self): web.header('Content-Type','text/html') return render.main() class api: def GET(self,code): web.header('Content-Type','text/javascript') return netdisk(code).json() urls = ( '/',main, '/api/(.*)',api, '/api/http://u\.115\.com/file/(.*)',api ) app = web.application(urls,globals()) #mapping = (r'wap\.ifancc\.com',app) #app2= web.subdomain_application(mapping) web.wsgi.runwsgi = lambda func, addr=None: web.wsgi.runfcgi(func,addr) if __name__ == '__main__': app.run() #print render.main()
Python
# -*- encoding:utf-8 -*- from mako import runtime, filters, cache UNDEFINED = runtime.UNDEFINED __M_dict_builtin = dict __M_locals_builtin = locals _magic_number = 6 _modified_time = 1309516407.3164999 _template_filename='templates/main.html' _template_uri='main.html' _template_cache=cache.Cache(__name__, _modified_time) _source_encoding='utf-8' _exports = [] def render_body(context,**pageargs): context.caller_stack._push_frame() try: __M_locals = __M_dict_builtin(pageargs=pageargs) __M_writer = context.writer() # SOURCE LINE 1 __M_writer(u'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n<html xmlns="http://www.w3.org/1999/xhtml">\n<head>\n<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />\n<title>115\u7f51\u76d8 \u67e5\u8be2\u5668</title>\n<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>\n<!--[if (gte IE 6)&(lte IE 8)]>\n <script type="text/javascript" src="/selectivizr-min.js"></script>\n<![endif]--> \n\n\n\n<script type="text/javascript">\n\n\t\t\n\nvar URIlabel = "\u8bf7\u8f93\u5165\u7f51\u5740\u6216\u63d0\u53d6\u7801";\n\n$(document).ready(function(){\n\t$("#115URI").blur(function(){\n\t\tif(this.value == \'\') this.value=URIlabel;\n\t\t});\n\t$("#115URI").focus(function(){\n\t\tif(this.value == URIlabel) this.value=\'\';\n\t\t});\n\t$("#115URIbotton").click(function(){\n\t\tvar pickcode = $("#115URI").attr("value");\n\t\tpickcode = pickcode.replace("http://u.115.com/file/","");\n\t\tpickcode = pickcode.replace("u.115.com/file/","");\n\t\t\n\t\t$.getJSON("/api/"+pickcode,function(data){\n\t\t\t\t\tif(data.state==false)\n\t\t\t\t\t{\n\t\t\t\t\t\talert(data.message);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\t$("#filename").html(data.filename);\n\t\t\t\t\t$("#sha").html(data.sha);\n\t\t\t\t\t$("#downURL1").html(data.urls[0]);\n\t\t\t\t\t$("#downURL2").html(data.urls[1]);\n\t\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\t);\n\t\t});\n});\n</script>\n<link href="base.css" rel="stylesheet" type="text/css" />\n</head>\n<body>\n<div id="wapper">\n\t<div id="toplogo">115\u7f51\u76d8\u4fe1\u606f\u67e5\u8be2</div>\n <div class="box">\n \u8bf7\u5728\u4e0b\u65b9\u8f93\u5165115\u7f51\u76d8\u7684\u63d0\u53d6\u7801\u6216\u63d0\u53d6\u9875\u9762\u7f51\u5740\n \t<div class="lin"></div>\n <form>\n \t<fieldset>\n <input id="115URIbotton" class="submit" type="botton" value="\u7ed9\u6211\u5206\u6790" />\n <input id="115URI" class="url" value="" size="40" maxlength="200" name="url" />\n </fieldset>\n </form>\n </div>\n <div id="resultbox" class="box">\n \t\u7f51\u76d8\u4fe1\u606f\n <div class="lin"></div>\n <table class="file-form" >\n <thead>\n <tr>\n <th scope="col" width="20%" >\u540d\u79f0&nbsp;</th>\n <th scope="col" width="80%">\u503c&nbsp;</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>\u6587\u4ef6\u540d&nbsp;</td>\n <td id="filename">&nbsp;</td>\n </tr>\n <tr>\n <td>sha1&nbsp;</td>\n <td id="sha">&nbsp;</td>\n </tr>\n <tr>\n <td>\u4e0b\u8f7d\u5730\u57401&nbsp;</td>\n <td id="downURL1">&nbsp;</td>\n </tr>\n <tr>\n <td>\u4e0b\u8f7d\u5730\u57402&nbsp;</td>\n <td id="downURL2">&nbsp;</td>\n </tr>\n </tbody>\n </table>\n\t\t</div>\n <div id="footer" class="box">\n\t\t\t<span style="color:red">coding:<a href="blog.ifancc.com">fancycode</a>.</span>Contact fancycode at gmail.com for more detail <noscritp><a href="http://www.51.la/?5012927" target="_blank"><img alt="&#x6211;&#x8981;&#x5566;&#x514D;&#x8D39;&#x7EDF;&#x8BA1;" src="http://img.users.51.la/5012927.asp" style="border:none" /></a></noscript>\n\t\t</div> \n\n \n</div>\n\n</body>\n</html>\n') return '' finally: context.caller_stack._pop_frame()
Python
#encoding:utf-8 import urllib import json class netdisk(): '''a class which can fetch 115 netdisk`s file though the given url or pickcode the request url examplehttp://uapi.115.com/?ct=upload_api&ac= get_pick_code_info&pickcode=aqbc8e20&version=1175"''' api = "http://uapi.115.com/?ct=upload_api&ac=get_pick_code_info\ &pickcode=%s&version=1175" def __init__(self,code): '''code is either URL of the file or pickcode''' self.__code = code f = urllib.urlopen(self.api %self.__code) data = f.read() self.__data = json.loads(data) self.state = self.__data['State'] self.message = urllib.unquote(self.__data['Message']) if self.state == True: self.Sha1 = self.__data['Sha1'] self.filename = urllib.unquote(self.__data['FileName']) self.urls = [url['Url'] for url in self.__data["DownloadUrl"]] def json(self): '''return a json str of the file`s info''' if self.state == True: return json.dumps({'filename':self.filename, 'sha':self.Sha1, 'urls':self.urls, 'state':True }) else: return json.dumps({'state':False, 'message':self.message}) #simple unit test if __name__=="__main__": a = netdisk("aqbc8e20") print a._netdisk__data print a.filename print a.json()
Python
#!/usr/bin/env python """ tesshelper.py -- Utility operations to compare, report stats, and copy public headers for tesseract 3.0x VS2008 Project $RCSfile: tesshelper.py,v $ $Revision: 7ca575b377aa $ $Date: 2012/03/07 17:26:31 $ """ r""" Requires: python 2.7 or greater: activestate.com http://www.activestate.com/activepython/downloads because using the new argparse module and new literal set syntax (s={1, 2}) . General Notes: -------------- Format for a .vcproj file entry: <File RelativePath="..\src\allheaders.h" > </File> """ epilogStr = r""" Examples: Assume that tesshelper.py is in c:\buildfolder\tesseract-3.02\vs2008, which is also the current directory. Then, python tesshelper .. compare will compare c:\buildfolder\tesseract-3.02 "library" directories to the libtesseract Project (c:\buildfolder\tesseract-3.02\vs2008\libtesseract\libtesseract.vcproj). python tesshelper .. report will display summary stats for c:\buildfolder\tesseract-3.02 "library" directories and the libtesseract Project. python tesshelper .. copy ..\..\include will copy all "public" libtesseract header files to c:\buildfolder\include. python tesshelper .. clean will clean the vs2008 folder of all build directories, and .user, .suo, .ncb, and other temp files. """ # imports of python standard library modules # See Python Documentation | Library Reference for details import collections import glob import argparse import os import re import shutil import sys # ==================================================================== VERSION = "1.0 %s" % "$Date: 2012/03/07 17:26:31 $".split()[1] PROJ_SUBDIR = r"vs2008\libtesseract" PROJFILE = "libtesseract.vcproj" NEWHEADERS_FILENAME = "newheaders.txt" NEWSOURCES_FILENAME = "newsources.txt" fileNodeTemplate = \ ''' <File RelativePath="..\..\%s" > </File> ''' # ==================================================================== def getProjectfiles(libTessDir, libProjectFile, nTrimChars): """Return sets of all, c, h, and resources files in libtesseract Project""" #extract filenames of header & source files from the .vcproj projectCFiles = set() projectHFiles = set() projectRFiles = set() projectFilesSet = set() f = open(libProjectFile, "r") data = f.read() f.close() projectFiles = re.findall(r'(?i)RelativePath="(\.[^"]+)"', data) for projectFile in projectFiles: root, ext = os.path.splitext(projectFile.lower()) if ext == ".c" or ext == ".cpp": projectCFiles.add(projectFile) elif ext == ".h": projectHFiles.add(projectFile) elif ext == ".rc": projectRFiles.add(projectFile) else: print "unknown file type: %s" % projectFile relativePath = os.path.join(libTessDir, projectFile) relativePath = os.path.abspath(relativePath) relativePath = relativePath[nTrimChars:].lower() projectFilesSet.add(relativePath) return projectFilesSet, projectHFiles, projectCFiles, projectRFiles def getTessLibFiles(tessDir, nTrimChars): """Return set of all libtesseract files in tessDir""" libDirs = [ "api", "ccmain", "ccstruct", "ccutil", "classify", "cube", "cutil", "dict", r"neural_networks\runtime", "opencl", "textord", "viewer", "wordrec", #"training", r"vs2008\port", r"vs2008\libtesseract", ] #create list of all .h, .c, .cpp files in "library" directories tessFiles = set() for curDir in libDirs: baseDir = os.path.join(tessDir, curDir) for filetype in ["*.c", "*.cpp", "*.h", "*.rc"]: pattern = os.path.join(baseDir, filetype) fileList = glob.glob(pattern) for curFile in fileList: curFile = os.path.abspath(curFile) relativePath = curFile[nTrimChars:].lower() tessFiles.add(relativePath) return tessFiles # ==================================================================== def tessCompare(tessDir): '''Compare libtesseract Project files and actual "sub-library" files.''' vs2008Dir = os.path.join(tessDir, "vs2008") libTessDir = os.path.join(vs2008Dir, "libtesseract") libProjectFile = os.path.join(libTessDir,"libtesseract.vcproj") tessAbsDir = os.path.abspath(tessDir) nTrimChars = len(tessAbsDir)+1 print 'Comparing VS2008 Project "%s" with\n "%s"' % (libProjectFile, tessAbsDir) projectFilesSet, projectHFiles, projectCFiles, projectRFiles = \ getProjectfiles(libTessDir, libProjectFile, nTrimChars) tessFiles = getTessLibFiles(tessDir, nTrimChars) extraFiles = tessFiles - projectFilesSet print "%2d Extra files (in %s but not in Project)" % (len(extraFiles), tessAbsDir) headerFiles = [] sourceFiles = [] sortedList = list(extraFiles) sortedList.sort() for filename in sortedList: root, ext = os.path.splitext(filename.lower()) if ext == ".h": headerFiles.append(filename) else: sourceFiles.append(filename) print " %s " % filename print print "%2d new header file items written to %s" % (len(headerFiles), NEWHEADERS_FILENAME) headerFiles.sort() with open(NEWHEADERS_FILENAME, "w") as f: for filename in headerFiles: f.write(fileNodeTemplate % filename) print "%2d new source file items written to %s" % (len(sourceFiles), NEWSOURCES_FILENAME) sourceFiles.sort() with open(NEWSOURCES_FILENAME, "w") as f: for filename in sourceFiles: f.write(fileNodeTemplate % filename) print deadFiles = projectFilesSet - tessFiles print "%2d Dead files (in Project but not in %s" % (len(deadFiles), tessAbsDir) sortedList = list(deadFiles) sortedList.sort() for filename in sortedList: print " %s " % filename # ==================================================================== def tessReport(tessDir): """Report summary stats on "sub-library" files and libtesseract Project file.""" vs2008Dir = os.path.join(tessDir, "vs2008") libTessDir = os.path.join(vs2008Dir, "libtesseract") libProjectFile = os.path.join(libTessDir,"libtesseract.vcproj") tessAbsDir = os.path.abspath(tessDir) nTrimChars = len(tessAbsDir)+1 projectFilesSet, projectHFiles, projectCFiles, projectRFiles = \ getProjectfiles(libTessDir, libProjectFile, nTrimChars) tessFiles = getTessLibFiles(tessDir, nTrimChars) print 'Summary stats for "%s" library directories' % tessAbsDir folderCounters = {} for tessFile in tessFiles: tessFile = tessFile.lower() folder, head = os.path.split(tessFile) file, ext = os.path.splitext(head) typeCounter = folderCounters.setdefault(folder, collections.Counter()) typeCounter[ext[1:]] += 1 folders = folderCounters.keys() folders.sort() totalFiles = 0 totalH = 0 totalCPP = 0 totalOther = 0 print print " total h cpp" print " ----- --- ---" for folder in folders: counters = folderCounters[folder] nHFiles = counters['h'] nCPPFiles = counters['cpp'] total = nHFiles + nCPPFiles totalFiles += total totalH += nHFiles totalCPP += nCPPFiles print " %5d %3d %3d %s" % (total, nHFiles, nCPPFiles, folder) print " ----- --- ---" print " %5d %3d %3d" % (totalFiles, totalH, totalCPP) print print 'Summary stats for VS2008 Project "%s"' % libProjectFile print " %5d %s" %(len(projectHFiles), "Header files") print " %5d %s" % (len(projectCFiles), "Source files") print " %5d %s" % (len(projectRFiles), "Resource files") print " -----" print " %5d" % (len(projectHFiles) + len(projectCFiles) + len(projectRFiles), ) # ==================================================================== def copyIncludes(fileSet, description, tessDir, includeDir): """Copy set of files to specified include dir.""" print print 'Copying libtesseract "%s" headers to %s' % (description, includeDir) print sortedList = list(fileSet) sortedList.sort() count = 0 errList = [] for includeFile in sortedList: filepath = os.path.join(tessDir, includeFile) if os.path.isfile(filepath): shutil.copy2(filepath, includeDir) print "Copied: %s" % includeFile count += 1 else: print '***Error: "%s" doesn\'t exist"' % filepath errList.append(filepath) print '%d header files successfully copied to "%s"' % (count, includeDir) if len(errList): print "The following %d files were not copied:" for filepath in errList: print " %s" % filepath def tessCopy(tessDir, includeDir): '''Copy all "public" libtesseract Project header files to include directory. Preserves directory hierarchy.''' baseIncludeSet = { r"api\baseapi.h", r"api\capi.h", r"api\apitypes.h", r"ccstruct\publictypes.h", r"ccmain\thresholder.h", r"ccutil\host.h", r"ccutil\basedir.h", r"ccutil\tesscallback.h", r"ccutil\unichar.h", r"ccutil\platform.h", } strngIncludeSet = { r"ccutil\strngs.h", r"ccutil\memry.h", r"ccutil\host.h", r"ccutil\serialis.h", r"ccutil\errcode.h", r"ccutil\fileerr.h", #r"ccutil\genericvector.h", } resultIteratorIncludeSet = { r"ccmain\ltrresultiterator.h", r"ccmain\pageiterator.h", r"ccmain\resultiterator.h", r"ccutil\genericvector.h", r"ccutil\tesscallback.h", r"ccutil\errcode.h", r"ccutil\host.h", r"ccutil\helpers.h", r"ccutil\ndminx.h", r"ccutil\params.h", r"ccutil\unicharmap.h", r"ccutil\unicharset.h", } genericVectorIncludeSet = { r"ccutil\genericvector.h", r"ccutil\tesscallback.h", r"ccutil\errcode.h", r"ccutil\host.h", r"ccutil\helpers.h", r"ccutil\ndminx.h", } blobsIncludeSet = { r"ccstruct\blobs.h", r"ccstruct\rect.h", r"ccstruct\points.h", r"ccstruct\ipoints.h", r"ccutil\elst.h", r"ccutil\host.h", r"ccutil\serialis.h", r"ccutil\lsterr.h", r"ccutil\ndminx.h", r"ccutil\tprintf.h", r"ccutil\params.h", r"viewer\scrollview.h", r"ccstruct\vecfuncs.h", } extraFilesSet = { #r"vs2008\include\stdint.h", r"vs2008\include\leptonica_versionnumbers.vsprops", r"vs2008\include\tesseract_versionnumbers.vsprops", } tessIncludeDir = os.path.join(includeDir, "tesseract") if os.path.isfile(tessIncludeDir): print 'Aborting: "%s" is a file not a directory.' % tessIncludeDir return if not os.path.exists(tessIncludeDir): os.mkdir(tessIncludeDir) #fileSet = baseIncludeSet | strngIncludeSet | genericVectorIncludeSet | blobsIncludeSet fileSet = baseIncludeSet | strngIncludeSet | resultIteratorIncludeSet copyIncludes(fileSet, "public", tessDir, tessIncludeDir) copyIncludes(extraFilesSet, "extra", tessDir, includeDir) # ==================================================================== def tessClean(tessDir): '''Clean vs2008 folder of all build directories and certain temp files.''' vs2008Dir = os.path.join(tessDir, "vs2008") vs2008AbsDir = os.path.abspath(vs2008Dir) answer = raw_input( 'Are you sure you want to clean the\n "%s" folder (Yes/No) [No]? ' % vs2008AbsDir) if answer.lower() not in ("yes",): return answer = raw_input('Only list the items to be deleted (Yes/No) [Yes]? ') answer = answer.strip() listOnly = answer.lower() not in ("no",) for rootDir, dirs, files in os.walk(vs2008AbsDir): for buildDir in ("LIB_Release", "LIB_Debug", "DLL_Release", "DLL_Debug"): if buildDir in dirs: dirs.remove(buildDir) absBuildDir = os.path.join(rootDir, buildDir) if listOnly: print "Would remove: %s" % absBuildDir else: print "Removing: %s" % absBuildDir shutil.rmtree(absBuildDir) if rootDir == vs2008AbsDir: for file in files: if file.lower() not in ("tesseract.sln", "tesshelper.py", "readme.txt"): absPath = os.path.join(rootDir, file) if listOnly: print "Would remove: %s" % absPath else: print "Removing: %s" % absPath os.remove(absPath) else: for file in files: root, ext = os.path.splitext(file) if ext.lower() in (".suo", ".ncb", ".user", ) or ( len(ext)>0 and ext[-1] == "~"): absPath = os.path.join(rootDir, file) if listOnly: print "Would remove: %s" % absPath else: print "Removing: %s" % absPath os.remove(absPath) # ==================================================================== def validateTessDir(tessDir): """Check that tessDir is a valid tesseract directory.""" if not os.path.isdir(tessDir): raise argparse.ArgumentTypeError('Directory "%s" doesn\'t exist.' % tessDir) projFile = os.path.join(tessDir, PROJ_SUBDIR, PROJFILE) if not os.path.isfile(projFile): raise argparse.ArgumentTypeError('Project file "%s" doesn\'t exist.' % projFile) return tessDir def validateDir(dir): """Check that dir is a valid directory named include.""" if not os.path.isdir(dir): raise argparse.ArgumentTypeError('Directory "%s" doesn\'t exist.' % dir) dirpath = os.path.abspath(dir) head, tail = os.path.split(dirpath) if tail.lower() != "include": raise argparse.ArgumentTypeError('Include directory "%s" must be named "include".' % tail) return dir def main (): parser = argparse.ArgumentParser( epilog=epilogStr, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--version", action="version", version="%(prog)s " + VERSION) parser.add_argument('tessDir', type=validateTessDir, help="tesseract installation directory") subparsers = parser.add_subparsers( dest="subparser_name", title="Commands") parser_changes = subparsers.add_parser('compare', help="compare libtesseract Project with tessDir") parser_changes.set_defaults(func=tessCompare) parser_report = subparsers.add_parser('report', help="report libtesseract summary stats") parser_report.set_defaults(func=tessReport) parser_copy = subparsers.add_parser('copy', help="copy public libtesseract header files to includeDir") parser_copy.add_argument('includeDir', type=validateDir, help="Directory to copy header files to.") parser_copy.set_defaults(func=tessCopy) parser_clean = subparsers.add_parser('clean', help="clean vs2008 folder of build folders and .user files") parser_clean.set_defaults(func=tessClean) #kludge because argparse has no ability to set default subparser if (len(sys.argv) == 2): sys.argv.append("compare") args = parser.parse_args() #handle commands if args.func == tessCopy: args.func(args.tessDir, args.includeDir) else: args.func(args.tessDir) if __name__ == '__main__' : main()
Python
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright 2012 Zdenko Podobný # Author: Zdenko Podobný # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Simple python demo script of tesseract-ocr 3.02 c-api """ import os import sys import ctypes # Demo variables lang = "eng" filename = "../phototest.tif" libpath = "/usr/local/lib64/" libpath_w = "../vs2008/DLL_Release/" TESSDATA_PREFIX = os.environ.get('TESSDATA_PREFIX') if not TESSDATA_PREFIX: TESSDATA_PREFIX = "../" if sys.platform == "win32": libname = libpath_w + "libtesseract302.dll" libname_alt = "libtesseract302.dll" os.environ["PATH"] += os.pathsep + libpath_w else: libname = libpath + "libtesseract.so.3.0.2" libname_alt = "libtesseract.so.3" try: tesseract = ctypes.cdll.LoadLibrary(libname) except: try: tesseract = ctypes.cdll.LoadLibrary(libname_alt) except WindowsError, err: print("Trying to load '%s'..." % libname) print("Trying to load '%s'..." % libname_alt) print(err) exit(1) tesseract.TessVersion.restype = ctypes.c_char_p tesseract_version = tesseract.TessVersion()[:4] # We need to check library version because libtesseract.so.3 is symlink # and can point to other version than 3.02 if float(tesseract_version) < 3.02: print("Found tesseract-ocr library version %s." % tesseract_version) print("C-API is present only in version 3.02!") exit(2) api = tesseract.TessBaseAPICreate() rc = tesseract.TessBaseAPIInit3(api, TESSDATA_PREFIX, lang); if (rc): tesseract.TessBaseAPIDelete(api) print("Could not initialize tesseract.\n") exit(3) text_out = tesseract.TessBaseAPIProcessPages(api, filename, None , 0); result_text = ctypes.string_at(text_out) print result_text
Python
#!/usr/bin/python import sys import os import matplotlib import numpy import matplotlib matplotlib.use('AGG') import matplotlib.pyplot as plt from matplotlib.ticker import MaxNLocator from matplotlib.ticker import FormatStrFormatter def getArg(param, default=""): if (sys.argv.count(param) == 0): return default i = sys.argv.index(param) return sys.argv[i + 1] lastsecs = int(getArg("lastsecs", 240)) fname = sys.argv[1] try: tdata = numpy.loadtxt(fname, delimiter=" ") except: exit(0) if len(tdata.shape) < 2 or tdata.shape[0] < 2 or tdata.shape[1] < 2: print "Too small data - do not try to plot yet." exit(0) times = tdata[:, 0] values = tdata[:, 1] lastt = max(times) #majorFormatter = FormatStrFormatter('%.2f') fig = plt.figure(figsize=(3.5, 2.0)) plt.plot(times[times > lastt - lastsecs], values[times > lastt - lastsecs]) plt.gca().xaxis.set_major_locator( MaxNLocator(nbins = 7, prune = 'lower') ) plt.xlim([max(0, lastt - lastsecs), lastt]) #plt.ylim([lastt - lastsecs, lastt]) plt.gca().yaxis.set_major_locator( MaxNLocator(nbins = 7, prune = 'lower') ) #plt.gca().yaxis.set_major_formatter(majorFormatter) plt.savefig(fname.replace(".dat", ".png"), format="png", bbox_inches='tight')
Python
from optparse import OptionParser import random import heapq from operator import itemgetter from collections import defaultdict class Split: def __init__(self): self.train = {} self.test = {} self.counts = {} def add(self,user,trustees): if len(trustees) >= opts.min_trustees: self.counts[user] = len(trustees) random.shuffle(trustees) self.train[user] = trustees[:opts.given] self.test[user] = trustees[opts.given:] def map_ids(self): utrans = IndexTranslator() ttrans = IndexTranslator() train_idx = defaultdict(list) for user,trustees in self.train.iteritems(): uidx = utrans.idx(user) for t in trustees: train_idx[uidx].append(ttrans.idx(t)) test_idx = defaultdict(list) for user,trustees in self.test.iteritems(): uidx = utrans.idx(user,allow_update=False) assert(uidx is not None) # shouldn't have any unique users for t in trustees: tidx = ttrans.idx(t,allow_update=False) if tidx is not None: test_idx[uidx].append(tidx) self.train = train_idx self.test = test_idx class IndexTranslator: def __init__(self): self.index = {} def idx(self,key,allow_update=True): if allow_update and key not in self.index: self.index[key] = len(self.index)+1 return self.index.get(key,None) class MMWriter: def __init__(self,filepath): self.filepath = filepath def write(self,mat): f = open(self.filepath,'w') self.write_header(f,mat) self.write_data(f,mat) def write_header(self,f,mat): tot = 0 maxid = 0 for user,trustees in mat.iteritems(): tot += len(trustees) maxid = max(maxid,max(trustees)) print >>f,'%%MatrixMarket matrix coordinate integer general' print >>f,'{0} {1} {2}'.format(max(mat.keys()),maxid,tot) def write_data(self,f,mat): for user,trustees in mat.iteritems(): for t in trustees: print >>f,user,t,1 parser = OptionParser() parser.add_option('-i','--infile',dest='infile',help='input dataset') parser.add_option('-o','--outpath',dest='outpath',help='root path for output datasets [default=infile]') parser.add_option('-m','--min_trustees',dest='min_trustees',type='int',help='omit users with fewer trustees') parser.add_option('-g','--given',dest='given',type='int',help='retain this many trustees in training set') parser.add_option('-d','--discard_top',dest='discard_top',type='int',default=3,help='discard this many overall top popular users [default=%default]') (opts,args) = parser.parse_args() if not opts.min_trustees or not opts.given or not opts.infile: parser.print_help() raise SystemExit if not opts.outpath: opts.outpath = opts.infile overall = defaultdict(list) counts = defaultdict(int) f = open(opts.infile) for line in f: if not line.startswith('%'): break for line in f: user,trustee,score = map(int,line.strip().split()) if score > 0: counts[trustee] += 1 top = heapq.nlargest(opts.discard_top,counts.iteritems(),key=itemgetter(1)) for user,_ in top: counts[user] = 0 # so we don't include them f = open(opts.infile) for line in f: if not line.startswith('%'): break for line in f: user,trustee,score = map(int,line.strip().split()) if score > 0 and counts[trustee] >= opts.min_trustees: overall[user].append(trustee) split = Split() for user,trustees in overall.iteritems(): split.add(user,trustees) split.map_ids() w = MMWriter(opts.outpath+'_train') w.write(split.train) w = MMWriter(opts.outpath+'_test') w.write(split.test)
Python
# -*- coding:utf-8 -*- import datetime import time import math import coord import tornado.ioloop def handle_bus_message(msg): bus_data = parse_message(msg) handle_bus_data(bus_data) buses = {} buses_state = {} def handle_bus_data(bus_data): name = bus_data["Name"] if bus_data.name not in buses: bus = {"Name":name, "Stop":False, "Fly":False} buses[bus_data.name] = bus state = {} buses_state[name] = state else: bus = buses[name] state = buses_state[name] if "Time" in bus and bus["Time"]>=bus_data["Time"]: return bus["Stop"] = False bus["Fly"] = False bus["Longitude"] = bus_data["Longitude"] bus["Latitude"] = bus_data["Latitude"] station_index, percent, distance, coord_index = get_closest(bus["Latitude"], bus["Longitude"]) if distance > 0.5: bus["Fly"] = True # log here return if index==0: bus["StationIndex"] = 1 bus["Station"] = IndexToStation[1] else: bus["StationIndex"] = index bus["Station"] = IndexToStation[index] if "coord_index" in state: if state["coord_index"] > coord_index: bus["Direction"] = True elif: state["coord_index"] < coord_index: bus["Direction"] = False if index==1 and percent<0 or index==0: percent = 0 if bus["Direction"] = True: percent *= -1 bus["Pencent"] = percent if index==0: bus["Stop"] = True else: bus["Time"] = bus_data["Time"] state["coord_index"] = coord_index def _timeout(): bus["Stop"] = True if "timeout" in state and state["timeout"] is not None: tornado.ioloop.IOLoop.instance().remove_timeout(state["timeout"]) state["timeout"] = None state["timeout"] = tornado.ioloop.IOLoop.instance().add_timeout(time.time()+5*60, _timeout) def parse_message(msg): if msg is None or len(msg)==0: return fields = msg.split(',') if len(fields) < 11: return name = fields[0].strip() latitude = dm2d(float(fields[4])) longitude = dm2d(float(fields[6])) _date = fields[10] _time = fields[2] timestamp = time.mktime(time.strptime(' '.join((_date, _time)), "%d%m%y %H%M%S")) return {"Name": name, "Latitude": latitude, "Longitude": longitude, "Time", timestamp} # 计算地球两经纬度间距离 def calc_distance(lat1, lgt1, lat2, lgt2): lat1, lgt1, lat2, lgt2 = d2r(lat1), d2r(lgt1), d2r(lat2), d2r(lgt2) dlat = lat2 - lat1 dlgt = lgt2 - lgt1 distance = 2 * math.asin(math.sqrt(math.Sin(dlat/2) ** 2 + math.cos(lat1)*math.cos(lat2)*(math.Sin(dlgt/2)**2))) * 6378.137 # 角分换算为角度 def dm2d(dm): return int(dm/100) + (dm%100)/60 # 角度换算为弧度 def d2r(d): return d / 360 * 2 * math.pi # 获取离坐标最近的 coord def get_closest(lat, lgt): shortest = float("inf") for i, coord in enumerate(data.Coords): distance = calc_distance(lat, lgt, coord.Latitude, coord.Longitude) if distance < shortest: shortest = distance station_index = coord_station_index(coord) percent = coord_percent(coord) coord_index = i return station_index, percent, distance, coord_index
Python
# -*- coding:utf-8 -*- import socket import functools import tornado.ioloop import busmanager import config _socket = None _ioloop = tornado.ioloop.IOLoop.instance() def start(): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setblocking(0) sock.bind(("127.0.0.1", config.UDP_PORT)) global _socket _socket = sock _ioloop.add_handler(_socket.fileno(), _read_callback, _ioloop.READ) def _read_callback(fd, events): b, _ = _socket.recvfrom(1024) busmanager.handle_bus_message(b) if __name__=="__main__": start() tornado.ioloop.IOLoop.instance().start()
Python
import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") application = tornado.web.Application([ (r"/", MainHandler), ]) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
Python
# -*- coding:utf-8 -*- Coords = [ (23.152793, 113.342832, 0.33, 0), (23.152792, 113.342624, -0.33, 1), (23.152790, 113.342417, 0.00, 1), (23.153019, 113.342402, 0.17, 1), (23.153249, 113.342386, 0.33, 1), (23.153478, 113.342371, 0.50, 1), (23.153707, 113.342356, -0.33, 2), (23.153937, 113.342340, -0.17, 2), (23.154166, 113.342325, 0.00, 2), (23.154163, 113.342050, 0.15, 2), (23.154161, 113.341776, 0.31, 2), (23.154159, 113.341501, 0.46, 2), (23.154156, 113.341226, -0.38, 3), (23.154363, 113.341200, -0.25, 3), (23.154571, 113.341174, -0.13, 3), (23.154778, 113.341148, 0.00, 3), (23.155019, 113.341134, 0.11, 3), (23.155259, 113.341120, 0.22, 3), (23.155500, 113.341105, 0.33, 3), (23.155740, 113.341091, 0.44, 3), (23.155981, 113.341077, -0.44, 4), (23.156221, 113.341063, -0.33, 4), (23.156462, 113.341048, -0.22, 4), (23.156702, 113.341034, -0.11, 4), (23.156943, 113.341020, 0.00, 4), (23.156935, 113.340790, 0.15, 4), (23.156926, 113.340560, 0.30, 4), (23.156918, 113.340330, 0.44, 4), (23.157180, 113.340290, -0.37, 5), (23.157443, 113.340250, -0.19, 5), (23.157705, 113.340210, 0.00, 5), (23.157719, 113.339932, 0.07, 5), (23.157734, 113.339655, 0.15, 5), (23.157748, 113.339377, 0.22, 5), (23.157762, 113.339099, 0.29, 5), (23.157777, 113.338822, 0.37, 5), (23.157791, 113.338544, 0.44, 5), (23.157719, 113.338271, -0.49, 6), (23.157646, 113.337998, -0.41, 6), (23.157574, 113.337725, -0.34, 6), (23.157501, 113.337452, -0.26, 6), (23.157429, 113.337179, -0.19, 6), (23.157615, 113.337056, -0.12, 6), (23.157800, 113.336934, -0.06, 6), (23.157986, 113.336811, 0.00, 6), (23.158173, 113.336675, 0.33, 6), (23.158359, 113.336539, -0.33, 7), (23.158546, 113.336403, 0.00, 7), (23.158757, 113.336492, 0.04, 7), (23.158967, 113.336580, 0.08, 7), (23.159177, 113.336669, 0.13, 7), (23.159388, 113.336757, 0.17, 7), (23.159599, 113.336845, 0.21, 7), (23.159809, 113.336934, 0.25, 7), (23.160039, 113.337005, 0.30, 7), (23.160269, 113.337076, 0.34, 7), (23.160498, 113.337146, 0.38, 7), (23.160728, 113.337217, 0.43, 7), (23.160958, 113.337288, 0.47, 7), (23.161169, 113.337466, -0.48, 8), (23.161379, 113.337644, -0.43, 8), (23.161590, 113.337822, -0.38, 8), (23.161801, 113.337999, -0.33, 8), (23.162012, 113.338177, -0.28, 8), (23.162222, 113.338355, -0.23, 8), (23.162433, 113.338533, -0.18, 8), (23.162673, 113.338513, -0.13, 8), (23.162914, 113.338493, -0.09, 8), (23.163154, 113.338472, -0.04, 8), (23.163394, 113.338452, 0.00, 8), (23.163616, 113.338411, 0.12, 8), (23.163838, 113.338370, 0.24, 8), (23.164060, 113.338330, 0.36, 8), (23.164282, 113.338289, 0.48, 8), (23.164504, 113.338248, -0.40, 9), (23.164747, 113.338293, -0.26, 9), (23.164991, 113.338338, -0.13, 9), (23.165234, 113.338383, 0.00, 9), (23.165499, 113.338369, 0.11, 9), (23.165763, 113.338354, 0.23, 9), (23.166028, 113.338340, 0.34, 9), (23.165860, 113.338372, 0.42, 9), (23.166051, 113.338299, -0.50, 10), (23.166241, 113.338225, -0.41, 10), (23.166432, 113.338152, -0.32, 10), (23.166626, 113.337982, -0.21, 10), (23.166820, 113.337812, -0.11, 10), (23.167014, 113.337642, 0.00, 10), (23.167071, 113.337389, 0.17, 10), (23.167128, 113.337136, 0.33, 10), (23.167185, 113.336883, 0.50, 10), (23.167241, 113.336630, -0.33, 11), (23.167298, 113.336377, -0.17, 11), (23.167355, 113.336124, 0.00, 11), (23.167481, 113.335938, 0.09, 11), (23.167608, 113.335752, 0.19, 11), (23.167734, 113.335566, 0.28, 11), (23.167814, 113.335361, 0.37, 11), (23.167894, 113.335156, 0.46, 11), (23.167975, 113.334951, -0.45, 12), (23.168055, 113.334746, -0.37, 12), (23.168211, 113.334593, -0.27, 12), (23.168368, 113.334440, -0.18, 12), (23.168525, 113.334287, -0.09, 12), (23.168681, 113.334134, 0.00, 12), ] def coord_latitude(coord): return coord[0] def coord_longitude(coord): return coord[1] def coord_percent(coord): return coord[2] def coord_station_index(coord); return coord[3] IndexToStation = [ "车场", "南门总站", "中山像站", "百步梯站", "27号楼站", "人文馆站", "西五站", "西秀村站", "修理厂站", "北门站", "北湖站", "卫生所站", "北二总站", ]
Python
# -*- coding:utf-8 -*- UDP_PORT = 6000 # 校巴终端上传数据端口 HTTP_PORT = 8001 # HTTP接口端口
Python
from composite import CompositeGoal from onek_onek import OneKingAttackOneKingEvaluator, OneKingFleeOneKingEvaluator class Goal_Think(CompositeGoal): def __init__(self, owner): CompositeGoal.__init__(self, owner) self.evaluators = [OneKingAttackOneKingEvaluator(1.0), OneKingFleeOneKingEvaluator(1.0)] def activate(self): self.arbitrate() self.status = self.ACTIVE def process(self): self.activateIfInactive() status = self.processSubgoals() if status == self.COMPLETED or status == self.FAILED: self.status = self.INACTIVE return status def terminate(self): pass def arbitrate(self): most_desirable = None best_score = 0 for e in self.evaluators: d = e.calculateDesirability() if d > best_score: most_desirable = e best_score = d if most_desirable: most_desirable.setGoal(self.owner) return best_score
Python
from goal import Goal class CompositeGoal(Goal): def __init__(self, owner): Goal.__init__(self, owner) self.subgoals = [] def removeAllSubgoals(self): for s in self.subgoals: s.terminate() self.subgoals = [] def processSubgoals(self): # remove all completed and failed goals from the front of the # subgoal list while (self.subgoals and (self.subgoals[0].isComplete or self.subgoals[0].hasFailed)): subgoal = self.subgoals.pop() subgoal.terminate() if (self.subgoals): subgoal = self.subgoals.pop() status = subgoal.process() if status == COMPLETED and len(self.subgoals) > 1: return ACTIVE return status else: return COMPLETED def addSubgoal(self, goal): self.subgoals.append(goal)
Python
import unittest import checkers import games from globalconst import * # (white) # 45 46 47 48 # 39 40 41 42 # 34 35 36 37 # 28 29 30 31 # 23 24 25 26 # 17 18 19 20 # 12 13 14 15 # 6 7 8 9 # (black) class TestBlackManSingleJump(unittest.TestCase): def setUp(self): self.game = checkers.Checkers() self.board = self.game.curr_state squares = self.board.squares self.board.clear() squares[6] = BLACK | MAN squares[12] = WHITE | MAN def testJump(self): moves = self.game.legal_moves(self.board) self.assertEqual(moves[0].affected_squares, [[6, BLACK | MAN, FREE], [12, WHITE | MAN, FREE], [18, FREE, BLACK | MAN]]) class TestBlackManDoubleJump(unittest.TestCase): def setUp(self): self.game = checkers.Checkers() self.board = self.game.curr_state squares = self.board.squares self.board.clear() squares[6] = BLACK | MAN squares[12] = WHITE | MAN squares[23] = WHITE | MAN def testJump(self): moves = self.game.legal_moves(self.board) self.assertEqual(moves[0].affected_squares, [[6, BLACK | MAN, FREE], [12, WHITE | MAN, FREE], [18, FREE, FREE], [23, WHITE | MAN, FREE], [28, FREE, BLACK | MAN]]) class TestBlackManCrownKingOnJump(unittest.TestCase): def setUp(self): self.game = checkers.Checkers() self.board = self.game.curr_state squares = self.board.squares self.board.clear() # (white) # 45 46 47 48 # 39 40 41 42 # 34 35 36 37 # 28 29 30 31 # 23 24 25 26 # 17 18 19 20 # 12 13 14 15 # 6 7 8 9 # (black) squares[12] = BLACK | MAN squares[18] = WHITE | MAN squares[30] = WHITE | MAN squares[41] = WHITE | MAN # set another man on 40 to test that crowning # move ends the turn squares[40] = WHITE | MAN def testJump(self): moves = self.game.legal_moves(self.board) self.assertEqual(moves[0].affected_squares, [[12, BLACK | MAN, FREE], [18, WHITE | MAN, FREE], [24, FREE, FREE], [30, WHITE | MAN, FREE], [36, FREE, FREE], [41, WHITE | MAN, FREE], [46, FREE, BLACK | KING]]) class TestBlackManCrownKingOnMove(unittest.TestCase): def setUp(self): self.game = checkers.Checkers() self.board = self.game.curr_state squares = self.board.squares self.board.clear() squares[39] = BLACK | MAN squares[18] = WHITE | MAN def testJump(self): moves = self.game.legal_moves(self.board) self.assertEqual(moves[0].affected_squares, [[39, BLACK | MAN, FREE], [45, FREE, BLACK | KING]]) class TestBlackKingOptionalJumpDiamond(unittest.TestCase): def setUp(self): self.game = checkers.Checkers() self.board = self.game.curr_state squares = self.board.squares self.board.clear() squares[13] = BLACK | KING squares[19] = WHITE | MAN squares[30] = WHITE | MAN squares[29] = WHITE | MAN squares[18] = WHITE | MAN def testJump(self): moves = self.game.legal_moves(self.board) self.assertEqual(moves[0].affected_squares, [[13, BLACK | KING, FREE], [18, WHITE | MAN, FREE], [23, FREE, FREE], [29, WHITE | MAN, FREE], [35, FREE, FREE], [30, WHITE | MAN, FREE], [25, FREE, FREE], [19, WHITE | MAN, FREE], [13, FREE, BLACK | KING]]) self.assertEqual(moves[1].affected_squares, [[13, BLACK | KING, FREE], [19, WHITE | MAN, FREE], [25, FREE, FREE], [30, WHITE | MAN, FREE], [35, FREE, FREE], [29, WHITE | MAN, FREE], [23, FREE, FREE], [18, WHITE | MAN, FREE], [13, FREE, BLACK | KING]]) class TestWhiteManSingleJump(unittest.TestCase): def setUp(self): self.game = checkers.Checkers() self.board = self.game.curr_state self.board.to_move = WHITE squares = self.board.squares self.board.clear() squares[41] = WHITE | MAN squares[36] = BLACK | MAN def testJump(self): moves = self.game.legal_moves(self.board) self.assertEqual(moves[0].affected_squares, [[41, WHITE | MAN, FREE], [36, BLACK | MAN, FREE], [31, FREE, WHITE | MAN]]) class TestWhiteManDoubleJump(unittest.TestCase): def setUp(self): self.game = checkers.Checkers() self.board = self.game.curr_state self.board.to_move = WHITE squares = self.board.squares self.board.clear() squares[41] = WHITE | MAN squares[36] = BLACK | MAN squares[25] = BLACK | MAN def testJump(self): moves = self.game.legal_moves(self.board) self.assertEqual(moves[0].affected_squares, [[41, WHITE | MAN, FREE], [36, BLACK | MAN, FREE], [31, FREE, FREE], [25, BLACK | MAN, FREE], [19, FREE, WHITE | MAN]]) class TestWhiteManCrownKingOnMove(unittest.TestCase): def setUp(self): self.game = checkers.Checkers() self.board = self.game.curr_state self.board.to_move = WHITE squares = self.board.squares self.board.clear() squares[15] = WHITE | MAN squares[36] = BLACK | MAN def testJump(self): moves = self.game.legal_moves(self.board) self.assertEqual(moves[0].affected_squares, [[15, WHITE | MAN, FREE], [9, FREE, WHITE | KING]]) class TestWhiteManCrownKingOnJump(unittest.TestCase): def setUp(self): self.game = checkers.Checkers() self.board = self.game.curr_state self.board.to_move = WHITE squares = self.board.squares self.board.clear() squares[41] = WHITE | MAN squares[36] = BLACK | MAN squares[25] = BLACK | MAN squares[13] = BLACK | KING # set another man on 10 to test that crowning # move ends the turn squares[12] = BLACK | KING def testJump(self): moves = self.game.legal_moves(self.board) self.assertEqual(moves[0].affected_squares, [[41, WHITE | MAN, FREE], [36, BLACK | MAN, FREE], [31, FREE, FREE], [25, BLACK | MAN, FREE], [19, FREE, FREE], [13, BLACK | KING, FREE], [7, FREE, WHITE | KING]]) class TestWhiteKingOptionalJumpDiamond(unittest.TestCase): def setUp(self): self.game = checkers.Checkers() self.board = self.game.curr_state self.board.to_move = WHITE squares = self.board.squares self.board.clear() squares[13] = WHITE | KING squares[19] = BLACK | MAN squares[30] = BLACK | MAN squares[29] = BLACK | MAN squares[18] = BLACK | MAN def testJump(self): moves = self.game.legal_moves(self.board) self.assertEqual(moves[0].affected_squares, [[13, WHITE | KING, FREE], [18, BLACK | MAN, FREE], [23, FREE, FREE], [29, BLACK | MAN, FREE], [35, FREE, FREE], [30, BLACK | MAN, FREE], [25, FREE, FREE], [19, BLACK | MAN, FREE], [13, FREE, WHITE | KING]]) self.assertEqual(moves[1].affected_squares, [[13, WHITE | KING, FREE], [19, BLACK | MAN, FREE], [25, FREE, FREE], [30, BLACK | MAN, FREE], [35, FREE, FREE], [29, BLACK | MAN, FREE], [23, FREE, FREE], [18, BLACK | MAN, FREE], [13, FREE, WHITE | KING]]) class TestUtilityFunc(unittest.TestCase): def setUp(self): self.game = checkers.Checkers() self.board = self.game.curr_state self.board.to_move = WHITE self.squares = self.board.squares def testInitialUtility(self): code = sum(self.board.value[s] for s in self.squares) nwm = code % 16 nwk = (code >> 4) % 16 nbm = (code >> 8) % 16 nbk = (code >> 12) % 16 nm = nbm + nwm nk = nbk + nwk self.assertEqual(self.board._eval_cramp(self.squares), 0) self.assertEqual(self.board._eval_backrankguard(self.squares), 0) self.assertEqual(self.board._eval_doublecorner(self.squares), 0) self.assertEqual(self.board._eval_center(self.squares), 0) self.assertEqual(self.board._eval_edge(self.squares), 0) self.assertEqual(self.board._eval_tempo(self.squares, nm, nbk, nbm, nwk, nwm), 0) self.assertEqual(self.board._eval_playeropposition(self.squares, nwm, nwk, nbk, nbm, nm, nk), 0) self.assertEqual(self.board.utility(WHITE), -2) class TestSuccessorFuncForBlack(unittest.TestCase): def setUp(self): self.game = checkers.Checkers() self.board = self.game.curr_state def testInitialBlackMoves(self): # Tests whether initial game moves are correct from # Black's perspective moves = [m for m, _ in self.game.successors(self.board)] self.assertEqual(moves[0].affected_squares, [[17, BLACK | MAN, FREE], [23, FREE, BLACK | MAN]]) self.assertEqual(moves[1].affected_squares, [[18, BLACK | MAN, FREE], [23, FREE, BLACK | MAN]]) self.assertEqual(moves[2].affected_squares, [[18, BLACK | MAN, FREE], [24, FREE, BLACK | MAN]]) self.assertEqual(moves[3].affected_squares, [[19, BLACK | MAN, FREE], [24, FREE, BLACK | MAN]]) self.assertEqual(moves[4].affected_squares, [[19, BLACK | MAN, FREE], [25, FREE, BLACK | MAN]]) self.assertEqual(moves[5].affected_squares, [[20, BLACK | MAN, FREE], [25, FREE, BLACK | MAN]]) self.assertEqual(moves[6].affected_squares, [[20, BLACK | MAN, FREE], [26, FREE, BLACK | MAN]]) class TestSuccessorFuncForWhite(unittest.TestCase): def setUp(self): self.game = checkers.Checkers() self.board = self.game.curr_state # I'm cheating here ... white never moves first in # a real game, but I want to see that the moves # would work anyway. self.board.to_move = WHITE def testInitialWhiteMoves(self): # Tests whether initial game moves are correct from # White's perspective moves = [m for m, _ in self.game.successors(self.board)] self.assertEqual(moves[0].affected_squares, [[34, WHITE | MAN, FREE], [29, FREE, WHITE | MAN]]) self.assertEqual(moves[1].affected_squares, [[34, WHITE | MAN, FREE], [28, FREE, WHITE | MAN]]) self.assertEqual(moves[2].affected_squares, [[35, WHITE | MAN, FREE], [30, FREE, WHITE | MAN]]) self.assertEqual(moves[3].affected_squares, [[35, WHITE | MAN, FREE], [29, FREE, WHITE | MAN]]) self.assertEqual(moves[4].affected_squares, [[36, WHITE | MAN, FREE], [31, FREE, WHITE | MAN]]) self.assertEqual(moves[5].affected_squares, [[36, WHITE | MAN, FREE], [30, FREE, WHITE | MAN]]) self.assertEqual(moves[6].affected_squares, [[37, WHITE | MAN, FREE], [31, FREE, WHITE | MAN]]) if __name__ == '__main__': unittest.main()
Python
import utils class Observer(object): def update(self, change): utils.abstract()
Python
import re import sys class LinkRules(object): """Rules for recognizing external links.""" # For the link targets: proto = r'http|https|ftp|nntp|news|mailto|telnet|file|irc' extern = r'(?P<extern_addr>(?P<extern_proto>%s):.*)' % proto interwiki = r''' (?P<inter_wiki> [A-Z][a-zA-Z]+ ) : (?P<inter_page> .* ) ''' def __init__(self): self.addr_re = re.compile('|'.join([ self.extern, self.interwiki, ]), re.X | re.U) # for addresses class Rules(object): """Hold all the rules for generating regular expressions.""" # For the inline elements: proto = r'http|https|ftp|nntp|news|mailto|telnet|file|irc' link = r'''(?P<link> \[\[ (?P<link_target>.+?) \s* ([|] \s* (?P<link_text>.+?) \s*)? ]] )''' image = r'''(?P<image> {{ (?P<image_target>.+?) \s* ([|] \s* (?P<image_text>.+?) \s*)? }} )''' macro = r'''(?P<macro> << (?P<macro_name> \w+) (\( (?P<macro_args> .*?) \))? \s* ([|] \s* (?P<macro_text> .+?) \s* )? >> )''' code = r'(?P<code> {{{ (?P<code_text>.*?) }}} )' emph = r'(?P<emph> (?<!:)// )' # there must be no : in front of the // # avoids italic rendering in urls with # unknown protocols strong = r'(?P<strong> \*\* )' linebreak = r'(?P<break> \\\\ )' escape = r'(?P<escape> ~ (?P<escaped_char>\S) )' char = r'(?P<char> . )' # For the block elements: separator = r'(?P<separator> ^ \s* ---- \s* $ )' # horizontal line line = r'(?P<line> ^ \s* $ )' # empty line that separates paragraphs head = r'''(?P<head> ^ \s* (?P<head_head>=+) \s* (?P<head_text> .*? ) \s* (?P<head_tail>=*) \s* $ )''' text = r'(?P<text> .+ )' list = r'''(?P<list> ^ [ \t]* ([*][^*\#]|[\#][^\#*]).* $ ( \n[ \t]* [*\#]+.* $ )* )''' # Matches the whole list, separate items are parsed later. The # list *must* start with a single bullet. item = r'''(?P<item> ^ \s* (?P<item_head> [\#*]+) \s* (?P<item_text> .*?) $ )''' # Matches single list items pre = r'''(?P<pre> ^{{{ \s* $ (\n)? (?P<pre_text> ([\#]!(?P<pre_kind>\w*?)(\s+.*)?$)? (.|\n)+? ) (\n)? ^}}} \s*$ )''' pre_escape = r' ^(?P<indent>\s*) ~ (?P<rest> \}\}\} \s*) $' table = r'''(?P<table> ^ \s* [|].*? \s* [|]? \s* $ )''' # For splitting table cells: cell = r''' \| \s* ( (?P<head> [=][^|]+ ) | (?P<cell> ( %s | [^|])+ ) ) \s* ''' % '|'.join([link, macro, image, code]) def __init__(self, bloglike_lines=False, url_protocols=None, wiki_words=False): c = re.compile # For pre escaping, in creole 1.0 done with ~: self.pre_escape_re = c(self.pre_escape, re.M | re.X) # for link descriptions self.link_re = c('|'.join([self.image, self.linebreak, self.char]), re.X | re.U) # for list items self.item_re = c(self.item, re.X | re.U | re.M) # for table cells self.cell_re = c(self.cell, re.X | re.U) # For block elements: if bloglike_lines: self.text = r'(?P<text> .+ ) (?P<break> (?<!\\)$\n(?!\s*$) )?' self.block_re = c('|'.join([self.line, self.head, self.separator, self.pre, self.list, self.table, self.text]), re.X | re.U | re.M) # For inline elements: if url_protocols is not None: self.proto = '|'.join(re.escape(p) for p in url_protocols) self.url = r'''(?P<url> (^ | (?<=\s | [.,:;!?()/=])) (?P<escaped_url>~)? (?P<url_target> (?P<url_proto> %s ):\S+? ) ($ | (?=\s | [,.:;!?()] (\s | $))))''' % self.proto inline_elements = [self.link, self.url, self.macro, self.code, self.image, self.strong, self.emph, self.linebreak, self.escape, self.char] if wiki_words: import unicodedata up_case = u''.join(unichr(i) for i in xrange(sys.maxunicode) if unicodedata.category(unichr(i))=='Lu') self.wiki = ur'''(?P<wiki>[%s]\w+[%s]\w+)''' % (up_case, up_case) inline_elements.insert(3, self.wiki) self.inline_re = c('|'.join(inline_elements), re.X | re.U)
Python
from Tkinter import * class AutoScrollbar(Scrollbar): def __init__(self, master=None, cnf={}, **kw): self.container = kw.pop('container', None) self.row = kw.pop('row', 0) self.column = kw.pop('column', 0) self.sticky = kw.pop('sticky', '') Scrollbar.__init__(self, master, cnf, **kw) # a scrollbar that hides itself if it's not needed. only # works if you use the grid geometry manager. def set(self, lo, hi): if float(lo) <= 0.0 and float(hi) >= 1.0: # grid_remove is currently missing from Tkinter! self.tk.call('grid', 'remove', self) else: if not self.container: self.grid() else: self.grid(in_=self.container, row=self.row, column=self.column, sticky=self.sticky) Scrollbar.set(self, lo, hi) def pack(self, **kw): raise TclError, 'cannot use pack with this widget' def place(self, **kw): raise TclError, 'cannot use place with this widget'
Python
import games import copy import multiprocessing import time import random from controller import Controller from transpositiontable import TranspositionTable from globalconst import * class AlphaBetaController(Controller): def __init__(self, **props): self._model = props['model'] self._view = props['view'] self._end_turn_event = props['end_turn_event'] self._highlights = [] self._search_time = props['searchtime'] # in seconds self._before_turn_event = None self._parent_conn, self._child_conn = multiprocessing.Pipe() self._term_event = multiprocessing.Event() self.process = multiprocessing.Process() self._start_time = None self._call_id = 0 self._trans_table = TranspositionTable(50000) def set_before_turn_event(self, evt): self._before_turn_event = evt def add_highlights(self): for h in self._highlights: self._view.highlight_square(h, OUTLINE_COLOR) def remove_highlights(self): for h in self._highlights: self._view.highlight_square(h, DARK_SQUARES) def start_turn(self): if self._model.terminal_test(): self._before_turn_event() self._model.curr_state.attach(self._view) return self._view.update_statusbar('Thinking ...') self.process = multiprocessing.Process(target=calc_move, args=(self._model, self._trans_table, self._search_time, self._term_event, self._child_conn)) self._start_time = time.time() self.process.daemon = True self.process.start() self._view.canvas.after(100, self.get_move) def get_move(self): #if self._term_event.is_set() and self._model.curr_state.ok_to_move: # self._end_turn_event() # return self._highlights = [] moved = self._parent_conn.poll() while (not moved and (time.time() - self._start_time) < self._search_time * 2): self._call_id = self._view.canvas.after(500, self.get_move) return self._view.canvas.after_cancel(self._call_id) move = self._parent_conn.recv() #if self._model.curr_state.ok_to_move: self._before_turn_event() # highlight remaining board squares used in move step = 2 if len(move.affected_squares) > 2 else 1 for m in move.affected_squares[0::step]: idx = m[0] self._view.highlight_square(idx, OUTLINE_COLOR) self._highlights.append(idx) self._model.curr_state.attach(self._view) self._model.make_move(move, None, True, True, self._view.get_annotation()) # a new move obliterates any more redo's along a branch of the game tree self._model.curr_state.delete_redo_list() self._end_turn_event() def set_search_time(self, time): self._search_time = time # in seconds def stop_process(self): self._term_event.set() self._view.canvas.after_cancel(self._call_id) def end_turn(self): self._view.update_statusbar() self._model.curr_state.detach(self._view) def longest_of(moves): length = -1 selected = None for move in moves: l = len(move.affected_squares) if l > length: length = l selected = move return selected def calc_move(model, table, search_time, term_event, child_conn): move = None term_event.clear() captures = model.captures_available() if captures: time.sleep(0.7) move = longest_of(captures) else: depth = 0 start_time = time.time() curr_time = start_time checkpoint = start_time model_copy = copy.deepcopy(model) while 1: depth += 1 table.set_hash_move(depth, -1) move = games.alphabeta_search(model_copy.curr_state, model_copy, depth) checkpoint = curr_time curr_time = time.time() rem_time = search_time - (curr_time - checkpoint) if term_event.is_set(): # a signal means terminate term_event.clear() move = None break if (curr_time - start_time > search_time or ((curr_time - checkpoint) * 2) > rem_time or depth > MAXDEPTH): break child_conn.send(move) #model.curr_state.ok_to_move = True
Python
from goal import Goal from composite import CompositeGoal class Goal_OneKingAttack(CompositeGoal): def __init__(self, owner): CompositeGoal.__init__(self, owner) def activate(self): self.status = self.ACTIVE self.removeAllSubgoals() # because goals are *pushed* onto the front of the subgoal list they must # be added in reverse order. self.addSubgoal(Goal_MoveTowardEnemy(self.owner)) self.addSubgoal(Goal_PinEnemy(self.owner)) def process(self): self.activateIfInactive() return self.processSubgoals() def terminate(self): self.status = self.INACTIVE class Goal_MoveTowardEnemy(Goal): def __init__(self, owner): Goal.__init__(self, owner) def activate(self): self.status = self.ACTIVE def process(self): # if status is inactive, activate self.activateIfInactive() # only moves (not captures) are a valid goal if self.owner.captures: self.status = self.FAILED return # identify player king and enemy king plr_color = self.owner.to_move enemy_color = self.owner.enemy player = self.owner.get_pieces(plr_color)[0] p_idx, _ = player p_row, p_col = self.owner.row_col_for_index(p_idx) enemy = self.owner.get_pieces(enemy_color)[0] e_idx, _ = enemy e_row, e_col = self.owner.row_col_for_index(e_idx) # if distance between player and enemy is already down # to 2 rows or cols, then goal is complete. if abs(p_row - e_row) == 2 or abs(p_col - e_col) == 2: self.status = self.COMPLETED # select the available move that decreases the distance # between the player and the enemy. If no such move exists, # the goal has failed. good_move = None for m in self.owner.moves: # try a move and gather the new row & col for the player self.owner.make_move(m, False, False) plr_update = self.owner.get_pieces(plr_color)[0] pu_idx, _ = plr_update pu_row, pu_col = self.owner.row_col_for_index(pu_idx) self.owner.undo_move(m, False, False) new_diff = abs(pu_row - e_row) + abs(pu_col - e_col) old_diff = abs(p_row - e_row) + abs(p_col - e_col) if new_diff < old_diff: good_move = m break if good_move: self.owner.make_move(good_move, True, True) else: self.status = self.FAILED def terminate(self): self.status = self.INACTIVE class Goal_PinEnemy(Goal): def __init__(self, owner): Goal.__init__(self, owner) def activate(self): self.status = self.ACTIVE def process(self): # for now, I'm not even sure I need this goal, but I'm saving it # as a placeholder. self.status = self.COMPLETED def terminate(self): self.status = self.INACTIVE
Python
import math, os, sys from ConfigParser import RawConfigParser DEFAULT_SIZE = 400 BOARD_SIZE = 8 CHECKER_SIZE = 30 MAX_VALID_SQ = 32 MOVE = 0 JUMP = 1 OCCUPIED = 0 BLACK = 1 WHITE = 2 MAN = 4 KING = 8 FREE = 16 COLORS = BLACK | WHITE TYPES = OCCUPIED | BLACK | WHITE | MAN | KING | FREE HUMAN = 0 COMPUTER = 1 MIN = 0 MAX = 1 IMAGE_DIR = 'images' + os.sep RAVEN_ICON = IMAGE_DIR + '_raven.ico' BULLET_IMAGE = IMAGE_DIR + 'bullet_green.gif' CROWN_IMAGE = IMAGE_DIR + 'crown.gif' BOLD_IMAGE = IMAGE_DIR + 'text_bold.gif' ITALIC_IMAGE = IMAGE_DIR + 'text_italic.gif' BULLETS_IMAGE = IMAGE_DIR + 'text_list_bullets.gif' NUMBERS_IMAGE = IMAGE_DIR + 'text_list_numbers.gif' ADDLINK_IMAGE = IMAGE_DIR + 'link.gif' REMLINK_IMAGE = IMAGE_DIR + 'link_break.gif' UNDO_IMAGE = IMAGE_DIR + 'resultset_previous.gif' UNDOALL_IMAGE = IMAGE_DIR + 'resultset_first.gif' REDO_IMAGE = IMAGE_DIR + 'resultset_next.gif' REDOALL_IMAGE = IMAGE_DIR + 'resultset_last.gif' LIGHT_SQUARES = 'tan' DARK_SQUARES = 'dark green' OUTLINE_COLOR = 'white' LIGHT_CHECKERS = 'white' DARK_CHECKERS = 'red' WHITE_CHAR = 'w' WHITE_KING = 'W' BLACK_CHAR = 'b' BLACK_KING = 'B' FREE_CHAR = '.' OCCUPIED_CHAR = '-' INFINITY = 9999999 MAXDEPTH = 10 VERSION = '0.4' TITLE = 'Raven ' + VERSION PROGRAM_TITLE = 'Raven Checkers' CUR_DIR = sys.path[0] TRAINING_DIR = 'training' # search values for transposition table hashfALPHA, hashfBETA, hashfEXACT = range(3) # constants for evaluation function TURN = 2 # color to move gets + turn BRV = 3 # multiplier for back rank KCV = 5 # multiplier for kings in center MCV = 1 # multiplier for men in center MEV = 1 # multiplier for men on edge KEV = 5 # multiplier for kings on edge CRAMP = 5 # multiplier for cramp OPENING = 2 # multipliers for tempo MIDGAME = -1 ENDGAME = 2 INTACTDOUBLECORNER = 3 BLACK_IDX = [5,6] WHITE_IDX = [-5,-6] KING_IDX = [-6,-5,5,6] FIRST = 0 MID = 1 LAST = -1 # (white) # 45 46 47 48 # 39 40 41 42 # 34 35 36 37 # 28 29 30 31 # 23 24 25 26 # 17 18 19 20 # 12 13 14 15 # 6 7 8 9 # (black) # other squares reachable from a particular square with a white man WHITEMAP = {45: set([39,40,34,35,28,29,30,23,24,25,17,18,19,20,12,13,14,15,6,7,8,9]), 46: set([40,41,34,35,36,28,29,30,31,23,24,25,26,17,18,19,20,12,13,14,15,6,7,8,9]), 47: set([41,42,35,36,37,29,30,31,23,24,25,26,17,18,19,20,12,13,14,15,6,7,8,9]), 48: set([42,36,37,30,31,24,25,26,18,19,20,12,13,14,15,6,7,8,9]), 39: set([34,28,29,23,24,17,18,19,12,13,14,6,7,8,9]), 40: set([34,35,28,29,30,23,24,25,17,18,19,20,12,13,14,15,6,7,8,9]), 41: set([35,36,29,30,31,23,24,25,26,17,18,19,20,12,13,14,15,6,7,8,9]), 42: set([36,37,30,31,24,25,26,18,19,20,12,13,14,15,6,7,8,9]), 34: set([28,29,23,24,17,18,19,12,13,14,6,7,8,9]), 35: set([29,30,23,24,25,17,18,19,20,12,13,14,15,6,7,8,9]), 36: set([30,31,24,25,26,18,19,20,12,13,14,15,6,7,8,9]), 37: set([31,25,26,19,20,13,14,15,7,8,9]), 28: set([23,17,18,12,13,6,7,8]), 29: set([23,24,17,18,19,12,13,14,6,7,8,9]), 30: set([24,25,18,19,20,12,13,14,15,6,7,8,9]), 31: set([25,26,19,20,13,14,15,7,8,9]), 23: set([17,18,12,13,6,7,8]), 24: set([18,19,12,13,14,6,7,8,9]), 25: set([19,20,13,14,15,7,8,9]), 26: set([20,14,15,8,9]), 17: set([12,6,7]), 18: set([12,13,6,7,8]), 19: set([13,14,7,8,9]), 20: set([14,15,8,9]), 12: set([6,7]), 13: set([7,8]), 14: set([8,9]), 15: set([9]), 6: set(), 7: set(), 8: set(), 9: set()} # (white) # 45 46 47 48 # 39 40 41 42 # 34 35 36 37 # 28 29 30 31 # 23 24 25 26 # 17 18 19 20 # 12 13 14 15 # 6 7 8 9 # (black) # other squares reachable from a particular square with a black man BLACKMAP = {6: set([12,17,18,23,24,28,29,30,34,35,36,39,40,41,42,45,46,47,48]), 7: set([12,13,17,18,19,23,24,25,28,29,30,31,34,35,36,37,39,40,41,42,45,46,47,48]), 8: set([13,14,18,19,20,23,24,25,26,28,29,30,31,34,35,36,37,39,40,41,42,45,46,47,48]), 9: set([14,15,19,20,24,25,26,29,30,31,34,35,36,37,39,40,41,42,45,46,47,48]), 12: set([17,18,23,24,28,29,30,34,35,36,39,40,41,42,45,46,47,48]), 13: set([18,19,23,24,25,28,29,30,31,34,35,36,37,39,40,41,42,45,46,47,48]), 14: set([19,20,24,25,26,29,30,31,34,35,36,37,39,40,41,42,45,46,47,48]), 15: set([20,25,26,30,31,35,36,37,40,41,42,45,46,47,48]), 17: set([23,28,29,34,35,39,40,41,45,46,47]), 18: set([23,24,28,29,30,34,35,36,39,40,41,42,45,46,47,48]), 19: set([24,25,29,30,31,34,35,36,37,39,40,41,42,45,46,47,48]), 20: set([25,26,30,31,35,36,37,40,41,42,45,46,47,48]), 23: set([28,29,34,35,39,40,41,45,46,47]), 24: set([29,30,34,35,36,39,40,41,42,45,46,47,48]), 25: set([30,31,35,36,37,40,41,42,45,46,47,48]), 26: set([31,36,37,41,42,46,47,48]), 28: set([34,39,40,45,46]), 29: set([34,35,39,40,41,45,46,47]), 30: set([35,36,40,41,42,45,46,47,48]), 31: set([36,37,41,42,46,47,48]), 34: set([39,40,45,46]), 35: set([40,41,45,46,47]), 36: set([41,42,46,47,48]), 37: set([42,47,48]), 39: set([45]), 40: set([45,46]), 41: set([46,47]), 42: set([47,48]), 45: set(), 46: set(), 47: set(), 48: set()} # translate from simple input notation to real checkerboard notation IMAP = {'a1': 5, 'c1': 6, 'e1': 7, 'g1': 8, 'b2': 10, 'd2': 11, 'f2': 12, 'h2': 13, 'a3': 14, 'c3': 15, 'e3': 16, 'g3': 17, 'b4': 19, 'd4': 20, 'f4': 21, 'h4': 22, 'a5': 23, 'c5': 24, 'e5': 25, 'g5': 26, 'b6': 28, 'd6': 29, 'f6': 30, 'h6': 31, 'a7': 32, 'c7': 33, 'e7': 34, 'g7': 35, 'b8': 37, 'd8': 38, 'f8': 39, 'h8': 40} CBMAP = {5:4, 6:3, 7:2, 8:1, 10:8, 11:7, 12:6, 13:5, 14:12, 15:11, 16:10, 17:9, 19:16, 20:15, 21:14, 22:13, 23:20, 24:19, 25:18, 26:17, 28:24, 29:23, 30:22, 31:21, 32:28, 33:27, 34:26, 35:25, 37:32, 38:31, 39:30, 40:29} def create_position_map(): """ Maps compressed grid indices xi + yi * 8 to internal board indices """ pos = {} pos[1] = 45; pos[3] = 46; pos[5] = 47; pos[7] = 48 pos[8] = 39; pos[10] = 40; pos[12] = 41; pos[14] = 42 pos[17] = 34; pos[19] = 35; pos[21] = 36; pos[23] = 37 pos[24] = 28; pos[26] = 29; pos[28] = 30; pos[30] = 31 pos[33] = 23; pos[35] = 24; pos[37] = 25; pos[39] = 26 pos[40] = 17; pos[42] = 18; pos[44] = 19; pos[46] = 20 pos[49] = 12; pos[51] = 13; pos[53] = 14; pos[55] = 15 pos[56] = 6; pos[58] = 7; pos[60] = 8; pos[62] = 9 return pos def create_key_map(): """ Maps internal board indices to checkerboard label numbers """ key = {} key[6] = 4; key[7] = 3; key[8] = 2; key[9] = 1 key[12] = 8; key[13] = 7; key[14] = 6; key[15] = 5 key[17] = 12; key[18] = 11; key[19] = 10; key[20] = 9 key[23] = 16; key[24] = 15; key[25] = 14; key[26] = 13 key[28] = 20; key[29] = 19; key[30] = 18; key[31] = 17 key[34] = 24; key[35] = 23; key[36] = 22; key[37] = 21 key[39] = 28; key[40] = 27; key[41] = 26; key[42] = 25 key[45] = 32; key[46] = 31; key[47] = 30; key[48] = 29 return key def create_grid_map(): """ Maps internal board indices to grid (row, col) coordinates """ grd = {} grd[6] = (7,0); grd[7] = (7,2); grd[8] = (7,4); grd[9] = (7,6) grd[12] = (6,1); grd[13] = (6,3); grd[14] = (6,5); grd[15] = (6,7) grd[17] = (5,0); grd[18] = (5,2); grd[19] = (5,4); grd[20] = (5,6) grd[23] = (4,1); grd[24] = (4,3); grd[25] = (4,5); grd[26] = (4,7) grd[28] = (3,0); grd[29] = (3,2); grd[30] = (3,4); grd[31] = (3,6) grd[34] = (2,1); grd[35] = (2,3); grd[36] = (2,5); grd[37] = (2,7) grd[39] = (1,0); grd[40] = (1,2); grd[41] = (1,4); grd[42] = (1,6) grd[45] = (0,1); grd[46] = (0,3); grd[47] = (0,5); grd[48] = (0,7) return grd def flip_dict(m): d = {} keys = [k for k, _ in m.iteritems()] vals = [v for _, v in m.iteritems()] for k, v in zip(vals, keys): d[k] = v return d def reverse_dict(m): d = {} keys = [k for k, _ in m.iteritems()] vals = [v for _, v in m.iteritems()] for k, v in zip(keys, reversed(vals)): d[k] = v return d def similarity(pattern, pieces): global grid p1 = [grid[i] for i in pattern] p2 = [grid[j] for j in pieces] return sum(min(math.hypot(x1-x2, y1-y2) for x1, y1 in p1) for x2, y2 in p2) def get_preferences_from_file(): config = RawConfigParser() if not os.access('raven.ini',os.F_OK): # no .ini file yet, so make one config.add_section('AnnotationWindow') config.set('AnnotationWindow', 'font', 'Arial') config.set('AnnotationWindow', 'size', '12') # Writing our configuration file to 'raven.ini' with open('raven.ini', 'wb') as configfile: config.write(configfile) config.read('raven.ini') font = config.get('AnnotationWindow', 'font') size = config.get('AnnotationWindow', 'size') return font, size def write_preferences_to_file(font, size): config = RawConfigParser() config.add_section('AnnotationWindow') config.set('AnnotationWindow', 'font', font) config.set('AnnotationWindow', 'size', size) # Writing our configuration file to 'raven.ini' with open('raven.ini', 'wb') as configfile: config.write(configfile) def parse_index(idx): line, _, char = idx.partition('.') return int(line), int(char) def to_string(line, char): return "%d.%d" % (line, char) grid = create_grid_map() keymap = create_key_map() squaremap = flip_dict(keymap)
Python
import os from Tkinter import * from Tkconstants import END, N, S, E, W from command import * from observer import * from globalconst import * from autoscrollbar import AutoScrollbar from textserialize import Serializer from hyperlinkmgr import HyperlinkManager from tkFileDialog import askopenfilename from tkFont import Font from tooltip import ToolTip class BoardView(Observer): def __init__(self, root, **props): self._statusbar = props['statusbar'] self.root = root self._model = props['model'] self._model.curr_state.attach(self) self._gameMgr = props['parent'] self._board_side = props.get('side') or DEFAULT_SIZE self.light_squares = props.get('lightsquares') or LIGHT_SQUARES self.dark_squares = props.get('darksquares') or DARK_SQUARES self.light_color = props.get('lightcheckers') or LIGHT_CHECKERS self.dark_color = props.get('darkcheckers') or DARK_CHECKERS self._square_size = self._board_side / 8 self._piece_offset = self._square_size / 5 self._crownpic = PhotoImage(file=CROWN_IMAGE) self._boardpos = create_position_map() self._gridpos = create_grid_map() self.canvas = Canvas(root, width=self._board_side, height=self._board_side, borderwidth=0, highlightthickness=0) right_panel = Frame(root, borderwidth=1, relief='sunken') self.toolbar = Frame(root) font, size = get_preferences_from_file() self.scrollbar = AutoScrollbar(root, container=right_panel, row=1, column=1, sticky='ns') self.txt = Text(root, width=40, height=1, borderwidth=0, font=(font,size), wrap='word', yscrollcommand=self.scrollbar.set) self.scrollbar.config(command=self.txt.yview) self.canvas.pack(side='left', fill='both', expand=False) self.toolbar.grid(in_=right_panel, row=0, column=0, sticky='ew') right_panel.pack(side='right', fill='both', expand=True) self.txt.grid(in_=right_panel, row=1, column=0, sticky='nsew') right_panel.grid_rowconfigure(1, weight=1) right_panel.grid_columnconfigure(0, weight=1) self.init_images() self.init_toolbar_buttons() self.init_font_sizes(font, size) self.init_tags() self._register_event_handlers() self.btnset = set([self.bold, self.italic, self.addLink, self.remLink]) self.btnmap = {'bold': self.bold, 'italic': self.italic, 'bullet': self.bullets, 'number': self.numbers, 'hyper': self.addLink} self.hypermgr = HyperlinkManager(self.txt, self._gameMgr.load_game) self.serializer = Serializer(self.txt, self.hypermgr) self.curr_annotation = '' self._setup_board(root) starting_squares = [i for i in self._model.curr_state.valid_squares if self._model.curr_state.squares[i] & (BLACK | WHITE)] self._draw_checkers(Command(add=starting_squares)) self.flip_view = False # black on bottom self._label_board() self.update_statusbar() def _toggle_state(self, tags, btn): # toggle the text state based on the first character in the # selected range. if self.txt.tag_ranges('sel'): current_tags = self.txt.tag_names('sel.first') elif self.txt.tag_ranges('insert'): current_tags = self.txt.tag_names('insert') else: return for tag in tags: already_tagged = any((x for x in current_tags if x.startswith(tag))) for t in current_tags: if t != 'sel': self.txt.tag_remove(t, 'sel.first', 'sel.last') if not already_tagged: self.txt.tag_add(tag, 'sel.first', 'sel.last') btn.configure(relief='sunken') other_btns = self.btnset.difference([btn]) for b in other_btns: b.configure(relief='raised') else: btn.configure(relief='raised') def _on_bold(self): self.bold_tooltip.hide() self._toggle_state(['bold'], self.bold) def _on_italic(self): self.italic_tooltip.hide() self._toggle_state(['italic'], self.italic) def _on_bullets(self): self._process_button_click('bullet', self.bullets_tooltip, self._add_bullets_if_needed, self._remove_bullets_if_needed) def _on_numbers(self): self._process_button_click('number', self.numbers_tooltip, self._add_numbers_if_needed, self._remove_numbers_if_needed) def _process_button_click(self, tag, tooltip, add_func, remove_func): tooltip.hide() if self.txt.tag_ranges('sel'): startline, _ = parse_index(self.txt.index('sel.first')) endline, _ = parse_index(self.txt.index('sel.last')) else: startline, _ = parse_index(self.txt.index(INSERT)) endline = startline current_tags = self.txt.tag_names('%d.0' % startline) if tag not in current_tags: add_func(startline, endline) else: remove_func(startline, endline) def _add_bullets_if_needed(self, startline, endline): self._remove_numbers_if_needed(startline, endline) for line in range(startline, endline+1): current_tags = self.txt.tag_names('%d.0' % line) if 'bullet' not in current_tags: start = '%d.0' % line end = '%d.end' % line self.txt.insert(start, '\t') self.txt.image_create(start, image=self.bullet_image) self.txt.insert(start, '\t') self.txt.tag_add('bullet', start, end) self.bullets.configure(relief='sunken') self.numbers.configure(relief='raised') def _remove_bullets_if_needed(self, startline, endline): for line in range(startline, endline+1): current_tags = self.txt.tag_names('%d.0' % line) if 'bullet' in current_tags: start = '%d.0' % line end = '%d.end' % line self.txt.tag_remove('bullet', start, end) start = '%d.0' % line end = '%d.3' % line self.txt.delete(start, end) self.bullets.configure(relief='raised') def _add_numbers_if_needed(self, startline, endline): self._remove_bullets_if_needed(startline, endline) num = 1 for line in range(startline, endline+1): current_tags = self.txt.tag_names('%d.0' % line) if 'number' not in current_tags: start = '%d.0' % line end = '%d.end' % line self.txt.insert(start, '\t') numstr = '%d.' % num self.txt.insert(start, numstr) self.txt.insert(start, '\t') self.txt.tag_add('number', start, end) num += 1 self.numbers.configure(relief='sunken') self.bullets.configure(relief='raised') def _remove_numbers_if_needed(self, startline, endline): cnt = IntVar() for line in range(startline, endline+1): current_tags = self.txt.tag_names('%d.0' % line) if 'number' in current_tags: start = '%d.0' % line end = '%d.end' % line self.txt.tag_remove('number', start, end) # Regex to match a tab, followed by any number of digits, # followed by a period, all at the start of a line. # The cnt variable stores the number of characters matched. pos = self.txt.search('^\t\d+\.\t', start, end, None, None, None, True, None, cnt) if pos: end = '%d.%d' % (line, cnt.get()) self.txt.delete(start, end) self.numbers.configure(relief='raised') def _on_undo(self): self.undo_tooltip.hide() self._gameMgr.parent.undo_single_move() def _on_undo_all(self): self.undoall_tooltip.hide() self._gameMgr.parent.undo_all_moves() def _on_redo(self): self.redo_tooltip.hide() self._gameMgr.parent.redo_single_move() def _on_redo_all(self): self.redoall_tooltip.hide() self._gameMgr.parent.redo_all_moves() def _on_add_link(self): filename = askopenfilename(initialdir='training') if filename: filename = os.path.relpath(filename, CUR_DIR) self._toggle_state(self.hypermgr.add(filename), self.addLink) def _on_remove_link(self): if self.txt.tag_ranges('sel'): current_tags = self.txt.tag_names('sel.first') if 'hyper' in current_tags: self._toggle_state(['hyper'], self.addLink) def _register_event_handlers(self): self.txt.event_add('<<KeyRel>>', '<KeyRelease-Home>', '<KeyRelease-End>', '<KeyRelease-Left>', '<KeyRelease-Right>', '<KeyRelease-Up>', '<KeyRelease-Down>', '<KeyRelease-Delete>', '<KeyRelease-BackSpace>') Widget.bind(self.txt, '<<Selection>>', self._sel_changed) Widget.bind(self.txt, '<ButtonRelease-1>', self._sel_changed) Widget.bind(self.txt, '<<KeyRel>>', self._key_release) def _key_release(self, event): line, char = parse_index(self.txt.index(INSERT)) self.update_button_state(to_string(line, char)) def _sel_changed(self, event): self.update_button_state(self.txt.index(INSERT)) def is_dirty(self): return self.curr_annotation != self.get_annotation() def reset_toolbar_buttons(self): for btn in self.btnset: btn.configure(relief='raised') def update_button_state(self, index): if self.txt.tag_ranges('sel'): current_tags = self.txt.tag_names('sel.first') else: current_tags = self.txt.tag_names(index) for btn in self.btnmap.itervalues(): btn.configure(relief='raised') for tag in current_tags: if tag in self.btnmap.keys(): self.btnmap[tag].configure(relief='sunken') def init_font_sizes(self, font, size): self.txt.config(font=[font, size]) self._b_font = Font(self.root, (font, size, 'bold')) self._i_font = Font(self.root, (font, size, 'italic')) def init_tags(self): self.txt.tag_config('bold', font=self._b_font, wrap='word') self.txt.tag_config('italic', font=self._i_font, wrap='word') self.txt.tag_config('number', tabs='.5c center 1c left', lmargin1='0', lmargin2='1c') self.txt.tag_config('bullet', tabs='.5c center 1c left', lmargin1='0', lmargin2='1c') def init_images(self): self.bold_image = PhotoImage(file=BOLD_IMAGE) self.italic_image = PhotoImage(file=ITALIC_IMAGE) self.addlink_image = PhotoImage(file=ADDLINK_IMAGE) self.remlink_image = PhotoImage(file=REMLINK_IMAGE) self.bullets_image = PhotoImage(file=BULLETS_IMAGE) self.bullet_image = PhotoImage(file=BULLET_IMAGE) self.numbers_image = PhotoImage(file=NUMBERS_IMAGE) self.undo_image = PhotoImage(file=UNDO_IMAGE) self.undoall_image= PhotoImage(file=UNDOALL_IMAGE) self.redo_image = PhotoImage(file=REDO_IMAGE) self.redoall_image = PhotoImage(file=REDOALL_IMAGE) def init_toolbar_buttons(self): self.bold = Button(name='bold', image=self.bold_image, borderwidth=1, command=self._on_bold) self.bold.grid(in_=self.toolbar, row=0, column=0, sticky=W) self.italic = Button(name='italic', image=self.italic_image, borderwidth=1, command=self._on_italic) self.italic.grid(in_=self.toolbar, row=0, column=1, sticky=W) self.bullets = Button(name='bullets', image=self.bullets_image, borderwidth=1, command=self._on_bullets) self.bullets.grid(in_=self.toolbar, row=0, column=2, sticky=W) self.numbers = Button(name='numbers', image=self.numbers_image, borderwidth=1, command=self._on_numbers) self.numbers.grid(in_=self.toolbar, row=0, column=3, sticky=W) self.addLink = Button(name='addlink', image=self.addlink_image, borderwidth=1, command=self._on_add_link) self.addLink.grid(in_=self.toolbar, row=0, column=4, sticky=W) self.remLink = Button(name='remlink', image=self.remlink_image, borderwidth=1, command=self._on_remove_link) self.remLink.grid(in_=self.toolbar, row=0, column=5, sticky=W) self.frame = Frame(width=0) self.frame.grid(in_=self.toolbar, padx=5, row=0, column=6, sticky=W) self.undoall = Button(name='undoall', image=self.undoall_image, borderwidth=1, command=self._on_undo_all) self.undoall.grid(in_=self.toolbar, row=0, column=7, sticky=W) self.undo = Button(name='undo', image=self.undo_image, borderwidth=1, command=self._on_undo) self.undo.grid(in_=self.toolbar, row=0, column=8, sticky=W) self.redo = Button(name='redo', image=self.redo_image, borderwidth=1, command=self._on_redo) self.redo.grid(in_=self.toolbar, row=0, column=9, sticky=W) self.redoall = Button(name='redoall', image=self.redoall_image, borderwidth=1, command=self._on_redo_all) self.redoall.grid(in_=self.toolbar, row=0, column=10, sticky=W) self.bold_tooltip = ToolTip(self.bold, 'Bold') self.italic_tooltip = ToolTip(self.italic, 'Italic') self.bullets_tooltip = ToolTip(self.bullets, 'Bullet list') self.numbers_tooltip = ToolTip(self.numbers, 'Numbered list') self.addlink_tooltip = ToolTip(self.addLink, 'Add hyperlink') self.remlink_tooltip = ToolTip(self.remLink, 'Remove hyperlink') self.undoall_tooltip = ToolTip(self.undoall, 'First move') self.undo_tooltip = ToolTip(self.undo, 'Back one move') self.redo_tooltip = ToolTip(self.redo, 'Forward one move') self.redoall_tooltip = ToolTip(self.redoall, 'Last move') def reset_view(self, model): self._model = model self.txt.delete('1.0', END) sq = self._model.curr_state.valid_squares self.canvas.delete(self.dark_color) self.canvas.delete(self.light_color) starting_squares = [i for i in sq if (self._model.curr_state.squares[i] & (BLACK | WHITE))] self._draw_checkers(Command(add=starting_squares)) for i in sq: self.highlight_square(i, DARK_SQUARES) def calc_board_loc(self, x, y): vx, vy = self.calc_valid_xy(x, y) xi = int(vx / self._square_size) yi = int(vy / self._square_size) return xi, yi def calc_board_pos(self, xi, yi): return self._boardpos.get(xi + yi * 8, 0) def calc_grid_pos(self, pos): return self._gridpos[pos] def highlight_square(self, idx, color): row, col = self._gridpos[idx] hpos = col + row * 8 self.canvas.itemconfigure('o'+str(hpos), outline=color) def calc_valid_xy(self, x, y): return (min(max(0, self.canvas.canvasx(x)), self._board_side-1), min(max(0, self.canvas.canvasy(y)), self._board_side-1)) def notify(self, move): add_lst = [] rem_lst = [] for idx, _, newval in move.affected_squares: if newval & FREE: rem_lst.append(idx) else: add_lst.append(idx) cmd = Command(add=add_lst, remove=rem_lst) self._draw_checkers(cmd) self.txt.delete('1.0', END) self.serializer.restore(move.annotation) self.curr_annotation = move.annotation if self.txt.get('1.0','end').strip() == '': start = keymap[move.affected_squares[FIRST][0]] dest = keymap[move.affected_squares[LAST][0]] movestr = '%d-%d' % (start, dest) self.txt.insert('1.0', movestr) def get_annotation(self): return self.serializer.dump() def erase_checker(self, index): self.canvas.delete('c'+str(index)) def flip_board(self, flip): self._delete_labels() self.canvas.delete(self.dark_color) self.canvas.delete(self.light_color) if self.flip_view != flip: self.flip_view = flip self._gridpos = reverse_dict(self._gridpos) self._boardpos = reverse_dict(self._boardpos) self._label_board() starting_squares = [i for i in self._model.curr_state.valid_squares if self._model.curr_state.squares[i] & (BLACK | WHITE)] all_checkers = Command(add=starting_squares) self._draw_checkers(all_checkers) def update_statusbar(self, output=None): if output: self._statusbar['text'] = output self.root.update() return if self._model.terminal_test(): text = "Game over. " if self._model.curr_state.to_move == WHITE: text += "Black won." else: text += "White won." self._statusbar['text'] = text return if self._model.curr_state.to_move == WHITE: self._statusbar['text'] = "White to move" else: self._statusbar['text'] = "Black to move" def get_positions(self, type): return map(str, sorted((keymap[i] for i in self._model.curr_state.valid_squares if self._model.curr_state.squares[i] == type))) # private functions def _setup_board(self, root): for r in range(0, 8, 2): row = r * self._square_size for c in range(0, 8, 2): col = c * self._square_size self.canvas.create_rectangle(col, row, col+self._square_size-1, row+self._square_size-1, fill=LIGHT_SQUARES, outline=LIGHT_SQUARES) for c in range(1, 8, 2): col = c * self._square_size self.canvas.create_rectangle(col, row+self._square_size, col+self._square_size-1, row+self._square_size*2-1, fill=LIGHT_SQUARES, outline=LIGHT_SQUARES) for r in range(0, 8, 2): row = r * self._square_size for c in range(1, 8, 2): col = c * self._square_size self.canvas.create_rectangle(col, row, col+self._square_size-1, row+self._square_size-1, fill=DARK_SQUARES, outline=DARK_SQUARES, tags='o'+str(r*8+c)) for c in range(0, 8, 2): col = c * self._square_size self.canvas.create_rectangle(col, row+self._square_size, col+self._square_size-1, row+self._square_size*2-1, fill=DARK_SQUARES, outline=DARK_SQUARES, tags='o'+str(((r+1)*8)+c)) def _label_board(self): for key, pair in self._gridpos.iteritems(): row, col = pair xpos, ypos = col * self._square_size, row * self._square_size self.canvas.create_text(xpos+self._square_size-7, ypos+self._square_size-7, text=str(keymap[key]), fill=LIGHT_SQUARES, tag='label') def _delete_labels(self): self.canvas.delete('label') def _draw_checkers(self, change): if change == None: return for i in change.remove: self.canvas.delete('c'+str(i)) for i in change.add: checker = self._model.curr_state.squares[i] color = self.dark_color if checker & COLORS == BLACK else self.light_color row, col = self._gridpos[i] x = col * self._square_size + self._piece_offset y = row * self._square_size + self._piece_offset tag = 'c'+str(i) self.canvas.create_oval(x+2, y+2, x+2+CHECKER_SIZE, y+2+CHECKER_SIZE, outline='black', fill='black', tags=(color, tag)) self.canvas.create_oval(x, y, x+CHECKER_SIZE, y+CHECKER_SIZE, outline='black', fill=color, tags=(color, tag)) if checker & KING: self.canvas.create_image(x+15, y+15, image=self._crownpic, anchor=CENTER, tags=(color, tag))
Python
import sys import games from globalconst import * class Player(object): def __init__(self, color): self.col = color def _get_color(self): return self.col color = property(_get_color, doc="Player color") class AlphabetaPlayer(Player): def __init__(self, color, depth=4): Player.__init__(self, color) self.searchDepth = depth def select_move(self, game, state): sys.stdout.write('\nThinking ... ') movelist = games.alphabeta_search(state, game, False, self.searchDepth) positions = [] step = 2 if game.captures_available(state) else 1 for i in range(0, len(movelist), step): idx, old, new = movelist[i] positions.append(str(CBMAP[idx])) move = '-'.join(positions) print 'I move %s' % move return movelist class HumanPlayer(Player): def __init__(self, color): Player.__init__(self, color) def select_move(self, game, state): while 1: moves = game.legal_moves(state) positions = [] idx = 0 while 1: reqstr = 'Move to? ' if positions else 'Move from? ' # do any positions match the input pos = self._valid_pos(raw_input(reqstr), moves, idx) if pos: positions.append(pos) # reduce moves to number matching the positions entered moves = self._filter_moves(pos, moves, idx) if game.captures_available(state): idx += 2 else: idx += 1 if len(moves) <= 1: break if len(moves) == 1: return moves[0] else: print "Illegal move!" def _valid_pos(self, pos, moves, idx): t_pos = IMAP.get(pos.lower(), 0) if t_pos == 0: return None # move is illegal for m in moves: if idx < len(m) and m[idx][0] == t_pos: return t_pos return None def _filter_moves(self, pos, moves, idx): del_list = [] for i, m in enumerate(moves): if pos != m[idx][0]: del_list.append(i) for i in reversed(del_list): del moves[i] return moves
Python
from UserDict import UserDict class TranspositionTable (UserDict): def __init__ (self, maxSize): UserDict.__init__(self) assert maxSize > 0 self.maxSize = maxSize self.krono = [] self.maxdepth = 0 self.killer1 = [-1]*20 self.killer2 = [-1]*20 self.hashmove = [-1]*20 def __setitem__ (self, key, item): if not key in self: if len(self) >= self.maxSize: try: del self[self.krono[0]] except KeyError: pass # Overwritten del self.krono[0] self.data[key] = item self.krono.append(key) def probe (self, hash, depth, alpha, beta): if not hash in self: return move, score, hashf, ply = self[hash] if ply < depth: return if hashf == hashfEXACT: return move, score, hashf if hashf == hashfALPHA and score <= alpha: return move, alpha, hashf if hashf == hashfBETA and score >= beta: return move, beta, hashf def record (self, hash, move, score, hashf, ply): self[hash] = (move, score, hashf, ply) def add_killer (self, ply, move): if self.killer1[ply] == -1: self.killer1[ply] = move elif move != self.killer1[ply]: self.killer2[ply] = move def is_killer (self, ply, move): if self.killer1[ply] == move: return 10 elif self.killer2[ply] == move: return 8 if ply >= 2: if self.killer1[ply-2] == move: return 6 elif self.killer2[ply-2] == move: return 4 return 0 def set_hash_move (self, ply, move): self.hashmove[ply] = move def is_hash_move (self, ply, move): return self.hashmove[ply] == move
Python
import re import sys from rules import Rules from document import DocNode class Parser(object): """ Parse the raw text and create a document object that can be converted into output using Emitter. A separate instance should be created for parsing a new document. The first parameter is the raw text to be parsed. An optional second argument is the Rules object to use. You can customize the parsing rules to enable optional features or extend the parser. """ def __init__(self, raw, rules=None): self.rules = rules or Rules() self.raw = raw self.root = DocNode('document', None) self.cur = self.root # The most recent document node self.text = None # The node to add inline characters to def _upto(self, node, kinds): """ Look up the tree to the first occurence of one of the listed kinds of nodes or root. Start at the node node. """ while node.parent is not None and not node.kind in kinds: node = node.parent return node # The _*_repl methods called for matches in regexps. Sometimes the # same method needs several names, because of group names in regexps. def _url_repl(self, groups): """Handle raw urls in text.""" if not groups.get('escaped_url'): # this url is NOT escaped target = groups.get('url_target', '') node = DocNode('link', self.cur) node.content = target DocNode('text', node, node.content) self.text = None else: # this url is escaped, we render it as text if self.text is None: self.text = DocNode('text', self.cur, u'') self.text.content += groups.get('url_target') def _link_repl(self, groups): """Handle all kinds of links.""" target = groups.get('link_target', '') text = (groups.get('link_text', '') or '').strip() parent = self.cur self.cur = DocNode('link', self.cur) self.cur.content = target self.text = None self.parse_re(text, self.rules.link_re) self.cur = parent self.text = None def _wiki_repl(self, groups): """Handle WikiWord links, if enabled.""" text = groups.get('wiki', '') node = DocNode('link', self.cur) node.content = text DocNode('text', node, node.content) self.text = None def _macro_repl(self, groups): """Handles macros using the placeholder syntax.""" name = groups.get('macro_name', '') text = (groups.get('macro_text', '') or '').strip() node = DocNode('macro', self.cur, name) node.args = groups.get('macro_args', '') or '' DocNode('text', node, text or name) self.text = None def _image_repl(self, groups): """Handles images and attachemnts included in the page.""" target = groups.get('image_target', '').strip() text = (groups.get('image_text', '') or '').strip() node = DocNode("image", self.cur, target) DocNode('text', node, text or node.content) self.text = None def _separator_repl(self, groups): self.cur = self._upto(self.cur, ('document', 'section', 'blockquote')) DocNode('separator', self.cur) def _item_repl(self, groups): bullet = groups.get('item_head', u'') text = groups.get('item_text', u'') if bullet[-1] == '#': kind = 'number_list' else: kind = 'bullet_list' level = len(bullet) lst = self.cur # Find a list of the same kind and level up the tree while (lst and not (lst.kind in ('number_list', 'bullet_list') and lst.level == level) and not lst.kind in ('document', 'section', 'blockquote')): lst = lst.parent if lst and lst.kind == kind: self.cur = lst else: # Create a new level of list self.cur = self._upto(self.cur, ('list_item', 'document', 'section', 'blockquote')) self.cur = DocNode(kind, self.cur) self.cur.level = level self.cur = DocNode('list_item', self.cur) self.parse_inline(text) self.text = None def _list_repl(self, groups): text = groups.get('list', u'') self.parse_re(text, self.rules.item_re) def _head_repl(self, groups): self.cur = self._upto(self.cur, ('document', 'section', 'blockquote')) node = DocNode('header', self.cur, groups.get('head_text', '').strip()) node.level = len(groups.get('head_head', ' ')) def _text_repl(self, groups): text = groups.get('text', '') if self.cur.kind in ('table', 'table_row', 'bullet_list', 'number_list'): self.cur = self._upto(self.cur, ('document', 'section', 'blockquote')) if self.cur.kind in ('document', 'section', 'blockquote'): self.cur = DocNode('paragraph', self.cur) else: text = u' ' + text self.parse_inline(text) if groups.get('break') and self.cur.kind in ('paragraph', 'emphasis', 'strong', 'code'): DocNode('break', self.cur, '') self.text = None _break_repl = _text_repl def _table_repl(self, groups): row = groups.get('table', '|').strip() self.cur = self._upto(self.cur, ( 'table', 'document', 'section', 'blockquote')) if self.cur.kind != 'table': self.cur = DocNode('table', self.cur) tb = self.cur tr = DocNode('table_row', tb) text = '' for m in self.rules.cell_re.finditer(row): cell = m.group('cell') if cell: self.cur = DocNode('table_cell', tr) self.text = None self.parse_inline(cell) else: cell = m.group('head') self.cur = DocNode('table_head', tr) self.text = DocNode('text', self.cur, u'') self.text.content = cell.strip('=') self.cur = tb self.text = None def _pre_repl(self, groups): self.cur = self._upto(self.cur, ('document', 'section', 'blockquote')) kind = groups.get('pre_kind', None) text = groups.get('pre_text', u'') def remove_tilde(m): return m.group('indent') + m.group('rest') text = self.rules.pre_escape_re.sub(remove_tilde, text) node = DocNode('preformatted', self.cur, text) node.sect = kind or '' self.text = None def _line_repl(self, groups): self.cur = self._upto(self.cur, ('document', 'section', 'blockquote')) def _code_repl(self, groups): DocNode('code', self.cur, groups.get('code_text', u'').strip()) self.text = None def _emph_repl(self, groups): if self.cur.kind != 'emphasis': self.cur = DocNode('emphasis', self.cur) else: self.cur = self._upto(self.cur, ('emphasis', )).parent self.text = None def _strong_repl(self, groups): if self.cur.kind != 'strong': self.cur = DocNode('strong', self.cur) else: self.cur = self._upto(self.cur, ('strong', )).parent self.text = None def _break_repl(self, groups): DocNode('break', self.cur, None) self.text = None def _escape_repl(self, groups): if self.text is None: self.text = DocNode('text', self.cur, u'') self.text.content += groups.get('escaped_char', u'') def _char_repl(self, groups): if self.text is None: self.text = DocNode('text', self.cur, u'') self.text.content += groups.get('char', u'') def parse_inline(self, raw): """Recognize inline elements inside blocks.""" self.parse_re(raw, self.rules.inline_re) def parse_re(self, raw, rules_re): """Parse a fragment according to the compiled rules.""" for match in rules_re.finditer(raw): groups = dict((k, v) for (k, v) in match.groupdict().iteritems() if v is not None) name = match.lastgroup function = getattr(self, '_%s_repl' % name) function(groups) def parse(self): """Parse the text given as self.raw and return DOM tree.""" self.parse_re(self.raw, self.rules.block_re) return self.root
Python
from Tkinter import * from ttk import Combobox, Label from tkFont import families from tkSimpleDialog import Dialog class PreferencesDialog(Dialog): def __init__(self, parent, title, font, size): self._master = parent self.result = False self.font = font self.size = size Dialog.__init__(self, parent, title) def body(self, master): self._npFrame = LabelFrame(master, text='Annotation window text') self._npFrame.pack(fill=X) self._fontFrame = Frame(self._npFrame, borderwidth=0) self._fontLabel = Label(self._fontFrame, text='Font:', width=5) self._fontLabel.pack(side=LEFT, padx=3) self._fontCombo = Combobox(self._fontFrame, values=sorted(families()), state='readonly') self._fontCombo.pack(side=RIGHT, fill=X) self._sizeFrame = Frame(self._npFrame, borderwidth=0) self._sizeLabel = Label(self._sizeFrame, text='Size:', width=5) self._sizeLabel.pack(side=LEFT, padx=3) self._sizeCombo = Combobox(self._sizeFrame, values=range(8,15), state='readonly') self._sizeCombo.pack(side=RIGHT, fill=X) self._fontFrame.pack() self._sizeFrame.pack() self._npFrame.pack(fill=X) self._fontCombo.set(self.font) self._sizeCombo.set(self.size) def apply(self): self.font = self._fontCombo.get() self.size = self._sizeCombo.get() self.result = True def cancel(self, event=None): if self.parent is not None: self.parent.focus_set() self.destroy()
Python
from Tkinter import PhotoImage from Tkconstants import * from globalconst import BULLET_IMAGE from creoleparser import Parser from rules import LinkRules class TextTagEmitter(object): """ Generate tagged output compatible with the Tkinter Text widget """ def __init__(self, root, txtWidget, hyperMgr, bulletImage, link_rules=None): self.root = root self.link_rules = link_rules or LinkRules() self.txtWidget = txtWidget self.hyperMgr = hyperMgr self.line = 1 self.index = 0 self.number = 1 self.bullet = False self.bullet_image = bulletImage self.begin_italic = '' self.begin_bold = '' self.begin_list_item = '' self.list_item = '' self.begin_link = '' # visit/leave methods for emitting nodes of the document: def visit_document(self, node): pass def leave_document(self, node): # leave_paragraph always leaves two extra carriage returns at the # end of the text. This deletes them. txtindex = '%d.%d' % (self.line-1, self.index) self.txtWidget.delete(txtindex, END) def visit_text(self, node): if self.begin_list_item: self.list_item = node.content elif self.begin_link: pass else: txtindex = '%d.%d' % (self.line, self.index) self.txtWidget.insert(txtindex, node.content) def leave_text(self, node): if not self.begin_list_item: self.index += len(node.content) def visit_separator(self, node): raise NotImplementedError def leave_separator(self, node): raise NotImplementedError def visit_paragraph(self, node): pass def leave_paragraph(self, node): txtindex = '%d.%d' % (self.line, self.index) self.txtWidget.insert(txtindex, '\n\n') self.line += 2 self.index = 0 self.number = 1 def visit_bullet_list(self, node): self.bullet = True def leave_bullet_list(self, node): txtindex = '%d.%d' % (self.line, self.index) self.txtWidget.insert(txtindex, '\n') self.line += 1 self.index = 0 self.bullet = False def visit_number_list(self, node): self.number = 1 def leave_number_list(self, node): txtindex = '%d.%d' % (self.line, self.index) self.txtWidget.insert(txtindex, '\n') self.line += 1 self.index = 0 def visit_list_item(self, node): self.begin_list_item = '%d.%d' % (self.line, self.index) def leave_list_item(self, node): if self.bullet: self.txtWidget.insert(self.begin_list_item, '\t') next = '%d.%d' % (self.line, self.index+1) self.txtWidget.image_create(next, image=self.bullet_image) next = '%d.%d' % (self.line, self.index+2) content = '\t%s\t\n' % self.list_item self.txtWidget.insert(next, content) end_list_item = '%d.%d' % (self.line, self.index + len(content)+2) self.txtWidget.tag_add('bullet', self.begin_list_item, end_list_item) elif self.number: content = '\t%d.\t%s\n' % (self.number, self.list_item) end_list_item = '%d.%d' % (self.line, self.index + len(content)) self.txtWidget.insert(self.begin_list_item, content) self.txtWidget.tag_add('number', self.begin_list_item, end_list_item) self.number += 1 self.begin_list_item = '' self.list_item = '' self.line += 1 self.index = 0 def visit_emphasis(self, node): self.begin_italic = '%d.%d' % (self.line, self.index) def leave_emphasis(self, node): end_italic = '%d.%d' % (self.line, self.index) self.txtWidget.tag_add('italic', self.begin_italic, end_italic) def visit_strong(self, node): self.begin_bold = '%d.%d' % (self.line, self.index) def leave_strong(self, node): end_bold = '%d.%d' % (self.line, self.index) self.txtWidget.tag_add('bold', self.begin_bold, end_bold) def visit_link(self, node): self.begin_link = '%d.%d' % (self.line, self.index) def leave_link(self, node): end_link = '%d.%d' % (self.line, self.index) # TODO: Revisit unicode encode/decode issues later. # 1. Decode early. 2. Unicode everywhere 3. Encode late # However, decoding filename and link_text here works for now. fname = str(node.content).replace('%20', ' ') link_text = str(node.children[0].content).replace('%20', ' ') self.txtWidget.insert(self.begin_link, link_text, self.hyperMgr.add(fname)) self.begin_link = '' def visit_break(self, node): txtindex = '%d.%d' % (self.line, self.index) self.txtWidget.insert(txtindex, '\n') def leave_break(self, node): self.line += 1 self.index = 0 def visit_default(self, node): """Fallback function for visiting unknown nodes.""" raise TypeError def leave_default(self, node): """Fallback function for leaving unknown nodes.""" raise TypeError def emit_children(self, node): """Emit all the children of a node.""" for child in node.children: self.emit_node(child) def emit_node(self, node): """Visit/depart a single node and its children.""" visit = getattr(self, 'visit_%s' % node.kind, self.visit_default) visit(node) self.emit_children(node) leave = getattr(self, 'leave_%s' % node.kind, self.leave_default) leave(node) def emit(self): """Emit the document represented by self.root DOM tree.""" return self.emit_node(self.root) class Serializer(object): def __init__(self, txtWidget, hyperMgr): self.txt = txtWidget self.hyperMgr = hyperMgr self.bullet_image = PhotoImage(file=BULLET_IMAGE) self._reset() def _reset(self): self.number = 0 self.bullet = False self.filename = '' self.link_start = False self.first_tab = True self.list_end = False def dump(self, index1='1.0', index2=END): # outputs contents from Text widget in Creole format. creole = '' self._reset() for key, value, index in self.txt.dump(index1, index2): if key == 'tagon': if value == 'bold': creole += '**' elif value == 'italic': creole += '//' elif value == 'bullet': creole += '*' self.bullet = True self.list_end = False elif value.startswith('hyper-'): self.filename = self.hyperMgr.filenames[value] self.link_start = True elif value == 'number': creole += '#' self.number += 1 elif key == 'tagoff': if value == 'bold': creole += '**' elif value == 'italic': creole += '//' elif value.startswith('hyper-'): creole += ']]' elif value == 'number': numstr = '#\t%d.\t' % self.number if numstr in creole: creole = creole.replace(numstr, '# ', 1) self.list_end = True elif value == 'bullet': creole = creole.replace('\n*\t\t', '\n* ', 1) self.bullet = False self.list_end = True elif key == 'text': if self.link_start: # TODO: Revisit unicode encode/decode issues later. # 1. Decode early. 2. Unicode everywhere 3. Encode late # However, encoding filename and link_text here works for # now. fname = self.filename.replace(' ', '%20').encode('utf-8') link_text = value.replace(' ', '%20') value = '[[%s|%s' % (fname, link_text) self.link_start = False numstr = '%d.\t' % self.number if self.list_end and value != '\n' and numstr not in value: creole += '\n' self.number = 0 self.list_end = False creole += value return creole.rstrip() def restore(self, creole): self.hyperMgr.reset() document = Parser(unicode(creole, 'utf-8', 'ignore')).parse() return TextTagEmitter(document, self.txt, self.hyperMgr, self.bullet_image).emit()
Python
import os from Tkinter import * from Tkconstants import W, E import Tkinter as tk from tkMessageBox import askyesnocancel from multiprocessing import freeze_support from globalconst import * from aboutbox import AboutBox from setupboard import SetupBoard from gamemanager import GameManager from centeredwindow import CenteredWindow from prefdlg import PreferencesDialog class MainFrame(object, CenteredWindow): def __init__(self, master): self.root = master self.root.withdraw() self.root.iconbitmap(RAVEN_ICON) self.root.title('Raven ' + VERSION) self.root.protocol('WM_DELETE_WINDOW', self._on_close) self.thinkTime = IntVar(value=5) self.manager = GameManager(root=self.root, parent=self) self.menubar = tk.Menu(self.root) self.create_game_menu() self.create_options_menu() self.create_help_menu() self.root.config(menu=self.menubar) CenteredWindow.__init__(self, self.root) self.root.deiconify() def _on_close(self): if self.manager.view.is_dirty(): msg = 'Do you want to save your changes before exiting?' result = askyesnocancel(TITLE, msg) if result == True: self.manager.save_game() elif result == None: return self.root.destroy() def set_title_bar_filename(self, filename=None): if not filename: self.root.title(TITLE) else: self.root.title(TITLE + ' - ' + os.path.basename(filename)) def undo_all_moves(self, *args): self.stop_processes() self.manager.model.undo_all_moves(None, self.manager.view.get_annotation()) self.manager._controller1.remove_highlights() self.manager._controller2.remove_highlights() self.manager.view.update_statusbar() def redo_all_moves(self, *args): self.stop_processes() self.manager.model.redo_all_moves(None, self.manager.view.get_annotation()) self.manager._controller1.remove_highlights() self.manager._controller2.remove_highlights() self.manager.view.update_statusbar() def undo_single_move(self, *args): self.stop_processes() self.manager.model.undo_move(None, None, True, True, self.manager.view.get_annotation()) self.manager._controller1.remove_highlights() self.manager._controller2.remove_highlights() self.manager.view.update_statusbar() def redo_single_move(self, *args): self.stop_processes() annotation = self.manager.view.get_annotation() self.manager.model.redo_move(None, None, annotation) self.manager._controller1.remove_highlights() self.manager._controller2.remove_highlights() self.manager.view.update_statusbar() def create_game_menu(self): game = Menu(self.menubar, tearoff=0) game.add_command(label='New game', underline=0, command=self.manager.new_game) game.add_command(label='Open game ...', underline=0, command=self.manager.open_game) game.add_separator() game.add_command(label='Save game', underline=0, command=self.manager.save_game) game.add_command(label='Save game As ...', underline=10, command=self.manager.save_game_as) game.add_separator() game.add_command(label='Set up Board ...', underline=7, command=self.show_setup_board_dialog) game.add_command(label='Flip board', underline=0, command=self.flip_board) game.add_separator() game.add_command(label='Exit', underline=0, command=self._on_close) self.menubar.add_cascade(label='Game', menu=game) def create_options_menu(self): options = Menu(self.menubar, tearoff=0) think = Menu(options, tearoff=0) think.add_radiobutton(label="1 second", underline=None, command=self.set_think_time, variable=self.thinkTime, value=1) think.add_radiobutton(label="2 seconds", underline=None, command=self.set_think_time, variable=self.thinkTime, value=2) think.add_radiobutton(label="5 seconds", underline=None, command=self.set_think_time, variable=self.thinkTime, value=5) think.add_radiobutton(label="10 seconds", underline=None, command=self.set_think_time, variable=self.thinkTime, value=10) think.add_radiobutton(label="30 seconds", underline=None, command=self.set_think_time, variable=self.thinkTime, value=30) think.add_radiobutton(label="1 minute", underline=None, command=self.set_think_time, variable=self.thinkTime, value=60) options.add_cascade(label='CPU think time', underline=0, menu=think) options.add_separator() options.add_command(label='Preferences ...', underline=0, command=self.show_preferences_dialog) self.menubar.add_cascade(label='Options', menu=options) def create_help_menu(self): helpmenu = Menu(self.menubar, tearoff=0) helpmenu.add_command(label='About Raven ...', underline=0, command=self.show_about_box) self.menubar.add_cascade(label='Help', menu=helpmenu) def stop_processes(self): # stop any controller processes from making moves self.manager.model.curr_state.ok_to_move = False self.manager._controller1.stop_process() self.manager._controller2.stop_process() def show_about_box(self): AboutBox(self.root, 'About Raven') def show_setup_board_dialog(self): self.stop_processes() dlg = SetupBoard(self.root, 'Set up board', self.manager) self.manager.set_controllers() self.root.focus_set() self.manager.turn_finished() def show_preferences_dialog(self): font, size = get_preferences_from_file() dlg = PreferencesDialog(self.root, 'Preferences', font, size) if dlg.result: self.manager.view.init_font_sizes(dlg.font, dlg.size) self.manager.view.init_tags() write_preferences_to_file(dlg.font, dlg.size) def set_think_time(self): self.manager._controller1.set_search_time(self.thinkTime.get()) self.manager._controller2.set_search_time(self.thinkTime.get()) def flip_board(self): if self.manager.model.to_move == BLACK: self.manager._controller1.remove_highlights() else: self.manager._controller2.remove_highlights() self.manager.view.flip_board(not self.manager.view.flip_view) if self.manager.model.to_move == BLACK: self.manager._controller1.add_highlights() else: self.manager._controller2.add_highlights() def start(): root = Tk() mainframe = MainFrame(root) mainframe.root.update() mainframe.root.mainloop() if __name__=='__main__': freeze_support() start()
Python
from globalconst import BLACK, WHITE, MAN, KING from goalevaluator import GoalEvaluator from onekingattack import Goal_OneKingAttack class OneKingAttackOneKingEvaluator(GoalEvaluator): def __init__(self, bias): GoalEvaluator.__init__(self, bias) def calculateDesirability(self, board): plr_color = board.to_move enemy_color = board.enemy # if we don't have one man on each side or the player # doesn't have the opposition, then goal is undesirable. if (board.count(BLACK) != 1 or board.count(WHITE) != 1 or not board.has_opposition(plr_color)): return 0.0 player = board.get_pieces(plr_color)[0] p_idx, p_val = player p_row, p_col = board.row_col_for_index(p_idx) enemy = board.get_pieces(enemy_color)[0] e_idx, e_val = enemy e_row, e_col = board.row_col_for_index(e_idx) # must be two kings against each other and the distance # between them at least three rows away if ((p_val & KING) and (e_val & KING) and (abs(p_row - e_row) > 2 or abs(p_col - e_col) > 2)): return 1.0 return 0.0 def setGoal(self, board): player = board.to_move board.removeAllSubgoals() if player == WHITE: goalset = board.addWhiteSubgoal else: goalset = board.addBlackSubgoal goalset(Goal_OneKingAttack(board)) class OneKingFleeOneKingEvaluator(GoalEvaluator): def __init__(self, bias): GoalEvaluator.__init__(self, bias) def calculateDesirability(self, board): plr_color = board.to_move enemy_color = board.enemy # if we don't have one man on each side or the player # has the opposition (meaning we should attack instead), # then goal is not applicable. if (board.count(BLACK) != 1 or board.count(WHITE) != 1 or board.has_opposition(plr_color)): return 0.0 player = board.get_pieces(plr_color)[0] p_idx, p_val = player enemy = board.get_pieces(enemy_color)[0] e_idx, e_val = enemy # must be two kings against each other; otherwise it's # not applicable. if not ((p_val & KING) and (e_val & KING)): return 0.0 return 1.0 def setGoal(self, board): player = board.to_move board.removeAllSubgoals() if player == WHITE: goalset = board.addWhiteSubgoal else: goalset = board.addBlackSubgoal goalset(Goal_OneKingFlee(board))
Python
from Tkinter import * class CenteredWindow: def __init__(self, root): self.root = root self.root.after_idle(self.center_on_screen) self.root.update() def center_on_screen(self): self.root.update_idletasks() sw = self.root.winfo_screenwidth() sh = self.root.winfo_screenheight() w = self.root.winfo_reqwidth() h = self.root.winfo_reqheight() new_geometry = "+%d+%d" % ((sw-w)/2, (sh-h)/2) self.root.geometry(newGeometry=new_geometry)
Python
import sys from goal import Goal from composite import CompositeGoal class Goal_OneKingFlee(CompositeGoal): def __init__(self, owner): CompositeGoal.__init__(self, owner) def activate(self): self.status = self.ACTIVE self.removeAllSubgoals() # because goals are *pushed* onto the front of the subgoal list they must # be added in reverse order. self.addSubgoal(Goal_MoveTowardNearestDoubleCorner(self.owner)) self.addSubgoal(Goal_SeeSaw(self.owner)) def process(self): self.activateIfInactive() return self.processSubgoals() def terminate(self): self.status = self.INACTIVE class Goal_MoveTowardBestDoubleCorner(Goal): def __init__(self, owner): Goal.__init__(self, owner) self.dc = [8, 13, 27, 32] def activate(self): self.status = self.ACTIVE def process(self): # if status is inactive, activate self.activateIfInactive() # only moves (not captures) are a valid goal if self.owner.captures: self.status = self.FAILED return # identify player king and enemy king plr_color = self.owner.to_move enemy_color = self.owner.enemy player = self.owner.get_pieces(plr_color)[0] p_idx, _ = player p_row, p_col = self.owner.row_col_for_index(p_idx) enemy = self.owner.get_pieces(enemy_color)[0] e_idx, _ = enemy e_row, e_col = self.owner.row_col_for_index(e_idx) # pick DC that isn't blocked by enemy lowest_dist = sys.maxint dc = 0 for i in self.dc: dc_row, dc_col = self.owner.row_col_for_index(i) pdist = abs(dc_row - p_row) + abs(dc_col - p_col) edist = abs(dc_row - e_row) + abs(dc_col - e_col) if pdist < lowest_dist and edist > pdist: lowest_dist = pdist dc = i # if lowest distance is 0, then goal is complete. if lowest_dist == 0: self.status = self.COMPLETED return # select the available move that decreases the distance # between the original player position and the chosen double corner. # If no such move exists, the goal has failed. dc_row, dc_col = self.owner.row_col_for_index(dc) good_move = None for m in self.owner.moves: # try a move and gather the new row & col for the player self.owner.make_move(m, False, False) plr_update = self.owner.get_pieces(plr_color)[0] pu_idx, _ = plr_update pu_row, pu_col = self.owner.row_col_for_index(pu_idx) self.owner.undo_move(m, False, False) new_diff = abs(pu_row - dc_row) + abs(pu_col - dc_col) if new_diff < lowest_dist: good_move = m break if good_move: self.owner.make_move(good_move, True, True) else: self.status = self.FAILED def terminate(self): self.status = self.INACTIVE class Goal_SeeSaw(Goal): def __init__(self, owner): Goal.__init__(self, owner) def activate(self): self.status = self.ACTIVE def process(self): # for now, I'm not even sure I need this goal, but I'm saving it # as a placeholder. self.status = self.COMPLETED def terminate(self): self.status = self.INACTIVE
Python
"""Provide some widely useful utilities. Safe for "from utils import *".""" from __future__ import generators import operator, math, random, copy, sys, os.path, bisect #______________________________________________________________________________ # Simple Data Structures: booleans, infinity, Dict, Struct infinity = 1.0e400 def Dict(**entries): """Create a dict out of the argument=value arguments. Ex: Dict(a=1, b=2, c=3) ==> {'a':1, 'b':2, 'c':3}""" return entries class DefaultDict(dict): """Dictionary with a default value for unknown keys. Ex: d = DefaultDict(0); d['x'] += 1; d['x'] ==> 1 d = DefaultDict([]); d['x'] += [1]; d['y'] += [2]; d['x'] ==> [1]""" def __init__(self, default): self.default = default def __getitem__(self, key): if key in self: return self.get(key) return self.setdefault(key, copy.deepcopy(self.default)) class Struct: """Create an instance with argument=value slots. This is for making a lightweight object whose class doesn't matter. Ex: s = Struct(a=1, b=2); s.a ==> 1; s.a = 3; s ==> Struct(a=3, b=2)""" def __init__(self, **entries): self.__dict__.update(entries) def __cmp__(self, other): if isinstance(other, Struct): return cmp(self.__dict__, other.__dict__) else: return cmp(self.__dict__, other) def __repr__(self): args = ['%s=%s' % (k, repr(v)) for (k, v) in vars(self).items()] return 'Struct(%s)' % ', '.join(args) def update(x, **entries): """Update a dict, or an object with slots, according to entries. Ex: update({'a': 1}, a=10, b=20) ==> {'a': 10, 'b': 20} update(Struct(a=1), a=10, b=20) ==> Struct(a=10, b=20)""" if isinstance(x, dict): x.update(entries) else: x.__dict__.update(entries) return x #______________________________________________________________________________ # Functions on Sequences (mostly inspired by Common Lisp) # NOTE: Sequence functions (count_if, find_if, every, some) take function # argument first (like reduce, filter, and map). def sort(seq, compare=cmp): """Sort seq (mutating it) and return it. compare is the 2nd arg to .sort. Ex: sort([3, 1, 2]) ==> [1, 2, 3]; reverse(sort([3, 1, 2])) ==> [3, 2, 1] sort([-3, 1, 2], comparer(abs)) ==> [1, 2, -3]""" if isinstance(seq, str): seq = ''.join(sort(list(seq), compare)) elif compare == cmp: seq.sort() else: seq.sort(compare) return seq def comparer(key=None, cmp=cmp): """Build a compare function suitable for sort. The most common use is to specify key, meaning compare the values of key(x), key(y).""" if key == None: return cmp else: return lambda x,y: cmp(key(x), key(y)) def removeall(item, seq): """Return a copy of seq (or string) with all occurences of item removed. Ex: removeall(3, [1, 2, 3, 3, 2, 1, 3]) ==> [1, 2, 2, 1] removeall(4, [1, 2, 3]) ==> [1, 2, 3]""" if isinstance(seq, str): return seq.replace(item, '') else: return [x for x in seq if x != item] def reverse(seq): """Return the reverse of a string or list or tuple. Mutates the seq. Ex: reverse([1, 2, 3]) ==> [3, 2, 1]; reverse('abc') ==> 'cba'""" if isinstance(seq, str): return ''.join(reverse(list(seq))) elif isinstance(seq, tuple): return tuple(reverse(list(seq))) else: seq.reverse(); return seq def unique(seq): """Remove duplicate elements from seq. Assumes hashable elements. Ex: unique([1, 2, 3, 2, 1]) ==> [1, 2, 3] # order may vary""" return list(set(seq)) def count_if(predicate, seq): """Count the number of elements of seq for which the predicate is true. count_if(callable, [42, None, max, min]) ==> 2""" f = lambda count, x: count + (not not predicate(x)) return reduce(f, seq, 0) def find_if(predicate, seq): """If there is an element of seq that satisfies predicate, return it. Ex: find_if(callable, [3, min, max]) ==> min find_if(callable, [1, 2, 3]) ==> None""" for x in seq: if predicate(x): return x return None def every(predicate, seq): """True if every element of seq satisfies predicate. Ex: every(callable, [min, max]) ==> 1; every(callable, [min, 3]) ==> 0""" for x in seq: if not predicate(x): return False return True def some(predicate, seq): """If some element x of seq satisfies predicate(x), return predicate(x). Ex: some(callable, [min, 3]) ==> 1; some(callable, [2, 3]) ==> 0""" for x in seq: px = predicate(x) if px: return px return False # Added by Brandon def flatten(x): if type(x) != type([]): return [x] if x == []: return x return flatten(x[0]) + flatten(x[1:]) #______________________________________________________________________________ # Functions on sequences of numbers # NOTE: these take the sequence argument first, like min and max, # and like standard math notation: \sigma (i = 1..n) fn(i) # A lot of programing is finding the best value that satisfies some condition; # so there are three versions of argmin/argmax, depending on what you want to # do with ties: return the first one, return them all, or pick at random. def sum(seq, fn=None): """Sum the elements seq[i], or fn(seq[i]) if fn is given. Ex: sum([1, 2, 3]) ==> 6; sum(range(8), lambda x: 2**x) ==> 255""" if fn: seq = map(fn, seq) return reduce(operator.add, seq, 0) def product(seq, fn=None): """Multiply the elements seq[i], or fn(seq[i]) if fn is given. product([1, 2, 3]) ==> 6; product([1, 2, 3], lambda x: x*x) ==> 1*4*9""" if fn: seq = map(fn, seq) return reduce(operator.mul, seq, 1) def argmin(gen, fn): """Return an element with lowest fn(x) score; tie goes to first one. Gen must be a generator. Ex: argmin(['one', 'to', 'three'], len) ==> 'to'""" best = gen.next(); best_score = fn(best) for x in gen: x_score = fn(x) if x_score < best_score: best, best_score = x, x_score return best def argmin_list(gen, fn): """Return a list of elements of gen with the lowest fn(x) scores. Ex: argmin_list(['one', 'to', 'three', 'or'], len) ==> ['to', 'or']""" best_score, best = fn(gen.next()), [] for x in gen: x_score = fn(x) if x_score < best_score: best, best_score = [x], x_score elif x_score == best_score: best.append(x) return best #def argmin_list(seq, fn): # """Return a list of elements of seq[i] with the lowest fn(seq[i]) scores. # Ex: argmin_list(['one', 'to', 'three', 'or'], len) ==> ['to', 'or']""" # best_score, best = fn(seq[0]), [] # for x in seq: # x_score = fn(x) # if x_score < best_score: # best, best_score = [x], x_score # elif x_score == best_score: # best.append(x) # return best def argmin_random_tie(gen, fn): """Return an element with lowest fn(x) score; break ties at random. Thus, for all s,f: argmin_random_tie(s, f) in argmin_list(s, f)""" try: best = gen.next(); best_score = fn(best); n = 0 except StopIteration: return [] for x in gen: x_score = fn(x) if x_score < best_score: best, best_score = x, x_score; n = 1 elif x_score == best_score: n += 1 if random.randrange(n) == 0: best = x return best #def argmin_random_tie(seq, fn): # """Return an element with lowest fn(seq[i]) score; break ties at random. # Thus, for all s,f: argmin_random_tie(s, f) in argmin_list(s, f)""" # best_score = fn(seq[0]); n = 0 # for x in seq: # x_score = fn(x) # if x_score < best_score: # best, best_score = x, x_score; n = 1 # elif x_score == best_score: # n += 1 # if random.randrange(n) == 0: # best = x # return best def argmax(gen, fn): """Return an element with highest fn(x) score; tie goes to first one. Ex: argmax(['one', 'to', 'three'], len) ==> 'three'""" return argmin(gen, lambda x: -fn(x)) def argmax_list(seq, fn): """Return a list of elements of gen with the highest fn(x) scores. Ex: argmax_list(['one', 'three', 'seven'], len) ==> ['three', 'seven']""" return argmin_list(seq, lambda x: -fn(x)) def argmax_random_tie(seq, fn): "Return an element with highest fn(x) score; break ties at random." return argmin_random_tie(seq, lambda x: -fn(x)) #______________________________________________________________________________ # Statistical and mathematical functions def histogram(values, mode=0, bin_function=None): """Return a list of (value, count) pairs, summarizing the input values. Sorted by increasing value, or if mode=1, by decreasing count. If bin_function is given, map it over values first. Ex: vals = [100, 110, 160, 200, 160, 110, 200, 200, 220] histogram(vals) ==> [(100, 1), (110, 2), (160, 2), (200, 3), (220, 1)] histogram(vals, 1) ==> [(200, 3), (160, 2), (110, 2), (100, 1), (220, 1)] histogram(vals, 1, lambda v: round(v, -2)) ==> [(200.0, 6), (100.0, 3)]""" if bin_function: values = map(bin_function, values) bins = {} for val in values: bins[val] = bins.get(val, 0) + 1 if mode: return sort(bins.items(), lambda x,y: cmp(y[1],x[1])) else: return sort(bins.items()) def log2(x): """Base 2 logarithm. Ex: log2(1024) ==> 10.0; log2(1.0) ==> 0.0; log2(0) raises OverflowError""" return math.log10(x) / math.log10(2) def mode(values): """Return the most common value in the list of values. Ex: mode([1, 2, 3, 2]) ==> 2""" return histogram(values, mode=1)[0][0] def median(values): """Return the middle value, when the values are sorted. If there are an odd number of elements, try to average the middle two. If they can't be averaged (e.g. they are strings), choose one at random. Ex: median([10, 100, 11]) ==> 11; median([1, 2, 3, 4]) ==> 2.5""" n = len(values) values = sort(values[:]) if n % 2 == 1: return values[n/2] else: middle2 = values[(n/2)-1:(n/2)+1] try: return mean(middle2) except TypeError: return random.choice(middle2) def mean(values): """Return the arithmetic average of the values.""" return sum(values) / float(len(values)) def stddev(values, meanval=None): """The standard deviation of a set of values. Pass in the mean if you already know it.""" if meanval == None: meanval = mean(values) return math.sqrt(sum([(x - meanval)**2 for x in values])) def dotproduct(X, Y): """Return the sum of the element-wise product of vectors x and y. Ex: dotproduct([1, 2, 3], [1000, 100, 10]) ==> 1230""" return sum([x * y for x, y in zip(X, Y)]) def vector_add(a, b): """Component-wise addition of two vectors. Ex: vector_add((0, 1), (8, 9)) ==> (8, 10)""" return tuple(map(operator.add, a, b)) def probability(p): "Return true with probability p." return p > random.uniform(0.0, 1.0) def num_or_str(x): """The argument is a string; convert to a number if possible, or strip it. Ex: num_or_str('42') ==> 42; num_or_str(' 42x ') ==> '42x' """ try: return int(x) except ValueError: try: return float(x) except ValueError: return str(x).strip() def distance((ax, ay), (bx, by)): "The distance between two (x, y) points." return math.hypot((ax - bx), (ay - by)) def distance2((ax, ay), (bx, by)): "The square of the distance between two (x, y) points." return (ax - bx)**2 + (ay - by)**2 def normalize(numbers, total=1.0): """Multiply each number by a constant such that the sum is 1.0 (or total). Ex: normalize([1,2,1]) ==> [0.25, 0.5, 0.25]""" k = total / sum(numbers) return [k * n for n in numbers] #______________________________________________________________________________ # Misc Functions def printf(format, *args): """Format args with the first argument as format string, and write. Return the last arg, or format itself if there are no args.""" sys.stdout.write(str(format) % args) return if_(args, args[-1], format) def print_(*args): """Print the args and return the last one.""" for arg in args: print arg, print return if_(args, args[-1], None) def memoize(fn, slot=None): """Memoize fn: make it remember the computed value for any argument list. If slot is specified, store result in that slot of first argument. If slot is false, store results in a dictionary. Ex: def fib(n): return (n<=1 and 1) or (fib(n-1) + fib(n-2)); fib(9) ==> 55 # Now we make it faster: fib = memoize(fib); fib(9) ==> 55""" if slot: def memoized_fn(obj, *args): if hasattr(obj, slot): return getattr(obj, slot) else: val = fn(obj, *args) setattr(obj, slot, val) return val else: def memoized_fn(*args): if not memoized_fn.cache.has_key(args): memoized_fn.cache[args] = fn(*args) return memoized_fn.cache[args] memoized_fn.cache = {} return memoized_fn def method(name, *args): """Return a function that invokes the named method with the optional args. Ex: map(method('upper'), ['a', 'b', 'cee']) ==> ['A', 'B', 'CEE'] map(method('count', 't'), ['this', 'is', 'a', 'test']) ==> [1, 0, 0, 2]""" return lambda x: getattr(x, name)(*args) def method2(name, *static_args): """Return a function that invokes the named method with the optional args. Ex: map(method('upper'), ['a', 'b', 'cee']) ==> ['A', 'B', 'CEE'] map(method('count', 't'), ['this', 'is', 'a', 'test']) ==> [1, 0, 0, 2]""" return lambda x, *dyn_args: getattr(x, name)(*(dyn_args + static_args)) def abstract(): """Indicate abstract methods that should be implemented in a subclass. Ex: def m(): abstract() # Similar to Java's 'abstract void m()'""" raise NotImplementedError(caller() + ' must be implemented in subclass') def caller(n=1): """Return the name of the calling function n levels up in the frame stack. Ex: caller(0) ==> 'caller'; def f(): return caller(); f() ==> 'f'""" import inspect return inspect.getouterframes(inspect.currentframe())[n][3] def indexed(seq): """Like [(i, seq[i]) for i in range(len(seq))], but with yield. Ex: for i, c in indexed('abc'): print i, c""" i = 0 for x in seq: yield i, x i += 1 def if_(test, result, alternative): """Like C++ and Java's (test ? result : alternative), except both result and alternative are always evaluated. However, if either evaluates to a function, it is applied to the empty arglist, so you can delay execution by putting it in a lambda. Ex: if_(2 + 2 == 4, 'ok', lambda: expensive_computation()) ==> 'ok' """ if test: if callable(result): return result() return result else: if callable(alternative): return alternative() return alternative def name(object): "Try to find some reasonable name for the object." return (getattr(object, 'name', 0) or getattr(object, '__name__', 0) or getattr(getattr(object, '__class__', 0), '__name__', 0) or str(object)) def isnumber(x): "Is x a number? We say it is if it has a __int__ method." return hasattr(x, '__int__') def issequence(x): "Is x a sequence? We say it is if it has a __getitem__ method." return hasattr(x, '__getitem__') def print_table(table, header=None, sep=' ', numfmt='%g'): """Print a list of lists as a table, so that columns line up nicely. header, if specified, will be printed as the first row. numfmt is the format for all numbers; you might want e.g. '%6.2f'. (If you want different formats in differnt columns, don't use print_table.) sep is the separator between columns.""" justs = [if_(isnumber(x), 'rjust', 'ljust') for x in table[0]] if header: table = [header] + table table = [[if_(isnumber(x), lambda: numfmt % x, x) for x in row] for row in table] maxlen = lambda seq: max(map(len, seq)) sizes = map(maxlen, zip(*[map(str, row) for row in table])) for row in table: for (j, size, x) in zip(justs, sizes, row): print getattr(str(x), j)(size), sep, print def AIMAFile(components, mode='r'): "Open a file based at the AIMA root directory." dir = os.path.dirname(__file__) return open(apply(os.path.join, [dir] + components), mode) def DataFile(name, mode='r'): "Return a file in the AIMA /data directory." return AIMAFile(['data', name], mode) #______________________________________________________________________________ # Queues: Stack, FIFOQueue, PriorityQueue class Queue: """Queue is an abstract class/interface. There are three types: Stack(): A Last In First Out Queue. FIFOQueue(): A First In First Out Queue. PriorityQueue(lt): Queue where items are sorted by lt, (default <). Each type supports the following methods and functions: q.append(item) -- add an item to the queue q.extend(items) -- equivalent to: for item in items: q.append(item) q.pop() -- return the top item from the queue len(q) -- number of items in q (also q.__len()) Note that isinstance(Stack(), Queue) is false, because we implement stacks as lists. If Python ever gets interfaces, Queue will be an interface.""" def __init__(self): abstract() def extend(self, items): for item in items: self.append(item) def Stack(): """Return an empty list, suitable as a Last-In-First-Out Queue. Ex: q = Stack(); q.append(1); q.append(2); q.pop(), q.pop() ==> (2, 1)""" return [] class FIFOQueue(Queue): """A First-In-First-Out Queue. Ex: q = FIFOQueue();q.append(1);q.append(2); q.pop(), q.pop() ==> (1, 2)""" def __init__(self): self.A = []; self.start = 0 def append(self, item): self.A.append(item) def __len__(self): return len(self.A) - self.start def extend(self, items): self.A.extend(items) def pop(self): e = self.A[self.start] self.start += 1 if self.start > 5 and self.start > len(self.A)/2: self.A = self.A[self.start:] self.start = 0 return e class PriorityQueue(Queue): """A queue in which the minimum (or maximum) element (as determined by f and order) is returned first. If order is min, the item with minimum f(x) is returned first; if order is max, then it is the item with maximum f(x).""" def __init__(self, order=min, f=lambda x: x): update(self, A=[], order=order, f=f) def append(self, item): bisect.insort(self.A, (self.f(item), item)) def __len__(self): return len(self.A) def pop(self): if self.order == min: return self.A.pop(0)[1] else: return self.A.pop()[1] #______________________________________________________________________________ ## NOTE: Once we upgrade to Python 2.3, the following class can be replaced by ## from sets import set class set: """This implements the set class from PEP 218, except it does not overload the infix operators. Ex: s = set([1,2,3]); 1 in s ==> True; 4 in s ==> False s.add(4); 4 in s ==> True; len(s) ==> 4 s.discard(999); s.remove(4); 4 in s ==> False s2 = set([3,4,5]); s.union(s2) ==> set([1,2,3,4,5]) s.intersection(s2) ==> set([3]) set([1,2,3]) == set([3,2,1]); repr(s) == '{1, 2, 3}' for e in s: pass""" def __init__(self, elements): self.dict = {} for e in elements: self.dict[e] = 1 def __contains__(self, element): return element in self.dict def add(self, element): self.dict[element] = 1 def remove(self, element): del self.dict[element] def discard(self, element): if element in self.dict: del self.dict[element] def clear(self): self.dict.clear() def union(self, other): return set(self).union_update(other) def intersection(self, other): return set(self).intersection_update(other) def union_update(self, other): for e in other: self.add(e) def intersection_update(self, other): for e in self.dict.keys(): if e not in other: self.remove(e) def __iter__(self): for e in self.dict: yield e def __len__(self): return len(self.dict) def __cmp__(self, other): return (self is other or (isinstance(other, set) and self.dict == other.dict)) def __repr__(self): return "{%s}" % ", ".join([str(e) for e in self.dict.keys()]) #______________________________________________________________________________ # Additional tests _docex = """ def is_even(x): return x % 2 == 0 sort([1, 2, -3]) ==> [-3, 1, 2] sort(range(10), comparer(key=is_even)) ==> [1, 3, 5, 7, 9, 0, 2, 4, 6, 8] sort(range(10), lambda x,y: y-x) ==> [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] removeall(4, []) ==> [] removeall('s', 'This is a test. Was a test.') ==> 'Thi i a tet. Wa a tet.' removeall('s', 'Something') ==> 'Something' removeall('s', '') ==> '' reverse([]) ==> [] reverse('') ==> '' count_if(is_even, [1, 2, 3, 4]) ==> 2 count_if(is_even, []) ==> 0 sum([]) ==> 0 product([]) ==> 1 argmax([1], lambda x: x*x) ==> 1 argmin([1], lambda x: x*x) ==> 1 argmax([]) raises TypeError argmin([]) raises TypeError # Test of memoize with slots in structures countries = [Struct(name='united states'), Struct(name='canada')] # Pretend that 'gnp' was some big hairy operation: def gnp(country): return len(country.name) * 1e10 gnp = memoize(gnp, '_gnp') map(gnp, countries) ==> [13e10, 6e10] countries # note the _gnp slot. # This time we avoid re-doing the calculation map(gnp, countries) ==> [13e10, 6e10] # Test Queues: nums = [1, 8, 2, 7, 5, 6, -99, 99, 4, 3, 0] def qtest(q): return [q.extend(nums), [q.pop() for i in range(len(q))]][1] qtest(Stack()) ==> reverse(nums) qtest(FIFOQueue()) ==> nums qtest(PriorityQueue(min)) ==> [-99, 0, 1, 2, 3, 4, 5, 6, 7, 8, 99] qtest(PriorityQueue(max)) ==> [99, 8, 7, 6, 5, 4, 3, 2, 1, 0, -99] qtest(PriorityQueue(min, abs)) ==> [0, 1, 2, 3, 4, 5, 6, 7, 8, -99, 99] qtest(PriorityQueue(max, abs)) ==> [99, -99, 8, 7, 6, 5, 4, 3, 2, 1, 0] """
Python
import games import time from move import Move from globalconst import BLACK, WHITE, KING, MAN, OCCUPIED, BLACK_CHAR, WHITE_CHAR from globalconst import BLACK_KING, WHITE_KING, FREE, OCCUPIED_CHAR, FREE_CHAR from globalconst import COLORS, TYPES, TURN, CRAMP, BRV, KEV, KCV, MEV, MCV from globalconst import INTACTDOUBLECORNER, ENDGAME, OPENING, MIDGAME from globalconst import create_grid_map, KING_IDX, BLACK_IDX, WHITE_IDX import copy class Checkerboard(object): # (white) # 45 46 47 48 # 39 40 41 42 # 34 35 36 37 # 28 29 30 31 # 23 24 25 26 # 17 18 19 20 # 12 13 14 15 # 6 7 8 9 # (black) valid_squares = [6,7,8,9,12,13,14,15,17,18,19,20,23,24,25,26, 28,29,30,31,34,35,36,37,39,40,41,42,45,46, 47,48] # values of pieces (KING, MAN, BLACK, WHITE, FREE) value = [0,0,0,0,0,1,256,0,0,16,4096,0,0,0,0,0,0] edge = [6,7,8,9,15,17,26,28,37,39,45,46,47,48] center = [18,19,24,25,29,30,35,36] # values used to calculate tempo -- one for each square on board (0, 48) row = [0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,2,2,2,2,0,0,3,3,3,3,0, 4,4,4,4,0,0,5,5,5,5,0,6,6,6,6,0,0,7,7,7,7] safeedge = [9,15,39,45] rank = {0:0, 1:-1, 2:1, 3:0, 4:1, 5:1, 6:2, 7:1, 8:1, 9:0, 10:7, 11:4, 12:2, 13:2, 14:9, 15:8} def __init__(self): self.squares = [OCCUPIED for i in range(56)] s = self.squares for i in range(0, 4): s[6+i] = s[12+i] = s[17+i] = BLACK | MAN s[34+i] = s[39+i] = s[45+i] = WHITE | MAN s[23+i] = s[28+i] = FREE self.to_move = BLACK self.charlookup = {BLACK | MAN: BLACK_CHAR, WHITE | MAN: WHITE_CHAR, BLACK | KING: BLACK_KING, WHITE | KING: WHITE_KING, OCCUPIED: OCCUPIED_CHAR, FREE: FREE_CHAR} self.observers = [] self.white_pieces = [] self.black_pieces = [] self.undo_list = [] self.redo_list = [] self.white_total = 12 self.black_total = 12 self.gridmap = create_grid_map() self.ok_to_move = True def __repr__(self): bc = self.count(BLACK) wc = self.count(WHITE) sq = self.squares lookup = self.lookup s = "[%s=%2d %s=%2d (%+d)]\n" % (BLACK_CHAR, bc, WHITE_CHAR, wc, bc - wc) s += "8 %s %s %s %s\n" % (lookup(sq[45]), lookup(sq[46]), lookup(sq[47]), lookup(sq[48])) s += "7 %s %s %s %s\n" % (lookup(sq[39]), lookup(sq[40]), lookup(sq[41]), lookup(sq[42])) s += "6 %s %s %s %s\n" % (lookup(sq[34]), lookup(sq[35]), lookup(sq[36]), lookup(sq[37])) s += "5 %s %s %s %s\n" % (lookup(sq[28]), lookup(sq[29]), lookup(sq[30]), lookup(sq[31])) s += "4 %s %s %s %s\n" % (lookup(sq[23]), lookup(sq[24]), lookup(sq[25]), lookup(sq[26])) s += "3 %s %s %s %s\n" % (lookup(sq[17]), lookup(sq[18]), lookup(sq[19]), lookup(sq[20])) s += "2 %s %s %s %s\n" % (lookup(sq[12]), lookup(sq[13]), lookup(sq[14]), lookup(sq[15])) s += "1 %s %s %s %s\n" % (lookup(sq[6]), lookup(sq[7]), lookup(sq[8]), lookup(sq[9])) s += " a b c d e f g h" return s def _get_enemy(self): if self.to_move == BLACK: return WHITE return BLACK enemy = property(_get_enemy, doc="The color for the player that doesn't have the current turn") def attach(self, observer): if observer not in self.observers: self.observers.append(observer) def detach(self, observer): if observer in self.observers: self.observers.remove(observer) def clear(self): s = self.squares for i in range(0, 4): s[6+i] = s[12+i] = s[17+i] = FREE s[23+i] = s[28+i] = FREE s[34+i] = s[39+i] = s[45+i] = FREE def lookup(self, square): return self.charlookup[square & TYPES] def count(self, color): return self.white_total if color == WHITE else self.black_total def get_pieces(self, color): return self.black_pieces if color == BLACK else self.white_pieces def has_opposition(self, color): sq = self.squares cols = range(6,10) if self.to_move == BLACK else range(12,16) pieces_in_system = 0 for i in cols: for j in range(4): if sq[i+11*j] != FREE: pieces_in_system += 1 return pieces_in_system % 2 == 1 def row_col_for_index(self, idx): return self.gridmap[idx] def update_piece_count(self): self.white_pieces = [] for i, piece in enumerate(self.squares): if piece & COLORS == WHITE: self.white_pieces.append((i, piece)) self.black_pieces = [] for i, piece in enumerate(self.squares): if piece & COLORS == BLACK: self.black_pieces.append((i, piece)) self.white_total = len(self.white_pieces) self.black_total = len(self.black_pieces) def delete_redo_list(self): del self.redo_list[:] def make_move(self, move, notify=True, undo=True, annotation=''): sq = self.squares for idx, _, newval in move.affected_squares: sq[idx] = newval self.to_move ^= COLORS if notify: self.update_piece_count() for o in self.observers: o.notify(move) if undo: move.annotation = annotation self.undo_list.append(move) return self def undo_move(self, move=None, notify=True, redo=True, annotation=''): if move is None: if not self.undo_list: return if redo: move = self.undo_list.pop() rev_move = Move([[idx, dest, src] for idx, src, dest in move.affected_squares]) rev_move.annotation = move.annotation self.make_move(rev_move, notify, False) if redo: move.annotation = annotation self.redo_list.append(move) def undo_all_moves(self, annotation=''): while self.undo_list: move = self.undo_list.pop() rev_move = Move([[idx, dest, src] for idx, src, dest in move.affected_squares]) rev_move.annotation = move.annotation self.make_move(rev_move, True, False) move.annotation = annotation self.redo_list.append(move) annotation = rev_move.annotation def redo_move(self, move=None, annotation=''): if move is None: if not self.redo_list: return move = self.redo_list.pop() self.make_move(move, True, True, annotation) def redo_all_moves(self, annotation=''): while self.redo_list: move = self.redo_list.pop() next_annotation = move.annotation self.make_move(move, True, True, annotation) annotation = next_annotation def reset_undo(self): self.undo_list = [] self.redo_list = [] def utility(self, player): """ Player evaluation function """ sq = self.squares code = sum(self.value[s] for s in sq) nwm = code % 16 nwk = (code >> 4) % 16 nbm = (code >> 8) % 16 nbk = (code >> 12) % 16 v1 = 100 * nbm + 130 * nbk v2 = 100 * nwm + 130 * nwk eval = v1 - v2 # material values # favor exchanges if in material plus eval += (250 * (v1 - v2))/(v1 + v2) nm = nbm + nwm nk = nbk + nwk # fine evaluation below if player == BLACK: eval += TURN mult = -1 else: eval -= TURN mult = 1 return mult * \ (eval + self._eval_cramp(sq) + self._eval_backrankguard(sq) + self._eval_doublecorner(sq) + self._eval_center(sq) + self._eval_edge(sq) + self._eval_tempo(sq, nm, nbk, nbm, nwk, nwm) + self._eval_playeropposition(sq, nwm, nwk, nbk, nbm, nm, nk)) def _extend_capture(self, valid_moves, captures, add_sq_func, visited): player = self.to_move enemy = self.enemy squares = self.squares final_captures = [] while captures: c = captures.pop() new_captures = [] for j in valid_moves: capture = c.affected_squares[:] last_pos = capture[-1][0] mid = last_pos+j dest = last_pos+j*2 if ((last_pos, mid, dest) not in visited and (dest, mid, last_pos) not in visited and squares[mid] & enemy and squares[dest] & FREE): sq2, sq3 = add_sq_func(player, squares, mid, dest, last_pos) capture[-1][2] = FREE capture.extend([sq2, sq3]) visited.add((last_pos, mid, dest)) new_captures.append(Move(capture)) if new_captures: captures.extend(new_captures) else: final_captures.append(Move(capture)) return final_captures def _capture_man(self, player, squares, mid, dest, last_pos): sq2 = [mid, squares[mid], FREE] if ((player == BLACK and last_pos>=34) or (player == WHITE and last_pos<=20)): sq3 = [dest, FREE, player | KING] else: sq3 = [dest, FREE, player | MAN] return sq2, sq3 def _capture_king(self, player, squares, mid, dest, last_pos): sq2 = [mid, squares[mid], FREE] sq3 = [dest, squares[dest], player | KING] return sq2, sq3 def _get_captures(self): player = self.to_move enemy = self.enemy squares = self.squares valid_indices = WHITE_IDX if player == WHITE else BLACK_IDX all_captures = [] for i in self.valid_squares: if squares[i] & player and squares[i] & MAN: for j in valid_indices: mid = i+j dest = i+j*2 if squares[mid] & enemy and squares[dest] & FREE: sq1 = [i, player | MAN, FREE] sq2 = [mid, squares[mid], FREE] if ((player == BLACK and i>=34) or (player == WHITE and i<=20)): sq3 = [dest, FREE, player | KING] else: sq3 = [dest, FREE, player | MAN] capture = [Move([sq1, sq2, sq3])] visited = set() visited.add((i, mid, dest)) temp = squares[i] squares[i] = FREE captures = self._extend_capture(valid_indices, capture, self._capture_man, visited) squares[i] = temp all_captures.extend(captures) if squares[i] & player and squares[i] & KING: for j in KING_IDX: mid = i+j dest = i+j*2 if squares[mid] & enemy and squares[dest] & FREE: sq1 = [i, player | KING, FREE] sq2 = [mid, squares[mid], FREE] sq3 = [dest, squares[dest], player | KING] capture = [Move([sq1, sq2, sq3])] visited = set() visited.add((i, mid, dest)) temp = squares[i] squares[i] = FREE captures = self._extend_capture(KING_IDX, capture, self._capture_king, visited) squares[i] = temp all_captures.extend(captures) return all_captures captures = property(_get_captures, doc="Forced captures for the current player") def _get_moves(self): player = self.to_move squares = self.squares valid_indices = WHITE_IDX if player == WHITE else BLACK_IDX moves = [] for i in self.valid_squares: for j in valid_indices: dest = i+j if (squares[i] & player and squares[i] & MAN and squares[dest] & FREE): sq1 = [i, player | MAN, FREE] if ((player == BLACK and i>=39) or (player == WHITE and i<=15)): sq2 = [dest, FREE, player | KING] else: sq2 = [dest, FREE, player | MAN] moves.append(Move([sq1, sq2])) for j in KING_IDX: dest = i+j if (squares[i] & player and squares[i] & KING and squares[dest] & FREE): sq1 = [i, player | KING, FREE] sq2 = [dest, FREE, player | KING] moves.append(Move([sq1, sq2])) return moves moves = property(_get_moves, doc="Available moves for the current player") def _eval_cramp(self, sq): eval = 0 if sq[28] == BLACK | MAN and sq[34] == WHITE | MAN: eval += CRAMP if sq[26] == WHITE | MAN and sq[20] == BLACK | MAN: eval -= CRAMP return eval def _eval_backrankguard(self, sq): eval = 0 code = 0 if sq[6] & MAN: code += 1 if sq[7] & MAN: code += 2 if sq[8] & MAN: code += 4 if sq[9] & MAN: code += 8 backrank = self.rank[code] code = 0 if sq[45] & MAN: code += 8 if sq[46] & MAN: code += 4 if sq[47] & MAN: code += 2 if sq[48] & MAN: code += 1 backrank = backrank - self.rank[code] eval *= BRV * backrank return eval def _eval_doublecorner(self, sq): eval = 0 if sq[9] == BLACK | MAN: if sq[14] == BLACK | MAN or sq[15] == BLACK | MAN: eval += INTACTDOUBLECORNER if sq[45] == WHITE | MAN: if sq[39] == WHITE | MAN or sq[40] == WHITE | MAN: eval -= INTACTDOUBLECORNER return eval def _eval_center(self, sq): eval = 0 nbmc = nbkc = nwmc = nwkc = 0 for c in self.center: if sq[c] != FREE: if sq[c] == BLACK | MAN: nbmc += 1 if sq[c] == BLACK | KING: nbkc += 1 if sq[c] == WHITE | MAN: nwmc += 1 if sq[c] == WHITE | KING: nwkc += 1 eval += (nbmc-nwmc) * MCV eval += (nbkc-nwkc) * KCV return eval def _eval_edge(self, sq): eval = 0 nbme = nbke = nwme = nwke = 0 for e in self.edge: if sq[e] != FREE: if sq[e] == BLACK | MAN: nbme += 1 if sq[e] == BLACK | KING: nbke += 1 if sq[e] == WHITE | MAN: nwme += 1 if sq[e] == WHITE | KING: nwke += 1 eval -= (nbme-nwme) * MEV eval -= (nbke-nwke) * KEV return eval def _eval_tempo(self, sq, nm, nbk, nbm, nwk, nwm): eval = tempo = 0 for i in range(6, 49): if sq[i] == BLACK | MAN: tempo += self.row[i] if sq[i] == WHITE | MAN: tempo -= 7 - self.row[i] if nm >= 16: eval += OPENING * tempo if nm <= 15 and nm >= 12: eval += MIDGAME * tempo if nm < 9: eval += ENDGAME * tempo for s in self.safeedge: if nbk + nbm > nwk + nwm and nwk < 3: if sq[s] == WHITE | KING: eval -= 15 if nwk + nwm > nbk + nbm and nbk < 3: if sq[s] == BLACK | KING: eval += 15 return eval def _eval_playeropposition(self, sq, nwm, nwk, nbk, nbm, nm, nk): eval = 0 pieces_in_system = 0 tn = nm + nk if nwm + nwk - nbk - nbm == 0: if self.to_move == BLACK: for i in range(6, 10): for j in range(4): if sq[i+11*j] != FREE: pieces_in_system += 1 if pieces_in_system % 2: if tn <= 12: eval += 1 if tn <= 10: eval += 1 if tn <= 8: eval += 2 if tn <= 6: eval += 2 else: if tn <= 12: eval -= 1 if tn <= 10: eval -= 1 if tn <= 8: eval -= 2 if tn <= 6: eval -= 2 else: for i in range(12, 16): for j in range(4): if sq[i+11*j] != FREE: pieces_in_system += 1 if pieces_in_system % 2 == 0: if tn <= 12: eval += 1 if tn <= 10: eval += 1 if tn <= 8: eval += 2 if tn <= 6: eval += 2 else: if tn <= 12: eval -= 1 if tn <= 10: eval -= 1 if tn <= 8: eval -= 2 if tn <= 6: eval -= 2 return eval class Checkers(games.Game): def __init__(self): self.curr_state = Checkerboard() def captures_available(self, curr_state=None): state = curr_state or self.curr_state return state.captures def legal_moves(self, curr_state=None): state = curr_state or self.curr_state return state.captures or state.moves def make_move(self, move, curr_state=None, notify=True, undo=True, annotation=''): state = curr_state or self.curr_state return state.make_move(move, notify, undo, annotation) def undo_move(self, move=None, curr_state=None, notify=True, redo=True, annotation=''): state = curr_state or self.curr_state return state.undo_move(move, notify, redo, annotation) def undo_all_moves(self, curr_state=None, annotation=''): state = curr_state or self.curr_state return state.undo_all_moves(annotation) def redo_move(self, move=None, curr_state=None, annotation=''): state = curr_state or self.curr_state return state.redo_move(move, annotation) def redo_all_moves(self, curr_state=None, annotation=''): state = curr_state or self.curr_state return state.redo_all_moves(annotation) def utility(self, player, curr_state=None): state = curr_state or self.curr_state return state.utility(player) def terminal_test(self, curr_state=None): state = curr_state or self.curr_state return not self.legal_moves(state) def successors(self, curr_state=None): state = curr_state or self.curr_state moves = self.legal_moves(state) if not moves: yield [], state else: undone = False try: try: for move in moves: undone = False self.make_move(move, state, False) yield move, state self.undo_move(move, state, False) undone = True except GeneratorExit: raise finally: if moves and not undone: self.undo_move(move, state, False) def perft(self, depth, curr_state=None): if depth == 0: return 1 state = curr_state or self.curr_state nodes = 0 for move in self.legal_moves(state): state.make_move(move, False, False) nodes += self.perft(depth-1, state) state.undo_move(move, False, False) return nodes def play(): game = Checkers() for depth in range(1, 11): start = time.time() print "Perft for depth %d: %d. Time: %5.3f sec" % (depth, game.perft(depth), time.time() - start) if __name__ == '__main__': play()
Python
from Tkinter import * from Tkconstants import W, E, N, S from tkFileDialog import askopenfilename, asksaveasfilename from tkMessageBox import askyesnocancel, showerror from globalconst import * from checkers import Checkers from boardview import BoardView from playercontroller import PlayerController from alphabetacontroller import AlphaBetaController from gamepersist import SavedGame from textserialize import Serializer class GameManager(object): def __init__(self, **props): self.model = Checkers() self._root = props['root'] self.parent = props['parent'] statusbar = Label(self._root, relief=SUNKEN, font=('Helvetica',7), anchor=NW) statusbar.pack(side='bottom', fill='x') self.view = BoardView(self._root, model=self.model, parent=self, statusbar=statusbar) self.player_color = BLACK self.num_players = 1 self.set_controllers() self._controller1.start_turn() self.filename = None def set_controllers(self): think_time = self.parent.thinkTime.get() if self.num_players == 0: self._controller1 = AlphaBetaController(model=self.model, view=self.view, searchtime=think_time, end_turn_event=self.turn_finished) self._controller2 = AlphaBetaController(model=self.model, view=self.view, searchtime=think_time, end_turn_event=self.turn_finished) elif self.num_players == 1: # assumption here is that Black is the player self._controller1 = PlayerController(model=self.model, view=self.view, end_turn_event=self.turn_finished) self._controller2 = AlphaBetaController(model=self.model, view=self.view, searchtime=think_time, end_turn_event=self.turn_finished) # swap controllers if White is selected as the player if self.player_color == WHITE: self._controller1, self._controller2 = self._controller2, self._controller1 elif self.num_players == 2: self._controller1 = PlayerController(model=self.model, view=self.view, end_turn_event=self.turn_finished) self._controller2 = PlayerController(model=self.model, view=self.view, end_turn_event=self.turn_finished) self._controller1.set_before_turn_event(self._controller2.remove_highlights) self._controller2.set_before_turn_event(self._controller1.remove_highlights) def _stop_updates(self): # stop alphabeta threads from making any moves self.model.curr_state.ok_to_move = False self._controller1.stop_process() self._controller2.stop_process() def _save_curr_game_if_needed(self): if self.view.is_dirty(): msg = 'Do you want to save your changes' if self.filename: msg += ' to %s?' % self.filename else: msg += '?' result = askyesnocancel(TITLE, msg) if result == True: self.save_game() return result else: return False def new_game(self): self._stop_updates() self._save_curr_game_if_needed() self.filename = None self._root.title('Raven ' + VERSION) self.model = Checkers() self.player_color = BLACK self.view.reset_view(self.model) self.think_time = self.parent.thinkTime.get() self.set_controllers() self.view.update_statusbar() self.view.reset_toolbar_buttons() self.view.curr_annotation = '' self._controller1.start_turn() def load_game(self, filename): self._stop_updates() try: saved_game = SavedGame() saved_game.read(filename) self.model.curr_state.clear() self.model.curr_state.to_move = saved_game.to_move self.num_players = saved_game.num_players squares = self.model.curr_state.squares for i in saved_game.black_men: squares[squaremap[i]] = BLACK | MAN for i in saved_game.black_kings: squares[squaremap[i]] = BLACK | KING for i in saved_game.white_men: squares[squaremap[i]] = WHITE | MAN for i in saved_game.white_kings: squares[squaremap[i]] = WHITE | KING self.model.curr_state.reset_undo() self.model.curr_state.redo_list = saved_game.moves self.model.curr_state.update_piece_count() self.view.reset_view(self.model) self.view.serializer.restore(saved_game.description) self.view.curr_annotation = self.view.get_annotation() self.view.flip_board(saved_game.flip_board) self.view.update_statusbar() self.parent.set_title_bar_filename(filename) self.filename = filename except IOError as (err): showerror(PROGRAM_TITLE, 'Invalid file. ' + str(err)) def open_game(self): self._stop_updates() self._save_curr_game_if_needed() f = askopenfilename(filetypes=(('Raven Checkers files','*.rcf'), ('All files','*.*')), initialdir=TRAINING_DIR) if not f: return self.load_game(f) def save_game_as(self): self._stop_updates() filename = asksaveasfilename(filetypes=(('Raven Checkers files','*.rcf'), ('All files','*.*')), initialdir=TRAINING_DIR, defaultextension='.rcf') if filename == '': return self._write_file(filename) def save_game(self): self._stop_updates() filename = self.filename if not self.filename: filename = asksaveasfilename(filetypes=(('Raven Checkers files','*.rcf'), ('All files','*.*')), initialdir=TRAINING_DIR, defaultextension='.rcf') if filename == '': return self._write_file(filename) def _write_file(self, filename): try: saved_game = SavedGame() # undo moves back to the beginning of play undo_steps = 0 while self.model.curr_state.undo_list: undo_steps += 1 self.model.curr_state.undo_move(None, True, True, self.view.get_annotation()) # save the state of the board saved_game.to_move = self.model.curr_state.to_move saved_game.num_players = self.num_players saved_game.black_men = [] saved_game.black_kings = [] saved_game.white_men = [] saved_game.white_kings = [] for i, sq in enumerate(self.model.curr_state.squares): if sq == BLACK | MAN: saved_game.black_men.append(keymap[i]) elif sq == BLACK | KING: saved_game.black_kings.append(keymap[i]) elif sq == WHITE | MAN: saved_game.white_men.append(keymap[i]) elif sq == WHITE | KING: saved_game.white_kings.append(keymap[i]) saved_game.description = self.view.serializer.dump() saved_game.moves = self.model.curr_state.redo_list saved_game.flip_board = self.view.flip_view saved_game.write(filename) # redo moves forward to the previous state for i in range(undo_steps): annotation = self.view.get_annotation() self.model.curr_state.redo_move(None, annotation) # record current filename in title bar self.parent.set_title_bar_filename(filename) self.filename = filename except IOError: showerror(PROGRAM_TITLE, 'Could not save file.') def turn_finished(self): if self.model.curr_state.to_move == BLACK: self._controller2.end_turn() # end White's turn self._root.update() self.view.update_statusbar() self._controller1.start_turn() # begin Black's turn else: self._controller1.end_turn() # end Black's turn self._root.update() self.view.update_statusbar() self._controller2.start_turn() # begin White's turn
Python
class Move(object): def __init__(self, squares, annotation=''): self.affected_squares = squares self.annotation = annotation def __repr__(self): return str(self.affected_squares)
Python
"""Games, or Adversarial Search. (Chapters 6) """ from utils import infinity, argmax, argmax_random_tie, num_or_str, Dict, update from utils import if_, Struct import random import time #______________________________________________________________________________ # Minimax Search def minimax_decision(state, game): """Given a state in a game, calculate the best move by searching forward all the way to the terminal states. [Fig. 6.4]""" player = game.to_move(state) def max_value(state): if game.terminal_test(state): return game.utility(state, player) v = -infinity for (_, s) in game.successors(state): v = max(v, min_value(s)) return v def min_value(state): if game.terminal_test(state): return game.utility(state, player) v = infinity for (_, s) in game.successors(state): v = min(v, max_value(s)) return v # Body of minimax_decision starts here: action, state = argmax(game.successors(state), lambda ((a, s)): min_value(s)) return action #______________________________________________________________________________ def alphabeta_full_search(state, game): """Search game to determine best action; use alpha-beta pruning. As in [Fig. 6.7], this version searches all the way to the leaves.""" player = game.to_move(state) def max_value(state, alpha, beta): if game.terminal_test(state): return game.utility(state, player) v = -infinity for (a, s) in game.successors(state): v = max(v, min_value(s, alpha, beta)) if v >= beta: return v alpha = max(alpha, v) return v def min_value(state, alpha, beta): if game.terminal_test(state): return game.utility(state, player) v = infinity for (a, s) in game.successors(state): v = min(v, max_value(s, alpha, beta)) if v <= alpha: return v beta = min(beta, v) return v # Body of alphabeta_search starts here: action, state = argmax(game.successors(state), lambda ((a, s)): min_value(s, -infinity, infinity)) return action def alphabeta_search(state, game, d=4, cutoff_test=None, eval_fn=None): """Search game to determine best action; use alpha-beta pruning. This version cuts off search and uses an evaluation function.""" player = game.to_move(state) def max_value(state, alpha, beta, depth): if cutoff_test(state, depth): return eval_fn(state) v = -infinity succ = game.successors(state) for (a, s) in succ: v = max(v, min_value(s, alpha, beta, depth+1)) if v >= beta: succ.close() return v alpha = max(alpha, v) return v def min_value(state, alpha, beta, depth): if cutoff_test(state, depth): return eval_fn(state) v = infinity succ = game.successors(state) for (a, s) in succ: v = min(v, max_value(s, alpha, beta, depth+1)) if v <= alpha: succ.close() return v beta = min(beta, v) return v # Body of alphabeta_search starts here: # The default test cuts off at depth d or at a terminal state cutoff_test = (cutoff_test or (lambda state,depth: depth>d or game.terminal_test(state))) eval_fn = eval_fn or (lambda state: game.utility(player, state)) action, state = argmax_random_tie(game.successors(state), lambda ((a, s)): min_value(s, -infinity, infinity, 0)) return action #______________________________________________________________________________ # Players for Games def query_player(game, state): "Make a move by querying standard input." game.display(state) return num_or_str(raw_input('Your move? ')) def random_player(game, state): "A player that chooses a legal move at random." return random.choice(game.legal_moves()) def alphabeta_player(game, state): return alphabeta_search(state, game) def play_game(game, *players): "Play an n-person, move-alternating game." print game.curr_state while True: for player in players: if game.curr_state.to_move == player.color: move = player.select_move(game) print game.make_move(move) if game.terminal_test(): return game.utility(player.color) #______________________________________________________________________________ # Some Sample Games class Game: """A game is similar to a problem, but it has a utility for each state and a terminal test instead of a path cost and a goal test. To create a game, subclass this class and implement legal_moves, make_move, utility, and terminal_test. You may override display and successors or you can inherit their default methods. You will also need to set the .initial attribute to the initial state; this can be done in the constructor.""" def legal_moves(self, state): "Return a list of the allowable moves at this point." abstract def make_move(self, move, state): "Return the state that results from making a move from a state." abstract def utility(self, state, player): "Return the value of this final state to player." abstract def terminal_test(self, state): "Return True if this is a final state for the game." return not self.legal_moves(state) def to_move(self, state): "Return the player whose move it is in this state." return state.to_move def display(self, state): "Print or otherwise display the state." print state def successors(self, state): "Return a list of legal (move, state) pairs." return [(move, self.make_move(move, state)) for move in self.legal_moves(state)] def __repr__(self): return '<%s>' % self.__class__.__name__ class Fig62Game(Game): """The game represented in [Fig. 6.2]. Serves as a simple test case. >>> g = Fig62Game() >>> minimax_decision('A', g) 'a1' >>> alphabeta_full_search('A', g) 'a1' >>> alphabeta_search('A', g) 'a1' """ succs = {'A': [('a1', 'B'), ('a2', 'C'), ('a3', 'D')], 'B': [('b1', 'B1'), ('b2', 'B2'), ('b3', 'B3')], 'C': [('c1', 'C1'), ('c2', 'C2'), ('c3', 'C3')], 'D': [('d1', 'D1'), ('d2', 'D2'), ('d3', 'D3')]} utils = Dict(B1=3, B2=12, B3=8, C1=2, C2=4, C3=6, D1=14, D2=5, D3=2) initial = 'A' def successors(self, state): return self.succs.get(state, []) def utility(self, state, player): if player == 'MAX': return self.utils[state] else: return -self.utils[state] def terminal_test(self, state): return state not in ('A', 'B', 'C', 'D') def to_move(self, state): return if_(state in 'BCD', 'MIN', 'MAX') class TicTacToe(Game): """Play TicTacToe on an h x v board, with Max (first player) playing 'X'. A state has the player to move, a cached utility, a list of moves in the form of a list of (x, y) positions, and a board, in the form of a dict of {(x, y): Player} entries, where Player is 'X' or 'O'.""" def __init__(self, h=3, v=3, k=3): update(self, h=h, v=v, k=k) moves = [(x, y) for x in range(1, h+1) for y in range(1, v+1)] self.initial = Struct(to_move='X', utility=0, board={}, moves=moves) def legal_moves(self, state): "Legal moves are any square not yet taken." return state.moves def make_move(self, move, state): if move not in state.moves: return state # Illegal move has no effect board = state.board.copy(); board[move] = state.to_move moves = list(state.moves); moves.remove(move) return Struct(to_move=if_(state.to_move == 'X', 'O', 'X'), utility=self.compute_utility(board, move, state.to_move), board=board, moves=moves) def utility(self, state): "Return the value to X; 1 for win, -1 for loss, 0 otherwise." return state.utility def terminal_test(self, state): "A state is terminal if it is won or there are no empty squares." return state.utility != 0 or len(state.moves) == 0 def display(self, state): board = state.board for x in range(1, self.h+1): for y in range(1, self.v+1): print board.get((x, y), '.'), print def compute_utility(self, board, move, player): "If X wins with this move, return 1; if O return -1; else return 0." if (self.k_in_row(board, move, player, (0, 1)) or self.k_in_row(board, move, player, (1, 0)) or self.k_in_row(board, move, player, (1, -1)) or self.k_in_row(board, move, player, (1, 1))): return if_(player == 'X', +1, -1) else: return 0 def k_in_row(self, board, move, player, (delta_x, delta_y)): "Return true if there is a line through move on board for player." x, y = move n = 0 # n is number of moves in row while board.get((x, y)) == player: n += 1 x, y = x + delta_x, y + delta_y x, y = move while board.get((x, y)) == player: n += 1 x, y = x - delta_x, y - delta_y n -= 1 # Because we counted move itself twice return n >= self.k class ConnectFour(TicTacToe): """A TicTacToe-like game in which you can only make a move on the bottom row, or in a square directly above an occupied square. Traditionally played on a 7x6 board and requiring 4 in a row.""" def __init__(self, h=7, v=6, k=4): TicTacToe.__init__(self, h, v, k) def legal_moves(self, state): "Legal moves are any square not yet taken." return [(x, y) for (x, y) in state.moves if y == 0 or (x, y-1) in state.board]
Python
from Tkinter import * from tkSimpleDialog import Dialog from globalconst import * class AboutBox(Dialog): def body(self, master): self.canvas = Canvas(self, width=300, height=275) self.canvas.pack(side=TOP, fill=BOTH, expand=0) self.canvas.create_text(152,47,text='Raven', fill='black', font=('Helvetica', 36)) self.canvas.create_text(150,45,text='Raven', fill='white', font=('Helvetica', 36)) self.canvas.create_text(150,85,text='Version '+ VERSION, fill='black', font=('Helvetica', 12)) self.canvas.create_text(150,115,text='An open source checkers program', fill='black', font=('Helvetica', 10)) self.canvas.create_text(150,130,text='by Brandon Corfman', fill='black', font=('Helvetica', 10)) self.canvas.create_text(150,160,text='Evaluation function translated from', fill='black', font=('Helvetica', 10)) self.canvas.create_text(150,175,text="Martin Fierz's Simple Checkers", fill='black', font=('Helvetica', 10)) self.canvas.create_text(150,205,text="Alpha-beta search code written by", fill='black', font=('Helvetica', 10)) self.canvas.create_text(150,220,text="Peter Norvig for the AIMA project;", fill='black', font=('Helvetica', 10)) self.canvas.create_text(150,235,text="adopted for checkers usage", fill='black', font=('Helvetica', 10)) self.canvas.create_text(150,250,text="by Brandon Corfman", fill='black', font=('Helvetica', 10)) return self.canvas def cancel(self, event=None): self.destroy() def buttonbox(self): self.button = Button(self, text='OK', padx='5m', command=self.cancel) self.blank = Canvas(self, width=10, height=20) self.blank.pack(side=BOTTOM, fill=BOTH, expand=0) self.button.pack(side=BOTTOM) self.button.focus_set() self.bind("<Escape>", self.cancel)
Python
import copy, textwrap from globalconst import * from move import Move from checkers import Checkers class SavedGame(object): def __init__(self): self._model = Checkers() self.to_move = None self.moves = [] self.description = '' self.black_men = [] self.white_men = [] self.black_kings = [] self.white_kings = [] self.flip_board = False self.num_players = 1 self._move_check = False self._bm_check = False self._bk_check = False self._wm_check = False self._wk_check = False def _write_positions(self, f, prefix, positions): f.write(prefix + ' ') for p in sorted(positions): f.write('%d ' % p) f.write('\n') def _write_moves(self, f): f.write('<moves>\n') for move in reversed(self.moves): start = keymap[move.affected_squares[FIRST][0]] dest = keymap[move.affected_squares[LAST][0]] movestr = '%d-%d' % (start, dest) annotation = move.annotation if annotation.startswith(movestr): annotation = annotation.replace(movestr, '', 1).rstrip() f.write('%s;%s\n' % (movestr, annotation)) def write(self, filename): with open(filename, 'w') as f: f.write('<description>\n') for line in self.description.splitlines(): # numbered lists or hyperlinks are not word wrapped. if line.startswith('# ') or '[[' in line: f.write(line + '\n') continue else: f.write(textwrap.fill(line, 80) + '\n') f.write('<setup>\n') if self.to_move == WHITE: f.write('white_first\n') elif self.to_move == BLACK: f.write('black_first\n') else: raise ValueError, "Unknown value for to_move variable" if self.num_players >=0 and self.num_players <=2: f.write('%d_player_game\n' % self.num_players) else: raise ValueError, "Unknown value for num_players variable" if self.flip_board: f.write('flip_board 1\n') else: f.write('flip_board 0\n') self._write_positions(f, 'black_men', self.black_men) self._write_positions(f, 'black_kings', self.black_kings) self._write_positions(f, 'white_men', self.white_men) self._write_positions(f, 'white_kings', self.white_kings) self._write_moves(f) def read(self, filename): with open(filename, 'r') as f: lines = f.readlines() linelen = len(lines) i = 0 while True: if i >= linelen: break line = lines[i].strip() if line.startswith('<description>'): self.description = '' i += 1 while i < linelen and not lines[i].startswith('<setup>'): self.description += lines[i] i += 1 elif line.startswith('<setup>'): i = self._parse_setup(lines, i, linelen) elif line.startswith('<moves>'): i = self._parse_moves(lines, i, linelen) else: raise IOError, 'Unrecognized section in file, line %d' % (i+1) def _parse_items(self, line): men = line.split()[1:] return map(int, men) def _add_men_to_board(self, locations, val): squares = self._model.curr_state.squares try: for loc in locations: idx = squaremap[loc] squares[idx] = val except ValueError: raise IOError, 'Checker location not valid, line %d' % (i+1) def _parse_setup(self, lines, idx, linelen): curr_state = self._model.curr_state curr_state.clear() idx += 1 while idx < linelen and '<moves>' not in lines[idx]: line = lines[idx].strip().lower() if line == 'white_first': self.to_move = curr_state.to_move = WHITE self._move_check = True elif line == 'black_first': self.to_move = curr_state.to_move = BLACK self._move_check = True elif line.endswith('player_game'): numstr, _ = line.split('_', 1) self.num_players = int(numstr) elif line.startswith('flip_board'): _, setting = line.split() val = int(setting) self.flip_board = True if val else False elif line.startswith('black_men'): self.black_men = self._parse_items(line) self._add_men_to_board(self.black_men, BLACK | MAN) self._bm_check = True elif line.startswith('white_men'): self.white_men = self._parse_items(line) self._add_men_to_board(self.white_men, WHITE | MAN) self._wm_check = True elif line.startswith('black_kings'): self.black_kings = self._parse_items(line) self._add_men_to_board(self.black_kings, BLACK | KING) self._bk_check = True elif line.startswith('white_kings'): self.white_kings = self._parse_items(line) self._add_men_to_board(self.white_kings, WHITE | KING) self._wk_check = True idx += 1 if (not self._move_check and not self._bm_check and not self._wm_check and not self._bk_check and not self._wk_check): raise IOError, 'Error in <setup> section: not all required items found' return idx def _is_move(self, delta): return delta in KING_IDX def _is_jump(self, delta): return delta not in KING_IDX def _try_move(self, idx, start, dest, state_copy, annotation): legal_moves = self._model.legal_moves(state_copy) # match move from file with available moves on checkerboard found = False startsq, destsq = squaremap[start], squaremap[dest] for move in legal_moves: if (startsq == move.affected_squares[FIRST][0] and destsq == move.affected_squares[LAST][0]): self._model.make_move(move, state_copy, False, False) move.annotation = annotation self.moves.append(move) found = True break if not found: raise IOError, 'Illegal move found in file, line %d' % (idx+1) def _try_jump(self, idx, start, dest, state_copy, annotation): if not self._model.captures_available(state_copy): return False legal_moves = self._model.legal_moves(state_copy) # match jump from file with available jumps on checkerboard startsq, destsq = squaremap[start], squaremap[dest] small, large = min(startsq, destsq), max(startsq, destsq) found = False for move in legal_moves: # a valid jump may either have a single jump in it, or # multiple jumps. In the multiple jump case, startsq is the # source of the first jump, and destsq is the endpoint of the # last jump. if (startsq == move.affected_squares[FIRST][0] and destsq == move.affected_squares[LAST][0]): self._model.make_move(move, state_copy, False, False) move.annotation = annotation self.moves.append(move) found = True break return found def _parse_moves(self, lines, idx, linelen): """ Each move in the file lists the beginning and ending square, along with an optional annotation string (in Creole format) that describes it. Since the move listing in the file contains less information than we need inside our Checkerboard model, I make sure that each move works on a copy of the model before I commit to using it inside the code. """ state_copy = copy.deepcopy(self._model.curr_state) idx += 1 while idx < linelen: line = lines[idx].strip() if line == "": idx += 1 continue # ignore blank lines try: movestr, annotation = line.split(';', 1) except ValueError: raise IOError, 'Unrecognized section in file, line %d' % (idx+1) # move is always part of the annotation; I just don't want to # have to repeat it explicitly in the file. annotation = movestr + annotation # analyze affected squares to perform a move or jump. try: start, dest = [int(x) for x in movestr.split('-')] except ValueError: raise IOError, 'Bad move format in file, line %d' % idx delta = squaremap[start] - squaremap[dest] if self._is_move(delta): self._try_move(idx, start, dest, state_copy, annotation) else: jumped = self._try_jump(idx, start, dest, state_copy, annotation) if not jumped: raise IOError, 'Bad move format in file, line %d' % idx idx += 1 self.moves.reverse() return idx
Python
from Tkinter import Widget from controller import Controller from globalconst import * class PlayerController(Controller): def __init__(self, **props): self._model = props['model'] self._view = props['view'] self._before_turn_event = None self._end_turn_event = props['end_turn_event'] self._highlights = [] self._move_in_progress = False def _register_event_handlers(self): Widget.bind(self._view.canvas, '<Button-1>', self.mouse_click) def _unregister_event_handlers(self): Widget.unbind(self._view.canvas, '<Button-1>') def stop_process(self): pass def set_search_time(self, time): pass def get_player_type(self): return HUMAN def set_before_turn_event(self, evt): self._before_turn_event = evt def add_highlights(self): for h in self._highlights: self._view.highlight_square(h, OUTLINE_COLOR) def remove_highlights(self): for h in self._highlights: self._view.highlight_square(h, DARK_SQUARES) def start_turn(self): self._register_event_handlers() self._model.curr_state.attach(self._view) def end_turn(self): self._unregister_event_handlers() self._model.curr_state.detach(self._view) def mouse_click(self, event): xi, yi = self._view.calc_board_loc(event.x, event.y) pos = self._view.calc_board_pos(xi, yi) sq = self._model.curr_state.squares[pos] if not self._move_in_progress: player = self._model.curr_state.to_move self.moves = self._model.legal_moves() if (sq & player) and self.moves: self._before_turn_event() # highlight the start square the user clicked on self._view.highlight_square(pos, OUTLINE_COLOR) self._highlights = [pos] # reduce moves to number matching the positions entered self.moves = self._filter_moves(pos, self.moves, 0) self.idx = 2 if self._model.captures_available() else 1 # if only one move available, take it. if len(self.moves) == 1: self._make_move() self._view.canvas.after(100, self._end_turn_event) return self._move_in_progress = True else: if sq & FREE: self.moves = self._filter_moves(pos, self.moves, self.idx) if len(self.moves) == 0: # illegal move # remove previous square highlights for h in self._highlights: self._view.highlight_square(h, DARK_SQUARES) self._move_in_progress = False return else: self._view.highlight_square(pos, OUTLINE_COLOR) self._highlights.append(pos) if len(self.moves) == 1: self._make_move() self._view.canvas.after(100, self._end_turn_event) return self.idx += 2 if self._model.captures_available() else 1 def _filter_moves(self, pos, moves, idx): del_list = [] for i, m in enumerate(moves): if pos != m.affected_squares[idx][0]: del_list.append(i) for i in reversed(del_list): del moves[i] return moves def _make_move(self): move = self.moves[0].affected_squares step = 2 if len(move) > 2 else 1 # highlight remaining board squares used in move for m in move[step::step]: idx = m[0] self._view.highlight_square(idx, OUTLINE_COLOR) self._highlights.append(idx) self._model.make_move(self.moves[0], None, True, True, self._view.get_annotation()) # a new move obliterates any more redo's along a branch of the game tree self._model.curr_state.delete_redo_list() self._move_in_progress = False
Python
from abc import ABCMeta, abstractmethod class GoalEvaluator(object): __metaclass__ = ABCMeta def __init__(self, bias): self.bias = bias @abstractmethod def calculateDesirability(self, board): pass @abstractmethod def setGoal(self, board): pass
Python
from Tkinter import * from time import time, localtime, strftime class ToolTip( Toplevel ): """ Provides a ToolTip widget for Tkinter. To apply a ToolTip to any Tkinter widget, simply pass the widget to the ToolTip constructor """ def __init__( self, wdgt, msg=None, msgFunc=None, delay=1, follow=True ): """ Initialize the ToolTip Arguments: wdgt: The widget this ToolTip is assigned to msg: A static string message assigned to the ToolTip msgFunc: A function that retrieves a string to use as the ToolTip text delay: The delay in seconds before the ToolTip appears(may be float) follow: If True, the ToolTip follows motion, otherwise hides """ self.wdgt = wdgt self.parent = self.wdgt.master # The parent of the ToolTip is the parent of the ToolTips widget Toplevel.__init__( self, self.parent, bg='black', padx=1, pady=1 ) # Initalise the Toplevel self.withdraw() # Hide initially self.overrideredirect( True ) # The ToolTip Toplevel should have no frame or title bar self.msgVar = StringVar() # The msgVar will contain the text displayed by the ToolTip if msg == None: self.msgVar.set( 'No message provided' ) else: self.msgVar.set( msg ) self.msgFunc = msgFunc self.delay = delay self.follow = follow self.visible = 0 self.lastMotion = 0 Message( self, textvariable=self.msgVar, bg='#FFFFDD', aspect=1000 ).grid() # The test of the ToolTip is displayed in a Message widget self.wdgt.bind( '<Enter>', self.spawn, '+' ) # Add bindings to the widget. This will NOT override bindings that the widget already has self.wdgt.bind( '<Leave>', self.hide, '+' ) self.wdgt.bind( '<Motion>', self.move, '+' ) def spawn( self, event=None ): """ Spawn the ToolTip. This simply makes the ToolTip eligible for display. Usually this is caused by entering the widget Arguments: event: The event that called this funciton """ self.visible = 1 self.after( int( self.delay * 1000 ), self.show ) # The after function takes a time argument in miliseconds def show( self ): """ Displays the ToolTip if the time delay has been long enough """ if self.visible == 1 and time() - self.lastMotion > self.delay: self.visible = 2 if self.visible == 2: self.deiconify() def move( self, event ): """ Processes motion within the widget. Arguments: event: The event that called this function """ self.lastMotion = time() if self.follow == False: # If the follow flag is not set, motion within the widget will make the ToolTip dissapear self.withdraw() self.visible = 1 self.geometry( '+%i+%i' % ( event.x_root+10, event.y_root+10 ) ) # Offset the ToolTip 10x10 pixes southwest of the pointer try: self.msgVar.set( self.msgFunc() ) # Try to call the message function. Will not change the message if the message function is None or the message function fails except: pass self.after( int( self.delay * 1000 ), self.show ) def hide( self, event=None ): """ Hides the ToolTip. Usually this is caused by leaving the widget Arguments: event: The event that called this function """ self.visible = 0 self.withdraw() def xrange2d( n,m ): """ Returns a generator of values in a 2d range Arguments: n: The number of rows in the 2d range m: The number of columns in the 2d range Returns: A generator of values in a 2d range """ return ( (i,j) for i in xrange(n) for j in xrange(m) ) def range2d( n,m ): """ Returns a list of values in a 2d range Arguments: n: The number of rows in the 2d range m: The number of columns in the 2d range Returns: A list of values in a 2d range """ return [(i,j) for i in range(n) for j in range(m) ] def print_time(): """ Prints the current time in the following format: HH:MM:SS.00 """ t = time() timeString = 'time=' timeString += strftime( '%H:%M:', localtime(t) ) timeString += '%.2f' % ( t%60, ) return timeString def main(): root = Tk() btnList = [] for (i,j) in range2d( 6, 4 ): text = 'delay=%i\n' % i delay = i if j >= 2: follow=True text += '+follow\n' else: follow = False text += '-follow\n' if j % 2 == 0: msg = None msgFunc = print_time text += 'Message Function' else: msg = 'Button at %s' % str( (i,j) ) msgFunc = None text += 'Static Message' btnList.append( Button( root, text=text ) ) ToolTip( btnList[-1], msg=msg, msgFunc=msgFunc, follow=follow, delay=delay) btnList[-1].grid( row=i, column=j, sticky=N+S+E+W ) root.mainloop() if __name__ == '__main__': main()
Python
class Command(object): def __init__(self, **props): self.add = props.get('add') or [] self.remove = props.get('remove') or []
Python
from globalconst import BLACK, WHITE, KING import checkers class Operator(object): pass class OneKingAttackOneKing(Operator): def precondition(self, board): plr_color = board.to_move opp_color = board.enemy return (board.count(plr_color) == 1 and board.count(opp_color) == 1 and any((x & KING for x in board.get_pieces(opp_color))) and any((x & KING for x in board.get_pieces(plr_color))) and board.has_opposition(plr_color)) def postcondition(self, board): board.make_move() class PinEnemyKingInCornerWithPlayerKing(Operator): def __init__(self): self.pidx = 0 self.eidx = 0 self.goal = 8 def precondition(self, state): self.pidx, plr = self.plr_lst[0] # only 1 piece per side self.eidx, enemy = self.enemy_lst[0] delta = abs(self.pidx - self.eidx) return ((self.player_total == 1) and (self.enemy_total == 1) and (plr & KING > 0) and (enemy & KING > 0) and not (8 <= delta <= 10) and state.have_opposition(plr)) def postcondition(self, state): new_state = None old_delta = abs(self.eidx - self.pidx) goal_delta = abs(self.goal - old_delta) for move in state.moves: for m in move: newidx, _, _ = m[1] new_delta = abs(self.eidx - newidx) if abs(goal - new_delta) < goal_delta: new_state = state.make_move(move) break return new_state # (white) # 37 38 39 40 # 32 33 34 35 # 28 29 30 31 # 23 24 25 26 # 19 20 21 22 # 14 15 16 17 # 10 11 12 13 # 5 6 7 8 # (black) class SingleKingFleeToDoubleCorner(Operator): def __init__(self): self.pidx = 0 self.eidx = 0 self.dest = [8, 13, 27, 32] self.goal_delta = 0 def precondition(self, state): # fail fast if self.player_total == 1 and self.enemy_total == 1: return False self.pidx, _ = self.plr_lst[0] self.eidx, _ = self.enemy_lst[0] for sq in self.dest: if abs(self.pidx - sq) < abs(self.eidx - sq): self.goal = sq return True return False def postcondition(self, state): self.goal_delta = abs(self.goal - self.pidx) for move in state.moves: for m in move: newidx, _, _ = m[1] new_delta = abs(self.goal - newidx) if new_delta < self.goal_delta: new_state = state.make_move(move) break return new_state class FormShortDyke(Operator): def precondition(self): pass
Python
class Controller(object): def stop_process(self): pass
Python
from abc import ABCMeta, abstractmethod class Goal: __metaclass__ = ABCMeta INACTIVE = 0 ACTIVE = 1 COMPLETED = 2 FAILED = 3 def __init__(self, owner): self.owner = owner self.status = self.INACTIVE @abstractmethod def activate(self): pass @abstractmethod def process(self): pass @abstractmethod def terminate(self): pass def handleMessage(self, msg): return False def addSubgoal(self, goal): raise NotImplementedError('Cannot add goals to atomic goals') def reactivateIfFailed(self): if self.status == self.FAILED: self.status = self.INACTIVE def activateIfInactive(self): if self.status == self.INACTIVE: self.status = self.ACTIVE
Python
from Tkinter import * from ttk import Checkbutton from tkSimpleDialog import Dialog from globalconst import * class SetupBoard(Dialog): def __init__(self, parent, title, gameManager): self._master = parent self._manager = gameManager self._load_entry_box_vars() self.result = False Dialog.__init__(self, parent, title) def body(self, master): self._npLFrame = LabelFrame(master, text='No. of players:') self._npFrameEx1 = Frame(self._npLFrame, width=30) self._npFrameEx1.pack(side=LEFT, pady=5, expand=1) self._npButton1 = Radiobutton(self._npLFrame, text='Zero (autoplay)', value=0, variable=self._num_players, command=self._disable_player_color) self._npButton1.pack(side=LEFT, pady=5, expand=1) self._npButton2 = Radiobutton(self._npLFrame, text='One', value=1, variable=self._num_players, command=self._enable_player_color) self._npButton2.pack(side=LEFT, pady=5, expand=1) self._npButton3 = Radiobutton(self._npLFrame, text='Two', value=2, variable=self._num_players, command=self._disable_player_color) self._npButton3.pack(side=LEFT, pady=5, expand=1) self._npFrameEx2 = Frame(self._npLFrame, width=30) self._npFrameEx2.pack(side=LEFT, pady=5, expand=1) self._npLFrame.pack(fill=X) self._playerFrame = LabelFrame(master, text='Player color:') self._playerFrameEx1 = Frame(self._playerFrame, width=50) self._playerFrameEx1.pack(side=LEFT, pady=5, expand=1) self._rbColor1 = Radiobutton(self._playerFrame, text='Black', value=BLACK, variable=self._player_color) self._rbColor1.pack(side=LEFT, padx=0, pady=5, expand=1) self._rbColor2 = Radiobutton(self._playerFrame, text='White', value=WHITE, variable=self._player_color) self._rbColor2.pack(side=LEFT, padx=0, pady=5, expand=1) self._playerFrameEx2 = Frame(self._playerFrame, width=50) self._playerFrameEx2.pack(side=LEFT, pady=5, expand=1) self._playerFrame.pack(fill=X) self._rbFrame = LabelFrame(master, text='Next to move:') self._rbFrameEx1 = Frame(self._rbFrame, width=50) self._rbFrameEx1.pack(side=LEFT, pady=5, expand=1) self._rbTurn1 = Radiobutton(self._rbFrame, text='Black', value=BLACK, variable=self._player_turn) self._rbTurn1.pack(side=LEFT, padx=0, pady=5, expand=1) self._rbTurn2 = Radiobutton(self._rbFrame, text='White', value=WHITE, variable=self._player_turn) self._rbTurn2.pack(side=LEFT, padx=0, pady=5, expand=1) self._rbFrameEx2 = Frame(self._rbFrame, width=50) self._rbFrameEx2.pack(side=LEFT, pady=5, expand=1) self._rbFrame.pack(fill=X) self._bcFrame = LabelFrame(master, text='Board configuration') self._wmFrame = Frame(self._bcFrame, borderwidth=0) self._wmLabel = Label(self._wmFrame, text='White men:') self._wmLabel.pack(side=LEFT, padx=7, pady=10) self._wmEntry = Entry(self._wmFrame, width=40, textvariable=self._white_men) self._wmEntry.pack(side=LEFT, padx=10) self._wmFrame.pack() self._wkFrame = Frame(self._bcFrame, borderwidth=0) self._wkLabel = Label(self._wkFrame, text='White kings:') self._wkLabel.pack(side=LEFT, padx=5, pady=10) self._wkEntry = Entry(self._wkFrame, width=40, textvariable=self._white_kings) self._wkEntry.pack(side=LEFT, padx=10) self._wkFrame.pack() self._bmFrame = Frame(self._bcFrame, borderwidth=0) self._bmLabel = Label(self._bmFrame, text='Black men:') self._bmLabel.pack(side=LEFT, padx=7, pady=10) self._bmEntry = Entry(self._bmFrame, width=40, textvariable=self._black_men) self._bmEntry.pack(side=LEFT, padx=10) self._bmFrame.pack() self._bkFrame = Frame(self._bcFrame, borderwidth=0) self._bkLabel = Label(self._bkFrame, text='Black kings:') self._bkLabel.pack(side=LEFT, padx=5, pady=10) self._bkEntry = Entry(self._bkFrame, width=40, textvariable=self._black_kings) self._bkEntry.pack(side=LEFT, padx=10) self._bkFrame.pack() self._bcFrame.pack(fill=X) self._bsState = IntVar() self._bsFrame = Frame(master, borderwidth=0) self._bsCheck = Checkbutton(self._bsFrame, variable=self._bsState, text='Start new game with the current setup?') self._bsCheck.pack() self._bsFrame.pack(fill=X) if self._num_players.get() == 1: self._enable_player_color() else: self._disable_player_color() def validate(self): self.wm_list = self._parse_int_list(self._white_men.get()) self.wk_list = self._parse_int_list(self._white_kings.get()) self.bm_list = self._parse_int_list(self._black_men.get()) self.bk_list = self._parse_int_list(self._black_kings.get()) if (self.wm_list == None or self.wk_list == None or self.bm_list == None or self.bk_list == None): return 0 # Error occurred during parsing if not self._all_unique(self.wm_list, self.wk_list, self.bm_list, self.bk_list): return 0 # A repeated index occurred return 1 def apply(self): mgr = self._manager model = mgr.model view = mgr.view state = model.curr_state mgr.player_color = self._player_color.get() mgr.num_players = self._num_players.get() mgr.model.curr_state.to_move = self._player_turn.get() # only reset the BoardView if men or kings have new positions if (sorted(self.wm_list) != sorted(self._orig_white_men) or sorted(self.wk_list) != sorted(self._orig_white_kings) or sorted(self.bm_list) != sorted(self._orig_black_men) or sorted(self.bk_list) != sorted(self._orig_black_kings) or self._bsState.get() == 1): state.clear() sq = state.squares for item in self.wm_list: idx = squaremap[item] sq[idx] = WHITE | MAN for item in self.wk_list: idx = squaremap[item] sq[idx] = WHITE | KING for item in self.bm_list: idx = squaremap[item] sq[idx] = BLACK | MAN for item in self.bk_list: idx = squaremap[item] sq[idx] = BLACK | KING state.to_move = self._player_turn.get() state.reset_undo() view.reset_view(mgr.model) if self._bsState.get() == 1: mgr.filename = None mgr.parent.set_title_bar_filename() state.ok_to_move = True self.result = True self.destroy() def cancel(self, event=None): self.destroy() def _load_entry_box_vars(self): self._white_men = StringVar() self._white_kings = StringVar() self._black_men = StringVar() self._black_kings = StringVar() self._player_color = IntVar() self._player_turn = IntVar() self._num_players = IntVar() self._player_color.set(self._manager.player_color) self._num_players.set(self._manager.num_players) model = self._manager.model self._player_turn.set(model.curr_state.to_move) view = self._manager.view self._white_men.set(', '.join(view.get_positions(WHITE | MAN))) self._white_kings.set(', '.join(view.get_positions(WHITE | KING))) self._black_men.set(', '.join(view.get_positions(BLACK | MAN))) self._black_kings.set(', '.join(view.get_positions(BLACK | KING))) self._orig_white_men = map(int, view.get_positions(WHITE | MAN)) self._orig_white_kings = map(int, view.get_positions(WHITE | KING)) self._orig_black_men = map(int, view.get_positions(BLACK | MAN)) self._orig_black_kings = map(int, view.get_positions(BLACK | KING)) def _disable_player_color(self): self._rbColor1.configure(state=DISABLED) self._rbColor2.configure(state=DISABLED) def _enable_player_color(self): self._rbColor1.configure(state=NORMAL) self._rbColor2.configure(state=NORMAL) def _all_unique(self, *lists): s = set() total_list = [] for i in lists: total_list.extend(i) s = s.union(i) return sorted(total_list) == sorted(s) def _parse_int_list(self, parsestr): try: lst = parsestr.split(',') except AttributeError: return None if lst == ['']: return [] try: lst = [int(i) for i in lst] except ValueError: return None if not all(((x>=1 and x<=MAX_VALID_SQ) for x in lst)): return None return lst
Python
from Tkinter import * class HyperlinkManager(object): def __init__(self, textWidget, linkFunc): self.txt = textWidget self.linkfunc = linkFunc self.txt.tag_config('hyper', foreground='blue', underline=1) self.txt.tag_bind('hyper', '<Enter>', self._enter) self.txt.tag_bind('hyper', '<Leave>', self._leave) self.txt.tag_bind('hyper', '<Button-1>', self._click) self.reset() def reset(self): self.filenames = {} def add(self, filename): # Add a link with associated filename. The link function returns tags # to use in the associated text widget. tag = 'hyper-%d' % len(self.filenames) self.filenames[tag] = filename return 'hyper', tag def _enter(self, event): self.txt.config(cursor='hand2') def _leave(self, event): self.txt.config(cursor='') def _click(self, event): for tag in self.txt.tag_names(CURRENT): if tag.startswith('hyper-'): self.linkfunc(self.filenames[tag]) return
Python
class DocNode(object): """ A node in the document. """ def __init__(self, kind='', parent=None, content=None): self.children = [] self.parent = parent self.kind = kind self.content = content if self.parent is not None: self.parent.children.append(self)
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2010 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == This is the "File Uploader" for Python """ import os from fckutil import * from fckcommands import * # default command's implementation from fckconnector import FCKeditorConnectorBase # import base connector import config as Config class FCKeditorQuickUpload( FCKeditorConnectorBase, UploadFileCommandMixin, BaseHttpMixin, BaseHtmlMixin): def doResponse(self): "Main function. Process the request, set headers and return a string as response." # Check if this connector is disabled if not(Config.Enabled): return self.sendUploadResults(1, "This file uploader is disabled. Please check the \"editor/filemanager/connectors/py/config.py\"") command = 'QuickUpload' # The file type (from the QueryString, by default 'File'). resourceType = self.request.get('Type','File') currentFolder = "/" # Check for invalid paths if currentFolder is None: return self.sendUploadResults(102, '', '', "") # Check if it is an allowed command if ( not command in Config.ConfigAllowedCommands ): return self.sendUploadResults( 1, '', '', 'The %s command isn\'t allowed' % command ) if ( not resourceType in Config.ConfigAllowedTypes ): return self.sendUploadResults( 1, '', '', 'Invalid type specified' ) # Setup paths self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType] self.webUserFilesFolder = Config.QuickUploadPath[resourceType] if not self.userFilesFolder: # no absolute path given (dangerous...) self.userFilesFolder = mapServerPath(self.environ, self.webUserFilesFolder) # Ensure that the directory exists. if not os.path.exists(self.userFilesFolder): try: self.createServerFoldercreateServerFolder( self.userFilesFolder ) except: return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ") # File upload doesn't have to return XML, so intercept here return self.uploadFile(resourceType, currentFolder) # Running from command line (plain old CGI) if __name__ == '__main__': try: # Create a Connector Instance conn = FCKeditorQuickUpload() data = conn.doResponse() for header in conn.headers: if not header is None: print '%s: %s' % header print print data except: print "Content-Type: text/plain" print import cgi cgi.print_exception()
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2010 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector for Python (CGI and WSGI). """ from time import gmtime, strftime import string def escape(text, replace=string.replace): """ Converts the special characters '<', '>', and '&'. RFC 1866 specifies that these characters be represented in HTML as &lt; &gt; and &amp; respectively. In Python 1.5 we use the new string.replace() function for speed. """ text = replace(text, '&', '&amp;') # must be done 1st text = replace(text, '<', '&lt;') text = replace(text, '>', '&gt;') text = replace(text, '"', '&quot;') return text def convertToXmlAttribute(value): if (value is None): value = "" return escape(value) class BaseHttpMixin(object): def setHttpHeaders(self, content_type='text/xml'): "Purpose: to prepare the headers for the xml to return" # Prevent the browser from caching the result. # Date in the past self.setHeader('Expires','Mon, 26 Jul 1997 05:00:00 GMT') # always modified self.setHeader('Last-Modified',strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime())) # HTTP/1.1 self.setHeader('Cache-Control','no-store, no-cache, must-revalidate') self.setHeader('Cache-Control','post-check=0, pre-check=0') # HTTP/1.0 self.setHeader('Pragma','no-cache') # Set the response format. self.setHeader( 'Content-Type', content_type + '; charset=utf-8' ) return class BaseXmlMixin(object): def createXmlHeader(self, command, resourceType, currentFolder, url): "Purpose: returns the xml header" self.setHttpHeaders() # Create the XML document header s = """<?xml version="1.0" encoding="utf-8" ?>""" # Create the main connector node s += """<Connector command="%s" resourceType="%s">""" % ( command, resourceType ) # Add the current folder node s += """<CurrentFolder path="%s" url="%s" />""" % ( convertToXmlAttribute(currentFolder), convertToXmlAttribute(url), ) return s def createXmlFooter(self): "Purpose: returns the xml footer" return """</Connector>""" def sendError(self, number, text): "Purpose: in the event of an error, return an xml based error" self.setHttpHeaders() return ("""<?xml version="1.0" encoding="utf-8" ?>""" + """<Connector>""" + self.sendErrorNode (number, text) + """</Connector>""" ) def sendErrorNode(self, number, text): if number != 1: return """<Error number="%s" />""" % (number) else: return """<Error number="%s" text="%s" />""" % (number, convertToXmlAttribute(text)) class BaseHtmlMixin(object): def sendUploadResults( self, errorNo = 0, fileUrl = '', fileName = '', customMsg = '' ): self.setHttpHeaders("text/html") "This is the function that sends the results of the uploading process" "Minified version of the document.domain automatic fix script (#1919)." "The original script can be found at _dev/domain_fix_template.js" return """<script type="text/javascript"> (function(){var d=document.domain;while (true){try{var A=window.parent.document.domain;break;}catch(e) {};d=d.replace(/.*?(?:\.|$)/,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})(); window.parent.OnUploadCompleted(%(errorNumber)s,"%(fileUrl)s","%(fileName)s","%(customMsg)s"); </script>""" % { 'errorNumber': errorNo, 'fileUrl': fileUrl.replace ('"', '\\"'), 'fileName': fileName.replace ( '"', '\\"' ) , 'customMsg': customMsg.replace ( '"', '\\"' ), }
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2010 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Utility functions for the File Manager Connector for Python """ import string, re import os import config as Config # Generic manipulation functions def removeExtension(fileName): index = fileName.rindex(".") newFileName = fileName[0:index] return newFileName def getExtension(fileName): index = fileName.rindex(".") + 1 fileExtension = fileName[index:] return fileExtension def removeFromStart(string, char): return string.lstrip(char) def removeFromEnd(string, char): return string.rstrip(char) # Path functions def combinePaths( basePath, folder ): return removeFromEnd( basePath, '/' ) + '/' + removeFromStart( folder, '/' ) def getFileName(filename): " Purpose: helper function to extrapolate the filename " for splitChar in ["/", "\\"]: array = filename.split(splitChar) if (len(array) > 1): filename = array[-1] return filename def sanitizeFolderName( newFolderName ): "Do a cleanup of the folder name to avoid possible problems" # Remove . \ / | : ? * " < > and control characters return re.sub( '\\.|\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[\x00-\x1f\x7f-\x9f]', '_', newFolderName ) def sanitizeFileName( newFileName ): "Do a cleanup of the file name to avoid possible problems" # Replace dots in the name with underscores (only one dot can be there... security issue). if ( Config.ForceSingleExtension ): # remove dots newFileName = re.sub ( '\\.(?![^.]*$)', '_', newFileName ) ; newFileName = newFileName.replace('\\','/') # convert windows to unix path newFileName = os.path.basename (newFileName) # strip directories # Remove \ / | : ? * return re.sub ( '\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[\x00-\x1f\x7f-\x9f]/', '_', newFileName ) def getCurrentFolder(currentFolder): if not currentFolder: currentFolder = '/' # Check the current folder syntax (must begin and end with a slash). if (currentFolder[-1] <> "/"): currentFolder += "/" if (currentFolder[0] <> "/"): currentFolder = "/" + currentFolder # Ensure the folder path has no double-slashes while '//' in currentFolder: currentFolder = currentFolder.replace('//','/') # Check for invalid folder paths (..) if '..' in currentFolder or '\\' in currentFolder: return None # Check for invalid folder paths (..) if re.search( '(/\\.)|(//)|([\\\\:\\*\\?\\""\\<\\>\\|]|[\x00-\x1F]|[\x7f-\x9f])', currentFolder ): return None return currentFolder def mapServerPath( environ, url): " Emulate the asp Server.mapPath function. Given an url path return the physical directory that it corresponds to " # This isn't correct but for the moment there's no other solution # If this script is under a virtual directory or symlink it will detect the problem and stop return combinePaths( getRootPath(environ), url ) def mapServerFolder(resourceTypePath, folderPath): return combinePaths ( resourceTypePath , folderPath ) def getRootPath(environ): "Purpose: returns the root path on the server" # WARNING: this may not be thread safe, and doesn't work w/ VirtualServer/mod_python # Use Config.UserFilesAbsolutePath instead if environ.has_key('DOCUMENT_ROOT'): return environ['DOCUMENT_ROOT'] else: realPath = os.path.realpath( './' ) selfPath = environ['SCRIPT_FILENAME'] selfPath = selfPath [ : selfPath.rfind( '/' ) ] selfPath = selfPath.replace( '/', os.path.sep) position = realPath.find(selfPath) # This can check only that this script isn't run from a virtual dir # But it avoids the problems that arise if it isn't checked raise realPath if ( position < 0 or position <> len(realPath) - len(selfPath) or realPath[ : position ]==''): raise Exception('Sorry, can\'t map "UserFilesPath" to a physical path. You must set the "UserFilesAbsolutePath" value in "editor/filemanager/connectors/py/config.py".') return realPath[ : position ]
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2010 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == This is the "File Uploader" for Python """ import os from fckutil import * from fckcommands import * # default command's implementation from fckconnector import FCKeditorConnectorBase # import base connector import config as Config class FCKeditorQuickUpload( FCKeditorConnectorBase, UploadFileCommandMixin, BaseHttpMixin, BaseHtmlMixin): def doResponse(self): "Main function. Process the request, set headers and return a string as response." # Check if this connector is disabled if not(Config.Enabled): return self.sendUploadResults(1, "This file uploader is disabled. Please check the \"editor/filemanager/connectors/py/config.py\"") command = 'QuickUpload' # The file type (from the QueryString, by default 'File'). resourceType = self.request.get('Type','File') currentFolder = "/" # Check for invalid paths if currentFolder is None: return self.sendUploadResults(102, '', '', "") # Check if it is an allowed command if ( not command in Config.ConfigAllowedCommands ): return self.sendUploadResults( 1, '', '', 'The %s command isn\'t allowed' % command ) if ( not resourceType in Config.ConfigAllowedTypes ): return self.sendUploadResults( 1, '', '', 'Invalid type specified' ) # Setup paths self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType] self.webUserFilesFolder = Config.QuickUploadPath[resourceType] if not self.userFilesFolder: # no absolute path given (dangerous...) self.userFilesFolder = mapServerPath(self.environ, self.webUserFilesFolder) # Ensure that the directory exists. if not os.path.exists(self.userFilesFolder): try: self.createServerFoldercreateServerFolder( self.userFilesFolder ) except: return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ") # File upload doesn't have to return XML, so intercept here return self.uploadFile(resourceType, currentFolder) # Running from command line (plain old CGI) if __name__ == '__main__': try: # Create a Connector Instance conn = FCKeditorQuickUpload() data = conn.doResponse() for header in conn.headers: if not header is None: print '%s: %s' % header print print data except: print "Content-Type: text/plain" print import cgi cgi.print_exception()
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2010 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Base Connector for Python (CGI and WSGI). See config.py for configuration settings """ import cgi, os from fckutil import * from fckcommands import * # default command's implementation from fckoutput import * # base http, xml and html output mixins import config as Config class FCKeditorConnectorBase( object ): "The base connector class. Subclass it to extend functionality (see Zope example)" def __init__(self, environ=None): "Constructor: Here you should parse request fields, initialize variables, etc." self.request = FCKeditorRequest(environ) # Parse request self.headers = [] # Clean Headers if environ: self.environ = environ else: self.environ = os.environ # local functions def setHeader(self, key, value): self.headers.append ((key, value)) return class FCKeditorRequest(object): "A wrapper around the request object" def __init__(self, environ): if environ: # WSGI self.request = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ, keep_blank_values=1) self.environ = environ else: # plain old cgi self.environ = os.environ self.request = cgi.FieldStorage() if 'REQUEST_METHOD' in self.environ and 'QUERY_STRING' in self.environ: if self.environ['REQUEST_METHOD'].upper()=='POST': # we are in a POST, but GET query_string exists # cgi parses by default POST data, so parse GET QUERY_STRING too self.get_request = cgi.FieldStorage(fp=None, environ={ 'REQUEST_METHOD':'GET', 'QUERY_STRING':self.environ['QUERY_STRING'], }, ) else: self.get_request={} def has_key(self, key): return self.request.has_key(key) or self.get_request.has_key(key) def get(self, key, default=None): if key in self.request.keys(): field = self.request[key] elif key in self.get_request.keys(): field = self.get_request[key] else: return default if hasattr(field,"filename") and field.filename: #file upload, do not convert return value return field else: return field.value
Python
#!/usr/bin/env python """ FCKeditor - The text editor for Internet - http://www.fckeditor.net Copyright (C) 2003-2010 Frederico Caldeira Knabben == BEGIN LICENSE == Licensed under the terms of any of the following licenses at your choice: - GNU General Public License Version 2 or later (the "GPL") http://www.gnu.org/licenses/gpl.html - GNU Lesser General Public License Version 2.1 or later (the "LGPL") http://www.gnu.org/licenses/lgpl.html - Mozilla Public License Version 1.1 or later (the "MPL") http://www.mozilla.org/MPL/MPL-1.1.html == END LICENSE == Connector/QuickUpload for Python (WSGI wrapper). See config.py for configuration settings """ from connector import FCKeditorConnector from upload import FCKeditorQuickUpload import cgitb from cStringIO import StringIO # Running from WSGI capable server (recomended) def App(environ, start_response): "WSGI entry point. Run the connector" if environ['SCRIPT_NAME'].endswith("connector.py"): conn = FCKeditorConnector(environ) elif environ['SCRIPT_NAME'].endswith("upload.py"): conn = FCKeditorQuickUpload(environ) else: start_response ("200 Ok", [('Content-Type','text/html')]) yield "Unknown page requested: " yield environ['SCRIPT_NAME'] return try: # run the connector data = conn.doResponse() # Start WSGI response: start_response ("200 Ok", conn.headers) # Send response text yield data except: start_response("500 Internal Server Error",[("Content-type","text/html")]) file = StringIO() cgitb.Hook(file = file).handle() yield file.getvalue()
Python