repo_name
stringlengths
5
100
path
stringlengths
4
294
copies
stringclasses
990 values
size
stringlengths
4
7
content
stringlengths
666
1M
license
stringclasses
15 values
Transkribus/TranskribusDU
TranskribusDU/tasks/DU_Table/rowDetection.py
1
90019
# -*- coding: utf-8 -*- """ Build Rows for a BIESO model H. Déjean copyright Xerox 2017, Naver 2017, 2018 READ project Developed for the EU project READ. The READ project has received funding from the European Union's Horizon 2020 research and innovation programme under grant agreement No 674943. """ import sys, os.path sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(sys.argv[0])))) import collections from lxml import etree from sklearn.metrics import adjusted_rand_score from sklearn.metrics import homogeneity_score from sklearn.metrics import completeness_score import common.Component as Component from common.trace import traceln import config.ds_xml_def as ds_xml from ObjectModel.xmlDSDocumentClass import XMLDSDocument from ObjectModel.XMLDSTEXTClass import XMLDSTEXTClass from ObjectModel.XMLDSTABLEClass import XMLDSTABLEClass from ObjectModel.XMLDSCELLClass import XMLDSTABLECELLClass from ObjectModel.XMLDSTableRowClass import XMLDSTABLEROWClass from ObjectModel.XMLDSTableColumnClass import XMLDSTABLECOLUMNClass from spm.spmTableRow import tableRowMiner from xml_formats.Page2DS import primaAnalysis from util.partitionEvaluation import evalPartitions, jaccard, iuo from util.geoTools import sPoints2tuplePoints from shapely.geometry import Polygon from shapely import affinity from shapely.ops import cascaded_union class RowDetection(Component.Component): """ row detection @precondition: column detection done, BIES tagging done for text elements 11/9/2018: last idea: suppose the cell segmentation good enough: group cells which are unambiguous with the cell in the (none empty) next column . 12/11/2018: already done in mergehorinzontalCells !! 12/11/2018: assume perfect cells: build simple: take next lright as same row then look for elements belonging to several rows """ usage = "" version = "v.1.1" description = "description: rowDetection from BIO textlines" #--- INIT ------------------------------------------------------------------------------------------------------------- def __init__(self): """ Always call first the Component constructor. """ Component.Component.__init__(self, "RowDetection", self.usage, self.version, self.description) self.colname = None self.docid= None self.do2DS= False self.THHighSupport = 0.20 self.bYCut = False self.bCellOnly = False # for --test self.bCreateRef = False self.bCreateRefCluster = False self.BTAG= 'B' self.STAG = 'S' self.bNoTable = False self.bEvalCluster=False self.evalData = None def setParams(self, dParams): """ Always call first the Component setParams Here, we set our internal attribute according to a possibly specified value (otherwise it stays at its default value) """ Component.Component.setParams(self, dParams) # if dParams.has_key("coldir"): # self.colname = dParams["coldir"] if "docid" in dParams: self.docid = dParams["docid"] if "dsconv" in dParams: self.do2DS = dParams["dsconv"] if "createref" in dParams: self.bCreateRef = dParams["createref"] if "bNoColumn" in dParams: self.bNoTable = dParams["bNoColumn"] if "createrefCluster" in dParams: self.bCreateRefCluster = dParams["createrefCluster"] if "evalCluster" in dParams: self.bEvalCluster = dParams["evalCluster"] if "thhighsupport" in dParams: self.THHighSupport = dParams["thhighsupport"] * 0.01 if 'BTAG' in dParams: self.BTAG = dParams["BTAG"] if 'STAG' in dParams: self.STAG = dParams["STAG"] if 'YCut' in dParams: self.bYCut = dParams["YCut"] if 'bCellOnly' in dParams: self.bCellOnly = dParams["bCellOnly"] def createCells(self, table): """ create new cells using BIESO tags @input: tableObeject with old cells @return: tableObject with BIES cells @precondition: requires columns if DU_col = M : ignore """ # print ('nbcells:',len(table.getAllNamedObjects(XMLDSTABLECELLClass))) table._lObjects = [] lSkipped =[] for col in table.getColumns(): # print (col) lNewCells=[] # keep original positions try:col.resizeMe(XMLDSTABLECELLClass) except: pass # in order to ignore existing cells from GT: collect all objects from cells lObjects = [txt for cell in col.getCells() for txt in cell.getObjects() ] lObjects.sort(key=lambda x:x.getY()) curChunk=[] lChunks = [] for txt in lObjects: # do no yse it for the moment if txt.getAttribute("DU_col") == 'Mx': lSkipped.append(txt) elif txt.getAttribute("DU_row") == self.STAG: if curChunk != []: lChunks.append(curChunk) curChunk=[] lChunks.append([txt]) elif txt.getAttribute("DU_row") in ['I', 'E']: curChunk.append(txt) elif txt.getAttribute("DU_row") == self.BTAG: if curChunk != []: lChunks.append(curChunk) curChunk=[txt] elif txt.getAttribute("DU_row") == 'O': ## add Other as well??? no curChunk.append(txt) # pass if curChunk != []: lChunks.append(curChunk) if lChunks != []: # create new cells # table.delCell(cell) irow= txt.getParent().getIndex()[0] for i,c in enumerate(lChunks): #create a new cell per chunk and replace 'cell' newCell = XMLDSTABLECELLClass() newCell.setPage(txt.getParent().getPage()) newCell.setParent(table) newCell.setName(ds_xml.sCELL) # newCell.setIndex(irow+i,txt.getParent().getIndex()[1]) newCell.setIndex(i,txt.getParent().getIndex()[1]) newCell.setObjectsList(c) # newCell.addAttribute('type','new') newCell.resizeMe(XMLDSTEXTClass) newCell.tagMe2() for o in newCell.getObjects(): o.setParent(newCell) o.tagMe() # contour = self.createContourFromListOfElements(newCell.getObjects()) # if contour is not None: # # newCell.addAttribute('points',','.join("%s,%s"%(x[0],x[1]) for x in contour.lXY)) # newCell.addAttribute('points',','.join("%s,%s"%(x[0],x[1]) for x in contour)) # newCell.tagMe2() # table.addCell(newCell) lNewCells.append(newCell) # if txt.getParent().getNode().getparent() is not None: txt.getParent().getNode().getparent().remove(txt.getParent().getNode()) # del(txt.getParent()) #delete all cells for cell in col.getCells(): # print (cell) try: if cell.getNode().getparent() is not None: cell.getNode().getparent().remove(cell.getNode()) except: pass [table.delCell(cell) for cell in col.getCells() ] # print ('\t nbcells 2:',len(table.getAllNamedObjects(XMLDSTABLECELLClass))) col._lcells= [] col._lObjects=[] # print (col.getAllNamedObjects(XMLDSTABLECELLClass)) [table.addCell(c) for c in lNewCells] [col.addCell(c) for c in lNewCells] # print ('\t nbcells 3:',len(table.getAllNamedObjects(XMLDSTABLECELLClass))) # print ('\tnbcells:',len(table.getAllNamedObjects(XMLDSTABLECELLClass))) def matchCells(self,table): """ use lcs (dtw?) for matching dtw: detect merging situation for each col: match with next col series 1 : col1 set of cells series 2 : col2 set of cells distance = Yoverlap """ dBest = {} #in(self.y2, tb.y2) - max(self.y1, tb.y1) def distY(c1,c2): o = min(c1.getY2() , c2.getY2()) - max(c1.getY() , c2.getY()) if o < 0: return 1 # d = (2* (min(c1.getY2() , c2.getY2()) - max(c1.getY() , c2.getY()))) / (c1.getHeight() + c2.getHeight()) # print(c1,c1.getY(),c1.getY2(), c2,c2.getY(),c2.getY2(),o,d) return 1 - (1 * (min(c1.getY2() , c2.getY2()) - max(c1.getY() , c2.getY()))) / min(c1.getHeight() , c2.getHeight()) laErr=[] for icol, col in enumerate(table.getColumns()): lc = col.getCells() + laErr lc.sort(key=lambda x:x.getY()) if icol+1 < table.getNbColumns(): col2 = table.getColumns()[icol+1] if col2.getCells() != []: cntOk,cntErr,cntMissed, lFound,lErr,lMissed = evalPartitions(lc,col2.getCells(), .25,distY) [laErr.append(x) for x in lErr if x not in laErr] [laErr.remove(x) for x,y in lFound if x in laErr] # lErr: cell not matched in col1 # lMissed: cell not matched in col2 print (col,col2,cntOk,cntErr,cntMissed,lErr) #, lFound,lErr,lMissed) for x,y in lFound: dBest[x]=y else: [laErr.append(x) for x in lc if x not in laErr] # create row #sort keys by x skeys = sorted(dBest.keys(),key=lambda x:x.getX()) lcovered=[] llR=[] for key in skeys: # print (key,lcovered) if key not in lcovered: lcovered.append(key) nextC = dBest[key] # print ("\t",key,nextC,lcovered) lrow = [key] while nextC: lrow.append(nextC) lcovered.append(nextC) try: nextC=dBest[nextC] except KeyError: print ('\txx\t',lrow) llR.append(lrow) nextC=None for lrow in llR: contour = self.createContourFromListOfElements(lrow) if contour is not None: spoints = ','.join("%s,%s"%(x[0],x[1]) for x in contour) r = XMLDSTABLEROWClass(1) r.setParent(table) r.addAttribute('points',spoints) r.tagMe('VV') def assessCuts(self,table,lYCuts): """ input: table, ycuts output: """ # features or values ? try:lYCuts = map(lambda x:x.getValue(),lYCuts) except:pass lCells = table.getCells() prevCut = table.getY() irowIndex = 0 lRows= [] dCellOverlap = {} for _,cut in enumerate(lYCuts): row=[] if cut - prevCut > 0: [b1,b2] = prevCut, cut for c in lCells: [a1, a2] = c.getY(),c.getY() + c.getHeight() if min(a2, b2) >= max(a1, b1): row.append(c) lRows.append(row) irowIndex += 1 prevCut = cut ## BIO coherence def buildLineCandidates(self,table): """ return a lits of lines corresponding to top row line candidates """ def mineTableRowPattern(self,table): """ find rows and columns patterns in terms of typographical position // mandatory cells,... input: a set of rows (table) action: seq mining of rows output: pattern Mining at table/page level # of cells per row # of cells per colmun # cell with content (j: freq ; i: freq) Sequential pattern:(itemset: setofrows; item cells?) """ # which col is mandatory # text alignment in cells (per col) for row in table.getRows(): # self.mineTypography() a = row.computeSkewing() """ skewing detection: use synthetic data !! simply scan row by row with previous row and adjust with coherence """ def getSkewingRepresentation(self,lcuts): """ input: list of featureObject output: skewed cut (a,b) alog: for each feature: get the text nodes baselines and create a skewed line (a,b) """ def miningSeparatorShape(self,table,lCuts): # import numpy as np from shapely.geometry import MultiLineString for cut in lCuts: xordered= list(cut.getNodes()) print(cut,[x.getX() for x in xordered]) xordered.sort(key = lambda x:x.getX()) lSeparators = [ (x.getX(),x.getY()) for x in [xordered[0],xordered[-1]]] print( lSeparators) ml = MultiLineString(lSeparators) print (ml.wkt) # X = [x[0] for x in lSeparators] # Y = [x[1] for x in lSeparators] # print(X,Y) # a, b = np.polynomial.polynomial.polyfit(X, Y, 1) # xmin, xmax = table.getX(), table.getX2() # y1 = a + b * xmin # y2 = a + b * xmax # print (y1,y2) # print ([ (x.getObjects()[0].getBaseline().getY(),x.getObjects()[0].getBaseline().getAngle(),x.getY()) for x in xordered]) def processRows(self, table, predefinedCuts=[]): """ Apply mining to get Y cuts for rows If everything is centered? Try thnum= [5,10,20,30,40,50] and keep better coherence! Then adjust skewing ? using features values: for c in lYcuts: print (c, [x.getY() for x in c.getNodes()]) replace columnMining by cell matching from col to col!! simply best match (max overlap) between two cells NONONO perform chk of cells (tagging is now very good!) and use it for column mining (chk + remaining cells) """ # self.matchCells(table) # return fMaxCoherence = 0.0 rowMiner= tableRowMiner() # % of columns needed lTHSUP= [0.2,0.3,0.4] # lTHSUP= [0.2] bestTHSUP =None bestthnum= None bestYcuts = None for thnum in [10,20,30]: # must be correlated with leading/text height? # for thnum in [30]: # must be correlated with leading/text height? # for thnum in [50]: # must be correlated with leading/text height? """ 07/1/2018: to be replace by HChunks for each hchunks: % of cuts(beginning) = validate the top line as segmentor ## hchunk at cell level : if yes select hchunks at textline level as well? """ lLYcuts = rowMiner.columnMining(table,thnum,lTHSUP,predefinedCuts) # print (lLYcuts) # get skewing represenation # [ x.setValue(x.getValue()-0) for x in lYcuts ] for iy,lYcuts in enumerate(lLYcuts): # print ("%s %s " %(thnum, lTHSUP[iy])) # lYcuts.sort(key= lambda x:x.getValue()) # self.miningSeparatorShape(table,lYcuts) # self.assessCuts(table, lYcuts) # self.createRowsWithCuts2(table,lYcuts) table.createRowsWithCuts(lYcuts) table.reintegrateCellsInColRow() coherence = self.computeCoherenceScore(table) if coherence > fMaxCoherence: fMaxCoherence = coherence bestYcuts= lYcuts[:] bestTHSUP = lTHSUP[iy] bestthnum= thnum # else: break # print ('coherence Score for (%s,%s): %f\t%s'%(thnum,lTHSUP[iy],coherence,bestYcuts)) if bestYcuts is not None: ### create the separation with the hullcontour : row as polygon!! ## if no intersection with previous row : OK ## if intersection # print (bestYcuts) # for y in bestYcuts: # ## get top elements of the cells to build the boundary ?? # print ('%s %s'%(y.getValue(),[(c.getX(),c.getY()) for c in sorted(y.getNodes(),key=lambda x:x.getX())])) ## what about elements outside the cut (beforeà) ## try "skew option and evaluate""!! ## take max -H ## take skew table.createRowsWithCuts(bestYcuts) table.reintegrateCellsInColRow() for row in table.getRows(): row.addAttribute('points',"0,0") contour = self.createContourFromListOfElements([x for c in row.getCells() for x in c.getObjects()]) if contour is not None: spoints = ','.join("%s,%s"%(x[0],x[1]) for x in contour) row.addAttribute('points',spoints) # print (len(table.getPage().getAllNamedObjects(XMLDSTABLECELLClass))) table.buildNDARRAY() # self.mineTableRowPattern(table) # def defineRowTopBoundary(self,row,ycut): # """ # define a top row boundary # """ def findBoundaryLinesFromChunks(self,table,lhckh): """ create lines from chunks (create with cells) take each chunk and create (a,b) with top contour """ from util.Polygon import Polygon as dspp import numpy as np dTop_lSgmt = collections.defaultdict(list) for chk in lhckh: sPoints = chk.getAttribute('points') #.replace(',',' ') spoints = ' '.join("%s,%s"%((x,y)) for x,y in zip(*[iter(sPoints.split(','))]*2)) it_sXsY = (sPair.split(',') for sPair in spoints.split(' ')) plgn = dspp((float(sx), float(sy)) for sx, sy in it_sXsY) try: lT, lR, lB, lL = plgn.partitionSegmentTopRightBottomLeft() dTop_lSgmt[chk].extend(lT) except ValueError: pass #now make linear regression to draw relevant separators def getX(lSegment): lX = list() for x1,y1,x2,y2 in lSegment: lX.append(x1) lX.append(x2) return lX def getY(lSegment): lY = list() for x1,y1,x2,y2 in lSegment: lY.append(y1) lY.append(y2) return lY dAB = collections.defaultdict(list) icmpt=0 for icol, lSegment in dTop_lSgmt.items(): #sorted(dTop_lSgmt.items()): print (icol,lSegment) X = getX(lSegment) Y = getY(lSegment) #sum(l,()) lfNorm = [np.linalg.norm([[x1,y1], [x2,y2]]) for x1,y1,x2,y2 in lSegment] #duplicate each element W = [fN for fN in lfNorm for _ in (0,1)] # a * x + b a, b = np.polynomial.polynomial.polyfit(X, Y, 1, w=W) xmin, xmax = min(X), max(X) y1 = a + b * (0) y2 = a + b * table.getX2() dAB[b].append((a,b)) rowline = XMLDSTABLEROWClass(icmpt) rowline.setPage(table.getPage()) rowline.setParent(table) icmpt+=1 # table.addColumn(rowline) # prevx1, prevymin,x1, ymin, x2, ymax, prevx2, prevymax)) rowline.addAttribute('points',"%s,%s %s,%s"%(0, y1, table.getX2(),y2)) # rowline.setX(prevxmin) # rowline.setY(prevy1) # rowline.setHeight(y2 - prevy1) # rowline.setWidth(xmax- xmin) rowline.tagMe('SeparatorRegion') # print (a,b) # for b in sorted(dAB.keys()): # print (b,dAB[b]) def processRows3(self,table,predefinedCuts=[] ): """ build rows: for a given cell: if One single Y overlapping cell in the next column: integrate it in the row """ from tasks.TwoDChunking import TwoDChunking hchk = TwoDChunking() lElts=[] [lElts.append(x) for col in table.getColumns() for x in col.getCells()] lhchk = hchk.HorizonalChunk(table.getPage(),lElts=lElts,bStrict=False) # lRows = [] # curRow = [] # for col in table.getColumns(): # lcells = col.getCells() def processRows2(self,table,predefinedCuts=[]): """ Apply mining to get Y cuts for rows """ from tasks.TwoDChunking import TwoDChunking hchk = TwoDChunking() lhchk = hchk.HorizonalChunk(table.getPage(),lElts=table.getCells()) # create bounday lines from lhckh # lYcuts = self.findBoundaryLinesFromChunks(table,lhchk) # lYcuts.sort(key= lambda x:x.getValue()) # self.getSkewingRepresentation(lYcuts) # self.assessCuts(table, lYcuts) # self.createRowsWithCuts2(table,lYcuts) # table.createRowsWithCuts(lYcuts) # table.reintegrateCellsInColRow() # # table.buildNDARRAY() def checkInputFormat(self,lPages): """ delete regions : copy regions elements at page object unlink subnodes """ for page in lPages: lTables = page.getAllNamedObjects(XMLDSTABLEClass) for table in lTables: lRegions = table.getAllNamedObjects("CELL") lElts=[] [lElts.extend(x.getObjects()) for x in lRegions] [table.addObject(x,bDom=True) for x in lElts] [table.removeObject(x,bDom=True) for x in lRegions] def processYCuts(self,ODoc): from util.XYcut import mergeSegments self.checkInputFormat(ODoc.getPages()) for page in ODoc.getPages(): traceln("page: %d" % page.getNumber()) lTables = page.getAllNamedObjects(XMLDSTABLEClass) for table in lTables: print ('nb Y: %s'% len(set([round(x.getY()) for x in page.getAllNamedObjects(XMLDSTEXTClass)])),len(page.getAllNamedObjects(XMLDSTEXTClass))) # lCuts, _, _ = mergeSegments([(x.getY(),x.getY() + x.getHeight(),x) for x in page.getAllNamedObjects(XMLDSTEXTClass)],0) # for i, (y,_,cut) in enumerate(lCuts): # ll =list(cut) # ll.sort(key=lambda x:x.getY()) # #add column # myRow= XMLDSTABLEROWClass(i) # myRow.setPage(page) # myRow.setParent(table) # table.addObject(myRow) # myRow.setY(y) # myRow.setX(table.getX()) # myRow.setWidth(table.getWidth()) # if i +1 < len(lCuts): # myRow.setHeight(lCuts[i+1][0]-y) # else: # use table # myRow.setHeight(table.getY2()-y) # table.addRow(myRow) # print (myRow) # myRow.tagMe(ds_xml.sROW) def mergeHorizontalCells(self,table): """ merge cell a to b|next col iff b overlap horizontally with a (using right border from points) input: a table, with candidate cells output: cluster of cells as row candidates simply ignore cells which overlap several cells in the next column then: extend row candidates if needed if no column known: simply take the first cell in lright if cells in lright do ot X overlap (the first nearest w/o issue) """ # firtst create an index for hor neighbours lNBNeighboursNextCol=collections.defaultdict(list) lNBNeighboursPrevCol=collections.defaultdict(list) for cell in table.getCells(): # get next col icol = cell.getIndex()[1] if icol < table.getNbColumns()-1: nextColCells=table.getColumns()[icol+1].getCells() sorted(nextColCells,key=lambda x:x.getY()) lHOverlap= [] [lHOverlap.append(c) for c in nextColCells if cell.signedRatioOverlapY(c)> 1] # if no overlap: take icol + 2 lNBNeighboursNextCol[cell].extend(lHOverlap) if icol > 1: prevColCells=table.getColumns()[icol-1].getCells() sorted(prevColCells,key=lambda x:x.getY()) lHOverlap= [] [lHOverlap.append(c) for c in prevColCells if cell.signedRatioOverlapY(c)> 1] # if not overlap take icol-2 lNBNeighboursPrevCol[cell].extend(lHOverlap) lcovered=[] for icol,col in enumerate(table.getColumns()): sortedC = sorted(col.getCells(),key=lambda x:x.getY()) for cell in sortedC: if len(lNBNeighboursNextCol[cell]) < 2 and len(lNBNeighboursPrevCol[cell]) < 2: if cell not in lcovered: print(type(cell.getContent())) print ('START :', icol,cell, cell.getContent(),cell.getY(),cell.getY2()) lcovered.append(cell) lcurRow = [cell] iicol=icol curCell = cell while iicol < table.getNbColumns()-1: nextColCells=table.getColumns()[iicol+1].getCells() sorted(nextColCells,key=lambda x:x.getY()) for c in nextColCells: if len(lNBNeighboursNextCol[c]) < 2 and len(lNBNeighboursPrevCol[c]) < 2: if curCell.signedRatioOverlapY(c) > 0.25 * curCell.getHeight(): lcovered.append(c) lcurRow.append(c) print (curCell, curCell.getY(),curCell.getHeight(),c, curCell.signedRatioOverlapY(c),c.getY(), c.getHeight(),list(map(lambda x:x.getContent(),lcurRow))) curCell = c iicol +=1 print ("FINAL", list(map(lambda x:(x,x.getContent()),lcurRow)) ) print ("\t", list(map(lambda x:x.getIndex(),lcurRow)) ) if len(lcurRow)>1: # create a contour for visualization # order by col: get top and bottom polylines for them contour = self.createContourFromListOfElements(lcurRow) spoints = ','.join("%s,%s"%(x[0],x[1]) for x in contour) r = XMLDSTABLEROWClass(1) r.setParent(table) r.addAttribute('points',spoints) r.tagMe('HH') # def mergeHorizontalTextLines(self,table): # """ # merge text lines which are aligned # input: a table, with candidate textlines # output: cluster of textlines as row candidates # # """ # from shapely.geometry import Polygon as pp # from rtree import index # # cellidx = index.Index() # lTexts = [] # lPText=[] # lReverseIndex = {} # # Populate R-tree index with bounds of grid cells # it=0 # for cell in table.getCells(): # for text in cell.getObjects(): # tt = pp( [(text.getX(),text.getY()),(text.getX2(),text.getY()),(text.getX2(),text.getY2()), ((text.getX(),text.getY2()))] ) # lTexts.append(text) # lPText.append(tt) # cellidx.insert(it, tt.bounds) # it += 1 # lReverseIndex[tt.bounds] = text # # lcovered=[] # lfulleval= [] # for text in lTexts: # if text not in lcovered: # # print ('START :', text, text.getContent()) # lcovered.append(text) # lcurRow = [text] # curText= text # while curText is not None: # # print (curText, lcurRow) # # sPoints = text.getAttribute('points') # sPoints = curText.getAttribute('blpoints') # # print (sPoints) # # modify for creating aline to the right # # take the most right X # lastx,lasty = list([(float(x),float(y)) for x,y in zip(*[iter(sPoints.split(','))]*2)])[-1] # # polytext = pp([(float(x),float(y)) for x,y in zip(*[iter(sPoints.split(','))]*2)]) # polytext = pp([(lastx,lasty-10),(lastx+1000,lasty-10),(lastx+1000,lasty),(lastx,lasty)]) # # print([(lastx,lasty-10),(lastx+1000,lasty-10),(lastx+1000,lasty),(lastx,lasty)]) # ltover = [lPText[pos] for pos in cellidx.intersection(polytext.bounds)] # ltover.sort(key=lambda x:x.centroid.coords[0]) # lnextStep=[] # # print ('\tnext\t',list(map(lambda x:lReverseIndex[x.bounds].getContent(),ltover))) # # for t1 in ltover: # # here conditions: vertical porjection and Y overlap ; not area! # if polytext.intersection(t1).area > 0.1: #t1.area*0.5: # if t1 not in lnextStep and lReverseIndex[t1.bounds] not in lcovered: # lnextStep.append(t1) # if lnextStep != []: # lnextStep.sort(key=lambda x:x.centroid.coords[0]) # # print ('\t',list(map(lambda x:(lReverseIndex[x.bounds].getX(),lReverseIndex[x.bounds].getContent()),lnextStep))) # nextt = lnextStep[0] # lcurRow.append(lReverseIndex[nextt.bounds]) # lcovered.append(lReverseIndex[nextt.bounds]) # curText = lReverseIndex[nextt.bounds] # else:curText = None # # # print ("FINAL", list(map(lambda x:(x,x.getContent()),lcurRow)) ) # # print ("FINAL", list(map(lambda x:(x,x.getParent()),lcurRow)) ) # lfulleval.append(self.comptureClusterHomogeneity(lcurRow,0)) # # if len(lcurRow)>1: # # create a contour for visualization # # order by col: get top and bottom polylines for them # contour = self.createContourFromListOfElements(lcurRow) # spoints = ','.join("%s,%s"%(x[0],x[1]) for x in contour) # r = XMLDSTABLEROWClass(1) # r.setParent(table) # r.addAttribute('points',spoints) # r.tagMe('VV') # r.tagMe() # # print (sum(lfulleval)/len(lfulleval)) def mergeHorVerTextLines(self,table): """ build HV lines """ from util import TwoDNeighbourhood as TwoDRel lTexts = [] if self.bNoTable: lTexts = table.getAllNamedObjects(XMLDSTEXTClass) else: for cell in table.getCells(): # bug to be fixed!! if cell.getRowSpan() == 1 and cell.getColSpan() == 1: lTexts.extend(set(cell.getObjects())) for e in lTexts: e.lright=[] e.lleft=[] e.ltop=[] e.lbottom=[] lVEdge = TwoDRel.findVerticalNeighborEdges(lTexts) for a,b in lVEdge: a.lbottom.append( b ) b.ltop.append(a) for elt in lTexts: # dirty! elt.setHeight(max(5,elt.getHeight()-3)) elt.setWidth(max(5,elt.getWidth()-3)) TwoDRel.rotateMinus90degOLD(elt) lHEdge = TwoDRel.findVerticalNeighborEdges(lTexts) for elt in lTexts: # elt.tagMe() TwoDRel.rotatePlus90degOLD(elt) # return for a,b in lHEdge: a.lright.append( b ) b.lleft.append(a) # ss for elt in lTexts: elt.lleft.sort(key = lambda x:x.getX(),reverse=True) # elt.lright.sort(key = lambda x:x.getX()) if len(elt.lright) > 1: elt.lright = [] elt.lright.sort(key = lambda x:elt.signedRatioOverlapY(x),reverse=True) # print (elt, elt.getY(), elt.lright) elt.ltop.sort(key = lambda x:x.getY()) if len(elt.lbottom) >1: elt.lbottom = [] elt.lbottom.sort(key = lambda x:elt.signedRatioOverlapX(x),reverse=True) # Horizontal lTexts.sort(key = lambda x:x.getX()) lcovered=[] lfulleval = [] for text in lTexts: if text not in lcovered: # print ('START :', text, text.getContent()) lcovered.append(text) lcurRow = [text] curText= text while curText is not None: try: nextT = curText.lright[0] # print ('\t',[(x,curText.signedRatioOverlapY(x)) for x in curText.lright]) if nextT not in lcovered: lcurRow.append(nextT) lcovered.append(nextT) curText = nextT except IndexError:curText = None # print ("FINAL", list(map(lambda x:(x,x.getContent()),lcurRow)) ) # lfulleval.append(self.comptureClusterHomogeneity(lcurRow,0)) if len(lcurRow) > 1: # create a contour for visualization # order by col: get top and bottom polylines for them contour = self.createContourFromListOfElements(lcurRow) if contour is not None: spoints = ','.join("%s,%s"%(x[0],x[1]) for x in contour) r = XMLDSTABLEROWClass(1) r.setParent(table) r.addAttribute('points',spoints) r.tagMe('HH') # print (sum(lfulleval)/len(lfulleval)) # Vertical lTexts.sort(key = lambda x:x.getY()) lcovered=[] lfulleval = [] for text in lTexts: if text not in lcovered: # print ('START :', text, text.getContent()) lcovered.append(text) lcurCol = [text] curText= text while curText is not None: try: nextT = curText.lbottom[0] # print ('\t',[(x,curText.signedRatioOverlapY(x)) for x in curText.lright]) if nextT not in lcovered and len(nextT.lbottom) == 1: lcurCol.append(nextT) lcovered.append(nextT) curText = nextT except IndexError:curText = None # print ("FINAL", list(map(lambda x:(x,x.getContent()),lcurCol)) ) # lfulleval.append(self.comptureClusterHomogeneity(lcurCol,1)) if len(lcurCol)>1: # create a contour for visualization # order by col: get top and bottom polylines for them contour = self.createContourFromListOfElements(lcurCol) if contour is not None: spoints = ','.join("%s,%s"%(x[0],x[1]) for x in contour) r = XMLDSTABLEROWClass(1) r.setParent(table) r.addAttribute('points',spoints) # r.setDimensions(...) r.tagMe('VV') # print (sum(lfulleval)/len(lfulleval)) def mergeHorVerCells(self,table): """ build HV chunks cells """ from util import TwoDNeighbourhood as TwoDRel lTexts = [] for cell in table.getCells(): # bug to be fixed!! if cell.getRowSpan() == 1 and cell.getColSpan() == 1: # lTexts.extend(set(cell.getObjects())) lTexts.append(cell) for e in lTexts: e.lright=[] e.lleft=[] e.ltop=[] e.lbottom=[] lVEdge = TwoDRel.findVerticalNeighborEdges(lTexts) for a,b in lVEdge: a.lbottom.append( b ) b.ltop.append(a) for elt in lTexts: # dirty! elt.setHeight(max(5,elt.getHeight()-3)) elt.setWidth(max(5,elt.getWidth()-3)) TwoDRel.rotateMinus90degOLD(elt) lHEdge = TwoDRel.findVerticalNeighborEdges(lTexts) for elt in lTexts: # elt.tagMe() TwoDRel.rotatePlus90degOLD(elt) # return for a,b in lHEdge: a.lright.append( b ) b.lleft.append(a) # ss for elt in lTexts: elt.lleft.sort(key = lambda x:x.getX(),reverse=True) # elt.lright.sort(key = lambda x:x.getX()) elt.lright.sort(key = lambda x:elt.signedRatioOverlapY(x),reverse=True) if len(elt.lright) >1: elt.lright = [] # print (elt, elt.getY(), elt.lright) elt.ltop.sort(key = lambda x:x.getY()) elt.lbottom.sort(key = lambda x:elt.signedRatioOverlapX(x),reverse=True) # Horizontal lTexts.sort(key = lambda x:x.getX()) lcovered=[] lfulleval = [] for text in lTexts: if text not in lcovered: # print ('START :', text, text.getContent()) lcovered.append(text) lcurRow = [text] curText= text while curText is not None: try: nextT = curText.lright[0] # print ('\t',[(x,curText.signedRatioOverlapY(x)) for x in curText.lright]) if nextT not in lcovered: lcurRow.append(nextT) lcovered.append(nextT) curText = nextT except IndexError:curText = None print ("FINAL", list(map(lambda x:(x,x.getContent()),lcurRow)) ) # lfulleval.append(self.comptureClusterHomogeneity(lcurRow,0)) if len(lcurRow) > 1: # create a contour for visualization # order by col: get top and bottom polylines for them contour = self.createContourFromListOfElements(lcurRow) if contour is not None: spoints = ','.join("%s,%s"%(x[0],x[1]) for x in contour) r = XMLDSTABLEROWClass(1) r.setParent(table) r.addAttribute('points',spoints) r.tagMe('HH') # print (sum(lfulleval)/len(lfulleval)) # # Vertical # lTexts.sort(key = lambda x:x.getY()) # lcovered=[] # lfulleval = [] # for text in lTexts: # if text not in lcovered: # # print ('START :', text, text.getContent()) # lcovered.append(text) # lcurCol = [text] # curText= text # while curText is not None: # try: # nextT = curText.lbottom[0] # # print ('\t',[(x,curText.signedRatioOverlapY(x)) for x in curText.lright]) # if nextT not in lcovered: # lcurCol.append(nextT) # lcovered.append(nextT) # curText = nextT # except IndexError:curText = None # # # print ("FINAL", list(map(lambda x:(x,x.getContent()),lcurRow)) ) # lfulleval.append(self.comptureClusterHomogeneity(lcurCol,1)) # if len(lcurCol)>1: # # create a contour for visualization # # order by col: get top and bottom polylines for them # contour = self.createContourFromListOfElements(lcurCol) # if contour is not None: # spoints = ','.join("%s,%s"%(x[0],x[1]) for x in contour) # r = XMLDSTABLEROWClass(1) # r.setParent(table) # r.addAttribute('points',spoints) # r.tagMe('VV') # print (sum(lfulleval)/len(lfulleval)) def createContourFromListOfElements(self, lElts): """ create a polyline from a list of elements input : list of elements output: Polygon object """ from shapely.geometry import Polygon as pp from shapely.ops import cascaded_union lP = [] for elt in lElts: sPoints = elt.getAttribute('points') if sPoints is None: lP.append(pp([(elt.getX(),elt.getY()),(elt.getX(),elt.getY2()), (elt.getX2(),elt.getY2()),(elt.getX2(),elt.getY())] )) else: lP.append(pp([(float(x),float(y)) for x,y in zip(*[iter(sPoints.split(','))]*2)])) try:ss = cascaded_union(lP) except ValueError: # print(lElts,lP) return None if not ss.is_empty: return list(ss.convex_hull.exterior.coords) else: return None def comptureClusterHomogeneity(self,c,dir): """ % of elements belonging to the same structre dir: 0 : row, 1 column """ ldict = collections.defaultdict(list) [ ldict[elt.getParent().getIndex()[dir]].append(elt) for elt in c] lstat = ([(k,len(ldict[k])) for k in ldict]) total = sum([x[1] for x in lstat]) leval = (max(([len(ldict[x])/total for x in ldict]))) return leval def findRowsInDoc(self,ODoc): """ find rows for each table in document input: a document output: a document where tables have rows """ from tasks.TwoDChunking import TwoDChunking self.lPages = ODoc.getPages() # hchk = TwoDChunking() # not always? # self.mergeLineAndCells(self.lPages) for page in self.lPages: traceln("page: %d" % page.getNumber()) # print (len(page.getAllNamedObjects(XMLDSTABLECELLClass))) lTables = page.getAllNamedObjects(XMLDSTABLEClass) for table in lTables: # col as polygon self.getPolylinesForRowsColumns(table) # self.getPolylinesForRows(table) # rowscuts = list(map(lambda r:r.getY(),table.getRows())) rowscuts=[] # traceln ('initial cuts:',rowscuts) self.createCells(table) # lhchk = hchk.HorizonalChunk(page,lElts=table.getCells()) # hchk.VerticalChunk(page,tag=XMLDSTEXTClass) # self.mergeHorizontalCells(table) # then merge overlaping then sort Y and index : then insert ambiguous textlines # self.mergeHorizontalTextLines(table) # self.mergeHorVerTextLines(table) # self.processRows3(table) if self.bCellOnly: continue # self.mergeHorizontalCells(table) # self.mergeHorVerCells(table) self.processRows(table,rowscuts) # self.mineTableRowPattern(table) table.tagMe() if self.bNoTable: self.mergeHorVerTextLines(page) # def extendLines(self,table): # """ # Extend textlines up to table width using baseline # input:table # output: table with extended baselines # """ # for col in table.getColumns(): # for cell in col.getCells(): # for elt in cell.getObjects(): # if elt.getWidth()> 100: # #print ([ (x.getObjects()[0].getBaseline().getY(),x.getObjects()[0].getBaseline().getAngle(),x.getY()) for x in xordered]) # print (elt,elt.getBaseline().getAngle(), elt.getBaseline().getBx(),elt.getBaseline().getPoints()) # newBl = [(table.getX(),elt.getBaseline().getAngle()* table.getX() + elt.getBaseline().getBx()), # (table.getX2(),elt.getBaseline().getAngle()* table.getX2() + elt.getBaseline().getBx()) # ] # elt.getBaseline().setPoints(newBl) # myPoints = '%f,%f,%f,%f'%(newBl[0][0],newBl[0][1],newBl[1][0],newBl[1][1]) # elt.addAttribute('blpoints',myPoints) # sys.exit(0) def getPolylinesForRowsColumns(self,table): """ input: list of cells (=table) output: columns defined by polylines (not Bounding box) """ import numpy as np from util.Polygon import Polygon from shapely.geometry import Polygon as pp # from shapely.ops import cascaded_union from rtree import index cellidx = index.Index() lCells = [] lReverseIndex = {} # Populate R-tree index with bounds of grid cells for pos, cell in enumerate(table.getCells()): # assuming cell is a shapely object cc = pp( [(cell.getX(),cell.getY()),(cell.getX2(),cell.getY()),(cell.getX2(),cell.getY2()), ((cell.getX(),cell.getY2()))] ) lCells.append(cc) cellidx.insert(pos, cc.bounds) lReverseIndex[cc.bounds] = cell dColSep_lSgmt = collections.defaultdict(list) dRowSep_lSgmt = collections.defaultdict(list) for cell in table.getCells(): row, col, rowSpan, colSpan = [int(cell.getAttribute(sProp)) for sProp \ in ["row", "col", "rowSpan", "colSpan"] ] sPoints = cell.getAttribute('points') #.replace(',',' ') # print (cell,sPoints) spoints = ' '.join("%s,%s"%((x,y)) for x,y in zip(*[iter(sPoints.split(','))]*2)) it_sXsY = (sPair.split(',') for sPair in spoints.split(' ')) plgn = Polygon((float(sx), float(sy)) for sx, sy in it_sXsY) # print (plgn.getBoundingBox(),spoints) try: lT, lR, lB, lL = plgn.partitionSegmentTopRightBottomLeft() #now the top segments contribute to row separator of index: row dRowSep_lSgmt[row].extend(lT) dRowSep_lSgmt[row+rowSpan].extend(lB) dColSep_lSgmt[col].extend(lL) dColSep_lSgmt[col+colSpan].extend(lR) except ValueError: pass #now make linear regression to draw relevant separators def getX(lSegment): lX = list() for x1,y1,x2,y2 in lSegment: lX.append(x1) lX.append(x2) return lX def getY(lSegment): lY = list() for x1,y1,x2,y2 in lSegment: lY.append(y1) lY.append(y2) return lY prevx1 , prevx2 , prevymin , prevymax = None,None,None,None #table.getX(),table.getX(),table.getY(),table.getY2() # erase columns: table.eraseColumns() icmpt=0 for icol, lSegment in sorted(dColSep_lSgmt.items()): X = getX(lSegment) Y = getY(lSegment) #sum(l,()) lfNorm = [np.linalg.norm([[x1,y1], [x2,y2]]) for x1,y1,x2,y2 in lSegment] #duplicate each element W = [fN for fN in lfNorm for _ in (0,1)] # a * x + b a, b = np.polynomial.polynomial.polyfit(Y, X, 1, w=W) ymin, ymax = min(Y), max(Y) x1 = a + b * ymin x2 = a + b * ymax if prevx1: col = XMLDSTABLECOLUMNClass() col.setPage(table.getPage()) col.setParent(table) col.setIndex(icmpt) icmpt+=1 table.addColumn(col) col.addAttribute('points',"%s,%s %s,%s,%s,%s %s,%s"%(prevx1, prevymin,x1, ymin, x2, ymax, prevx2, prevymax)) col.setX(prevx1) col.setY(prevymin) col.setHeight(ymax- ymin) col.setWidth(x2-prevx1) col.tagMe() # from shapely.geometry import Polygon as pp polycol = pp([(prevx1, prevymin),(x1, ymin), (x2, ymax), (prevx2, prevymax)] ) # print ((prevx1, prevymin),(x1, ymin), (x2, ymax), (prevx2, prevymax)) # colCells = cascaded_union([cells[pos] for pos in cellidx.intersection(polycol.bounds)]) colCells = [lCells[pos] for pos in cellidx.intersection(polycol.bounds)] for cell in colCells: try: if polycol.intersection(cell).area > cell.area*0.5: col.addCell(lReverseIndex[cell.bounds]) except: pass prevx1 , prevx2 , prevymin , prevymax = x1, x2, ymin, ymax def getPolylinesForRows(self,table): """ input: list of candidate cells (=table) output: "rows" defined by top polylines """ import numpy as np from util.Polygon import Polygon from shapely.geometry import Polygon as pp # from shapely.ops import cascaded_union from rtree import index cellidx = index.Index() lCells = [] lReverseIndex = {} # Populate R-tree index with bounds of grid cells for pos, cell in enumerate(table.getCells()): # assuming cell is a shapely object cc = pp( [(cell.getX(),cell.getY()),(cell.getX2(),cell.getY()),(cell.getX2(),cell.getY2()), ((cell.getX(),cell.getY2()))] ) lCells.append(cc) cellidx.insert(pos, cc.bounds) lReverseIndex[cc.bounds] = cell dColSep_lSgmt = collections.defaultdict(list) dRowSep_lSgmt = collections.defaultdict(list) for cell in table.getCells(): row, col, rowSpan, colSpan = [int(cell.getAttribute(sProp)) for sProp \ in ["row", "col", "rowSpan", "colSpan"] ] sPoints = cell.getAttribute('points') #.replace(',',' ') # print (cell,sPoints) spoints = ' '.join("%s,%s"%((x,y)) for x,y in zip(*[iter(sPoints.split(','))]*2)) it_sXsY = (sPair.split(',') for sPair in spoints.split(' ')) plgn = Polygon((float(sx), float(sy)) for sx, sy in it_sXsY) # print (plgn.getBoundingBox(),spoints) try: lT, lR, lB, lL = plgn.partitionSegmentTopRightBottomLeft() #now the top segments contribute to row separator of index: row dRowSep_lSgmt[row].extend(lT) dRowSep_lSgmt[row+rowSpan].extend(lB) dColSep_lSgmt[col].extend(lL) dColSep_lSgmt[col+colSpan].extend(lR) except ValueError: pass #now make linear regression to draw relevant separators def getX(lSegment): lX = list() for x1,y1,x2,y2 in lSegment: lX.append(x1) lX.append(x2) return lX def getY(lSegment): lY = list() for x1,y1,x2,y2 in lSegment: lY.append(y1) lY.append(y2) return lY prevxmin , prevxmax , prevy1 , prevy2 = None,None,None,None #table.getX(),table.getX(),table.getY(),table.getY2() # erase columns: table.eraseColumns() icmpt=0 for _, lSegment in sorted(dRowSep_lSgmt.items()): X = getX(lSegment) Y = getY(lSegment) #sum(l,()) lfNorm = [np.linalg.norm([[x1,y1], [x2,y2]]) for x1,y1,x2,y2 in lSegment] #duplicate each element W = [fN for fN in lfNorm for _ in (0,1)] # a * x + b a, b = np.polynomial.polynomial.polyfit(X, Y, 1, w=W) xmin, xmax = min(X), max(X) y1 = a + b * xmin y2 = a + b * xmax if prevy1: col = XMLDSTABLEROWClass(icmpt) col.setPage(table.getPage()) col.setParent(table) icmpt+=1 table.addColumn(col) # prevx1, prevymin,x1, ymin, x2, ymax, prevx2, prevymax)) col.addAttribute('points',"%s,%s %s,%s,%s,%s %s,%s"%(prevxmin, prevy1, prevxmax,prevy2, xmax,y2, prevxmax,y1)) col.setX(prevxmin) col.setY(prevy1) col.setHeight(y2 - prevy1) col.setWidth(xmax- xmin) col.tagMe() # from shapely.geometry import Polygon as pp # polycol = pp([(prevx1, prevymin),(x1, ymin), (x2, ymax), (prevx2, prevymax)] ) # # print ((prevx1, prevymin),(x1, ymin), (x2, ymax), (prevx2, prevymax)) # # colCells = cascaded_union([cells[pos] for pos in cellidx.intersection(polycol.bounds)]) # colCells = [lCells[pos] for pos in cellidx.intersection(polycol.bounds)] # for cell in colCells: # if polycol.intersection(cell).area > cell.area*0.5: # col.addCell(lReverseIndex[cell.bounds]) prevy1 , prevy2 , prevxmin , prevxmax = y1, y2, xmin, xmax for cell in table.getCells(): del cell._lAttributes['points'] def testscale(self,ltexts): return for t in ltexts: if True or t.getAttribute('id')[-4:] == '1721': # print (t) # print (etree.tostring(t.getNode())) shrinked = affinity.scale(t.toPolygon(),3,-0.8) # print (list(t.toPolygon().exterior.coords), list(shrinked.exterior.coords)) ss = ",".join(["%s,%s"%(x,y) for x,y in shrinked.exterior.coords]) # print (ss) t.getNode().set("points",ss) # print (etree.tostring(t.getNode())) def testshapely(self,Odoc): for page in Odoc.lPages: self.testscale(page.getAllNamedObjects(XMLDSTEXTClass)) traceln("page: %d" % page.getNumber()) # lTables = page.getAllNamedObjects(XMLDSTABLEClass) # for table in lTables: # table.testPopulate() def run(self,doc): """ load dom and find rows """ # conver to DS if needed if self.bCreateRef: if self.do2DS: dsconv = primaAnalysis() doc = dsconv.convert2DS(doc,self.docid) refdoc = self.createRef(doc) return refdoc # single ref per page # refdoc= self.createRefPerPage(doc) # return None if self.bCreateRefCluster: if self.do2DS: dsconv = primaAnalysis() doc = dsconv.convert2DS(doc,self.docid) # refdoc = self.createRefCluster(doc) refdoc = self.createRefPartition(doc) return refdoc if self.do2DS: dsconv = primaAnalysis() self.doc = dsconv.convert2DS(doc,self.docid) else: self.doc= doc self.ODoc = XMLDSDocument() self.ODoc.loadFromDom(self.doc,listPages = range(self.firstPage,self.lastPage+1)) # self.testshapely(self.ODoc) # # self.ODoc.loadFromDom(self.doc,listPages = range(30,31)) if self.bYCut: self.processYCuts(self.ODoc) else: self.findRowsInDoc(self.ODoc) return self.doc def computeCoherenceScore(self,table): """ input: table with rows, BIEOS tagged textlines BIO now ! output: coherence score coherence score: float percentage of textlines those BIESO tagged is 'coherent with the row segmentation' """ coherenceScore = 0 nbTotalTextLines = 0 for row in table.getRows(): for cell in row.getCells(): nbTextLines = len(cell.getObjects()) nbTotalTextLines += nbTextLines if nbTextLines == 1 and cell.getObjects()[0].getAttribute("DU_row") == self.STAG: coherenceScore+=1 else: for ipos, textline in enumerate(cell.getObjects()): if ipos == 0: if textline.getAttribute("DU_row") in [self.BTAG]: coherenceScore += 1 else: if textline.getAttribute("DU_row") in ['I']: coherenceScore += 1 # if ipos == nbTextLines-1: # if textline.getAttribute("DU_row") in ['E']: coherenceScore += 1 # if ipos not in [0, nbTextLines-1]: # if textline.getAttribute("DU_row") in ['I']: coherenceScore += 1 if nbTotalTextLines == 0: return 0 else : return coherenceScore /nbTotalTextLines ################ TEST ################## def testRun(self, filename, outFile=None): """ evaluate using ABP new table dataset with tablecell """ self.evalData=None doc = self.loadDom(filename) doc =self.run(doc) if self.bEvalCluster: self._evalData = self.createRunPartition( self.ODoc) # self.evalData = self.createRefCluster(doc) else: self.evalData = self.createRef(doc) if outFile: self.writeDom(doc) return etree.tostring(self._evalData,encoding='unicode',pretty_print=True) def testCluster(self, srefData, srunData, bVisual=False): """ <DOCUMENT> <PAGE number="1" imageFilename="g" width="1457.52" height="1085.04"> <TABLE x="120.72" y="90.72" width="1240.08" height="923.28"> <ROW> <TEXT id="line_1502076498510_2209"/> <TEXT id="line_1502076500291_2210"/> <TEXT id="line_1502076502635_2211"/> <TEXT id="line_1502076505260_2212"/> NEED to work at page level !!?? then average? """ cntOk = cntErr = cntMissed = 0 RefData = etree.XML(srefData.strip("\n").encode('utf-8')) RunData = etree.XML(srunData.strip("\n").encode('utf-8')) lPages = RefData.xpath('//%s' % ('PAGE[@number]')) lRefKeys={} dY = {} lY={} dIDMap={} for page in lPages: pnum=page.get('number') key=page.get('pagekey') dIDMap[key]={} lY[key]=[] dY[key]={} xpath = ".//%s" % ("R") lrows = page.xpath(xpath) if len(lrows) > 0: for i,row in enumerate(lrows): xpath = ".//@id" lids = row.xpath(xpath) for id in lids: # with spanning an element can belong to several rows? if id not in dY[key]: dY[key][id]=i lY[key].append(i) dIDMap[key][id]=len(lY[key])-1 try:lRefKeys[key].append((pnum,key,lids)) except KeyError:lRefKeys[key] = [(pnum,key,lids)] rand_score = completeness = homogen_score = 0 if RunData is not None: lpages = RunData.xpath('//%s' % ('PAGE[@number]')) for page in lpages: pnum=page.get('number') key=page.get('pagekey') if key in lRefKeys: lX=[-1 for i in range(len(dIDMap[key]))] xpath = ".//%s" % ("ROW") lrows = page.xpath(xpath) if len(lrows) > 0: for i,row in enumerate(lrows): xpath = ".//@id" lids = row.xpath(xpath) for id in lids: lX[ dIDMap[key][id]] = i #adjusted_rand_score(ref,run) rand_score += adjusted_rand_score(lY[key],lX) completeness += completeness_score(lY[key], lX) homogen_score += homogeneity_score(lY[key], lX) ltisRefsRunbErrbMiss= list() return (rand_score/len(lRefKeys), completeness/len(lRefKeys), homogen_score/len(lRefKeys),ltisRefsRunbErrbMiss) def testGeometry(self, th, srefData, srunData, bVisual=False): """ compare geometrical zones (dtw + iou) :param returns tuple (cntOk, cntErr, cntMissed,ltisRefsRunbErrbMiss """ cntOk = cntErr = cntMissed = 0 ltisRefsRunbErrbMiss = list() RefData = etree.XML(srefData.strip("\n").encode('utf-8')) RunData = etree.XML(srunData.strip("\n").encode('utf-8')) lPages = RefData.xpath('//%s' % ('PAGE[@number]')) for ip,page in enumerate(lPages): lY=[] key=page.get('pagekey') xpath = ".//%s" % ("ROW") lrows = page.xpath(xpath) if len(lrows) > 0: for col in lrows: xpath = ".//@points" lpoints = col.xpath(xpath) colgeo = cascaded_union([ Polygon(sPoints2tuplePoints(p)) for p in lpoints]) if lpoints != []: lY.append(colgeo) if RunData is not None: lpages = RunData.xpath('//%s' % ('PAGE[@pagekey="%s"]' % key)) lX=[] if lpages != []: for page in lpages[0]: xpath = ".//%s" % ("ROW") lrows = page.xpath(xpath) if len(lrows) > 0: for col in lrows: xpath = ".//@points" lpoints = col.xpath(xpath) if lpoints != []: lX.append( Polygon(sPoints2tuplePoints(lpoints[0]))) lX = list(filter(lambda x:x.is_valid,lX)) ok , err , missed,lfound,lerr,lmissed = evalPartitions(lX, lY, th,iuo) cntOk += ok cntErr += err cntMissed +=missed [ltisRefsRunbErrbMiss.append((ip, y1.bounds, x1.bounds,False, False)) for (x1,y1) in lfound] [ltisRefsRunbErrbMiss.append((ip, y1.bounds, None,False, True)) for y1 in lmissed] [ltisRefsRunbErrbMiss.append((ip, None, x1.bounds,True, False)) for x1 in lerr] # ltisRefsRunbErrbMiss.append(( lfound, ip, ok,err, missed)) # print (key, cntOk , cntErr , cntMissed) return (cntOk , cntErr , cntMissed,ltisRefsRunbErrbMiss) def testCluster2(self, th, srefData, srunData, bVisual=False): """ <DOCUMENT> <PAGE number="1" imageFilename="g" width="1457.52" height="1085.04"> <TABLE x="120.72" y="90.72" width="1240.08" height="923.28"> <ROW> <TEXT id="line_1502076498510_2209"/> <TEXT id="line_1502076500291_2210"/> <TEXT id="line_1502076502635_2211"/> <TEXT id="line_1502076505260_2212"/> NEED to work at page level !!?? then average? """ RefData = etree.XML(srefData.strip("\n").encode('utf-8')) RunData = etree.XML(srunData.strip("\n").encode('utf-8')) lPages = RefData.xpath('//%s' % ('PAGE[@number]')) for page in lPages: lY=[] key=page.get('pagekey') xpath = ".//%s" % ("ROW") lrows = page.xpath(xpath) if len(lrows) > 0: for row in lrows: xpath = ".//@id" lid = row.xpath(xpath) if lid != []: lY.append(lid) # print (row.xpath(xpath)) if RunData is not None: lpages = RunData.xpath('//%s' % ('PAGE[@pagekey="%s"]' % key)) lX=[] for page in lpages[:1]: xpath = ".//%s" % ("ROW") lrows = page.xpath(xpath) if len(lrows) > 0: for row in lrows: xpath = ".//@id" lid = row.xpath(xpath) if lid != []: lX.append( lid) cntOk , cntErr , cntMissed,lf,le,lm = evalPartitions(lX, lY, th,jaccard) # print ( cntOk , cntErr , cntMissed) ltisRefsRunbErrbMiss= list() return (cntOk , cntErr , cntMissed,ltisRefsRunbErrbMiss) def overlapX(self,zone): [a1,a2] = self.getX(),self.getX()+ self.getWidth() [b1,b2] = zone.getX(),zone.getX()+ zone.getWidth() return min(a2, b2) >= max(a1, b1) def overlapY(self,zone): [a1,a2] = self.getY(),self.getY() + self.getHeight() [b1,b2] = zone.getY(),zone.getY() + zone.getHeight() return min(a2, b2) >= max(a1, b1) def signedRatioOverlap(self,z1,z2): """ overlap self and zone return surface of self in zone """ [x1,y1,h1,w1] = z1.getX(),z1.getY(),z1.getHeight(),z1.getWidth() [x2,y2,h2,w2] = z2.getX(),z2.getY(),z2.getHeight(),z2.getWidth() fOverlap = 0.0 if self.overlapX(z2) and self.overlapY(z2): [x11,y11,x12,y12] = [x1,y1,x1+w1,y1+h1] [x21,y21,x22,y22] = [x2,y2,x2+w2,y2+h2] s1 = w1 * h1 # possible ? if s1 == 0: s1 = 1.0 #intersection nx1 = max(x11,x21) nx2 = min(x12,x22) ny1 = max(y11,y21) ny2 = min(y12,y22) h = abs(nx2 - nx1) w = abs(ny2 - ny1) inter = h * w if inter > 0 : fOverlap = inter/s1 else: # if overX and Y this is not possible ! fOverlap = 0.0 return fOverlap def findSignificantOverlap(self,TOverlap,ref,run): """ return """ pref,rowref= ref prun, rowrun= run if pref != prun: return False return rowref.ratioOverlap(rowrun) >=TOverlap def testCPOUM(self, TOverlap, srefData, srunData, bVisual=False): """ TOverlap: Threshols used for comparing two surfaces Correct Detections: under and over segmentation? """ cntOk = cntErr = cntMissed = 0 RefData = etree.XML(srefData.strip("\n").encode('utf-8')) RunData = etree.XML(srunData.strip("\n").encode('utf-8')) # try: # RunData = libxml2.parseMemory(srunData.strip("\n"), len(srunData.strip("\n"))) # except: # RunData = None # return (cntOk, cntErr, cntMissed) lRun = [] if RunData is not None: lpages = RunData.xpath('//%s' % ('PAGE')) for page in lpages: pnum=page.get('number') #record level! lRows = page.xpath(".//%s" % ("ROW")) lORows = map(lambda x:XMLDSTABLEROWClass(0,x),lRows) for row in lORows: row.fromDom(row._domNode) row.setIndex(row.getAttribute('id')) lRun.append((pnum,row)) # print (lRun) lRef = [] lPages = RefData.xpath('//%s' % ('PAGE')) for page in lPages: pnum=page.get('number') lRows = page.xpath(".//%s" % ("ROW")) lORows = map(lambda x:XMLDSTABLEROWClass(0,x),lRows) for row in lORows: row.fromDom(row._domNode) row.setIndex(row.getAttribute('id')) lRef.append((pnum,row)) refLen = len(lRef) # bVisual = True ltisRefsRunbErrbMiss= list() lRefCovered = [] for i in range(0,len(lRun)): iRef = 0 bFound = False bErr , bMiss= False, False runElt = lRun[i] # print '\t\t===',runElt while not bFound and iRef <= refLen - 1: curRef = lRef[iRef] if runElt and curRef not in lRefCovered and self.findSignificantOverlap(TOverlap,runElt, curRef): bFound = True lRefCovered.append(curRef) iRef+=1 if bFound: if bVisual:print("FOUND:", runElt, ' -- ', lRefCovered[-1]) cntOk += 1 else: curRef='' cntErr += 1 bErr = True if bVisual:print("ERROR:", runElt) if bFound or bErr: ltisRefsRunbErrbMiss.append( (int(runElt[0]), curRef, runElt,bErr, bMiss) ) for i,curRef in enumerate(lRef): if curRef not in lRefCovered: if bVisual:print("MISSED:", curRef) ltisRefsRunbErrbMiss.append( (int(curRef[0]), curRef, '',False, True) ) cntMissed+=1 ltisRefsRunbErrbMiss.sort(key=lambda xyztu:xyztu[0]) # print cntOk, cntErr, cntMissed,ltisRefsRunbErrbMiss return (cntOk, cntErr, cntMissed,ltisRefsRunbErrbMiss) def testCompare(self, srefData, srunData, bVisual=False): """ as in Shahad et al, DAS 2010 Correct Detections Partial Detections Over-Segmented Under-Segmented Missed False Positive """ dicTestByTask = dict() if self.bEvalCluster: # dicTestByTask['CLUSTER']= self.testCluster(srefData,srunData,bVisual) dicTestByTask['CLUSTER100']= self.testCluster2(1.0,srefData,srunData,bVisual) dicTestByTask['CLUSTER90']= self.testCluster2(0.9,srefData,srunData,bVisual) dicTestByTask['CLUSTER80']= self.testCluster2(0.8,srefData,srunData,bVisual) # dicTestByTask['CLUSTER50']= self.testCluster2(0.5,srefData,srunData,bVisual) else: dicTestByTask['T80']= self.testGeometry(0.50,srefData,srunData,bVisual) # dicTestByTask['T50']= self.testCPOUM(0.50,srefData,srunData,bVisual) return dicTestByTask def createRowsWithCuts2(self,table,lYCuts): """ input: lcells, horizontal lcuts output: list of rows populated with appropriate cells (main overlap) Algo: create cell chunks and determine (a,b) for the cut (a.X +b = Y) does not solve everything ("russian mountains" in weddings) """ from tasks.TwoDChunking import TwoDChunking if lYCuts == []: return #reinit rows self._lrows = [] #build horizontal chunks hchk = TwoDChunking() hchk.HorizonalChunk(table.getPage(),tag=XMLDSTABLECELLClass) # #get all texts # lTexts = [] # [ lTexts.extend(colcell.getObjects()) for col in table.getColumns() for colcell in col.getObjects()] # lTexts.sort(lambda x:x.getY()) # # #initial Y: table top border # prevCut = self.getY() # # # ycuts: features or float # try:lYCuts = map(lambda x:x.getValue(),lYCuts) # except:pass # # itext = 0 # irowIndex = 0 # lrowcells = [] # lprevrowcells = [] # prevRowCoherenceScore = 0 # for irow,cut in enumerate(lYCuts): # yrow = prevCut # y2 = cut # h = cut - prevCut # lrowcells =[] # while lTexts[itext].getY() <= cut: # lrowcells.append(lTexts[itext]) # itext += 1 # if lprevrowcells == []: # pass # else: # # a new row: evaluate if this is better to create it or to merge ltext with current row # # check coherence of new texts # # assume columns! # coherence = self.computeCoherenceScoreForRows(lrowcells) # coherenceMerge = self.computeCoherenceScoreForRows(lrowcells+lprevrowcells) # if prevRowCoherenceScore + coherence > coherenceMerge: # cuthere # else: # merge # def createRowsWithCuts(self,lYCuts,table,tableNode,bTagDoc=False): """ REF XML """ prevCut = None # prevCut = table.getY() lYCuts.sort() for index,cut in enumerate(lYCuts): # first correspond to the table: no rpw if prevCut is not None: rowNode= etree.Element("ROW") if bTagDoc: tableNode.append(rowNode) else: tableNode.append(rowNode) rowNode.set('y',str(prevCut)) rowNode.set('height',str(cut - prevCut)) rowNode.set('x',str(table.getX())) rowNode.set('width',str(table.getWidth())) rowNode.set('id',str(index-1)) prevCut= cut #last cut=table.getY2() rowNode= etree.Element("ROW") tableNode.append(rowNode) rowNode.set('y',str(prevCut)) rowNode.set('height',str(cut - prevCut)) rowNode.set('x',str(table.getX())) rowNode.set('width',str(table.getWidth())) rowNode.set('id',str(index)) def createRefCluster(self,doc): """ Ref: a row = set of textlines """ self.ODoc = XMLDSDocument() self.ODoc.loadFromDom(doc,listPages = range(self.firstPage,self.lastPage+1)) root=etree.Element("DOCUMENT") refdoc=etree.ElementTree(root) for page in self.ODoc.getPages(): pageNode = etree.Element('PAGE') pageNode.set("number",page.getAttribute('number')) pageNode.set("pagekey",os.path.basename(page.getAttribute('imageFilename'))) pageNode.set("width",page.getAttribute('width')) pageNode.set("height",page.getAttribute('height')) root.append(pageNode) lTables = page.getAllNamedObjects(XMLDSTABLEClass) for table in lTables: dRows={} tableNode = etree.Element('TABLE') tableNode.set("x",table.getAttribute('x')) tableNode.set("y",table.getAttribute('y')) tableNode.set("width",table.getAttribute('width')) tableNode.set("height",table.getAttribute('height')) pageNode.append(tableNode) for cell in table.getAllNamedObjects(XMLDSTABLECELLClass): try:dRows[int(cell.getAttribute("row"))].extend(cell.getObjects()) except KeyError:dRows[int(cell.getAttribute("row"))] = cell.getObjects() for rowid in sorted(dRows.keys()): rowNode= etree.Element("ROW") tableNode.append(rowNode) for elt in dRows[rowid]: txtNode = etree.Element("TEXT") txtNode.set('id',elt.getAttribute('id')) rowNode.append(txtNode) return refdoc def createRef(self,doc): """ create a ref file from the xml one """ self.ODoc = XMLDSDocument() self.ODoc.loadFromDom(doc,listPages = range(self.firstPage,self.lastPage+1)) root=etree.Element("DOCUMENT") refdoc=etree.ElementTree(root) for page in self.ODoc.getPages(): #imageFilename="..\col\30275\S_Freyung_021_0001.jpg" width="977.52" height="780.0"> pageNode = etree.Element('PAGE') pageNode.set("number",page.getAttribute('number')) pageNode.set("pagekey",os.path.basename(page.getAttribute('imageFilename'))) pageNode.set("width",str(page.getAttribute('width'))) pageNode.set("height",str(page.getAttribute('height'))) root.append(pageNode) lTables = page.getAllNamedObjects(XMLDSTABLEClass) for table in lTables: print (table) dRows={} tableNode = etree.Element('TABLE') tableNode.set("x",str(table.getAttribute('x'))) tableNode.set("y",str(table.getAttribute('y'))) tableNode.set("width",str(table.getAttribute('width'))) tableNode.set("height",str(table.getAttribute('height'))) for cell in table.getAllNamedObjects(XMLDSTABLECELLClass): print (cell) try:dRows[int(cell.getAttribute("row"))].append(cell) except KeyError:dRows[int(cell.getAttribute("row"))] = [cell] lYcuts = [] for rowid in sorted(dRows.keys()): # print rowid, min(map(lambda x:x.getY(),dRows[rowid])) lYcuts.append(min(list(map(lambda x:x.getY(),dRows[rowid])))) if lYcuts != []: pageNode.append(tableNode) self.createRowsWithCuts(lYcuts,table,tableNode) return refdoc def createRefPerPage(self,doc): """ create a ref file from the xml one for DAS 2018 """ self.ODoc = XMLDSDocument() self.ODoc.loadFromDom(doc,listPages = range(self.firstPage,self.lastPage+1)) dRows={} for page in self.ODoc.getPages(): #imageFilename="..\col\30275\S_Freyung_021_0001.jpg" width="977.52" height="780.0"> pageNode = etree.Element('PAGE') # pageNode.set("number",page.getAttribute('number')) #SINGLER PAGE pnum=1 pageNode.set("number",'1') pageNode.set("imageFilename",page.getAttribute('imageFilename')) pageNode.set("width",page.getAttribute('width')) pageNode.set("height",page.getAttribute('height')) root=etree.Element("DOCUMENT") refdoc=etree.ElementTree(root) root.append(pageNode) lTables = page.getAllNamedObjects(XMLDSTABLEClass) for table in lTables: tableNode = etree.Element('TABLE') tableNode.set("x",table.getAttribute('x')) tableNode.set("y",table.getAttribute('y')) tableNode.set("width",table.getAttribute('width')) tableNode.set("height",table.getAttribute('height')) pageNode.append(tableNode) for cell in table.getAllNamedObjects(XMLDSTABLECELLClass): try:dRows[int(cell.getAttribute("row"))].append(cell) except KeyError:dRows[int(cell.getAttribute("row"))] = [cell] lYcuts = [] for rowid in sorted(dRows.keys()): # print rowid, min(map(lambda x:x.getY(),dRows[rowid])) lYcuts.append(min(list(map(lambda x:x.getY(),dRows[rowid])))) self.createRowsWithCuts(lYcuts,table,tableNode) self.outputFileName = os.path.basename(page.getAttribute('imageFilename')[:-3]+'ref') # print(self.outputFileName) self.writeDom(refdoc, bIndent=True) return refdoc # print refdoc.serialize('utf-8', True) # self.testCPOUM(0.5,refdoc.serialize('utf-8', True),refdoc.serialize('utf-8', True)) def createRefPartition(self,doc): """ Ref: a row = set of textlines :param doc: dox xml returns a doc (ref format): each column contains a set of ids (textlines ids) """ self.ODoc = XMLDSDocument() self.ODoc.loadFromDom(doc,listPages = range(self.firstPage,self.lastPage+1)) root=etree.Element("DOCUMENT") refdoc=etree.ElementTree(root) for page in self.ODoc.getPages(): pageNode = etree.Element('PAGE') pageNode.set("number",page.getAttribute('number')) pageNode.set("pagekey",os.path.basename(page.getAttribute('imageFilename'))) pageNode.set("width",str(page.getAttribute('width'))) pageNode.set("height",str(page.getAttribute('height'))) root.append(pageNode) lTables = page.getAllNamedObjects(XMLDSTABLEClass) for table in lTables: dCols={} tableNode = etree.Element('TABLE') tableNode.set("x",table.getAttribute('x')) tableNode.set("y",table.getAttribute('y')) tableNode.set("width",str(table.getAttribute('width'))) tableNode.set("height",str(table.getAttribute('height'))) pageNode.append(tableNode) for cell in table.getAllNamedObjects(XMLDSTABLECELLClass): try:dCols[int(cell.getAttribute("row"))].extend(cell.getObjects()) except KeyError:dCols[int(cell.getAttribute("row"))] = cell.getObjects() for rowid in sorted(dCols.keys()): rowNode= etree.Element("ROW") tableNode.append(rowNode) for elt in dCols[rowid]: txtNode = etree.Element("TEXT") txtNode.set('id',elt.getAttribute('id')) rowNode.append(txtNode) return refdoc def createRunPartition(self,doc): """ Ref: a row = set of textlines :param doc: dox xml returns a doc (ref format): each column contains a set of ids (textlines ids) """ # self.ODoc = doc #XMLDSDocument() # self.ODoc.loadFromDom(doc,listPages = range(self.firstPage,self.lastPage+1)) root=etree.Element("DOCUMENT") refdoc=etree.ElementTree(root) for page in self.ODoc.getPages(): pageNode = etree.Element('PAGE') pageNode.set("number",page.getAttribute('number')) pageNode.set("pagekey",os.path.basename(page.getAttribute('imageFilename'))) pageNode.set("width",str(page.getAttribute('width'))) pageNode.set("height",str(page.getAttribute('height'))) root.append(pageNode) tableNode = etree.Element('TABLE') tableNode.set("x","0") tableNode.set("y","0") tableNode.set("width","0") tableNode.set("height","0") pageNode.append(tableNode) table = page.getAllNamedObjects(XMLDSTABLEClass)[0] lRows = table.getRows() for row in lRows: cNode= etree.Element("ROW") tableNode.append(cNode) for elt in row.getAllNamedObjects(XMLDSTEXTClass): txtNode= etree.Element("TEXT") txtNode.set('id',elt.getAttribute('id')) cNode.append(txtNode) return refdoc if __name__ == "__main__": rdc = RowDetection() #prepare for the parsing of the command line rdc.createCommandLineParser() # rdc.add_option("--coldir", dest="coldir", action="store", type="string", help="collection folder") rdc.add_option("--docid", dest="docid", action="store", type="string", help="document id") rdc.add_option("--dsconv", dest="dsconv", action="store_true", default=False, help="convert page format to DS") rdc.add_option("--createref", dest="createref", action="store_true", default=False, help="create REF file for component") rdc.add_option("--createrefC", dest="createrefCluster", action="store_true", default=False, help="create REF file for component (cluster of textlines)") rdc.add_option("--evalC", dest="evalCluster", action="store_true", default=False, help="evaluation using clusters (of textlines)") rdc.add_option("--cell", dest="bCellOnly", action="store_true", default=False, help="generate cell candidate from BIO (no row)") rdc.add_option("--nocolumn", dest="bNoColumn", action="store_true", default=False, help="no existing table/colunm)") # rdc.add_option("--raw", dest="bRaw", action="store_true", default=False, help="no existing table/colunm)") rdc.add_option("--YC", dest="YCut", action="store_true", default=False, help="use Ycut") rdc.add_option("--BTAG", dest="BTAG", action="store", default='B',type="string", help="BTAG = B or S") rdc.add_option("--STAG", dest="STAG", action="store", default='S',type="string", help="STAG = S or None") rdc.add_option("--thhighsupport", dest="thhighsupport", action="store", type="int", default=33,help="TH for high support", metavar="NN") rdc.add_option('-f',"--first", dest="first", action="store", type="int", help="first page to be processed") rdc.add_option('-l',"--last", dest="last", action="store", type="int", help="last page to be processed") #parse the command line dParams, args = rdc.parseCommandLine() #Now we are back to the normal programmatic mode, we set the component parameters rdc.setParams(dParams) doc = rdc.loadDom() doc = rdc.run(doc) if doc is not None and rdc.getOutputFileName() != '-': rdc.writeDom(doc, bIndent=True)
bsd-3-clause
javert/tftpudGui
src/tftpudgui/qt4/TftpServer_rc.py
1
8206
# -*- coding: utf-8 -*- # Resource object code # # Created: Thu Jan 16 21:53:07 2014 # by: The Resource Compiler for PySide (Qt v4.8.0) # # WARNING! All changes made in this file will be lost! from PySide import QtCore qt_resource_data = "\x00\x00\x05\xda\x89PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\x00\x00\x18\x00\x00\x00\x18\x08\x06\x00\x00\x00\xe0w=\xf8\x00\x00\x00\x04gAMA\x00\x00\xd9\x04\xdc\xb2\xda\x02\x00\x00\x00\x06bKGD\x00\x00\x00\x00\x00\x00\xf9C\xbb\x7f\x00\x00\x00\x09pHYs\x00\x00\x00H\x00\x00\x00H\x00F\xc9k>\x00\x00\x00\x09vpAg\x00\x00\x00\x18\x00\x00\x00\x18\x00xL\xa5\xa6\x00\x00\x04LIDATH\xc7\xed\x94\xcboTU\x1c\xc7?\xe7\xdc;\xf7\xce\xdc\xb9\xf3(3}L;\xa5\xf2\x92B\x0b\x09\x896\x04\x8c\x9a\x881\x8aH0$\xc4\x18\x89q\xa3\xc6\x85+\x13\xc3\x8a\x7f\xc1\x9d\xae4Q\x22\xba\xd2\xb0\xc0W\x5c\xd4(B\xa8\xa0\x16\x1ahah\x85vZK;\xef\xb9w\xee\xbd\xe7\xb8\xe0\x11\x17Fai\xc2'9\xc99\xc9\xef\xf7\xfbl~\xe7\x0b\x0f\xf8\x0f\xc4\xbd\x16\x0e~\x08k\xb2\xa0\x80\xa5UX|\xed>\x05\xa5R\x89z\xb3\x8e\x5cu8R\xd9M\x90Y%\x9f\xecc\xad\xbb\x8dM\xee\x93\xbc:\xf0\x0e|p\xbb\xfeu\xf4{\xbf\x1c\xe5\xd2\xf7\xd7X\x9e\xaaS]h\xd2\xa8\xd4\xa9\xd6\xaaLNN\xfe\xb3\xe0\xd8\xf1c\x8c\xed\x18#\x8a\x05\x8c{\x9f\xf3~\xe9\xa8\xd1\x9312\xd9x\xa6\x90\x8a\xa5\x8b\x093\x99\x8f\x19\x96\x0b\x82H\x07\x8d\xc6bts\xe1\x93\xdc\x8d\xc6\xa4]n\x95\x83\xea\x1b_\xef\xef\x1c\x7f\xeb$\xd5\xe5\x1ag\xce\x9f\xbe+0\xef\x5c\x867\x0f\xa3\xb4\xca(\x9fL\xa9v.>\xd4\x95\xdb\xd5\xed\x14\x9f\xca\xc7\xfbGS\xb15\xbd\x96\x8c'\xa4\x101ED'\xf2\x83TL\xb5\x8da\x96+nk\xba\xb5\xdc9\xfb\xd9\xdb_\xfd\xe87\x82\xc93\xe7\xd5\xca\xf6W\x86\xf8\xed\xe3Y\x00\x0c\x80\xc3'\x0f\xe3L9\xb28X|.\xe6\x98G.\xd4\xce\x1d,\xab\xd2\xa1\xb4\x9d\xdd)\x84.4\xc2\xc5\xd4J\xe7Z|\xb9s\xc5Z\xee\x94\xac\xca\xcaJ\x5cO\xf5\xa6\x92Q\xae\xd7t\xf5\xb0r\xbc]A\xcc{LEj}oO\xe4\xfb\xe9\xfa\x92\xfb\x82\x1b\xac\xfeP\xc7\xdc\xf7\xe9>\xc6k\xe3\x1c\xea?d\xb5\xfd\xf6\xe6\x8c\x93\xd9Sh\x8e&&\x96~f\xa6\xe7\x12f\xb2\x850\x22\x04 \x04\x08\x09Q\xd9%\x1aw\xb1k\x0dl\xd7\x10\xca\xc1\xe98\x8d\xadb8\xda\xe4\xfa\xf6\x13\xd1\x96\xf0\xa3\x8a*\x1f\x03\x16\x8c\xbd/\xef\x95\x197\xb3\xa1\x95n\xbd\x947\xf2/\xda\xa1=\x98\xd5y\x99\xae\xf73__\xa0\xe6\xcc\x83\xd4h@k\xd0@\xa8\x14M]\xa7\x9a\x98g\xc5*S\x13\x0dR\xf9^\xb6<:j\x0cl-\xf6xV8\xdaZfV\x5c\xb2'\x8d\xf0\xf9ps\xd3o\xbe;33\xf3f\xba\x95\xdeXp\x0a\x86\xd7\xf6\xe8J\xe4\xa8\xc8?\x99\x95\x93D\xa1\x22\xf4\x0c\x82\x8e \xf0\x04\xa1\xd6\x90\xd1\xb8]Y\x12N\x8e\xb0/F\xc5ls\xed\xe2<W\xaf\xceQ\xd3\x1d\xdb\xce\xbau9f\x9c3\xa7\xab\xd3\x07\x8d\x15c\x7f\xf3\xdbf6\x95M\xd1w\xa0\x8f\x81\xfe\x01\xb4\x04\xad\x05A%Ani\x84\xa4\xd7E\xa4\x15Z)\x04\x92Bz-#\xdd\x8fp9s\x85/\x97Np\xe3\x9b\xeb\xc8\x0b\x124\xe8\xad\xdaJ\xeeq\xf6t\x9c\xce)\xb3\xe1Ww\xcay\x91\x89\x95\xe2xk=&&&H\xa7\xd3\xa4\xd2)h\xd8\x0cV\xc7\xd8)\x9f&\x95\xca\x80\x10\x98\xa6\x81m\xd9\x14\x07\x8a\xe4{\xba)]\x9fc\xe9\xe2<L\xc3H\xcf\x08RJ~\xbf\xf2\x1b\x8dm\x95|\xd4\xaf\xc7L\xd1&\xb0\xb2R%\x0a\x8e\x11\xaa\x08\xcb\xb2\x90R\x12\x86\x01\xddF\x0f\xf9d\x1f\xc5\xf8\x10\x02PJa\x98\x06B\x08*\x95\x0a\x11\x0a<M<eb\x15%\xed\xd56\x02A\xb2\xe8\xe0\xbb\x81\xf6j:2\xd5\x1c\xa7\x8d\x0d\x8cu\xefu\xfa\xd7\xb5\x06xh\xeb\x00K\xfe\x02Q\x85\x9a\x0c\xad\x06\xa1\xd4\x8b\xd52Zk\x0c\xc3\xc00n\x09\x9a\xcd&Zi\x9a\xa2-\x1c+\x9e\xb6\x9f1\xdc\xdcu\x17\xa9%j\xc8\xe1\x86\xae\xceGS\x9c5\xd5)N\x04\xc8B\xb0\xc9;\xb0\x90\xbe\x9c\xfbb\xf6\xaaZ\xbe\xd1\x983\xe7\x93'r^~\x0a\xadU\xa4\xa2[\xdf^\x08\xa4\x94H)\x09\x82\x00\xdf\xf3i\x8a\x96Y]\xd7\xde\xb1f\xbb\xfd\xac\xb1\xb3U0\x84\x10^\xb9\xbd\xe0_\x10\xc7\xf5i\xbe\x13\x80el4\xd7\xc7\xd7Y\x8f\xc7l\xf9p\xd8\x8c:\xdeb\xe7\xd7\xb0\x14\xfdD\x9b\x9b\xdc\xda\xcc\x7fC\x8a\x82\xe8Kl\x89\xefN\xf4Z#\x08-[\xe5\xce\x05\x7f\xba3\xae\xfePsw\xb2H\x02\xce\xed\xa3\x80&\xe0\xdd\xc3\xf0\xbfgZ\x02H\xde~\xdf\xe9Ww\xc3Nv\x99\x98\x1bmT-\x22\xba\xe6\xa3\xfd{\x9d}\xdb\xe0H\xac\xd1\x04\x1a\xe8L\xb5\xa1\xae\xee\xab\xff\x01\xffc\xfe\x02\xc7+\xf1\xd7\x14MZn\x00\x00\x00%tEXtdate:create\x002010-02-23T18:14:19-07:00\xee\xec\xaeC\x00\x00\x00%tEXtdate:modify\x002010-02-23T18:14:19-07:00\x9f\xb1\x16\xff\x00\x00\x005tEXtLicense\x00http://creativecommons.org/licenses/LGPL/2.1/;\xc1\xb4\x18\x00\x00\x00\x14tEXtSource\x00Crystal Clear\xf5\xe2\xe7\xa8\x00\x00\x00:tEXtSource_URL\x00http://commons.wikimedia.org/wiki/Crystal_Clear\xaf\xbeEc\x00\x00\x00\x00IEND\xaeB`\x82\x00\x00\x01\xf5\x89PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x04\x00\x00\x00\xb5\xfa7\xea\x00\x00\x00\x02sBIT\x08\x08U\xecF\x04\x00\x00\x00\x09pHYs\x00\x00\x01\xbb\x00\x00\x01\xbb\x01:\xec\xe3\xe2\x00\x00\x00\x19tEXtSoftware\x00www.inkscape.org\x9b\xee<\x1a\x00\x00\x01tIDAT\x18\x19\x05\xc1AKS\x01\x1c\x00\xf0\xff;\xf5\x11\xea\xda\xa1}\x84.]<F\x17um\xb3\x18\x96B\x9a\xa8 o\x13k\x96\xcc\x87\xe8\xcd\xbat\xeac\x04o\x84A_\xa0\xa8Ay\x08\xf1\xe2e\x19\xc5z\x06\xef0\xde\xf8\xf5\xfb\x85\x10B\x1c\xd6\x0e\xb2,\xef\x8f\xfa\xa3,?\xc8\x0ekB\x08\x11B\xf4\x93\xbd\xb4Wvl\xeb\xeb\xdb\xd6\xd1+\xf7\xd2~\x22D\x88\xdd\xa47\xd8\xf2\xcc\x89\xa1\x1f\xce|wb\xc7\x96\xde`7\x11!\xba\xe9\x86W\xbe\xf9i\xec\xca?\x85_\xce\x1d\xdb\xd0ME\xa4\xb5\xcd\xb2\xeb\xd4\x1f\xa5w\xaeLU&\x0a\x17\xb6m\x96i-\xd6\xb3e\x1f\xfdV\x9a:v\xe4+\xa8\x14\x86\x96\xad\xef\xc7J\xbe\xea\x8bB\x85=\xab\x1ex\xed\x0a\x13\x97\xd6\xac\xe4\xb14\xea\x1a\x1a\xab\xb0j\xde\x8c\x19\x8f|V\x19{ai\x14\x8b\xa3\x8eS\x85)n\xbb\xee\x9a[\xee\xfbd\xaa\xf0\xd2\xe2(\xda\xf9\x92\xa1\xb1\x0aw\xdctC\xc7_T\xc6\x9eh\xe7\xd1\xce\x1a\xde\xbb4\xc1=w}\x00L\x9cih\xef\xc7\xc3Z\xb3|\xea\x5c\xa1\xf2F\x01\xa8\x14\xba\x9a\xe5\xc3Z\x88V:\xe7\xc8\x85\xc2De\xaa2QxkN+\x15!\x16\x92\xd6`\xd6\x9a\xa1Kc\x85\xb13\x1d\xb3Z\x83\x85D\x84\x10\xad\xa4\x91\xd6\xcbY\x8bv<\xf7\xd8\xacz\xd9H[\x89\x10!\x84\x10\xcdZ#\xab\xe7\xf3\xa3\xf9Q=od\xcd\x9a\x10B\xfc\x07{-n\x9f/-7\x8c\x00\x00\x00\x00IEND\xaeB`\x82\x00\x00\x01\xf3\x89PNG\x0d\x0a\x1a\x0a\x00\x00\x00\x0dIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x04\x00\x00\x00\xb5\xfa7\xea\x00\x00\x00\x02sBIT\x08\x08U\xecF\x04\x00\x00\x00\x09pHYs\x00\x00\x01\xbb\x00\x00\x01\xbb\x01:\xec\xe3\xe2\x00\x00\x00\x19tEXtSoftware\x00www.inkscape.org\x9b\xee<\x1a\x00\x00\x01rIDAT(\xcfE\x91O+\x04q\x1c\xc6\xbf\xf32\xe4l\xde\x80\xa2D9\xbb\xec\x1f\xb3#m\x9b%\x8b\x10\xfdv6\xec\xa21\x89\x13\x0e.\xca\xfb\x98M{\xf0\x12\xb4\x85\x836\x17\x97\xb1\xa2\xe9G\xfd\x0ec\xb6\x8f\x83\xb5\x9e\xe7\xf6\xf4\xf4\x1c\x9e\x8f \xbf>\xb1\x8f\x83 \xf4#?\x0a\xc2\xe3\xe0\xc4\xfe\xcb\x05A|\xebP\xd5M\x95\x1a>>5\xaa\xd4\xcd\xa1\xf2\xad~\xa1a\xd5\x9b\xdb\xec\xd2\xa2\xcd\x13\x1d\x1eh\xb1\xc36\xf5f\xc3B\x04\xf1\xd4\x06\x17\xdc\xf3J\xcc'_h\xdex\xe6\x9c\x0d<\x85\x88\xb27\x8d\xc7#\x1f\x18\xbe\xe9\xd1#%A\xf3B\x8dM\xa3lY\x0f\x16\xb9\xe5\x1d\xc3\x15g\x1c\xa0\xd8B\x91\xa2i\xb3\xc8\xfa\x91T\xc2\x15\xee\xd0\xa4\x5c\xd2\xa0\x82K\x8eY \xa1\xcb\x1a\x95P\xca\x91G\x9b\x98\x94=\x96\xc91\xc58\xd3@J\xcc>\xe5HJQ\x95G4=\xb2\x8c2\x840\xc4(\xd0Cs@)\x92bX\xee/\xb8L0\xc20#L\xf4\x17\x96)\x86R\x0c\x1cn\xe8\x92\xb0\xc4\x0c\x93\x8c1\xc9\x0c\x90\xd0\xc1\xa1x$\xf3v\xc1\xac\xf2\x8c&\xe5_)\x1a\x8f\x82\x99\xb7\x05qU\x96S^\xd0$\xa4\x83\x1f\xae\xc9\xe2*D\x909\xcbmfX\xa3M\x97\x18ML\x87*\x19\xdc\xe6\x9c\xd5\x87\xe5Z\x8e\xca\x9b\x0c%v\xd8c\x81\x0cy\xe3(\xd7\x1a\xd0D\x90\x82\xed\x04\xf90\x17\xe5\xa2|\xe8\x04\x85\x01\xee\x1f\x8dBf\xb3\xf5\x8b\xfe\x99\x00\x00\x00\x00IEND\xaeB`\x82" qt_resource_name = "\x00\x05\x00o\xa6S\x00i\x00c\x00o\x00n\x00s\x00\x09\x0alxC\x00r\x00e\x00s\x00o\x00u\x00r\x00c\x00e\x00s\x00\x07\x08sW\x87\x00a\x00p\x00p\x00.\x00p\x00n\x00g\x00\x18\x0f\xa4\x86G\x00m\x00e\x00d\x00i\x00a\x00-\x00p\x00l\x00a\x00y\x00b\x00a\x00c\x00k\x00-\x00s\x00t\x00a\x00r\x00t\x00.\x00p\x00n\x00g\x00\x17\x09\x10jG\x00m\x00e\x00d\x00i\x00a\x00-\x00p\x00l\x00a\x00y\x00b\x00a\x00c\x00k\x00-\x00s\x00t\x00o\x00p\x00.\x00p\x00n\x00g" qt_resource_struct = "\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x00\x00\x02\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x10\x00\x02\x00\x00\x00\x03\x00\x00\x00\x03\x00\x00\x00(\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00r\x00\x00\x00\x00\x00\x01\x00\x00\x07\xd7\x00\x00\x00<\x00\x00\x00\x00\x00\x01\x00\x00\x05\xde" def qInitResources(): QtCore.qRegisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data) def qCleanupResources(): QtCore.qUnregisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data) qInitResources()
mit
ericblau/ipf-xsede
ipf/log.py
1
9917
############################################################################### # Copyright 2012-2014 The University of Texas at Austin # # # # 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. # ############################################################################### import logging import os import time import stat import sys from ipf.error import StepError ####################################################################################################################### logger = logging.getLogger(__name__) ####################################################################################################################### class LogFileWatcher(object): def __init__(self, callback, path, posdb_path=None): self.callback = callback self.path = path self.keep_running = True self.pos_db = PositionDB(posdb_path) def run(self): file = LogFile(self.path,self.callback,self.pos_db) file.open() while self.keep_running: try: file.handle() except IOError: # try to reopen in case of stale NFS file handle or similar file.reopen() file.handle() time.sleep(1) file.close() def stop(self): self.keep_running = False ####################################################################################################################### class LogDirectoryWatcher(object): """Discovers new lines in log files and sends them to the callback.""" def __init__(self, callback, dir, posdb_path=None): if not os.path.exists(dir): raise StepError("%s doesn't exist",dir) if not os.path.isdir(dir): raise StepError("%s isn't a directory",dir) self.callback = callback self.dir = dir self.pos_db = PositionDB(posdb_path) self.files = {} self.last_update = -1 logger.info("created watcher for directory %s",dir) def run(self): while True: self._updateFiles() for file in list(self.files.values()): try: file.handle() except IOError: # try to reopen in case of stale NFS file handle or similar file.reopen() file.handle() time.sleep(1) def _updateFiles(self): cur_time = time.time() if cur_time - self.last_update < 60: # update files once a minute return logger.debug("updating files") cur_files = self._getCurrentFiles() for file in cur_files: if file.id in self.files: self._handleExistingFile(file) else: self._handleNewFile(file) self._handleDeletedFiles(cur_files) self.last_update = cur_time def _getCurrentFiles(self): cur_files = [] for file_name in os.listdir(self.dir): path = os.path.join(self.dir,file_name) if not os.path.isfile(path): # only regular files continue if os.path.islink(path): # but not soft links continue cur_files.append(LogFile(path,self.callback,self.pos_db)) return cur_files def _handleExistingFile(self, file): logger.debug("existing file %s",file.path) if file.path != self.files[file.id].path: # file has been rotated logger.info("log file %s rotated to %s",self.files[file.id].path,file.path) self.files[file.id].path = file.path file.closeIfNeeded() def _handleNewFile(self, file): logger.info("new file %s %s",file.id,file.path) file.openIfNeeded() self.files[file.id] = file def _handleDeletedFiles(self, cur_files): cur_file_ids = set([file.id for file in cur_files]) for id in [id for id in list(self.files.keys()) if id not in cur_file_ids]: if self.files[id].file is not None: self.files[id].file.close() del self.files[id] for id in self.pos_db.ids(): if id not in self.files: self.pos_db.remove(id) ####################################################################################################################### class LogFile(object): def __init__(self, path, callback, pos_db = None): self.path = path st = os.stat(path) self.id = self._getId(st) self.callback = callback self.file = None if pos_db is None: self.pos_db = PositionDB() else: self.pos_db = pos_db def _getId(self, st): return "%s-%d" % (st.st_dev, st.st_ino) def openIfNeeded(self): if self._shouldOpen(): self.open() def _shouldOpen(self): if self.file is not None: return False st = os.stat(self.path) if st.st_mtime > time.time() - 15*60: return True return False def _seek(self): position = self.pos_db.get(self.id) if position is not None: self.file.seek(position) else: self.file.seek(0,os.SEEK_END) self._savePosition() def _savePosition(self): return self.pos_db.set(self.id,self.file.tell()) def _forgetPosition(self): self.pos_db.remove(self.id) def open(self): logger.info("opening file %s (%s)",self.id,self.path) if self.file is not None: logger.warn("attempting to open already open file %s",self.path) self.file = open(self.path,"r") self._seek() def reopen(self): logger.info("reopening file %s (%s)",self.id,self.path) self.file = open(self.path,"r") self._seek() def closeIfNeeded(self): if self._shouldClose(): self.close() #self._forgetPosition() def _shouldClose(self): if self.file is None: return False st = os.stat(self.path) if st.st_mtime < time.time() - 15*60: return True return False def close(self): logger.info("closing file %s (%s)",self.id,self.path) if self.file is None: logger.warn("attempting to close already closed file %s",self.path) return self.file.close() self.file = None def handle(self): if self.file is None: return logger.debug("checking log file %s",self.path) line = "junk" self._seek() while line: line = self.file.readline() if not line.endswith("\n"): self.callback(self.path,line) self._savePosition() else: break ####################################################################################################################### class PositionDB(object): def __init__(self, path=None): self.position = {} self.path = path self._read() def set(self, id, position): if id not in self.position or position != self.position[id]: self.position[id] = position self._write() def get(self, id): return self.position.get(id,None) def remove(self, id): del self.position[id] self._write() def ids(self): return list(self.position.keys()) def _read(self): if self.path is None: return self.position = {} if not os.path.exists(self.path): return try: file = open(self.path,"r") for line in file: (id,pos_str) = line.split() self.position[id] = int(pos_str) file.close() except IOError as e: logger.error("failed to read position database %s: %s" % (self.path,e)) def _write(self): if self.path is None: return try: file = open(self.path,"w") for key in self.position: file.write("%s %d\n" % (key,self.position[key])) file.close() except IOError as e: logger.error("failed to write position database %s: %s" % (self.path,e)) ####################################################################################################################### # testing def echo(path, message): print("%s: %s" % (path,message[:-1])) def doNothing(path, message): pass if __name__ == "__main__": if len(sys.argv) < 2: print("usage: log.py <log directory> [position file]") sys.exit(1) import logging.config from ipf.paths import IPF_ETC_PATH if len(sys.argv) >= 3: watcher = LogDirectoryWatcher(echo,sys.argv[1],sys.argv[2]) else: watcher = LogDirectoryWatcher(echo,sys.argv[1]) watcher.run()
apache-2.0
karstenw/nodebox-pyobjc
examples/Extended Application/matplotlib/examples/mplot3d/text3d.py
1
1226
''' ====================== Text annotations in 3D ====================== Demonstrates the placement of text annotations on a 3D plot. Functionality shown: - Using the text function with three types of 'zdir' values: None, an axis name (ex. 'x'), or a direction tuple (ex. (1, 1, 0)). - Using the text function with the color keyword. - Using the text2D function to place text on a fixed position on the ax object. ''' from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt fig = plt.figure() ax = fig.gca(projection='3d') # Demo 1: zdir zdirs = (None, 'x', 'y', 'z', (1, 1, 0), (1, 1, 1)) xs = (1, 4, 4, 9, 4, 1) ys = (2, 5, 8, 10, 1, 2) zs = (10, 3, 8, 9, 1, 8) for zdir, x, y, z in zip(zdirs, xs, ys, zs): label = '(%d, %d, %d), dir=%s' % (x, y, z, zdir) ax.text(x, y, z, label, zdir) # Demo 2: color ax.text(9, 0, 0, "red", color='red') # Demo 3: text2D # Placement 0, 0 would be the bottom left, 1, 1 would be the top right. ax.text2D(0.05, 0.95, "2D Text", transform=ax.transAxes) # Tweaking display region and labels ax.set_xlim(0, 10) ax.set_ylim(0, 10) ax.set_zlim(0, 10) ax.set_xlabel('X axis') ax.set_ylabel('Y axis') ax.set_zlabel('Z axis') plt.show()
mit
befelix/GPy
GPy/plotting/matplot_dep/base_plots.py
5
8394
# #Copyright (c) 2012, GPy authors (see AUTHORS.txt). # Licensed under the BSD 3-clause license (see LICENSE.txt) from matplotlib import pyplot as plt import numpy as np def ax_default(fignum, ax): if ax is None: fig = plt.figure(fignum) ax = fig.add_subplot(111) else: fig = ax.figure return fig, ax def meanplot(x, mu, color='#3300FF', ax=None, fignum=None, linewidth=2,**kw): _, axes = ax_default(fignum, ax) return axes.plot(x,mu,color=color,linewidth=linewidth,**kw) def gpplot(x, mu, lower, upper, edgecol='#3300FF', fillcol='#33CCFF', ax=None, fignum=None, **kwargs): _, axes = ax_default(fignum, ax) mu = mu.flatten() x = x.flatten() lower = lower.flatten() upper = upper.flatten() plots = [] #here's the mean plots.append(meanplot(x, mu, edgecol, axes)) #here's the box kwargs['linewidth']=0.5 if not 'alpha' in kwargs.keys(): kwargs['alpha'] = 0.3 plots.append(axes.fill(np.hstack((x,x[::-1])),np.hstack((upper,lower[::-1])),color=fillcol,**kwargs)) #this is the edge: plots.append(meanplot(x, upper,color=edgecol, linewidth=0.2, ax=axes)) plots.append(meanplot(x, lower,color=edgecol, linewidth=0.2, ax=axes)) return plots def gradient_fill(x, percentiles, ax=None, fignum=None, **kwargs): _, ax = ax_default(fignum, ax) plots = [] #here's the box if 'linewidth' not in kwargs: kwargs['linewidth'] = 0.5 if not 'alpha' in kwargs.keys(): kwargs['alpha'] = 1./(len(percentiles)) # pop where from kwargs where = kwargs.pop('where') if 'where' in kwargs else None # pop interpolate, which we actually do not do here! if 'interpolate' in kwargs: kwargs.pop('interpolate') def pairwise(inlist): l = len(inlist) for i in range(int(np.ceil(l/2.))): yield inlist[:][i], inlist[:][(l-1)-i] polycol = [] for y1, y2 in pairwise(percentiles): import matplotlib.mlab as mlab # Handle united data, such as dates ax._process_unit_info(xdata=x, ydata=y1) ax._process_unit_info(ydata=y2) # Convert the arrays so we can work with them from numpy import ma x = ma.masked_invalid(ax.convert_xunits(x)) y1 = ma.masked_invalid(ax.convert_yunits(y1)) y2 = ma.masked_invalid(ax.convert_yunits(y2)) if y1.ndim == 0: y1 = np.ones_like(x) * y1 if y2.ndim == 0: y2 = np.ones_like(x) * y2 if where is None: where = np.ones(len(x), np.bool) else: where = np.asarray(where, np.bool) if not (x.shape == y1.shape == y2.shape == where.shape): raise ValueError("Argument dimensions are incompatible") mask = reduce(ma.mask_or, [ma.getmask(a) for a in (x, y1, y2)]) if mask is not ma.nomask: where &= ~mask polys = [] for ind0, ind1 in mlab.contiguous_regions(where): xslice = x[ind0:ind1] y1slice = y1[ind0:ind1] y2slice = y2[ind0:ind1] if not len(xslice): continue N = len(xslice) X = np.zeros((2 * N + 2, 2), np.float) # the purpose of the next two lines is for when y2 is a # scalar like 0 and we want the fill to go all the way # down to 0 even if none of the y1 sample points do start = xslice[0], y2slice[0] end = xslice[-1], y2slice[-1] X[0] = start X[N + 1] = end X[1:N + 1, 0] = xslice X[1:N + 1, 1] = y1slice X[N + 2:, 0] = xslice[::-1] X[N + 2:, 1] = y2slice[::-1] polys.append(X) polycol.extend(polys) from matplotlib.collections import PolyCollection plots.append(PolyCollection(polycol, **kwargs)) ax.add_collection(plots[-1], autolim=True) ax.autoscale_view() return plots def gperrors(x, mu, lower, upper, edgecol=None, ax=None, fignum=None, **kwargs): _, axes = ax_default(fignum, ax) mu = mu.flatten() x = x.flatten() lower = lower.flatten() upper = upper.flatten() plots = [] if edgecol is None: edgecol='#3300FF' if not 'alpha' in kwargs.keys(): kwargs['alpha'] = 1. if not 'lw' in kwargs.keys(): kwargs['lw'] = 1. plots.append(axes.errorbar(x,mu,yerr=np.vstack([mu-lower,upper-mu]),color=edgecol,**kwargs)) plots[-1][0].remove() return plots def removeRightTicks(ax=None): ax = ax or plt.gca() for i, line in enumerate(ax.get_yticklines()): if i%2 == 1: # odd indices line.set_visible(False) def removeUpperTicks(ax=None): ax = ax or plt.gca() for i, line in enumerate(ax.get_xticklines()): if i%2 == 1: # odd indices line.set_visible(False) def fewerXticks(ax=None,divideby=2): ax = ax or plt.gca() ax.set_xticks(ax.get_xticks()[::divideby]) def align_subplots(N,M,xlim=None, ylim=None): """make all of the subplots have the same limits, turn off unnecessary ticks""" #find sensible xlim,ylim if xlim is None: xlim = [np.inf,-np.inf] for i in range(N*M): plt.subplot(N,M,i+1) xlim[0] = min(xlim[0],plt.xlim()[0]) xlim[1] = max(xlim[1],plt.xlim()[1]) if ylim is None: ylim = [np.inf,-np.inf] for i in range(N*M): plt.subplot(N,M,i+1) ylim[0] = min(ylim[0],plt.ylim()[0]) ylim[1] = max(ylim[1],plt.ylim()[1]) for i in range(N*M): plt.subplot(N,M,i+1) plt.xlim(xlim) plt.ylim(ylim) if (i)%M: plt.yticks([]) else: removeRightTicks() if i<(M*(N-1)): plt.xticks([]) else: removeUpperTicks() def align_subplot_array(axes,xlim=None, ylim=None): """ Make all of the axes in the array hae the same limits, turn off unnecessary ticks use plt.subplots() to get an array of axes """ #find sensible xlim,ylim if xlim is None: xlim = [np.inf,-np.inf] for ax in axes.flatten(): xlim[0] = min(xlim[0],ax.get_xlim()[0]) xlim[1] = max(xlim[1],ax.get_xlim()[1]) if ylim is None: ylim = [np.inf,-np.inf] for ax in axes.flatten(): ylim[0] = min(ylim[0],ax.get_ylim()[0]) ylim[1] = max(ylim[1],ax.get_ylim()[1]) N,M = axes.shape for i,ax in enumerate(axes.flatten()): ax.set_xlim(xlim) ax.set_ylim(ylim) if (i)%M: ax.set_yticks([]) else: removeRightTicks(ax) if i<(M*(N-1)): ax.set_xticks([]) else: removeUpperTicks(ax) def x_frame1D(X,plot_limits=None,resolution=None): """ Internal helper function for making plots, returns a set of input values to plot as well as lower and upper limits """ assert X.shape[1] ==1, "x_frame1D is defined for one-dimensional inputs" if plot_limits is None: from ...core.parameterization.variational import VariationalPosterior if isinstance(X, VariationalPosterior): xmin,xmax = X.mean.min(0),X.mean.max(0) else: xmin,xmax = X.min(0),X.max(0) xmin, xmax = xmin-0.2*(xmax-xmin), xmax+0.2*(xmax-xmin) elif len(plot_limits)==2: xmin, xmax = plot_limits else: raise ValueError("Bad limits for plotting") Xnew = np.linspace(xmin,xmax,resolution or 200)[:,None] return Xnew, xmin, xmax def x_frame2D(X,plot_limits=None,resolution=None): """ Internal helper function for making plots, returns a set of input values to plot as well as lower and upper limits """ assert X.shape[1] ==2, "x_frame2D is defined for two-dimensional inputs" if plot_limits is None: xmin,xmax = X.min(0),X.max(0) xmin, xmax = xmin-0.2*(xmax-xmin), xmax+0.2*(xmax-xmin) elif len(plot_limits)==2: xmin, xmax = plot_limits else: raise ValueError("Bad limits for plotting") resolution = resolution or 50 xx,yy = np.mgrid[xmin[0]:xmax[0]:1j*resolution,xmin[1]:xmax[1]:1j*resolution] Xnew = np.vstack((xx.flatten(),yy.flatten())).T return Xnew, xx, yy, xmin, xmax
bsd-3-clause
TeamExodus/external_chromium_org
tools/traceline/traceline/scripts/crit_sec.py
179
1416
#!/usr/bin/env python # Copyright (c) 2011 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import sys import os from syscalls import syscalls def parseEvents(z): crits = { } calls = { } for e in z: if (e['eventtype'] == 'EVENT_TYPE_ENTER_CS' or e['eventtype'] == 'EVENT_TYPE_TRYENTER_CS' or e['eventtype'] == 'EVENT_TYPE_LEAVE_CS'): cs = e['critical_section'] if not crits.has_key(cs): crits[cs] = [ ] crits[cs].append(e) # for cs, es in crits.iteritems(): # print 'cs: 0x%08x' % cs # for e in es: # print ' 0x%08x - %s - %f' % (e['thread'], e['eventtype'], e['ms']) for cs, es in crits.iteritems(): print 'cs: 0x%08x' % cs tid_stack = [ ] for e in es: if e['eventtype'] == 'EVENT_TYPE_ENTER_CS': tid_stack.append(e) elif e['eventtype'] == 'EVENT_TYPE_TRYENTER_CS': if e['retval'] != 0: tid_stack.append(e) elif e['eventtype'] == 'EVENT_TYPE_LEAVE_CS': if not tid_stack: raise repr(e) tid = tid_stack.pop() if tid['thread'] != e['thread']: raise repr(tid) + '--' + repr(e) # Critical section left locked? if tid_stack: #raise repr(tid_stack) pass def main(): execfile(sys.argv[1]) if __name__ == '__main__': main()
bsd-3-clause
knagra/farnsworth
legacy/models.py
1
3275
""" Project: Farnsworth Author: Karandeep Singh Nagra Legacy Kingman site data. """ from django.db import models class TeacherRequest(models.Model): """ A request from the previous Kingman website. """ request_type = models.CharField( max_length=15, null=True, blank=True, help_text="The request type for this request." ) teacher_key = models.CharField( max_length=24, null=True, blank=True, help_text="Legacy primary key based on datetime." ) timestamp = models.DateTimeField( null=True, blank=True, help_text="Date and time when this request was posted." ) name = models.CharField( max_length=255, null=True, blank=True, help_text="The name given by the user who posted this request." ) body = models.TextField( null=True, blank=True, help_text="The body of this request." ) def __unicode__(self): return self.teacher_key class Meta: ordering = ['-timestamp'] class TeacherResponse(models.Model): """ A response to a request from the previous Kingman website. """ request = models.ForeignKey( TeacherRequest, help_text="The request to which this is a response." ) timestamp = models.DateTimeField( null=True, blank=True, help_text="Date and time when this response was posted." ) name = models.CharField( max_length=255, null=True, blank=True, help_text="The name given by the user who posted this request." ) body = models.TextField( null=True, blank=True, help_text="The body of this response." ) def __unicode__(self): return "{key} - {name}".format( key=self.request.teacher_key, name=self.name ) class Meta: ordering = ['timestamp'] class TeacherNote(models.Model): """ A note posted for public consumption. """ timestamp = models.DateTimeField( null=True, blank=True, help_text="Date and time when this note was posted." ) name = models.CharField( max_length=255, null=True, blank=True, help_text="The name given by the user who posted this request." ) body = models.TextField( null=True, blank=True, help_text="The body of this note." ) def __unicode__(self): return "{time} - {name}".format( time=self.timestamp, name=self.name ) class Meta: ordering = ['-timestamp'] class TeacherEvent(models.Model): """ An event posted on the legacy Kingman website. """ date = models.DateField( null=True, blank=True, help_text="Date of this event." ) title = models.CharField( max_length=255, null=True, blank=True, help_text="The title of this event." ) description = models.TextField( null=True, blank=True, help_text="The description of this event." ) def __unicode__(self): return self.title class Meta: ordering = ['-date']
bsd-2-clause
40223142/cda11
static/Brython3.1.0-20150301-090019/Lib/signal.py
743
1646
"""This module provides mechanisms to use signal handlers in Python. Functions: alarm() -- cause SIGALRM after a specified time [Unix only] setitimer() -- cause a signal (described below) after a specified float time and the timer may restart then [Unix only] getitimer() -- get current value of timer [Unix only] signal() -- set the action for a given signal getsignal() -- get the signal action for a given signal pause() -- wait until a signal arrives [Unix only] default_int_handler() -- default SIGINT handler signal constants: SIG_DFL -- used to refer to the system default handler SIG_IGN -- used to ignore the signal NSIG -- number of defined signals SIGINT, SIGTERM, etc. -- signal numbers itimer constants: ITIMER_REAL -- decrements in real time, and delivers SIGALRM upon expiration ITIMER_VIRTUAL -- decrements only when the process is executing, and delivers SIGVTALRM upon expiration ITIMER_PROF -- decrements both when the process is executing and when the system is executing on behalf of the process. Coupled with ITIMER_VIRTUAL, this timer is usually used to profile the time spent by the application in user and kernel space. SIGPROF is delivered upon expiration. *** IMPORTANT NOTICE *** A signal handler function is called with two arguments: the first is the signal number, the second is the interrupted stack frame.""" CTRL_BREAK_EVENT=1 CTRL_C_EVENT=0 NSIG=23 SIGABRT=22 SIGBREAK=21 SIGFPE=8 SIGILL=4 SIGINT=2 SIGSEGV=11 SIGTERM=15 SIG_DFL=0 SIG_IGN=1 def signal(signalnum, handler) : pass
gpl-3.0
riptano/cassandra-dtest
mixed_version_test.py
4
3218
from cassandra import ConsistencyLevel, OperationTimedOut, ReadTimeout from cassandra.query import SimpleStatement from dtest import Tester, debug from tools.decorators import since class TestSchemaChanges(Tester): @since('2.0') def test_friendly_unrecognized_table_handling(self): """ After upgrading one of two nodes, create a new table (which will not be propagated to the old node) and check that queries against that table result in user-friendly warning logs. """ cluster = self.cluster cluster.populate(2) cluster.start() node1, node2 = cluster.nodelist() original_version = node1.get_cassandra_version() if original_version.vstring.startswith('2.0'): upgraded_version = 'github:apache/cassandra-2.1' elif original_version.vstring.startswith('2.1'): upgraded_version = 'github:apache/cassandra-2.2' else: self.skip("This test is only designed to work with 2.0 and 2.1 right now") # start out with a major behind the previous version # upgrade node1 node1.stop() node1.set_install_dir(version=upgraded_version) debug("Set new cassandra dir for %s: %s" % (node1.name, node1.get_install_dir())) node1.set_log_level("INFO") node1.start() session = self.patient_exclusive_cql_connection(node1) session.cluster.max_schema_agreement_wait = -1 # don't wait for schema agreement debug("Creating keyspace and table") session.execute("CREATE KEYSPACE test_upgrades WITH replication={'class': 'SimpleStrategy', 'replication_factor': '2'}") session.execute("CREATE TABLE test_upgrades.foo (a int primary key, b int)") pattern = r".*Got .* command for nonexistent table test_upgrades.foo.*" try: session.execute(SimpleStatement("SELECT * FROM test_upgrades.foo", consistency_level=ConsistencyLevel.ALL)) self.fail("expected failure") except (ReadTimeout, OperationTimedOut): debug("Checking node2 for warning in log") node2.watch_log_for(pattern, timeout=10) # non-paged range slice try: session.execute(SimpleStatement("SELECT * FROM test_upgrades.foo", consistency_level=ConsistencyLevel.ALL, fetch_size=None)) self.fail("expected failure") except (ReadTimeout, OperationTimedOut): debug("Checking node2 for warning in log") pattern = r".*Got .* command for nonexistent table test_upgrades.foo.*" node2.watch_log_for(pattern, timeout=10) # single-partition slice try: for i in range(20): session.execute(SimpleStatement("SELECT * FROM test_upgrades.foo WHERE a = %d" % (i,), consistency_level=ConsistencyLevel.ALL, fetch_size=None)) self.fail("expected failure") except (ReadTimeout, OperationTimedOut): debug("Checking node2 for warning in log") pattern = r".*Got .* command for nonexistent table test_upgrades.foo.*" node2.watch_log_for(pattern, timeout=10)
apache-2.0
wscullin/spack
var/spack/repos/builtin/packages/py-phonopy/package.py
3
1832
############################################################################## # Copyright (c) 2013-2017, Lawrence Livermore National Security, LLC. # Produced at the Lawrence Livermore National Laboratory. # # This file is part of Spack. # Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved. # LLNL-CODE-647188 # # For details, see https://github.com/llnl/spack # Please also see the NOTICE and LICENSE files for our notice and the LGPL. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (as # published by the Free Software Foundation) version 2.1, February 1999. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and # conditions of the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ############################################################################## from spack import * class PyPhonopy(PythonPackage): """Phonopy is an open source package for phonon calculations at harmonic and quasi-harmonic levels.""" homepage = "http://atztogo.github.io/phonopy/index.html" url = "http://sourceforge.net/projects/phonopy/files/phonopy/phonopy-1.10/phonopy-1.10.0.tar.gz" version('1.10.0', '973ed1bcea46e21b9bf747aab9061ff6') depends_on('py-numpy', type=('build', 'run')) depends_on('py-scipy', type=('build', 'run')) depends_on('py-matplotlib', type=('build', 'run')) depends_on('py-pyyaml', type=('build', 'run'))
lgpl-2.1
Deepakpatle/phantomjs
src/qt/qtwebkit/Tools/Scripts/webkitpy/common/net/failuremap.py
134
4062
# Copyright (C) 2010 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # FIXME: This probably belongs in the buildbot module. class FailureMap(object): def __init__(self): self._failures = [] def add_regression_window(self, builder, regression_window): self._failures.append({ 'builder': builder, 'regression_window': regression_window, }) def is_empty(self): return not self._failures def failing_revisions(self): failing_revisions = [failure_info['regression_window'].revisions() for failure_info in self._failures] return sorted(set(sum(failing_revisions, []))) def builders_failing_for(self, revision): return self._builders_failing_because_of([revision]) def tests_failing_for(self, revision): tests = [failure_info['regression_window'].failing_tests() for failure_info in self._failures if revision in failure_info['regression_window'].revisions() and failure_info['regression_window'].failing_tests()] result = set() for test in tests: result = result.union(test) return sorted(result) def failing_tests(self): return set(sum([self.tests_failing_for(revision) for revision in self.failing_revisions()], [])) def _old_failures(self, is_old_failure): return filter(lambda revision: is_old_failure(revision), self.failing_revisions()) def _builders_failing_because_of(self, revisions): revision_set = set(revisions) return [failure_info['builder'] for failure_info in self._failures if revision_set.intersection( failure_info['regression_window'].revisions())] # FIXME: We should re-process old failures after some time delay. # https://bugs.webkit.org/show_bug.cgi?id=36581 def filter_out_old_failures(self, is_old_failure): old_failures = self._old_failures(is_old_failure) old_failing_builder_names = set([builder.name() for builder in self._builders_failing_because_of(old_failures)]) # We filter out all the failing builders that could have been caused # by old_failures. We could miss some new failures this way, but # emperically, this reduces the amount of spam we generate. failures = self._failures self._failures = [failure_info for failure_info in failures if failure_info['builder'].name() not in old_failing_builder_names] self._cache = {}
bsd-3-clause
hollow/nepal
nepal/web/migrations/0005_phpini_add_vhost_ptr.py
1
9858
from south.db import db from django.db import models from nepal.web.models import * class Migration: def forwards(self, orm): # Adding field 'PHPIni.vhost' db.add_column('php_ini', 'vhost', orm['web.phpini:vhost']) def backwards(self, orm): # Deleting field 'PHPIni.vhost' db.delete_column('php_ini', 'vhost_id') models = { 'account.userprofile': { 'Meta': {'db_table': "'user_profile'"}, 'account_holder': ('django.db.models.fields.CharField', [], {'max_length': '64', 'blank': 'True'}), 'account_no': ('django.db.models.fields.IntegerField', [], {'max_length': '16', 'null': 'True', 'blank': 'True'}), 'bank_number': ('django.db.models.fields.IntegerField', [], {'max_length': '16', 'null': 'True', 'blank': 'True'}), 'canbeactivated': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}), 'city': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'company': ('django.db.models.fields.CharField', [], {'max_length': '128', 'blank': 'True'}), 'country': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['countries.Country']"}), 'customer_id': ('django.db.models.fields.CharField', [], {'max_length': '128', 'blank': 'True'}), 'fax': ('django.db.models.fields.CharField', [], {'max_length': '32', 'blank': 'True'}), 'iban': ('django.db.models.fields.CharField', [], {'max_length': '64', 'null': 'True', 'blank': 'True'}), 'jid': ('django.db.models.fields.EmailField', [], {'max_length': '128', 'blank': 'True'}), 'language': ('django.db.models.fields.CharField', [], {'max_length': '32', 'blank': 'True'}), 'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'child_set'", 'null': 'True', 'to': "orm['account.UserProfile']"}), 'phone': ('django.db.models.fields.CharField', [], {'max_length': '32', 'blank': 'True'}), 'role': ('django.db.models.fields.CharField', [], {'max_length': '1'}), 'state': ('django.db.models.fields.CharField', [], {'max_length': '128', 'null': 'True', 'blank': 'True'}), 'street': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'swift_bic': ('django.db.models.fields.CharField', [], {'max_length': '11', 'null': 'True', 'blank': 'True'}), 'user_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True', 'primary_key': 'True'}), 'vatin': ('django.db.models.fields.CharField', [], {'max_length': '16', 'null': 'True', 'blank': 'True'}), 'zip': ('django.db.models.fields.CharField', [], {'max_length': '16'}) }, 'auth.group': { 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'unique_together': "(('content_type', 'codename'),)"}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'unique_together': "(('app_label', 'model'),)", 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'countries.country': { 'Meta': {'db_table': "'country'"}, 'iso': ('django.db.models.fields.CharField', [], {'max_length': '2', 'primary_key': 'True'}), 'iso3': ('django.db.models.fields.CharField', [], {'max_length': '3', 'null': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'numcode': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True'}), 'printable_name': ('django.db.models.fields.CharField', [], {'max_length': '128'}) }, 'domain.domain': { 'Meta': {'unique_together': "(('name', 'parent'),)", 'db_table': "'domain'"}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'ip': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['ip.IP']"}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}), 'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'child_set'", 'null': 'True', 'to': "orm['domain.Domain']"}), 'profile': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['account.UserProfile']"}) }, 'ip.ip': { 'Meta': {'db_table': "'ip'"}, 'address': ('django.db.models.fields.IPAddressField', [], {'unique': 'True', 'max_length': '15'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'web.phpini': { 'Meta': {'db_table': "'php_ini'"}, 'allow_url_fopen': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'display_errors': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'domain': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['domain.Domain']", 'unique': 'True'}), 'error_reporting': ('django.db.models.fields.CharField', [], {'default': "'E_ALL & ~E_NOTICE'", 'max_length': '255'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'log_errors': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}), 'max_execution_time': ('django.db.models.fields.PositiveIntegerField', [], {'default': '30'}), 'max_input_time': ('django.db.models.fields.PositiveIntegerField', [], {'default': '60'}), 'memory_limit': ('django.db.models.fields.PositiveIntegerField', [], {'default': '128'}), 'post_max_size': ('django.db.models.fields.PositiveIntegerField', [], {'default': '8'}), 'register_globals': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}), 'register_long_arrays': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}), 'session_only_cookies': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}), 'vhost': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['web.VHost']", 'unique': 'True', 'null': 'True'}) }, 'web.vhost': { 'Meta': {'db_table': "'vhost'"}, 'domain': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['domain.Domain']", 'unique': 'True'}), 'forward_canonical': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}) }, 'web.vhostalias': { 'Meta': {'db_table': "'vhost_alias'"}, 'domain': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['domain.Domain']", 'unique': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'vhost': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['web.VHost']"}) } } complete_apps = ['web']
bsd-3-clause
schriftgestalt/drawbot
drawBot/ui/drawView.py
4
3054
from Foundation import NSURL from AppKit import NSDragOperationNone, NSBezelBorder from Quartz import PDFView, PDFThumbnailView, PDFDocument from vanilla import Group epsPasteBoardType = "CorePasteboardFlavorType 0x41494342" class DrawBotPDFThumbnailView(PDFThumbnailView): def draggingUpdated_(self, draggingInfo): return NSDragOperationNone class ThumbnailView(Group): nsViewClass = DrawBotPDFThumbnailView def setDrawView(self, view): self.getNSView().setPDFView_(view.getNSView()) def getSelection(self): try: # sometimes this goes weirdly wrong... selection = self.getNSView().selectedPages() except: return -1 if selection: for page in selection: document = page.document() index = document.indexForPage_(page) return index return -1 class DrawBotPDFView(PDFView): def performKeyEquivalent_(self, event): # catch a bug in PDFView # cmd + ` causes a traceback # DrawBot[15705]: -[__NSCFConstantString characterAtIndex:]: Range or index out of bounds try: return super(DrawBotPDFView, self).performKeyEquivalent_(event) except: return False class DrawView(Group): nsViewClass = DrawBotPDFView def __init__(self, posSize): super(DrawView, self).__init__(posSize) pdfView = self.getNSView() pdfView.setAutoScales_(True) view = pdfView.documentView() if view is not None: scrollview = view.enclosingScrollView() scrollview.setBorderType_(NSBezelBorder) def get(self): pdf = self.getNSView().document() if pdf is None: return None return pdf.dataRepresentation() def set(self, pdfData): pdf = PDFDocument.alloc().initWithData_(pdfData) self.setPDFDocument(pdf) def setPath(self, path): url = NSURL.fileURLWithPath_(path) document = PDFDocument.alloc().initWithURL_(url) self.setPDFDocument(document) def setPDFDocument(self, document): if document is None: document = PDFDocument.alloc().init() self.getNSView().setDocument_(document) def getPDFDocument(self): return self.getNSView().document() def setScale(self, scale): self.getNSView().setScaleFactor_(scale) def scale(self): return self.getNSView().scaleFactor() def scrollDown(self): document = self.getNSView().documentView() document.scrollPoint_((0, 0)) def scrollToPageIndex(self, index): pdf = self.getPDFDocument() if pdf is None: self.scrollDown() elif 0 <= index < pdf.pageCount(): try: # sometimes this goes weirdly wrong... page = pdf.pageAtIndex_(index) self.getNSView().goToPage_(page) except: self.scrollDown() else: self.scrollDown()
bsd-2-clause
bmotlaghFLT/FLT_PhantomJS
src/qt/qtwebkit/Tools/Scripts/webkitpy/port/server_process_unittest.py
121
5514
# Copyright (C) 2011 Google Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import sys import time import unittest2 as unittest from webkitpy.port.factory import PortFactory from webkitpy.port import server_process from webkitpy.common.system.systemhost import SystemHost from webkitpy.common.system.systemhost_mock import MockSystemHost from webkitpy.common.system.outputcapture import OutputCapture class TrivialMockPort(object): def __init__(self): self.host = MockSystemHost() self.host.executive.kill_process = lambda x: None self.host.executive.kill_process = lambda x: None def results_directory(self): return "/mock-results" def check_for_leaks(self, process_name, process_pid): pass def process_kill_time(self): return 1 class MockFile(object): def __init__(self, server_process): self._server_process = server_process self.closed = False def fileno(self): return 1 def write(self, line): self._server_process.broken_pipes.append(self) raise IOError def close(self): self.closed = True class MockProc(object): def __init__(self, server_process): self.stdin = MockFile(server_process) self.stdout = MockFile(server_process) self.stderr = MockFile(server_process) self.pid = 1 def poll(self): return 1 def wait(self): return 0 class FakeServerProcess(server_process.ServerProcess): def _start(self): self._proc = MockProc(self) self.stdin = self._proc.stdin self.stdout = self._proc.stdout self.stderr = self._proc.stderr self._pid = self._proc.pid self.broken_pipes = [] class TestServerProcess(unittest.TestCase): def test_basic(self): cmd = [sys.executable, '-c', 'import sys; import time; time.sleep(0.02); print "stdout"; sys.stdout.flush(); print >>sys.stderr, "stderr"'] host = SystemHost() factory = PortFactory(host) port = factory.get() now = time.time() proc = server_process.ServerProcess(port, 'python', cmd) proc.write('') self.assertEqual(proc.poll(), None) self.assertFalse(proc.has_crashed()) # check that doing a read after an expired deadline returns # nothing immediately. line = proc.read_stdout_line(now - 1) self.assertEqual(line, None) # FIXME: This part appears to be flaky. line should always be non-None. # FIXME: https://bugs.webkit.org/show_bug.cgi?id=88280 line = proc.read_stdout_line(now + 1.0) if line: self.assertEqual(line.strip(), "stdout") line = proc.read_stderr_line(now + 1.0) if line: self.assertEqual(line.strip(), "stderr") proc.stop(0) def test_cleanup(self): port_obj = TrivialMockPort() server_process = FakeServerProcess(port_obj=port_obj, name="test", cmd=["test"]) server_process._start() server_process.stop() self.assertTrue(server_process.stdin.closed) self.assertTrue(server_process.stdout.closed) self.assertTrue(server_process.stderr.closed) def test_broken_pipe(self): port_obj = TrivialMockPort() port_obj.host.platform.os_name = 'win' server_process = FakeServerProcess(port_obj=port_obj, name="test", cmd=["test"]) server_process.write("should break") self.assertTrue(server_process.has_crashed()) self.assertIsNotNone(server_process.pid()) self.assertIsNone(server_process._proc) self.assertEqual(server_process.broken_pipes, [server_process.stdin]) port_obj.host.platform.os_name = 'mac' server_process = FakeServerProcess(port_obj=port_obj, name="test", cmd=["test"]) server_process.write("should break") self.assertTrue(server_process.has_crashed()) self.assertIsNone(server_process._proc) self.assertEqual(server_process.broken_pipes, [server_process.stdin])
bsd-3-clause
simbha/mAngE-Gin
lib/django/utils/safestring.py
66
4366
""" Functions for working with "safe strings": strings that can be displayed safely without further escaping in HTML. Marking something as a "safe string" means that the producer of the string has already turned characters that should not be interpreted by the HTML engine (e.g. '<') into the appropriate entities. """ from django.utils.functional import curry, Promise from django.utils import six class EscapeData(object): pass class EscapeBytes(bytes, EscapeData): """ A byte string that should be HTML-escaped when output. """ pass class EscapeText(six.text_type, EscapeData): """ A unicode string object that should be HTML-escaped when output. """ pass if six.PY3: EscapeString = EscapeText else: EscapeString = EscapeBytes # backwards compatibility for Python 2 EscapeUnicode = EscapeText class SafeData(object): def __html__(self): """ Returns the html representation of a string. Allows interoperability with other template engines. """ return self class SafeBytes(bytes, SafeData): """ A bytes subclass that has been specifically marked as "safe" (requires no further escaping) for HTML output purposes. """ def __add__(self, rhs): """ Concatenating a safe byte string with another safe byte string or safe unicode string is safe. Otherwise, the result is no longer safe. """ t = super(SafeBytes, self).__add__(rhs) if isinstance(rhs, SafeText): return SafeText(t) elif isinstance(rhs, SafeBytes): return SafeBytes(t) return t def _proxy_method(self, *args, **kwargs): """ Wrap a call to a normal unicode method up so that we return safe results. The method that is being wrapped is passed in the 'method' argument. """ method = kwargs.pop('method') data = method(self, *args, **kwargs) if isinstance(data, bytes): return SafeBytes(data) else: return SafeText(data) decode = curry(_proxy_method, method=bytes.decode) class SafeText(six.text_type, SafeData): """ A unicode (Python 2) / str (Python 3) subclass that has been specifically marked as "safe" for HTML output purposes. """ def __add__(self, rhs): """ Concatenating a safe unicode string with another safe byte string or safe unicode string is safe. Otherwise, the result is no longer safe. """ t = super(SafeText, self).__add__(rhs) if isinstance(rhs, SafeData): return SafeText(t) return t def _proxy_method(self, *args, **kwargs): """ Wrap a call to a normal unicode method up so that we return safe results. The method that is being wrapped is passed in the 'method' argument. """ method = kwargs.pop('method') data = method(self, *args, **kwargs) if isinstance(data, bytes): return SafeBytes(data) else: return SafeText(data) encode = curry(_proxy_method, method=six.text_type.encode) if six.PY3: SafeString = SafeText else: SafeString = SafeBytes # backwards compatibility for Python 2 SafeUnicode = SafeText def mark_safe(s): """ Explicitly mark a string as safe for (HTML) output purposes. The returned object can be used everywhere a string or unicode object is appropriate. Can be called multiple times on a single string. """ if isinstance(s, SafeData): return s if isinstance(s, bytes) or (isinstance(s, Promise) and s._delegate_bytes): return SafeBytes(s) if isinstance(s, (six.text_type, Promise)): return SafeText(s) return SafeString(str(s)) def mark_for_escaping(s): """ Explicitly mark a string as requiring HTML escaping upon output. Has no effect on SafeData subclasses. Can be called multiple times on a single string (the resulting escaping is only applied once). """ if isinstance(s, (SafeData, EscapeData)): return s if isinstance(s, bytes) or (isinstance(s, Promise) and s._delegate_bytes): return EscapeBytes(s) if isinstance(s, (six.text_type, Promise)): return EscapeText(s) return EscapeBytes(bytes(s))
mit
elrosti/mopidy-gmusic
tests/test_lru_cache.py
2
1297
import unittest from mopidy_gmusic.lru_cache import LruCache class ExtensionTest(unittest.TestCase): def test_init(self): c = LruCache() self.assertIsNotNone(c) self.assertTrue(c.get_max_size() > 0, 'Size should be greater then zero!') def test_init_size(self): c = LruCache(5) self.assertEqual(c.get_max_size(), 5) def test_init_error(self): for size in [0, -1]: self.assertRaises(ValueError, LruCache, size) def test_add(self): c = LruCache(2) c['a'] = 1 c['b'] = 2 c['c'] = 3 self.assertNotIn('a', c) self.assertIn('b', c) self.assertIn('c', c) def test_update(self): c = LruCache(2) c['a'] = 1 c['b'] = 2 c['a'] = 4 c['c'] = 3 self.assertIn('a', c) self.assertNotIn('b', c) self.assertIn('c', c) def test_hit(self): c = LruCache(2) c['a'] = 1 c['b'] = 2 self.assertEqual(c.hit('a'), 1) c['c'] = 3 self.assertIn('a', c) self.assertNotIn('b', c) self.assertIn('c', c) def test_miss(self): c = LruCache(2) c['a'] = 1 c['b'] = 2 self.assertIsNone(c.hit('c'))
apache-2.0
augustozuniga/arisgames
zxing-master/cpp/scons/scons-local-2.0.0.final.0/SCons/Tool/dvi.py
34
2386
"""SCons.Tool.dvi Common DVI Builder definition for various other Tool modules that use it. """ # # Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 The SCons Foundation # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # __revision__ = "src/engine/SCons/Tool/dvi.py 5023 2010/06/14 22:05:46 scons" import SCons.Builder import SCons.Tool DVIBuilder = None def generate(env): try: env['BUILDERS']['DVI'] except KeyError: global DVIBuilder if DVIBuilder is None: # The suffix is hard-coded to '.dvi', not configurable via a # construction variable like $DVISUFFIX, because the output # file name is hard-coded within TeX. DVIBuilder = SCons.Builder.Builder(action = {}, source_scanner = SCons.Tool.LaTeXScanner, suffix = '.dvi', emitter = {}, source_ext_match = None) env['BUILDERS']['DVI'] = DVIBuilder def exists(env): # This only puts a skeleton Builder in place, so if someone # references this Tool directly, it's always "available." return 1 # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
mit
ActiveState/code
recipes/Python/483742_Easy_Cross_Platform_Excel_Parsing/recipe-483742.py
1
7477
class readexcel(object): """ Simple OS Independent Class for Extracting Data from Excel Files the using xlrd module found at http://www.lexicon.net/sjmachin/xlrd.htm Versions of Excel supported: 2004, 2002, XP, 2000, 97, 95, 5, 4, 3 xlrd version tested: 0.5.2 Data is extracted by creating a iterator object which can be used to return data one row at a time. The default extraction method assumes that the worksheet is in tabular format with the first nonblank row containing variable names and all subsequent rows containing values. This method returns a dictionary which uses the variables names as keys for each piece of data in the row. Data can also be extracted with each row represented by a list. Extracted data is represented fairly logically. By default dates are returned as strings in "yyyy/mm/dd" format or "yyyy/mm/dd hh:mm:ss", as appropriate. However, dates can be return as a tuple containing (Year, Month, Day, Hour, Min, Second) which is appropriate for usage with mxDateTime or DateTime. Numbers are returned as either INT or FLOAT, whichever is needed to support the data. Text, booleans, and error codes are also returned as appropriate representations. Quick Example: xl = readexcel('testdata.xls') sheetnames = xl.worksheets() for sheet in sheetnames: print sheet for row in xl.getiter(sheet): # Do Something here """ def __init__(self, filename): """ Returns a readexcel object of the specified filename - this may take a little while because the file must be parsed into memory """ import xlrd import os.path if not os.path.isfile(filename): raise NameError, "%s is not a valid filename" % filename self.__filename__ = filename self.__book__ = xlrd.open_workbook(filename) self.__sheets__ = {} self.__sheetnames__ = [] for i in self.__book__.sheet_names(): uniquevars = [] firstrow = 0 sheet = self.__book__.sheet_by_name(i) for row in range(sheet.nrows): types,values = sheet.row_types(row),sheet.row_values(row) nonblank = False for j in values: if j != '': nonblank=True break if nonblank: # Generate a listing of Unique Variable Names for Use as # Dictionary Keys In Extraction. Duplicate Names will # be replaced with "F#" variables = self.__formatrow__(types,values,False) unknown = 1 while variables: var = variables.pop(0) if var in uniquevars or var == '': var = 'F' + str(unknown) unknown += 1 uniquevars.append(str(var)) firstrow = row + 1 break self.__sheetnames__.append(i) self.__sheets__.setdefault(i,{}).__setitem__('rows',sheet.nrows) self.__sheets__.setdefault(i,{}).__setitem__('cols',sheet.ncols) self.__sheets__.setdefault(i,{}).__setitem__('firstrow',firstrow) self.__sheets__.setdefault(i,{}).__setitem__('variables',uniquevars[:]) def getiter(self, sheetname, returnlist=False, returntupledate=False): """ Return an generator object which yields the lines of a worksheet; Default returns a dictionary, specifing returnlist=True causes lists to be returned. Calling returntupledate=True causes dates to returned as tuples of (Year, Month, Day, Hour, Min, Second) instead of as a string """ if sheetname not in self.__sheets__.keys(): raise NameError, "%s is not present in %s" % (sheetname,\ self.__filename__) if returnlist: return __iterlist__(self, sheetname, returntupledate) else: return __iterdict__(self, sheetname, returntupledate) def worksheets(self): """ Returns a list of the Worksheets in the Excel File """ return self.__sheetnames__ def nrows(self, worksheet): """ Return the number of rows in a worksheet """ return self.__sheets__[worksheet]['rows'] def ncols(self, worksheet): """ Return the number of columns in a worksheet """ return self.__sheets__[worksheet]['cols'] def variables(self,worksheet): """ Returns a list of Column Names in the file, assuming a tabular format of course. """ return self.__sheets__[worksheet]['variables'] def __formatrow__(self, types, values, wanttupledate): """ Internal function used to clean up the incoming excel data """ ## Data Type Codes: ## EMPTY 0 ## TEXT 1 a Unicode string ## NUMBER 2 float ## DATE 3 float ## BOOLEAN 4 int; 1 means TRUE, 0 means FALSE ## ERROR 5 import xlrd returnrow = [] for i in range(len(types)): type,value = types[i],values[i] if type == 2: if value == int(value): value = int(value) elif type == 3: datetuple = xlrd.xldate_as_tuple(value, self.__book__.datemode) if wanttupledate: value = datetuple else: # time only no date component if datetuple[0] == 0 and datetuple[1] == 0 and \ datetuple[2] == 0: value = "%02d:%02d:%02d" % datetuple[3:] # date only, no time elif datetuple[3] == 0 and datetuple[4] == 0 and \ datetuple[5] == 0: value = "%04d/%02d/%02d" % datetuple[:3] else: # full date value = "%04d/%02d/%02d %02d:%02d:%02d" % datetuple elif type == 5: value = xlrd.error_text_from_code[value] returnrow.append(value) return returnrow def __iterlist__(excel, sheetname, tupledate): """ Function Used To Create the List Iterator """ sheet = excel.__book__.sheet_by_name(sheetname) for row in range(excel.__sheets__[sheetname]['rows']): types,values = sheet.row_types(row),sheet.row_values(row) yield excel.__formatrow__(types, values, tupledate) def __iterdict__(excel, sheetname, tupledate): """ Function Used To Create the Dictionary Iterator """ sheet = excel.__book__.sheet_by_name(sheetname) for row in range(excel.__sheets__[sheetname]['firstrow'],\ excel.__sheets__[sheetname]['rows']): types,values = sheet.row_types(row),sheet.row_values(row) formattedrow = excel.__formatrow__(types, values, tupledate) # Pad a Short Row With Blanks if Needed for i in range(len(formattedrow),\ len(excel.__sheets__[sheetname]['variables'])): formattedrow.append('') yield dict(zip(excel.__sheets__[sheetname]['variables'],formattedrow))
mit
jhoenicke/python-trezor
trezorlib/tests/device_tests/test_msg_lisk_getpublickey.py
3
1190
# This file is part of the Trezor project. # # Copyright (C) 2012-2018 SatoshiLabs and contributors # # This library is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License version 3 # as published by the Free Software Foundation. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the License along with this library. # If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>. import pytest from trezorlib import lisk from trezorlib.tools import parse_path from .common import TrezorTest LISK_PATH = parse_path("m/44h/134h/0h/0h") @pytest.mark.lisk class TestMsgLiskGetPublicKey(TrezorTest): def test_lisk_get_public_key(self): self.setup_mnemonic_nopin_nopassphrase() sig = lisk.get_public_key(self.client, LISK_PATH) assert ( sig.public_key.hex() == "eb56d7bbb5e8ea9269405f7a8527fe126023d1db2c973cfac6f760b60ae27294" )
lgpl-3.0
synsun/robotframework
src/robot/output/console/highlighting.py
2
6055
# Copyright 2008-2015 Nokia Solutions and Networks # # 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. # Windows highlighting code adapted from color_console.py. It is copyright # Andre Burgaud, licensed under the MIT License, and available here: # http://www.burgaud.com/bring-colors-to-the-windows-console-with-python/ from contextlib import contextmanager import os import sys try: from ctypes import windll, Structure, c_short, c_ushort, byref except ImportError: # Not on Windows or using Jython windll = None from robot.errors import DataError from robot.utils import console_encode, isatty, WINDOWS class HighlightingStream(object): def __init__(self, stream, colors='AUTO'): self.stream = stream self._highlighter = self._get_highlighter(stream, colors) def _get_highlighter(self, stream, colors): options = {'AUTO': Highlighter if isatty(stream) else NoHighlighting, 'ON': Highlighter, 'OFF': NoHighlighting, 'ANSI': AnsiHighlighter} try: highlighter = options[colors.upper()] except KeyError: raise DataError("Invalid console color value '%s'. Available " "'AUTO', 'ON', 'OFF' and 'ANSI'." % colors) return highlighter(stream) def write(self, text, flush=True): self.stream.write(console_encode(text, stream=self.stream)) if flush: self.flush() def flush(self): self.stream.flush() def highlight(self, text, status=None, flush=True): if self._must_flush_before_and_after_highlighting(): self.flush() flush = True with self._highlighting(status or text): self.write(text, flush) def _must_flush_before_and_after_highlighting(self): # Must flush on Windows before and after highlighting to make sure set # console colors only affect the actual highlighted text. Problems # only encountered with Python 3, but better to be safe than sorry. return WINDOWS and not isinstance(self._highlighter, NoHighlighting) def error(self, message, level): self.write('[ ', flush=False) self.highlight(level, flush=False) self.write(' ] %s\n' % message) @contextmanager def _highlighting(self, status): highlighter = self._highlighter start = {'PASS': highlighter.green, 'FAIL': highlighter.red, 'ERROR': highlighter.red, 'WARN': highlighter.yellow}[status] start() try: yield finally: highlighter.reset() def Highlighter(stream): if os.sep == '/': return AnsiHighlighter(stream) return DosHighlighter(stream) if windll else NoHighlighting(stream) class AnsiHighlighter(object): _ANSI_GREEN = '\033[32m' _ANSI_RED = '\033[31m' _ANSI_YELLOW = '\033[33m' _ANSI_RESET = '\033[0m' def __init__(self, stream): self._stream = stream def green(self): self._set_color(self._ANSI_GREEN) def red(self): self._set_color(self._ANSI_RED) def yellow(self): self._set_color(self._ANSI_YELLOW) def reset(self): self._set_color(self._ANSI_RESET) def _set_color(self, color): self._stream.write(color) class NoHighlighting(AnsiHighlighter): def _set_color(self, color): pass class DosHighlighter(object): _FOREGROUND_GREEN = 0x2 _FOREGROUND_RED = 0x4 _FOREGROUND_YELLOW = 0x6 _FOREGROUND_GREY = 0x7 _FOREGROUND_INTENSITY = 0x8 _BACKGROUND_MASK = 0xF0 _STDOUT_HANDLE = -11 _STDERR_HANDLE = -12 def __init__(self, stream): self._handle = self._get_std_handle(stream) self._orig_colors = self._get_colors() self._background = self._orig_colors & self._BACKGROUND_MASK def green(self): self._set_foreground_colors(self._FOREGROUND_GREEN) def red(self): self._set_foreground_colors(self._FOREGROUND_RED) def yellow(self): self._set_foreground_colors(self._FOREGROUND_YELLOW) def reset(self): self._set_colors(self._orig_colors) def _get_std_handle(self, stream): handle = self._STDOUT_HANDLE \ if stream is sys.__stdout__ else self._STDERR_HANDLE return windll.kernel32.GetStdHandle(handle) def _get_colors(self): csbi = _CONSOLE_SCREEN_BUFFER_INFO() ok = windll.kernel32.GetConsoleScreenBufferInfo(self._handle, byref(csbi)) if not ok: # Call failed, return default console colors (gray on black) return self._FOREGROUND_GREY return csbi.wAttributes def _set_foreground_colors(self, colors): self._set_colors(colors | self._FOREGROUND_INTENSITY | self._background) def _set_colors(self, colors): windll.kernel32.SetConsoleTextAttribute(self._handle, colors) if windll: class _COORD(Structure): _fields_ = [("X", c_short), ("Y", c_short)] class _SMALL_RECT(Structure): _fields_ = [("Left", c_short), ("Top", c_short), ("Right", c_short), ("Bottom", c_short)] class _CONSOLE_SCREEN_BUFFER_INFO(Structure): _fields_ = [("dwSize", _COORD), ("dwCursorPosition", _COORD), ("wAttributes", c_ushort), ("srWindow", _SMALL_RECT), ("dwMaximumWindowSize", _COORD)]
apache-2.0
gitHubOffical/shadowsocks_analysis
shadowsocks/crypto/m2.py
21
3442
#!/usr/bin/env python # Copyright (c) 2014 clowwindy # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from __future__ import absolute_import, division, print_function, \ with_statement import sys import logging __all__ = ['ciphers'] has_m2 = True try: __import__('M2Crypto') except ImportError: has_m2 = False if bytes != str: has_m2 = False def create_cipher(alg, key, iv, op, key_as_bytes=0, d=None, salt=None, i=1, padding=1): import M2Crypto.EVP return M2Crypto.EVP.Cipher(alg.replace('-', '_'), key, iv, op, key_as_bytes=0, d='md5', salt=None, i=1, padding=1) def err(alg, key, iv, op, key_as_bytes=0, d=None, salt=None, i=1, padding=1): logging.error(('M2Crypto is required to use %s, please run' ' `apt-get install python-m2crypto`') % alg) sys.exit(1) if has_m2: ciphers = { b'aes-128-cfb': (16, 16, create_cipher), b'aes-192-cfb': (24, 16, create_cipher), b'aes-256-cfb': (32, 16, create_cipher), b'bf-cfb': (16, 8, create_cipher), b'camellia-128-cfb': (16, 16, create_cipher), b'camellia-192-cfb': (24, 16, create_cipher), b'camellia-256-cfb': (32, 16, create_cipher), b'cast5-cfb': (16, 8, create_cipher), b'des-cfb': (8, 8, create_cipher), b'idea-cfb': (16, 8, create_cipher), b'rc2-cfb': (16, 8, create_cipher), b'rc4': (16, 0, create_cipher), b'seed-cfb': (16, 16, create_cipher), } else: ciphers = {} def run_method(method): from shadowsocks.crypto import util cipher = create_cipher(method, b'k' * 32, b'i' * 16, 1) decipher = create_cipher(method, b'k' * 32, b'i' * 16, 0) util.run_cipher(cipher, decipher) def check_env(): # skip this test on pypy and Python 3 try: import __pypy__ del __pypy__ from nose.plugins.skip import SkipTest raise SkipTest except ImportError: pass if bytes != str: from nose.plugins.skip import SkipTest raise SkipTest def test_aes_128_cfb(): check_env() run_method(b'aes-128-cfb') def test_aes_256_cfb(): check_env() run_method(b'aes-256-cfb') def test_bf_cfb(): check_env() run_method(b'bf-cfb') def test_rc4(): check_env() run_method(b'rc4') if __name__ == '__main__': test_aes_128_cfb()
mit
HellerCommaA/flask-angular
lib/python2.7/site-packages/sqlalchemy/dialects/sqlite/base.py
6
34406
# sqlite/base.py # Copyright (C) 2005-2013 the SQLAlchemy authors and contributors <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php """ .. dialect:: sqlite :name: SQLite Date and Time Types ------------------- SQLite does not have built-in DATE, TIME, or DATETIME types, and pysqlite does not provide out of the box functionality for translating values between Python `datetime` objects and a SQLite-supported format. SQLAlchemy's own :class:`~sqlalchemy.types.DateTime` and related types provide date formatting and parsing functionality when SQlite is used. The implementation classes are :class:`~.sqlite.DATETIME`, :class:`~.sqlite.DATE` and :class:`~.sqlite.TIME`. These types represent dates and times as ISO formatted strings, which also nicely support ordering. There's no reliance on typical "libc" internals for these functions so historical dates are fully supported. Auto Incrementing Behavior -------------------------- Background on SQLite's autoincrement is at: http://sqlite.org/autoinc.html Two things to note: * The AUTOINCREMENT keyword is **not** required for SQLite tables to generate primary key values automatically. AUTOINCREMENT only means that the algorithm used to generate ROWID values should be slightly different. * SQLite does **not** generate primary key (i.e. ROWID) values, even for one column, if the table has a composite (i.e. multi-column) primary key. This is regardless of the AUTOINCREMENT keyword being present or not. To specifically render the AUTOINCREMENT keyword on the primary key column when rendering DDL, add the flag ``sqlite_autoincrement=True`` to the Table construct:: Table('sometable', metadata, Column('id', Integer, primary_key=True), sqlite_autoincrement=True) Transaction Isolation Level --------------------------- :func:`.create_engine` accepts an ``isolation_level`` parameter which results in the command ``PRAGMA read_uncommitted <level>`` being invoked for every new connection. Valid values for this parameter are ``SERIALIZABLE`` and ``READ UNCOMMITTED`` corresponding to a value of 0 and 1, respectively. See the section :ref:`pysqlite_serializable` for an important workaround when using serializable isolation with Pysqlite. Database Locking Behavior / Concurrency --------------------------------------- Note that SQLite is not designed for a high level of concurrency. The database itself, being a file, is locked completely during write operations and within transactions, meaning exactly one connection has exclusive access to the database during this period - all other connections will be blocked during this time. The Python DBAPI specification also calls for a connection model that is always in a transaction; there is no BEGIN method, only commit and rollback. This implies that a SQLite DBAPI driver would technically allow only serialized access to a particular database file at all times. The pysqlite driver attempts to ameliorate this by deferring the actual BEGIN statement until the first DML (INSERT, UPDATE, or DELETE) is received within a transaction. While this breaks serializable isolation, it at least delays the exclusive locking inherent in SQLite's design. SQLAlchemy's default mode of usage with the ORM is known as "autocommit=False", which means the moment the :class:`.Session` begins to be used, a transaction is begun. As the :class:`.Session` is used, the autoflush feature, also on by default, will flush out pending changes to the database before each query. The effect of this is that a :class:`.Session` used in its default mode will often emit DML early on, long before the transaction is actually committed. This again will have the effect of serializing access to the SQLite database. If highly concurrent reads are desired against the SQLite database, it is advised that the autoflush feature be disabled, and potentially even that autocommit be re-enabled, which has the effect of each SQL statement and flush committing changes immediately. For more information on SQLite's lack of concurrency by design, please see `Situations Where Another RDBMS May Work Better - High Concurrency <http://www.sqlite.org/whentouse.html>`_ near the bottom of the page. .. _sqlite_foreign_keys: Foreign Key Support ------------------- SQLite supports FOREIGN KEY syntax when emitting CREATE statements for tables, however by default these constraints have no effect on the operation of the table. Constraint checking on SQLite has three prerequisites: * At least version 3.6.19 of SQLite must be in use * The SQLite libary must be compiled *without* the SQLITE_OMIT_FOREIGN_KEY or SQLITE_OMIT_TRIGGER symbols enabled. * The ``PRAGMA foreign_keys = ON`` statement must be emitted on all connections before use. SQLAlchemy allows for the ``PRAGMA`` statement to be emitted automatically for new connections through the usage of events:: from sqlalchemy.engine import Engine from sqlalchemy import event @event.listens_for(Engine, "connect") def set_sqlite_pragma(dbapi_connection, connection_record): cursor = dbapi_connection.cursor() cursor.execute("PRAGMA foreign_keys=ON") cursor.close() .. seealso:: `SQLite Foreign Key Support <http://www.sqlite.org/foreignkeys.html>`_ - on the SQLite web site. :ref:`event_toplevel` - SQLAlchemy event API. """ import datetime import re from sqlalchemy import sql, exc from sqlalchemy.engine import default, base, reflection from sqlalchemy import types as sqltypes from sqlalchemy import util from sqlalchemy.sql import compiler from sqlalchemy import processors from sqlalchemy.types import BIGINT, BLOB, BOOLEAN, CHAR,\ DECIMAL, FLOAT, REAL, INTEGER, NUMERIC, SMALLINT, TEXT,\ TIMESTAMP, VARCHAR class _DateTimeMixin(object): _reg = None _storage_format = None def __init__(self, storage_format=None, regexp=None, **kw): super(_DateTimeMixin, self).__init__(**kw) if regexp is not None: self._reg = re.compile(regexp) if storage_format is not None: self._storage_format = storage_format class DATETIME(_DateTimeMixin, sqltypes.DateTime): """Represent a Python datetime object in SQLite using a string. The default string storage format is:: "%(year)04d-%(month)02d-%(day)02d %(hour)02d:%(min)02d:%(second)02d.%(microsecond)06d" e.g.:: 2011-03-15 12:05:57.10558 The storage format can be customized to some degree using the ``storage_format`` and ``regexp`` parameters, such as:: import re from sqlalchemy.dialects.sqlite import DATETIME dt = DATETIME( storage_format="%(year)04d/%(month)02d/%(day)02d %(hour)02d:%(min)02d:%(second)02d", regexp=re.compile("(\d+)/(\d+)/(\d+) (\d+)-(\d+)-(\d+)") ) :param storage_format: format string which will be applied to the dict with keys year, month, day, hour, minute, second, and microsecond. :param regexp: regular expression which will be applied to incoming result rows. If the regexp contains named groups, the resulting match dict is applied to the Python datetime() constructor as keyword arguments. Otherwise, if positional groups are used, the the datetime() constructor is called with positional arguments via ``*map(int, match_obj.groups(0))``. """ _storage_format = ( "%(year)04d-%(month)02d-%(day)02d " "%(hour)02d:%(minute)02d:%(second)02d.%(microsecond)06d" ) def __init__(self, *args, **kwargs): truncate_microseconds = kwargs.pop('truncate_microseconds', False) super(DATETIME, self).__init__(*args, **kwargs) if truncate_microseconds: assert 'storage_format' not in kwargs, "You can specify only "\ "one of truncate_microseconds or storage_format." assert 'regexp' not in kwargs, "You can specify only one of "\ "truncate_microseconds or regexp." self._storage_format = ( "%(year)04d-%(month)02d-%(day)02d " "%(hour)02d:%(minute)02d:%(second)02d" ) def bind_processor(self, dialect): datetime_datetime = datetime.datetime datetime_date = datetime.date format = self._storage_format def process(value): if value is None: return None elif isinstance(value, datetime_datetime): return format % { 'year': value.year, 'month': value.month, 'day': value.day, 'hour': value.hour, 'minute': value.minute, 'second': value.second, 'microsecond': value.microsecond, } elif isinstance(value, datetime_date): return format % { 'year': value.year, 'month': value.month, 'day': value.day, 'hour': 0, 'minute': 0, 'second': 0, 'microsecond': 0, } else: raise TypeError("SQLite DateTime type only accepts Python " "datetime and date objects as input.") return process def result_processor(self, dialect, coltype): if self._reg: return processors.str_to_datetime_processor_factory( self._reg, datetime.datetime) else: return processors.str_to_datetime class DATE(_DateTimeMixin, sqltypes.Date): """Represent a Python date object in SQLite using a string. The default string storage format is:: "%(year)04d-%(month)02d-%(day)02d" e.g.:: 2011-03-15 The storage format can be customized to some degree using the ``storage_format`` and ``regexp`` parameters, such as:: import re from sqlalchemy.dialects.sqlite import DATE d = DATE( storage_format="%(month)02d/%(day)02d/%(year)04d", regexp=re.compile("(?P<month>\d+)/(?P<day>\d+)/(?P<year>\d+)") ) :param storage_format: format string which will be applied to the dict with keys year, month, and day. :param regexp: regular expression which will be applied to incoming result rows. If the regexp contains named groups, the resulting match dict is applied to the Python date() constructor as keyword arguments. Otherwise, if positional groups are used, the the date() constructor is called with positional arguments via ``*map(int, match_obj.groups(0))``. """ _storage_format = "%(year)04d-%(month)02d-%(day)02d" def bind_processor(self, dialect): datetime_date = datetime.date format = self._storage_format def process(value): if value is None: return None elif isinstance(value, datetime_date): return format % { 'year': value.year, 'month': value.month, 'day': value.day, } else: raise TypeError("SQLite Date type only accepts Python " "date objects as input.") return process def result_processor(self, dialect, coltype): if self._reg: return processors.str_to_datetime_processor_factory( self._reg, datetime.date) else: return processors.str_to_date class TIME(_DateTimeMixin, sqltypes.Time): """Represent a Python time object in SQLite using a string. The default string storage format is:: "%(hour)02d:%(minute)02d:%(second)02d.%(microsecond)06d" e.g.:: 12:05:57.10558 The storage format can be customized to some degree using the ``storage_format`` and ``regexp`` parameters, such as:: import re from sqlalchemy.dialects.sqlite import TIME t = TIME( storage_format="%(hour)02d-%(minute)02d-%(second)02d-%(microsecond)06d", regexp=re.compile("(\d+)-(\d+)-(\d+)-(?:-(\d+))?") ) :param storage_format: format string which will be applied to the dict with keys hour, minute, second, and microsecond. :param regexp: regular expression which will be applied to incoming result rows. If the regexp contains named groups, the resulting match dict is applied to the Python time() constructor as keyword arguments. Otherwise, if positional groups are used, the the time() constructor is called with positional arguments via ``*map(int, match_obj.groups(0))``. """ _storage_format = "%(hour)02d:%(minute)02d:%(second)02d.%(microsecond)06d" def __init__(self, *args, **kwargs): truncate_microseconds = kwargs.pop('truncate_microseconds', False) super(TIME, self).__init__(*args, **kwargs) if truncate_microseconds: assert 'storage_format' not in kwargs, "You can specify only "\ "one of truncate_microseconds or storage_format." assert 'regexp' not in kwargs, "You can specify only one of "\ "truncate_microseconds or regexp." self._storage_format = "%(hour)02d:%(minute)02d:%(second)02d" def bind_processor(self, dialect): datetime_time = datetime.time format = self._storage_format def process(value): if value is None: return None elif isinstance(value, datetime_time): return format % { 'hour': value.hour, 'minute': value.minute, 'second': value.second, 'microsecond': value.microsecond, } else: raise TypeError("SQLite Time type only accepts Python " "time objects as input.") return process def result_processor(self, dialect, coltype): if self._reg: return processors.str_to_datetime_processor_factory( self._reg, datetime.time) else: return processors.str_to_time colspecs = { sqltypes.Date: DATE, sqltypes.DateTime: DATETIME, sqltypes.Time: TIME, } ischema_names = { 'BIGINT': sqltypes.BIGINT, 'BLOB': sqltypes.BLOB, 'BOOL': sqltypes.BOOLEAN, 'BOOLEAN': sqltypes.BOOLEAN, 'CHAR': sqltypes.CHAR, 'DATE': sqltypes.DATE, 'DATETIME': sqltypes.DATETIME, 'DECIMAL': sqltypes.DECIMAL, 'FLOAT': sqltypes.FLOAT, 'INT': sqltypes.INTEGER, 'INTEGER': sqltypes.INTEGER, 'NUMERIC': sqltypes.NUMERIC, 'REAL': sqltypes.REAL, 'SMALLINT': sqltypes.SMALLINT, 'TEXT': sqltypes.TEXT, 'TIME': sqltypes.TIME, 'TIMESTAMP': sqltypes.TIMESTAMP, 'VARCHAR': sqltypes.VARCHAR, 'NVARCHAR': sqltypes.NVARCHAR, 'NCHAR': sqltypes.NCHAR, } class SQLiteCompiler(compiler.SQLCompiler): extract_map = util.update_copy( compiler.SQLCompiler.extract_map, { 'month': '%m', 'day': '%d', 'year': '%Y', 'second': '%S', 'hour': '%H', 'doy': '%j', 'minute': '%M', 'epoch': '%s', 'dow': '%w', 'week': '%W' }) def visit_now_func(self, fn, **kw): return "CURRENT_TIMESTAMP" def visit_localtimestamp_func(self, func, **kw): return 'DATETIME(CURRENT_TIMESTAMP, "localtime")' def visit_true(self, expr, **kw): return '1' def visit_false(self, expr, **kw): return '0' def visit_char_length_func(self, fn, **kw): return "length%s" % self.function_argspec(fn) def visit_cast(self, cast, **kwargs): if self.dialect.supports_cast: return super(SQLiteCompiler, self).visit_cast(cast) else: return self.process(cast.clause) def visit_extract(self, extract, **kw): try: return "CAST(STRFTIME('%s', %s) AS INTEGER)" % ( self.extract_map[extract.field], self.process(extract.expr, **kw) ) except KeyError: raise exc.CompileError( "%s is not a valid extract argument." % extract.field) def limit_clause(self, select): text = "" if select._limit is not None: text += "\n LIMIT " + self.process(sql.literal(select._limit)) if select._offset is not None: if select._limit is None: text += "\n LIMIT " + self.process(sql.literal(-1)) text += " OFFSET " + self.process(sql.literal(select._offset)) else: text += " OFFSET " + self.process(sql.literal(0)) return text def for_update_clause(self, select): # sqlite has no "FOR UPDATE" AFAICT return '' class SQLiteDDLCompiler(compiler.DDLCompiler): def get_column_specification(self, column, **kwargs): coltype = self.dialect.type_compiler.process(column.type) colspec = self.preparer.format_column(column) + " " + coltype default = self.get_column_default_string(column) if default is not None: colspec += " DEFAULT " + default if not column.nullable: colspec += " NOT NULL" if (column.primary_key and column.table.kwargs.get('sqlite_autoincrement', False) and len(column.table.primary_key.columns) == 1 and issubclass(column.type._type_affinity, sqltypes.Integer) and not column.foreign_keys): colspec += " PRIMARY KEY AUTOINCREMENT" return colspec def visit_primary_key_constraint(self, constraint): # for columns with sqlite_autoincrement=True, # the PRIMARY KEY constraint can only be inline # with the column itself. if len(constraint.columns) == 1: c = list(constraint)[0] if c.primary_key and \ c.table.kwargs.get('sqlite_autoincrement', False) and \ issubclass(c.type._type_affinity, sqltypes.Integer) and \ not c.foreign_keys: return None return super(SQLiteDDLCompiler, self).\ visit_primary_key_constraint(constraint) def visit_foreign_key_constraint(self, constraint): local_table = constraint._elements.values()[0].parent.table remote_table = list(constraint._elements.values())[0].column.table if local_table.schema != remote_table.schema: return None else: return super(SQLiteDDLCompiler, self).visit_foreign_key_constraint(constraint) def define_constraint_remote_table(self, constraint, table, preparer): """Format the remote table clause of a CREATE CONSTRAINT clause.""" return preparer.format_table(table, use_schema=False) def visit_create_index(self, create): return super(SQLiteDDLCompiler, self).\ visit_create_index(create, include_table_schema=False) class SQLiteTypeCompiler(compiler.GenericTypeCompiler): def visit_large_binary(self, type_): return self.visit_BLOB(type_) class SQLiteIdentifierPreparer(compiler.IdentifierPreparer): reserved_words = set([ 'add', 'after', 'all', 'alter', 'analyze', 'and', 'as', 'asc', 'attach', 'autoincrement', 'before', 'begin', 'between', 'by', 'cascade', 'case', 'cast', 'check', 'collate', 'column', 'commit', 'conflict', 'constraint', 'create', 'cross', 'current_date', 'current_time', 'current_timestamp', 'database', 'default', 'deferrable', 'deferred', 'delete', 'desc', 'detach', 'distinct', 'drop', 'each', 'else', 'end', 'escape', 'except', 'exclusive', 'explain', 'false', 'fail', 'for', 'foreign', 'from', 'full', 'glob', 'group', 'having', 'if', 'ignore', 'immediate', 'in', 'index', 'indexed', 'initially', 'inner', 'insert', 'instead', 'intersect', 'into', 'is', 'isnull', 'join', 'key', 'left', 'like', 'limit', 'match', 'natural', 'not', 'notnull', 'null', 'of', 'offset', 'on', 'or', 'order', 'outer', 'plan', 'pragma', 'primary', 'query', 'raise', 'references', 'reindex', 'rename', 'replace', 'restrict', 'right', 'rollback', 'row', 'select', 'set', 'table', 'temp', 'temporary', 'then', 'to', 'transaction', 'trigger', 'true', 'union', 'unique', 'update', 'using', 'vacuum', 'values', 'view', 'virtual', 'when', 'where', ]) def format_index(self, index, use_schema=True, name=None): """Prepare a quoted index and schema name.""" if name is None: name = index.name result = self.quote(name, index.quote) if (not self.omit_schema and use_schema and getattr(index.table, "schema", None)): result = self.quote_schema( index.table.schema, index.table.quote_schema) + "." + result return result class SQLiteExecutionContext(default.DefaultExecutionContext): @util.memoized_property def _preserve_raw_colnames(self): return self.execution_options.get("sqlite_raw_colnames", False) def _translate_colname(self, colname): # adjust for dotted column names. SQLite # in the case of UNION may store col names as # "tablename.colname" # in cursor.description if not self._preserve_raw_colnames and "." in colname: return colname.split(".")[1], colname else: return colname, None class SQLiteDialect(default.DefaultDialect): name = 'sqlite' supports_alter = False supports_unicode_statements = True supports_unicode_binds = True supports_default_values = True supports_empty_insert = False supports_cast = True supports_multivalues_insert = True default_paramstyle = 'qmark' execution_ctx_cls = SQLiteExecutionContext statement_compiler = SQLiteCompiler ddl_compiler = SQLiteDDLCompiler type_compiler = SQLiteTypeCompiler preparer = SQLiteIdentifierPreparer ischema_names = ischema_names colspecs = colspecs isolation_level = None supports_cast = True supports_default_values = True _broken_fk_pragma_quotes = False def __init__(self, isolation_level=None, native_datetime=False, **kwargs): default.DefaultDialect.__init__(self, **kwargs) self.isolation_level = isolation_level # this flag used by pysqlite dialect, and perhaps others in the # future, to indicate the driver is handling date/timestamp # conversions (and perhaps datetime/time as well on some # hypothetical driver ?) self.native_datetime = native_datetime if self.dbapi is not None: self.supports_default_values = \ self.dbapi.sqlite_version_info >= (3, 3, 8) self.supports_cast = \ self.dbapi.sqlite_version_info >= (3, 2, 3) self.supports_multivalues_insert = \ self.dbapi.sqlite_version_info >= (3, 7, 11) # http://www.sqlite.org/releaselog/3_7_11.html # see http://www.sqlalchemy.org/trac/ticket/2568 # as well as http://www.sqlite.org/src/info/600482d161 self._broken_fk_pragma_quotes = \ self.dbapi.sqlite_version_info < (3, 6, 14) _isolation_lookup = { 'READ UNCOMMITTED': 1, 'SERIALIZABLE': 0 } def set_isolation_level(self, connection, level): try: isolation_level = self._isolation_lookup[level.replace('_', ' ')] except KeyError: raise exc.ArgumentError( "Invalid value '%s' for isolation_level. " "Valid isolation levels for %s are %s" % (level, self.name, ", ".join(self._isolation_lookup)) ) cursor = connection.cursor() cursor.execute("PRAGMA read_uncommitted = %d" % isolation_level) cursor.close() def get_isolation_level(self, connection): cursor = connection.cursor() cursor.execute('PRAGMA read_uncommitted') res = cursor.fetchone() if res: value = res[0] else: # http://www.sqlite.org/changes.html#version_3_3_3 # "Optional READ UNCOMMITTED isolation (instead of the # default isolation level of SERIALIZABLE) and # table level locking when database connections # share a common cache."" # pre-SQLite 3.3.0 default to 0 value = 0 cursor.close() if value == 0: return "SERIALIZABLE" elif value == 1: return "READ UNCOMMITTED" else: assert False, "Unknown isolation level %s" % value def on_connect(self): if self.isolation_level is not None: def connect(conn): self.set_isolation_level(conn, self.isolation_level) return connect else: return None @reflection.cache def get_table_names(self, connection, schema=None, **kw): if schema is not None: qschema = self.identifier_preparer.quote_identifier(schema) master = '%s.sqlite_master' % qschema s = ("SELECT name FROM %s " "WHERE type='table' ORDER BY name") % (master,) rs = connection.execute(s) else: try: s = ("SELECT name FROM " " (SELECT * FROM sqlite_master UNION ALL " " SELECT * FROM sqlite_temp_master) " "WHERE type='table' ORDER BY name") rs = connection.execute(s) except exc.DBAPIError: s = ("SELECT name FROM sqlite_master " "WHERE type='table' ORDER BY name") rs = connection.execute(s) return [row[0] for row in rs] def has_table(self, connection, table_name, schema=None): quote = self.identifier_preparer.quote_identifier if schema is not None: pragma = "PRAGMA %s." % quote(schema) else: pragma = "PRAGMA " qtable = quote(table_name) statement = "%stable_info(%s)" % (pragma, qtable) cursor = _pragma_cursor(connection.execute(statement)) row = cursor.fetchone() # consume remaining rows, to work around # http://www.sqlite.org/cvstrac/tktview?tn=1884 while not cursor.closed and cursor.fetchone() is not None: pass return (row is not None) @reflection.cache def get_view_names(self, connection, schema=None, **kw): if schema is not None: qschema = self.identifier_preparer.quote_identifier(schema) master = '%s.sqlite_master' % qschema s = ("SELECT name FROM %s " "WHERE type='view' ORDER BY name") % (master,) rs = connection.execute(s) else: try: s = ("SELECT name FROM " " (SELECT * FROM sqlite_master UNION ALL " " SELECT * FROM sqlite_temp_master) " "WHERE type='view' ORDER BY name") rs = connection.execute(s) except exc.DBAPIError: s = ("SELECT name FROM sqlite_master " "WHERE type='view' ORDER BY name") rs = connection.execute(s) return [row[0] for row in rs] @reflection.cache def get_view_definition(self, connection, view_name, schema=None, **kw): quote = self.identifier_preparer.quote_identifier if schema is not None: qschema = self.identifier_preparer.quote_identifier(schema) master = '%s.sqlite_master' % qschema s = ("SELECT sql FROM %s WHERE name = '%s'" "AND type='view'") % (master, view_name) rs = connection.execute(s) else: try: s = ("SELECT sql FROM " " (SELECT * FROM sqlite_master UNION ALL " " SELECT * FROM sqlite_temp_master) " "WHERE name = '%s' " "AND type='view'") % view_name rs = connection.execute(s) except exc.DBAPIError: s = ("SELECT sql FROM sqlite_master WHERE name = '%s' " "AND type='view'") % view_name rs = connection.execute(s) result = rs.fetchall() if result: return result[0].sql @reflection.cache def get_columns(self, connection, table_name, schema=None, **kw): quote = self.identifier_preparer.quote_identifier if schema is not None: pragma = "PRAGMA %s." % quote(schema) else: pragma = "PRAGMA " qtable = quote(table_name) statement = "%stable_info(%s)" % (pragma, qtable) c = _pragma_cursor(connection.execute(statement)) rows = c.fetchall() columns = [] for row in rows: (name, type_, nullable, default, primary_key) = \ (row[1], row[2].upper(), not row[3], row[4], row[5]) columns.append(self._get_column_info(name, type_, nullable, default, primary_key)) return columns def _get_column_info(self, name, type_, nullable, default, primary_key): match = re.match(r'(\w+)(\(.*?\))?', type_) if match: coltype = match.group(1) args = match.group(2) else: coltype = "VARCHAR" args = '' try: coltype = self.ischema_names[coltype] if args is not None: args = re.findall(r'(\d+)', args) coltype = coltype(*[int(a) for a in args]) except KeyError: util.warn("Did not recognize type '%s' of column '%s'" % (coltype, name)) coltype = sqltypes.NullType() if default is not None: default = unicode(default) return { 'name': name, 'type': coltype, 'nullable': nullable, 'default': default, 'autoincrement': default is None, 'primary_key': primary_key } @reflection.cache def get_pk_constraint(self, connection, table_name, schema=None, **kw): cols = self.get_columns(connection, table_name, schema, **kw) pkeys = [] for col in cols: if col['primary_key']: pkeys.append(col['name']) return {'constrained_columns': pkeys, 'name': None} @reflection.cache def get_foreign_keys(self, connection, table_name, schema=None, **kw): quote = self.identifier_preparer.quote_identifier if schema is not None: pragma = "PRAGMA %s." % quote(schema) else: pragma = "PRAGMA " qtable = quote(table_name) statement = "%sforeign_key_list(%s)" % (pragma, qtable) c = _pragma_cursor(connection.execute(statement)) fkeys = [] fks = {} while True: row = c.fetchone() if row is None: break (numerical_id, rtbl, lcol, rcol) = (row[0], row[2], row[3], row[4]) self._parse_fk(fks, fkeys, numerical_id, rtbl, lcol, rcol) return fkeys def _parse_fk(self, fks, fkeys, numerical_id, rtbl, lcol, rcol): # sqlite won't return rcol if the table # was created with REFERENCES <tablename>, no col if rcol is None: rcol = lcol if self._broken_fk_pragma_quotes: rtbl = re.sub(r'^[\"\[`\']|[\"\]`\']$', '', rtbl) try: fk = fks[numerical_id] except KeyError: fk = { 'name': None, 'constrained_columns': [], 'referred_schema': None, 'referred_table': rtbl, 'referred_columns': [] } fkeys.append(fk) fks[numerical_id] = fk if lcol not in fk['constrained_columns']: fk['constrained_columns'].append(lcol) if rcol not in fk['referred_columns']: fk['referred_columns'].append(rcol) return fk @reflection.cache def get_indexes(self, connection, table_name, schema=None, **kw): quote = self.identifier_preparer.quote_identifier if schema is not None: pragma = "PRAGMA %s." % quote(schema) else: pragma = "PRAGMA " include_auto_indexes = kw.pop('include_auto_indexes', False) qtable = quote(table_name) statement = "%sindex_list(%s)" % (pragma, qtable) c = _pragma_cursor(connection.execute(statement)) indexes = [] while True: row = c.fetchone() if row is None: break # ignore implicit primary key index. # http://www.mail-archive.com/sqlite-users@sqlite.org/msg30517.html elif (not include_auto_indexes and row[1].startswith('sqlite_autoindex')): continue indexes.append(dict(name=row[1], column_names=[], unique=row[2])) # loop thru unique indexes to get the column names. for idx in indexes: statement = "%sindex_info(%s)" % (pragma, quote(idx['name'])) c = connection.execute(statement) cols = idx['column_names'] while True: row = c.fetchone() if row is None: break cols.append(row[2]) return indexes def _pragma_cursor(cursor): """work around SQLite issue whereby cursor.description is blank when PRAGMA returns no rows.""" if cursor.closed: cursor.fetchone = lambda: None cursor.fetchall = lambda: [] return cursor
mit
schleichdi2/OpenNfr_E2_Gui-6.0
lib/python/Components/FanControl.py
35
4097
import os from Components.config import config, ConfigSubList, ConfigSubsection, ConfigSlider from Tools.BoundFunction import boundFunction import NavigationInstance from enigma import iRecordableService, pNavigation from boxbranding import getBoxType class FanControl: # ATM there's only support for one fan def __init__(self): if os.path.exists("/proc/stb/fp/fan_vlt") or os.path.exists("/proc/stb/fp/fan_pwm") or os.path.exists("/proc/stb/fp/fan_speed"): self.fancount = 1 else: self.fancount = 0 self.createConfig() config.misc.standbyCounter.addNotifier(self.standbyCounterChanged, initial_call = False) def setVoltage_PWM(self): for fanid in range(self.getFanCount()): cfg = self.getConfig(fanid) self.setVoltage(fanid, cfg.vlt.value) self.setPWM(fanid, cfg.pwm.value) print "[FanControl]: setting fan values: fanid = %d, voltage = %d, pwm = %d" % (fanid, cfg.vlt.value, cfg.pwm.value) def setVoltage_PWM_Standby(self): for fanid in range(self.getFanCount()): cfg = self.getConfig(fanid) self.setVoltage(fanid, cfg.vlt_standby.value) self.setPWM(fanid, cfg.pwm_standby.value) print "[FanControl]: setting fan values (standby mode): fanid = %d, voltage = %d, pwm = %d" % (fanid, cfg.vlt_standby.value, cfg.pwm_standby.value) def getRecordEvent(self, recservice, event): recordings = len(NavigationInstance.instance.getRecordings(False,pNavigation.isRealRecording)) if event == iRecordableService.evEnd: if recordings == 0: self.setVoltage_PWM_Standby() elif event == iRecordableService.evStart: if recordings == 1: self.setVoltage_PWM() def leaveStandby(self): NavigationInstance.instance.record_event.remove(self.getRecordEvent) recordings = NavigationInstance.instance.getRecordings(False,pNavigation.isRealRecording) if not recordings: self.setVoltage_PWM() def standbyCounterChanged(self, configElement): from Screens.Standby import inStandby inStandby.onClose.append(self.leaveStandby) recordings = NavigationInstance.instance.getRecordings(False,pNavigation.isRealRecording) NavigationInstance.instance.record_event.append(self.getRecordEvent) if not recordings: self.setVoltage_PWM_Standby() def createConfig(self): def setVlt(fancontrol, fanid, configElement): fancontrol.setVoltage(fanid, configElement.value) def setPWM(fancontrol, fanid, configElement): fancontrol.setPWM(fanid, configElement.value) config.fans = ConfigSubList() for fanid in range(self.getFanCount()): fan = ConfigSubsection() fan.vlt = ConfigSlider(default = 15, increment = 5, limits = (0, 255)) if getBoxType() == 'tm2t': fan.pwm = ConfigSlider(default = 150, increment = 5, limits = (0, 255)) if getBoxType() == 'tmsingle': fan.pwm = ConfigSlider(default = 100, increment = 5, limits = (0, 255)) else: fan.pwm = ConfigSlider(default = 50, increment = 5, limits = (0, 255)) fan.vlt_standby = ConfigSlider(default = 5, increment = 5, limits = (0, 255)) fan.pwm_standby = ConfigSlider(default = 0, increment = 5, limits = (0, 255)) fan.vlt.addNotifier(boundFunction(setVlt, self, fanid)) fan.pwm.addNotifier(boundFunction(setPWM, self, fanid)) config.fans.append(fan) def getConfig(self, fanid): return config.fans[fanid] def getFanCount(self): return self.fancount def hasRPMSensor(self, fanid): return os.path.exists("/proc/stb/fp/fan_speed") def hasFanControl(self, fanid): return os.path.exists("/proc/stb/fp/fan_vlt") or os.path.exists("/proc/stb/fp/fan_pwm") def getFanSpeed(self, fanid): return int(open("/proc/stb/fp/fan_speed", "r").readline().strip()[:-4]) def getVoltage(self, fanid): return int(open("/proc/stb/fp/fan_vlt", "r").readline().strip(), 16) def setVoltage(self, fanid, value): if value > 255: return open("/proc/stb/fp/fan_vlt", "w").write("%x" % value) def getPWM(self, fanid): return int(open("/proc/stb/fp/fan_pwm", "r").readline().strip(), 16) def setPWM(self, fanid, value): if value > 255: return open("/proc/stb/fp/fan_pwm", "w").write("%x" % value) fancontrol = FanControl()
gpl-2.0
jmptrader/rethinkdb
external/gtest_1.7.0/test/gtest_xml_outfiles_test.py
2526
5340
#!/usr/bin/env python # # Copyright 2008, Google Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Unit test for the gtest_xml_output module.""" __author__ = "keith.ray@gmail.com (Keith Ray)" import os from xml.dom import minidom, Node import gtest_test_utils import gtest_xml_test_utils GTEST_OUTPUT_SUBDIR = "xml_outfiles" GTEST_OUTPUT_1_TEST = "gtest_xml_outfile1_test_" GTEST_OUTPUT_2_TEST = "gtest_xml_outfile2_test_" EXPECTED_XML_1 = """<?xml version="1.0" encoding="UTF-8"?> <testsuites tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*" name="AllTests"> <testsuite name="PropertyOne" tests="1" failures="0" disabled="0" errors="0" time="*"> <testcase name="TestSomeProperties" status="run" time="*" classname="PropertyOne" SetUpProp="1" TestSomeProperty="1" TearDownProp="1" /> </testsuite> </testsuites> """ EXPECTED_XML_2 = """<?xml version="1.0" encoding="UTF-8"?> <testsuites tests="1" failures="0" disabled="0" errors="0" time="*" timestamp="*" name="AllTests"> <testsuite name="PropertyTwo" tests="1" failures="0" disabled="0" errors="0" time="*"> <testcase name="TestSomeProperties" status="run" time="*" classname="PropertyTwo" SetUpProp="2" TestSomeProperty="2" TearDownProp="2" /> </testsuite> </testsuites> """ class GTestXMLOutFilesTest(gtest_xml_test_utils.GTestXMLTestCase): """Unit test for Google Test's XML output functionality.""" def setUp(self): # We want the trailing '/' that the last "" provides in os.path.join, for # telling Google Test to create an output directory instead of a single file # for xml output. self.output_dir_ = os.path.join(gtest_test_utils.GetTempDir(), GTEST_OUTPUT_SUBDIR, "") self.DeleteFilesAndDir() def tearDown(self): self.DeleteFilesAndDir() def DeleteFilesAndDir(self): try: os.remove(os.path.join(self.output_dir_, GTEST_OUTPUT_1_TEST + ".xml")) except os.error: pass try: os.remove(os.path.join(self.output_dir_, GTEST_OUTPUT_2_TEST + ".xml")) except os.error: pass try: os.rmdir(self.output_dir_) except os.error: pass def testOutfile1(self): self._TestOutFile(GTEST_OUTPUT_1_TEST, EXPECTED_XML_1) def testOutfile2(self): self._TestOutFile(GTEST_OUTPUT_2_TEST, EXPECTED_XML_2) def _TestOutFile(self, test_name, expected_xml): gtest_prog_path = gtest_test_utils.GetTestExecutablePath(test_name) command = [gtest_prog_path, "--gtest_output=xml:%s" % self.output_dir_] p = gtest_test_utils.Subprocess(command, working_dir=gtest_test_utils.GetTempDir()) self.assert_(p.exited) self.assertEquals(0, p.exit_code) # TODO(wan@google.com): libtool causes the built test binary to be # named lt-gtest_xml_outfiles_test_ instead of # gtest_xml_outfiles_test_. To account for this possibillity, we # allow both names in the following code. We should remove this # hack when Chandler Carruth's libtool replacement tool is ready. output_file_name1 = test_name + ".xml" output_file1 = os.path.join(self.output_dir_, output_file_name1) output_file_name2 = 'lt-' + output_file_name1 output_file2 = os.path.join(self.output_dir_, output_file_name2) self.assert_(os.path.isfile(output_file1) or os.path.isfile(output_file2), output_file1) expected = minidom.parseString(expected_xml) if os.path.isfile(output_file1): actual = minidom.parse(output_file1) else: actual = minidom.parse(output_file2) self.NormalizeXml(actual.documentElement) self.AssertEquivalentNodes(expected.documentElement, actual.documentElement) expected.unlink() actual.unlink() if __name__ == "__main__": os.environ["GTEST_STACK_TRACE_DEPTH"] = "0" gtest_test_utils.Main()
apache-2.0
stevenzhang18/Indeed-Flask
lib/flask/ctx.py
776
14266
# -*- coding: utf-8 -*- """ flask.ctx ~~~~~~~~~ Implements the objects required to keep the context. :copyright: (c) 2011 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ from __future__ import with_statement import sys from functools import update_wrapper from werkzeug.exceptions import HTTPException from .globals import _request_ctx_stack, _app_ctx_stack from .module import blueprint_is_module from .signals import appcontext_pushed, appcontext_popped class _AppCtxGlobals(object): """A plain object.""" def get(self, name, default=None): return self.__dict__.get(name, default) def __contains__(self, item): return item in self.__dict__ def __iter__(self): return iter(self.__dict__) def __repr__(self): top = _app_ctx_stack.top if top is not None: return '<flask.g of %r>' % top.app.name return object.__repr__(self) def after_this_request(f): """Executes a function after this request. This is useful to modify response objects. The function is passed the response object and has to return the same or a new one. Example:: @app.route('/') def index(): @after_this_request def add_header(response): response.headers['X-Foo'] = 'Parachute' return response return 'Hello World!' This is more useful if a function other than the view function wants to modify a response. For instance think of a decorator that wants to add some headers without converting the return value into a response object. .. versionadded:: 0.9 """ _request_ctx_stack.top._after_request_functions.append(f) return f def copy_current_request_context(f): """A helper function that decorates a function to retain the current request context. This is useful when working with greenlets. The moment the function is decorated a copy of the request context is created and then pushed when the function is called. Example:: import gevent from flask import copy_current_request_context @app.route('/') def index(): @copy_current_request_context def do_some_work(): # do some work here, it can access flask.request like you # would otherwise in the view function. ... gevent.spawn(do_some_work) return 'Regular response' .. versionadded:: 0.10 """ top = _request_ctx_stack.top if top is None: raise RuntimeError('This decorator can only be used at local scopes ' 'when a request context is on the stack. For instance within ' 'view functions.') reqctx = top.copy() def wrapper(*args, **kwargs): with reqctx: return f(*args, **kwargs) return update_wrapper(wrapper, f) def has_request_context(): """If you have code that wants to test if a request context is there or not this function can be used. For instance, you may want to take advantage of request information if the request object is available, but fail silently if it is unavailable. :: class User(db.Model): def __init__(self, username, remote_addr=None): self.username = username if remote_addr is None and has_request_context(): remote_addr = request.remote_addr self.remote_addr = remote_addr Alternatively you can also just test any of the context bound objects (such as :class:`request` or :class:`g` for truthness):: class User(db.Model): def __init__(self, username, remote_addr=None): self.username = username if remote_addr is None and request: remote_addr = request.remote_addr self.remote_addr = remote_addr .. versionadded:: 0.7 """ return _request_ctx_stack.top is not None def has_app_context(): """Works like :func:`has_request_context` but for the application context. You can also just do a boolean check on the :data:`current_app` object instead. .. versionadded:: 0.9 """ return _app_ctx_stack.top is not None class AppContext(object): """The application context binds an application object implicitly to the current thread or greenlet, similar to how the :class:`RequestContext` binds request information. The application context is also implicitly created if a request context is created but the application is not on top of the individual application context. """ def __init__(self, app): self.app = app self.url_adapter = app.create_url_adapter(None) self.g = app.app_ctx_globals_class() # Like request context, app contexts can be pushed multiple times # but there a basic "refcount" is enough to track them. self._refcnt = 0 def push(self): """Binds the app context to the current context.""" self._refcnt += 1 _app_ctx_stack.push(self) appcontext_pushed.send(self.app) def pop(self, exc=None): """Pops the app context.""" self._refcnt -= 1 if self._refcnt <= 0: if exc is None: exc = sys.exc_info()[1] self.app.do_teardown_appcontext(exc) rv = _app_ctx_stack.pop() assert rv is self, 'Popped wrong app context. (%r instead of %r)' \ % (rv, self) appcontext_popped.send(self.app) def __enter__(self): self.push() return self def __exit__(self, exc_type, exc_value, tb): self.pop(exc_value) class RequestContext(object): """The request context contains all request relevant information. It is created at the beginning of the request and pushed to the `_request_ctx_stack` and removed at the end of it. It will create the URL adapter and request object for the WSGI environment provided. Do not attempt to use this class directly, instead use :meth:`~flask.Flask.test_request_context` and :meth:`~flask.Flask.request_context` to create this object. When the request context is popped, it will evaluate all the functions registered on the application for teardown execution (:meth:`~flask.Flask.teardown_request`). The request context is automatically popped at the end of the request for you. In debug mode the request context is kept around if exceptions happen so that interactive debuggers have a chance to introspect the data. With 0.4 this can also be forced for requests that did not fail and outside of `DEBUG` mode. By setting ``'flask._preserve_context'`` to `True` on the WSGI environment the context will not pop itself at the end of the request. This is used by the :meth:`~flask.Flask.test_client` for example to implement the deferred cleanup functionality. You might find this helpful for unittests where you need the information from the context local around for a little longer. Make sure to properly :meth:`~werkzeug.LocalStack.pop` the stack yourself in that situation, otherwise your unittests will leak memory. """ def __init__(self, app, environ, request=None): self.app = app if request is None: request = app.request_class(environ) self.request = request self.url_adapter = app.create_url_adapter(self.request) self.flashes = None self.session = None # Request contexts can be pushed multiple times and interleaved with # other request contexts. Now only if the last level is popped we # get rid of them. Additionally if an application context is missing # one is created implicitly so for each level we add this information self._implicit_app_ctx_stack = [] # indicator if the context was preserved. Next time another context # is pushed the preserved context is popped. self.preserved = False # remembers the exception for pop if there is one in case the context # preservation kicks in. self._preserved_exc = None # Functions that should be executed after the request on the response # object. These will be called before the regular "after_request" # functions. self._after_request_functions = [] self.match_request() # XXX: Support for deprecated functionality. This is going away with # Flask 1.0 blueprint = self.request.blueprint if blueprint is not None: # better safe than sorry, we don't want to break code that # already worked bp = app.blueprints.get(blueprint) if bp is not None and blueprint_is_module(bp): self.request._is_old_module = True def _get_g(self): return _app_ctx_stack.top.g def _set_g(self, value): _app_ctx_stack.top.g = value g = property(_get_g, _set_g) del _get_g, _set_g def copy(self): """Creates a copy of this request context with the same request object. This can be used to move a request context to a different greenlet. Because the actual request object is the same this cannot be used to move a request context to a different thread unless access to the request object is locked. .. versionadded:: 0.10 """ return self.__class__(self.app, environ=self.request.environ, request=self.request ) def match_request(self): """Can be overridden by a subclass to hook into the matching of the request. """ try: url_rule, self.request.view_args = \ self.url_adapter.match(return_rule=True) self.request.url_rule = url_rule except HTTPException as e: self.request.routing_exception = e def push(self): """Binds the request context to the current context.""" # If an exception occurs in debug mode or if context preservation is # activated under exception situations exactly one context stays # on the stack. The rationale is that you want to access that # information under debug situations. However if someone forgets to # pop that context again we want to make sure that on the next push # it's invalidated, otherwise we run at risk that something leaks # memory. This is usually only a problem in testsuite since this # functionality is not active in production environments. top = _request_ctx_stack.top if top is not None and top.preserved: top.pop(top._preserved_exc) # Before we push the request context we have to ensure that there # is an application context. app_ctx = _app_ctx_stack.top if app_ctx is None or app_ctx.app != self.app: app_ctx = self.app.app_context() app_ctx.push() self._implicit_app_ctx_stack.append(app_ctx) else: self._implicit_app_ctx_stack.append(None) _request_ctx_stack.push(self) # Open the session at the moment that the request context is # available. This allows a custom open_session method to use the # request context (e.g. code that access database information # stored on `g` instead of the appcontext). self.session = self.app.open_session(self.request) if self.session is None: self.session = self.app.make_null_session() def pop(self, exc=None): """Pops the request context and unbinds it by doing that. This will also trigger the execution of functions registered by the :meth:`~flask.Flask.teardown_request` decorator. .. versionchanged:: 0.9 Added the `exc` argument. """ app_ctx = self._implicit_app_ctx_stack.pop() clear_request = False if not self._implicit_app_ctx_stack: self.preserved = False self._preserved_exc = None if exc is None: exc = sys.exc_info()[1] self.app.do_teardown_request(exc) # If this interpreter supports clearing the exception information # we do that now. This will only go into effect on Python 2.x, # on 3.x it disappears automatically at the end of the exception # stack. if hasattr(sys, 'exc_clear'): sys.exc_clear() request_close = getattr(self.request, 'close', None) if request_close is not None: request_close() clear_request = True rv = _request_ctx_stack.pop() assert rv is self, 'Popped wrong request context. (%r instead of %r)' \ % (rv, self) # get rid of circular dependencies at the end of the request # so that we don't require the GC to be active. if clear_request: rv.request.environ['werkzeug.request'] = None # Get rid of the app as well if necessary. if app_ctx is not None: app_ctx.pop(exc) def auto_pop(self, exc): if self.request.environ.get('flask._preserve_context') or \ (exc is not None and self.app.preserve_context_on_exception): self.preserved = True self._preserved_exc = exc else: self.pop(exc) def __enter__(self): self.push() return self def __exit__(self, exc_type, exc_value, tb): # do not pop the request stack if we are in debug mode and an # exception happened. This will allow the debugger to still # access the request object in the interactive shell. Furthermore # the context can be force kept alive for the test client. # See flask.testing for how this works. self.auto_pop(exc_value) def __repr__(self): return '<%s \'%s\' [%s] of %s>' % ( self.__class__.__name__, self.request.url, self.request.method, self.app.name, )
apache-2.0
henkhaus/wow
wowlib/wowapi.py
1
2529
import urllib.request, json, time #Variables apikey = "8sv23p3ruq39kfng2phrrau3nstevp4j" #realm = "Shadow-Council" #Build url for auction data requests def auctionurl (server): key = "8sv23p3ruq39kfng2phrrau3nstevp4j" realm = server base = "https://us.api.battle.net/wow/auction/data/" mid = "?locale=en_US&apikey=" url =(base + realm+mid + key) print(url) #grab header file #req = urllib.request(url) weburl = urllib.request.urlopen(url).read() encoding = weburl.decode('UTF-8') data = json.loads(encoding) #gather data from initial return time = (data['files'][0]['lastModified']) url = (data['files'][0]['url']) #get auction data #req = urllib.request(url) weburl = urllib.request.urlopen(url).read() encoding = weburl.decode('UTF-8') data = json.loads(encoding) return data['auctions'] #query users for guild and character indfo. returns Raw Json def char_query(name, realm): key = "8sv23p3ruq39kfng2phrrau3nstevp4j" base = 'https://us.api.battle.net/wow/character/' mid = '?fields=guild&locale=en_US&apikey=' server = realm.replace(' ','-') url = (base + server+ "/"+name+mid+key) print (url) #req = urllib2.Request(url) weburl = urllib.request.urlopen(url).read() encoding = weburl.decode('UTF-8') data = json.loads(encoding) return data def guild_query(guild, realm): guild = guild.replace(" ","%20") key = "8sv23p3ruq39kfng2phrrau3nstevp4j" base = 'https://us.api.battle.net/wow/guild/' mid = '?fields=members&locale=en_US&apikey=' server = realm.replace(' ','-') url = (base + server+ "/"+guild+mid+key) #print (url) #req = urllib2.Request(url) weburl = urllib.request.urlopen(url).read() encoding = weburl.decode('UTF-8') data = json.loads(encoding) return data def itemquery(itemnumber): item = str(itemnumber) key = "8sv23p3ruq39kfng2phrrau3nstevp4j" base = 'https://us.api.battle.net/wow/item/' mid = '?locale=en_US&apikey=' #server = realm.replace(' ','-') url = (base +item +mid+key) print (url) #req = urllib2.Request(url) weburl = urllib.request.urlopen(url).read() encoding = weburl.decode('UTF-8') data = json.loads(encoding) return data def print_time(unixtime): human_time = time.strftime("%D %H:%M", time.localtime(int(unixtime))) return human_time
apache-2.0
denys-duchier/django
django/utils/formats.py
11
9088
import datetime import decimal import unicodedata from importlib import import_module from django.conf import settings from django.utils import dateformat, datetime_safe, numberformat from django.utils.functional import lazy from django.utils.safestring import mark_safe from django.utils.translation import ( check_for_language, get_language, to_locale, ) # format_cache is a mapping from (format_type, lang) to the format string. # By using the cache, it is possible to avoid running get_format_modules # repeatedly. _format_cache = {} _format_modules_cache = {} ISO_INPUT_FORMATS = { 'DATE_INPUT_FORMATS': ['%Y-%m-%d'], 'TIME_INPUT_FORMATS': ['%H:%M:%S', '%H:%M:%S.%f', '%H:%M'], 'DATETIME_INPUT_FORMATS': [ '%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M:%S.%f', '%Y-%m-%d %H:%M', '%Y-%m-%d' ], } FORMAT_SETTINGS = frozenset([ 'DECIMAL_SEPARATOR', 'THOUSAND_SEPARATOR', 'NUMBER_GROUPING', 'FIRST_DAY_OF_WEEK', 'MONTH_DAY_FORMAT', 'TIME_FORMAT', 'DATE_FORMAT', 'DATETIME_FORMAT', 'SHORT_DATE_FORMAT', 'SHORT_DATETIME_FORMAT', 'YEAR_MONTH_FORMAT', 'DATE_INPUT_FORMATS', 'TIME_INPUT_FORMATS', 'DATETIME_INPUT_FORMATS', ]) def reset_format_cache(): """Clear any cached formats. This method is provided primarily for testing purposes, so that the effects of cached formats can be removed. """ global _format_cache, _format_modules_cache _format_cache = {} _format_modules_cache = {} def iter_format_modules(lang, format_module_path=None): """Find format modules.""" if not check_for_language(lang): return if format_module_path is None: format_module_path = settings.FORMAT_MODULE_PATH format_locations = [] if format_module_path: if isinstance(format_module_path, str): format_module_path = [format_module_path] for path in format_module_path: format_locations.append(path + '.%s') format_locations.append('django.conf.locale.%s') locale = to_locale(lang) locales = [locale] if '_' in locale: locales.append(locale.split('_')[0]) for location in format_locations: for loc in locales: try: yield import_module('%s.formats' % (location % loc)) except ImportError: pass def get_format_modules(lang=None, reverse=False): """Return a list of the format modules found.""" if lang is None: lang = get_language() if lang not in _format_modules_cache: _format_modules_cache[lang] = list(iter_format_modules(lang, settings.FORMAT_MODULE_PATH)) modules = _format_modules_cache[lang] if reverse: return list(reversed(modules)) return modules def get_format(format_type, lang=None, use_l10n=None): """ For a specific format type, return the format for the current language (locale). Default to the format in the settings. format_type is the name of the format, e.g. 'DATE_FORMAT'. If use_l10n is provided and is not None, it forces the value to be localized (or not), overriding the value of settings.USE_L10N. """ use_l10n = use_l10n or (use_l10n is None and settings.USE_L10N) if use_l10n and lang is None: lang = get_language() cache_key = (format_type, lang) try: return _format_cache[cache_key] except KeyError: pass # The requested format_type has not been cached yet. Try to find it in any # of the format_modules for the given lang if l10n is enabled. If it's not # there or if l10n is disabled, fall back to the project settings. val = None if use_l10n: for module in get_format_modules(lang): try: val = getattr(module, format_type) if val is not None: break except AttributeError: pass if val is None: if format_type not in FORMAT_SETTINGS: return format_type val = getattr(settings, format_type) elif format_type in ISO_INPUT_FORMATS.keys(): # If a list of input formats from one of the format_modules was # retrieved, make sure the ISO_INPUT_FORMATS are in this list. val = list(val) for iso_input in ISO_INPUT_FORMATS.get(format_type, ()): if iso_input not in val: val.append(iso_input) _format_cache[cache_key] = val return val get_format_lazy = lazy(get_format, str, list, tuple) def date_format(value, format=None, use_l10n=None): """ Format a datetime.date or datetime.datetime object using a localizable format. If use_l10n is provided and is not None, that will force the value to be localized (or not), overriding the value of settings.USE_L10N. """ return dateformat.format(value, get_format(format or 'DATE_FORMAT', use_l10n=use_l10n)) def time_format(value, format=None, use_l10n=None): """ Format a datetime.time object using a localizable format. If use_l10n is provided and is not None, it forces the value to be localized (or not), overriding the value of settings.USE_L10N. """ return dateformat.time_format(value, get_format(format or 'TIME_FORMAT', use_l10n=use_l10n)) def number_format(value, decimal_pos=None, use_l10n=None, force_grouping=False): """ Format a numeric value using localization settings. If use_l10n is provided and is not None, it forces the value to be localized (or not), overriding the value of settings.USE_L10N. """ if use_l10n or (use_l10n is None and settings.USE_L10N): lang = get_language() else: lang = None return numberformat.format( value, get_format('DECIMAL_SEPARATOR', lang, use_l10n=use_l10n), decimal_pos, get_format('NUMBER_GROUPING', lang, use_l10n=use_l10n), get_format('THOUSAND_SEPARATOR', lang, use_l10n=use_l10n), force_grouping=force_grouping ) def localize(value, use_l10n=None): """ Check if value is a localizable type (date, number...) and return it formatted as a string using current locale format. If use_l10n is provided and is not None, it forces the value to be localized (or not), overriding the value of settings.USE_L10N. """ if isinstance(value, str): # Handle strings first for performance reasons. return value elif isinstance(value, bool): # Make sure booleans don't get treated as numbers return mark_safe(str(value)) elif isinstance(value, (decimal.Decimal, float, int)): return number_format(value, use_l10n=use_l10n) elif isinstance(value, datetime.datetime): return date_format(value, 'DATETIME_FORMAT', use_l10n=use_l10n) elif isinstance(value, datetime.date): return date_format(value, use_l10n=use_l10n) elif isinstance(value, datetime.time): return time_format(value, 'TIME_FORMAT', use_l10n=use_l10n) return value def localize_input(value, default=None): """ Check if an input value is a localizable type and return it formatted with the appropriate formatting string of the current locale. """ if isinstance(value, str): # Handle strings first for performance reasons. return value elif isinstance(value, bool): # Don't treat booleans as numbers. return str(value) elif isinstance(value, (decimal.Decimal, float, int)): return number_format(value) elif isinstance(value, datetime.datetime): value = datetime_safe.new_datetime(value) format = default or get_format('DATETIME_INPUT_FORMATS')[0] return value.strftime(format) elif isinstance(value, datetime.date): value = datetime_safe.new_date(value) format = default or get_format('DATE_INPUT_FORMATS')[0] return value.strftime(format) elif isinstance(value, datetime.time): format = default or get_format('TIME_INPUT_FORMATS')[0] return value.strftime(format) return value def sanitize_separators(value): """ Sanitize a value according to the current decimal and thousand separator setting. Used with form field input. """ if isinstance(value, str): parts = [] decimal_separator = get_format('DECIMAL_SEPARATOR') if decimal_separator in value: value, decimals = value.split(decimal_separator, 1) parts.append(decimals) if settings.USE_THOUSAND_SEPARATOR: thousand_sep = get_format('THOUSAND_SEPARATOR') if thousand_sep == '.' and value.count('.') == 1 and len(value.split('.')[-1]) != 3: # Special case where we suspect a dot meant decimal separator (see #22171) pass else: for replacement in { thousand_sep, unicodedata.normalize('NFKD', thousand_sep)}: value = value.replace(replacement, '') parts.append(value) value = '.'.join(reversed(parts)) return value
bsd-3-clause
devcline/mtasa-blue
vendor/google-breakpad/src/tools/gyp/test/additional-targets/gyptest-additional.py
139
1530
#!/usr/bin/env python # Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies simple actions when using an explicit build target of 'all'. """ import TestGyp test = TestGyp.TestGyp() test.run_gyp('all.gyp', chdir='src') test.relocate('src', 'relocate/src') # Build all. test.build('all.gyp', chdir='relocate/src') if test.format=='xcode': chdir = 'relocate/src/dir1' else: chdir = 'relocate/src' # Output is as expected. file_content = 'Hello from emit.py\n' test.built_file_must_match('out2.txt', file_content, chdir=chdir) test.built_file_must_not_exist('out.txt', chdir='relocate/src') test.built_file_must_not_exist('foolib1', type=test.SHARED_LIB, chdir=chdir) # TODO(mmoss) Make consistent with msvs, with 'dir1' before 'out/Default'? if test.format in ('make', 'ninja', 'android', 'cmake'): chdir='relocate/src' else: chdir='relocate/src/dir1' # Build the action explicitly. test.build('actions.gyp', 'action1_target', chdir=chdir) # Check that things got run. file_content = 'Hello from emit.py\n' test.built_file_must_exist('out.txt', chdir=chdir) # Build the shared library explicitly. test.build('actions.gyp', 'foolib1', chdir=chdir) test.built_file_must_exist('foolib1', type=test.SHARED_LIB, chdir=chdir, subdir='dir1') test.pass_test()
gpl-3.0
yamila-moreno/django
tests/gis_tests/relatedapp/models.py
67
1844
from django.utils.encoding import python_2_unicode_compatible from ..models import models class SimpleModel(models.Model): objects = models.GeoManager() class Meta: abstract = True required_db_features = ['gis_enabled'] @python_2_unicode_compatible class Location(SimpleModel): point = models.PointField() def __str__(self): return self.point.wkt @python_2_unicode_compatible class City(SimpleModel): name = models.CharField(max_length=50) state = models.CharField(max_length=2) location = models.ForeignKey(Location) def __str__(self): return self.name class AugmentedLocation(Location): extra_text = models.TextField(blank=True) objects = models.GeoManager() class DirectoryEntry(SimpleModel): listing_text = models.CharField(max_length=50) location = models.ForeignKey(AugmentedLocation) @python_2_unicode_compatible class Parcel(SimpleModel): name = models.CharField(max_length=30) city = models.ForeignKey(City) center1 = models.PointField() # Throwing a curveball w/`db_column` here. center2 = models.PointField(srid=2276, db_column='mycenter') border1 = models.PolygonField() border2 = models.PolygonField(srid=2276) def __str__(self): return self.name # These use the GeoManager but do not have any geographic fields. class Author(SimpleModel): name = models.CharField(max_length=100) dob = models.DateField() class Article(SimpleModel): title = models.CharField(max_length=100) author = models.ForeignKey(Author, unique=True) class Book(SimpleModel): title = models.CharField(max_length=100) author = models.ForeignKey(Author, related_name='books', null=True) class Event(SimpleModel): name = models.CharField(max_length=100) when = models.DateTimeField()
bsd-3-clause
noslenfa/tdjangorest
uw/lib/python2.7/site-packages/paramiko/client.py
3
21652
# Copyright (C) 2006-2007 Robey Pointer <robeypointer@gmail.com> # # This file is part of paramiko. # # Paramiko is free software; you can redistribute it and/or modify it under the # terms of the GNU Lesser General Public License as published by the Free # Software Foundation; either version 2.1 of the License, or (at your option) # any later version. # # Paramiko is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # details. # # You should have received a copy of the GNU Lesser General Public License # along with Paramiko; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. """ L{SSHClient}. """ from binascii import hexlify import getpass import os import socket import warnings from paramiko.agent import Agent from paramiko.common import * from paramiko.config import SSH_PORT from paramiko.dsskey import DSSKey from paramiko.hostkeys import HostKeys from paramiko.resource import ResourceManager from paramiko.rsakey import RSAKey from paramiko.ssh_exception import SSHException, BadHostKeyException from paramiko.transport import Transport from paramiko.util import retry_on_signal class MissingHostKeyPolicy (object): """ Interface for defining the policy that L{SSHClient} should use when the SSH server's hostname is not in either the system host keys or the application's keys. Pre-made classes implement policies for automatically adding the key to the application's L{HostKeys} object (L{AutoAddPolicy}), and for automatically rejecting the key (L{RejectPolicy}). This function may be used to ask the user to verify the key, for example. """ def missing_host_key(self, client, hostname, key): """ Called when an L{SSHClient} receives a server key for a server that isn't in either the system or local L{HostKeys} object. To accept the key, simply return. To reject, raised an exception (which will be passed to the calling application). """ pass class AutoAddPolicy (MissingHostKeyPolicy): """ Policy for automatically adding the hostname and new host key to the local L{HostKeys} object, and saving it. This is used by L{SSHClient}. """ def missing_host_key(self, client, hostname, key): client._host_keys.add(hostname, key.get_name(), key) if client._host_keys_filename is not None: client.save_host_keys(client._host_keys_filename) client._log(DEBUG, 'Adding %s host key for %s: %s' % (key.get_name(), hostname, hexlify(key.get_fingerprint()))) class RejectPolicy (MissingHostKeyPolicy): """ Policy for automatically rejecting the unknown hostname & key. This is used by L{SSHClient}. """ def missing_host_key(self, client, hostname, key): client._log(DEBUG, 'Rejecting %s host key for %s: %s' % (key.get_name(), hostname, hexlify(key.get_fingerprint()))) raise SSHException('Server %r not found in known_hosts' % hostname) class WarningPolicy (MissingHostKeyPolicy): """ Policy for logging a python-style warning for an unknown host key, but accepting it. This is used by L{SSHClient}. """ def missing_host_key(self, client, hostname, key): warnings.warn('Unknown %s host key for %s: %s' % (key.get_name(), hostname, hexlify(key.get_fingerprint()))) class SSHClient (object): """ A high-level representation of a session with an SSH server. This class wraps L{Transport}, L{Channel}, and L{SFTPClient} to take care of most aspects of authenticating and opening channels. A typical use case is:: client = SSHClient() client.load_system_host_keys() client.connect('ssh.example.com') stdin, stdout, stderr = client.exec_command('ls -l') You may pass in explicit overrides for authentication and server host key checking. The default mechanism is to try to use local key files or an SSH agent (if one is running). @since: 1.6 """ def __init__(self): """ Create a new SSHClient. """ self._system_host_keys = HostKeys() self._host_keys = HostKeys() self._host_keys_filename = None self._log_channel = None self._policy = RejectPolicy() self._transport = None self._agent = None def load_system_host_keys(self, filename=None): """ Load host keys from a system (read-only) file. Host keys read with this method will not be saved back by L{save_host_keys}. This method can be called multiple times. Each new set of host keys will be merged with the existing set (new replacing old if there are conflicts). If C{filename} is left as C{None}, an attempt will be made to read keys from the user's local "known hosts" file, as used by OpenSSH, and no exception will be raised if the file can't be read. This is probably only useful on posix. @param filename: the filename to read, or C{None} @type filename: str @raise IOError: if a filename was provided and the file could not be read """ if filename is None: # try the user's .ssh key file, and mask exceptions filename = os.path.expanduser('~/.ssh/known_hosts') try: self._system_host_keys.load(filename) except IOError: pass return self._system_host_keys.load(filename) def load_host_keys(self, filename): """ Load host keys from a local host-key file. Host keys read with this method will be checked I{after} keys loaded via L{load_system_host_keys}, but will be saved back by L{save_host_keys} (so they can be modified). The missing host key policy L{AutoAddPolicy} adds keys to this set and saves them, when connecting to a previously-unknown server. This method can be called multiple times. Each new set of host keys will be merged with the existing set (new replacing old if there are conflicts). When automatically saving, the last hostname is used. @param filename: the filename to read @type filename: str @raise IOError: if the filename could not be read """ self._host_keys_filename = filename self._host_keys.load(filename) def save_host_keys(self, filename): """ Save the host keys back to a file. Only the host keys loaded with L{load_host_keys} (plus any added directly) will be saved -- not any host keys loaded with L{load_system_host_keys}. @param filename: the filename to save to @type filename: str @raise IOError: if the file could not be written """ # update local host keys from file (in case other SSH clients # have written to the known_hosts file meanwhile. if self._host_keys_filename is not None: self.load_host_keys(self._host_keys_filename) f = open(filename, 'w') for hostname, keys in self._host_keys.iteritems(): for keytype, key in keys.iteritems(): f.write('%s %s %s\n' % (hostname, keytype, key.get_base64())) f.close() def get_host_keys(self): """ Get the local L{HostKeys} object. This can be used to examine the local host keys or change them. @return: the local host keys @rtype: L{HostKeys} """ return self._host_keys def set_log_channel(self, name): """ Set the channel for logging. The default is C{"paramiko.transport"} but it can be set to anything you want. @param name: new channel name for logging @type name: str """ self._log_channel = name def set_missing_host_key_policy(self, policy): """ Set the policy to use when connecting to a server that doesn't have a host key in either the system or local L{HostKeys} objects. The default policy is to reject all unknown servers (using L{RejectPolicy}). You may substitute L{AutoAddPolicy} or write your own policy class. @param policy: the policy to use when receiving a host key from a previously-unknown server @type policy: L{MissingHostKeyPolicy} """ self._policy = policy def connect(self, hostname, port=SSH_PORT, username=None, password=None, pkey=None, key_filename=None, timeout=None, allow_agent=True, look_for_keys=True, compress=False, sock=None): """ Connect to an SSH server and authenticate to it. The server's host key is checked against the system host keys (see L{load_system_host_keys}) and any local host keys (L{load_host_keys}). If the server's hostname is not found in either set of host keys, the missing host key policy is used (see L{set_missing_host_key_policy}). The default policy is to reject the key and raise an L{SSHException}. Authentication is attempted in the following order of priority: - The C{pkey} or C{key_filename} passed in (if any) - Any key we can find through an SSH agent - Any "id_rsa" or "id_dsa" key discoverable in C{~/.ssh/} - Plain username/password auth, if a password was given If a private key requires a password to unlock it, and a password is passed in, that password will be used to attempt to unlock the key. @param hostname: the server to connect to @type hostname: str @param port: the server port to connect to @type port: int @param username: the username to authenticate as (defaults to the current local username) @type username: str @param password: a password to use for authentication or for unlocking a private key @type password: str @param pkey: an optional private key to use for authentication @type pkey: L{PKey} @param key_filename: the filename, or list of filenames, of optional private key(s) to try for authentication @type key_filename: str or list(str) @param timeout: an optional timeout (in seconds) for the TCP connect @type timeout: float @param allow_agent: set to False to disable connecting to the SSH agent @type allow_agent: bool @param look_for_keys: set to False to disable searching for discoverable private key files in C{~/.ssh/} @type look_for_keys: bool @param compress: set to True to turn on compression @type compress: bool @param sock: an open socket or socket-like object (such as a L{Channel}) to use for communication to the target host @type sock: socket @raise BadHostKeyException: if the server's host key could not be verified @raise AuthenticationException: if authentication failed @raise SSHException: if there was any other error connecting or establishing an SSH session @raise socket.error: if a socket error occurred while connecting """ if not sock: for (family, socktype, proto, canonname, sockaddr) in socket.getaddrinfo(hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM): if socktype == socket.SOCK_STREAM: af = family addr = sockaddr break else: # some OS like AIX don't indicate SOCK_STREAM support, so just guess. :( af, _, _, _, addr = socket.getaddrinfo(hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM) sock = socket.socket(af, socket.SOCK_STREAM) if timeout is not None: try: sock.settimeout(timeout) except: pass retry_on_signal(lambda: sock.connect(addr)) t = self._transport = Transport(sock) t.use_compression(compress=compress) if self._log_channel is not None: t.set_log_channel(self._log_channel) t.start_client() ResourceManager.register(self, t) server_key = t.get_remote_server_key() keytype = server_key.get_name() if port == SSH_PORT: server_hostkey_name = hostname else: server_hostkey_name = "[%s]:%d" % (hostname, port) our_server_key = self._system_host_keys.get(server_hostkey_name, {}).get(keytype, None) if our_server_key is None: our_server_key = self._host_keys.get(server_hostkey_name, {}).get(keytype, None) if our_server_key is None: # will raise exception if the key is rejected; let that fall out self._policy.missing_host_key(self, server_hostkey_name, server_key) # if the callback returns, assume the key is ok our_server_key = server_key if server_key != our_server_key: raise BadHostKeyException(hostname, server_key, our_server_key) if username is None: username = getpass.getuser() if key_filename is None: key_filenames = [] elif isinstance(key_filename, (str, unicode)): key_filenames = [ key_filename ] else: key_filenames = key_filename self._auth(username, password, pkey, key_filenames, allow_agent, look_for_keys) def close(self): """ Close this SSHClient and its underlying L{Transport}. """ if self._transport is None: return self._transport.close() self._transport = None if self._agent != None: self._agent.close() self._agent = None def exec_command(self, command, bufsize=-1, timeout=None, get_pty=False): """ Execute a command on the SSH server. A new L{Channel} is opened and the requested command is executed. The command's input and output streams are returned as python C{file}-like objects representing stdin, stdout, and stderr. @param command: the command to execute @type command: str @param bufsize: interpreted the same way as by the built-in C{file()} function in python @type bufsize: int @param timeout: set command's channel timeout. See L{Channel.settimeout}.settimeout @type timeout: int @return: the stdin, stdout, and stderr of the executing command @rtype: tuple(L{ChannelFile}, L{ChannelFile}, L{ChannelFile}) @raise SSHException: if the server fails to execute the command """ chan = self._transport.open_session() if(get_pty): chan.get_pty() chan.settimeout(timeout) chan.exec_command(command) stdin = chan.makefile('wb', bufsize) stdout = chan.makefile('rb', bufsize) stderr = chan.makefile_stderr('rb', bufsize) return stdin, stdout, stderr def invoke_shell(self, term='vt100', width=80, height=24, width_pixels=0, height_pixels=0): """ Start an interactive shell session on the SSH server. A new L{Channel} is opened and connected to a pseudo-terminal using the requested terminal type and size. @param term: the terminal type to emulate (for example, C{"vt100"}) @type term: str @param width: the width (in characters) of the terminal window @type width: int @param height: the height (in characters) of the terminal window @type height: int @param width_pixels: the width (in pixels) of the terminal window @type width_pixels: int @param height_pixels: the height (in pixels) of the terminal window @type height_pixels: int @return: a new channel connected to the remote shell @rtype: L{Channel} @raise SSHException: if the server fails to invoke a shell """ chan = self._transport.open_session() chan.get_pty(term, width, height, width_pixels, height_pixels) chan.invoke_shell() return chan def open_sftp(self): """ Open an SFTP session on the SSH server. @return: a new SFTP session object @rtype: L{SFTPClient} """ return self._transport.open_sftp_client() def get_transport(self): """ Return the underlying L{Transport} object for this SSH connection. This can be used to perform lower-level tasks, like opening specific kinds of channels. @return: the Transport for this connection @rtype: L{Transport} """ return self._transport def _auth(self, username, password, pkey, key_filenames, allow_agent, look_for_keys): """ Try, in order: - The key passed in, if one was passed in. - Any key we can find through an SSH agent (if allowed). - Any "id_rsa" or "id_dsa" key discoverable in ~/.ssh/ (if allowed). - Plain username/password auth, if a password was given. (The password might be needed to unlock a private key, or for two-factor authentication [for which it is required].) """ saved_exception = None two_factor = False allowed_types = [] if pkey is not None: try: self._log(DEBUG, 'Trying SSH key %s' % hexlify(pkey.get_fingerprint())) allowed_types = self._transport.auth_publickey(username, pkey) two_factor = (allowed_types == ['password']) if not two_factor: return except SSHException, e: saved_exception = e if not two_factor: for key_filename in key_filenames: for pkey_class in (RSAKey, DSSKey): try: key = pkey_class.from_private_key_file(key_filename, password) self._log(DEBUG, 'Trying key %s from %s' % (hexlify(key.get_fingerprint()), key_filename)) self._transport.auth_publickey(username, key) two_factor = (allowed_types == ['password']) if not two_factor: return break except SSHException, e: saved_exception = e if not two_factor and allow_agent: if self._agent == None: self._agent = Agent() for key in self._agent.get_keys(): try: self._log(DEBUG, 'Trying SSH agent key %s' % hexlify(key.get_fingerprint())) # for 2-factor auth a successfully auth'd key will result in ['password'] allowed_types = self._transport.auth_publickey(username, key) two_factor = (allowed_types == ['password']) if not two_factor: return break except SSHException, e: saved_exception = e if not two_factor: keyfiles = [] rsa_key = os.path.expanduser('~/.ssh/id_rsa') dsa_key = os.path.expanduser('~/.ssh/id_dsa') if os.path.isfile(rsa_key): keyfiles.append((RSAKey, rsa_key)) if os.path.isfile(dsa_key): keyfiles.append((DSSKey, dsa_key)) # look in ~/ssh/ for windows users: rsa_key = os.path.expanduser('~/ssh/id_rsa') dsa_key = os.path.expanduser('~/ssh/id_dsa') if os.path.isfile(rsa_key): keyfiles.append((RSAKey, rsa_key)) if os.path.isfile(dsa_key): keyfiles.append((DSSKey, dsa_key)) if not look_for_keys: keyfiles = [] for pkey_class, filename in keyfiles: try: key = pkey_class.from_private_key_file(filename, password) self._log(DEBUG, 'Trying discovered key %s in %s' % (hexlify(key.get_fingerprint()), filename)) # for 2-factor auth a successfully auth'd key will result in ['password'] allowed_types = self._transport.auth_publickey(username, key) two_factor = (allowed_types == ['password']) if not two_factor: return break except SSHException, e: saved_exception = e except IOError, e: saved_exception = e if password is not None: try: self._transport.auth_password(username, password) return except SSHException, e: saved_exception = e elif two_factor: raise SSHException('Two-factor authentication requires a password') # if we got an auth-failed exception earlier, re-raise it if saved_exception is not None: raise saved_exception raise SSHException('No authentication methods available') def _log(self, level, msg): self._transport._log(level, msg)
apache-2.0
fabiocerqueira/django-allauth
allauth/socialaccount/providers/foursquare/views.py
71
1366
import requests from allauth.socialaccount.providers.oauth2.views import (OAuth2Adapter, OAuth2LoginView, OAuth2CallbackView) from .provider import FoursquareProvider class FoursquareOAuth2Adapter(OAuth2Adapter): provider_id = FoursquareProvider.id access_token_url = 'https://foursquare.com/oauth2/access_token' # Issue ?? -- this one authenticates over and over again... # authorize_url = 'https://foursquare.com/oauth2/authorize' authorize_url = 'https://foursquare.com/oauth2/authenticate' profile_url = 'https://api.foursquare.com/v2/users/self' def complete_login(self, request, app, token, **kwargs): # Foursquare needs a version number for their API requests as documented here https://developer.foursquare.com/overview/versioning resp = requests.get(self.profile_url, params={'oauth_token': token.token, 'v': '20140116'}) extra_data = resp.json()['response']['user'] return self.get_provider().sociallogin_from_response(request, extra_data) oauth2_login = OAuth2LoginView.adapter_view(FoursquareOAuth2Adapter) oauth2_callback = OAuth2CallbackView.adapter_view(FoursquareOAuth2Adapter)
mit
openstack/heat
heat/engine/resources/aws/ec2/network_interface.py
8
6159
# # 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. from heat.common.i18n import _ from heat.engine import attributes from heat.engine import constraints from heat.engine import properties from heat.engine import resource class NetworkInterface(resource.Resource): PROPERTIES = ( DESCRIPTION, GROUP_SET, PRIVATE_IP_ADDRESS, SOURCE_DEST_CHECK, SUBNET_ID, TAGS, ) = ( 'Description', 'GroupSet', 'PrivateIpAddress', 'SourceDestCheck', 'SubnetId', 'Tags', ) _TAG_KEYS = ( TAG_KEY, TAG_VALUE, ) = ( 'Key', 'Value', ) ATTRIBUTES = ( PRIVATE_IP_ADDRESS_ATTR, ) = ( 'PrivateIpAddress', ) properties_schema = { DESCRIPTION: properties.Schema( properties.Schema.STRING, _('Description for this interface.') ), GROUP_SET: properties.Schema( properties.Schema.LIST, _('List of security group IDs associated with this interface.'), update_allowed=True ), PRIVATE_IP_ADDRESS: properties.Schema( properties.Schema.STRING ), SOURCE_DEST_CHECK: properties.Schema( properties.Schema.BOOLEAN, _('Flag indicating if traffic to or from instance is validated.'), implemented=False ), SUBNET_ID: properties.Schema( properties.Schema.STRING, _('Subnet ID to associate with this interface.'), required=True, constraints=[ constraints.CustomConstraint('neutron.subnet') ] ), TAGS: properties.Schema( properties.Schema.LIST, schema=properties.Schema( properties.Schema.MAP, _('List of tags associated with this interface.'), schema={ TAG_KEY: properties.Schema( properties.Schema.STRING, required=True ), TAG_VALUE: properties.Schema( properties.Schema.STRING, required=True ), }, implemented=False, ) ), } attributes_schema = { PRIVATE_IP_ADDRESS: attributes.Schema( _('Private IP address of the network interface.'), type=attributes.Schema.STRING ), } default_client_name = 'neutron' @staticmethod def network_id_from_subnet_id(neutronclient, subnet_id): subnet_info = neutronclient.show_subnet(subnet_id) return subnet_info['subnet']['network_id'] def __init__(self, name, json_snippet, stack): super(NetworkInterface, self).__init__(name, json_snippet, stack) self.fixed_ip_address = None def handle_create(self): subnet_id = self.properties[self.SUBNET_ID] network_id = self.client_plugin().network_id_from_subnet_id( subnet_id) fixed_ip = {'subnet_id': subnet_id} if self.properties[self.PRIVATE_IP_ADDRESS]: fixed_ip['ip_address'] = self.properties[self.PRIVATE_IP_ADDRESS] props = { 'name': self.physical_resource_name(), 'admin_state_up': True, 'network_id': network_id, 'fixed_ips': [fixed_ip] } # if without group_set, don't set the 'security_groups' property, # neutron will create the port with the 'default' securityGroup, # if has the group_set and the value is [], which means to create the # port without securityGroup(same as the behavior of neutron) if self.properties[self.GROUP_SET] is not None: sgs = self.client_plugin().get_secgroup_uuids( self.properties.get(self.GROUP_SET)) props['security_groups'] = sgs port = self.client().create_port({'port': props})['port'] self.resource_id_set(port['id']) def handle_delete(self): if self.resource_id is None: return with self.client_plugin().ignore_not_found: self.client().delete_port(self.resource_id) def handle_update(self, json_snippet, tmpl_diff, prop_diff): if prop_diff: update_props = {} if self.GROUP_SET in prop_diff: group_set = prop_diff.get(self.GROUP_SET) # update should keep the same behavior as creation, # if without the GroupSet in update template, we should # update the security_groups property to referent # the 'default' security group if group_set is not None: sgs = self.client_plugin().get_secgroup_uuids(group_set) else: sgs = self.client_plugin().get_secgroup_uuids(['default']) update_props['security_groups'] = sgs self.client().update_port(self.resource_id, {'port': update_props}) def _get_fixed_ip_address(self): if self.fixed_ip_address is None: port = self.client().show_port(self.resource_id)['port'] if port['fixed_ips'] and len(port['fixed_ips']) > 0: self.fixed_ip_address = port['fixed_ips'][0]['ip_address'] return self.fixed_ip_address def _resolve_attribute(self, name): if name == self.PRIVATE_IP_ADDRESS: return self._get_fixed_ip_address() def resource_mapping(): return { 'AWS::EC2::NetworkInterface': NetworkInterface, }
apache-2.0
wmvanvliet/mne-python
mne/io/tag.py
4
17633
# Authors: Alexandre Gramfort <alexandre.gramfort@inria.fr> # Matti Hämäläinen <msh@nmr.mgh.harvard.edu> # # License: BSD (3-clause) from functools import partial import struct import numpy as np from .constants import (FIFF, _dig_kind_named, _dig_cardinal_named, _ch_kind_named, _ch_coil_type_named, _ch_unit_named, _ch_unit_mul_named) from ..utils.numerics import _julian_to_cal ############################################################################## # HELPERS class Tag(object): """Tag in FIF tree structure. Parameters ---------- kind : int Kind of Tag. type_ : int Type of Tag. size : int Size in bytes. int : next Position of next Tag. pos : int Position of Tag is the original file. """ def __init__(self, kind, type_, size, next, pos=None): # noqa: D102 self.kind = int(kind) self.type = int(type_) self.size = int(size) self.next = int(next) self.pos = pos if pos is not None else next self.pos = int(self.pos) self.data = None def __repr__(self): # noqa: D105 out = ("<Tag | kind %s - type %s - size %s - next %s - pos %s" % (self.kind, self.type, self.size, self.next, self.pos)) if hasattr(self, 'data'): out += " - data %s" % self.data out += ">" return out def __eq__(self, tag): # noqa: D105 return int(self.kind == tag.kind and self.type == tag.type and self.size == tag.size and self.next == tag.next and self.pos == tag.pos and self.data == tag.data) def read_tag_info(fid): """Read Tag info (or header).""" tag = _read_tag_header(fid) if tag is None: return None if tag.next == 0: fid.seek(tag.size, 1) elif tag.next > 0: fid.seek(tag.next, 0) return tag def _frombuffer_rows(fid, tag_size, dtype=None, shape=None, rlims=None): """Get a range of rows from a large tag.""" if shape is not None: item_size = np.dtype(dtype).itemsize if not len(shape) == 2: raise ValueError('Only implemented for 2D matrices') want_shape = np.prod(shape) have_shape = tag_size // item_size if want_shape != have_shape: raise ValueError('Wrong shape specified, requested %s have %s' % (want_shape, have_shape)) if not len(rlims) == 2: raise ValueError('rlims must have two elements') n_row_out = rlims[1] - rlims[0] if n_row_out <= 0: raise ValueError('rlims must yield at least one output') row_size = item_size * shape[1] # # of bytes to skip at the beginning, # to read, where to end start_skip = int(rlims[0] * row_size) read_size = int(n_row_out * row_size) end_pos = int(fid.tell() + tag_size) # Move the pointer ahead to the read point fid.seek(start_skip, 1) # Do the reading out = np.frombuffer(fid.read(read_size), dtype=dtype) # Move the pointer ahead to the end of the tag fid.seek(end_pos) else: out = np.frombuffer(fid.read(tag_size), dtype=dtype) return out def _loc_to_coil_trans(loc): """Convert loc vector to coil_trans.""" assert loc.shape[-1] == 12 coil_trans = np.zeros(loc.shape[:-1] + (4, 4)) coil_trans[..., :3, 3] = loc[..., :3] coil_trans[..., :3, :3] = np.reshape( loc[..., 3:], loc.shape[:-1] + (3, 3)).swapaxes(-1, -2) coil_trans[..., -1, -1] = 1. return coil_trans def _coil_trans_to_loc(coil_trans): """Convert coil_trans to loc.""" coil_trans = coil_trans.astype(np.float64) return np.roll(coil_trans.T[:, :3], 1, 0).flatten() def _loc_to_eeg_loc(loc): """Convert a loc to an EEG loc.""" if not np.isfinite(loc[:3]).all(): raise RuntimeError('Missing EEG channel location') if np.isfinite(loc[3:6]).all() and (loc[3:6]).any(): return np.array([loc[0:3], loc[3:6]]).T else: return loc[0:3][:, np.newaxis].copy() ############################################################################## # READING FUNCTIONS # None of these functions have docstring because it's more compact that way, # and hopefully it's clear what they do by their names and variable values. # See ``read_tag`` for variable descriptions. Return values are implied # by the function names. _is_matrix = 4294901760 # ffff0000 _matrix_coding_dense = 16384 # 4000 _matrix_coding_CCS = 16400 # 4010 _matrix_coding_RCS = 16416 # 4020 _data_type = 65535 # ffff def _read_tag_header(fid): """Read only the header of a Tag.""" s = fid.read(4 * 4) if len(s) == 0: return None # struct.unpack faster than np.frombuffer, saves ~10% of time some places return Tag(*struct.unpack('>iIii', s)) _matrix_bit_dtype = { FIFF.FIFFT_INT: (4, '>i4'), FIFF.FIFFT_JULIAN: (4, '>i4'), FIFF.FIFFT_FLOAT: (4, '>f4'), FIFF.FIFFT_DOUBLE: (8, '>f8'), FIFF.FIFFT_COMPLEX_FLOAT: (8, '>f4'), FIFF.FIFFT_COMPLEX_DOUBLE: (16, '>f8'), } def _read_matrix(fid, tag, shape, rlims, matrix_coding): """Read a matrix (dense or sparse) tag.""" from scipy import sparse matrix_coding = matrix_coding >> 16 # This should be easy to implement (see _frombuffer_rows) # if we need it, but for now, it's not... if shape is not None: raise ValueError('Row reading not implemented for matrices ' 'yet') # Matrices if matrix_coding == _matrix_coding_dense: # Find dimensions and return to the beginning of tag data pos = fid.tell() fid.seek(tag.size - 4, 1) ndim = int(np.frombuffer(fid.read(4), dtype='>i4')) fid.seek(-(ndim + 1) * 4, 1) dims = np.frombuffer(fid.read(4 * ndim), dtype='>i4')[::-1] # # Back to where the data start # fid.seek(pos, 0) if ndim > 3: raise Exception('Only 2 or 3-dimensional matrices are ' 'supported at this time') matrix_type = _data_type & tag.type try: bit, dtype = _matrix_bit_dtype[matrix_type] except KeyError: raise RuntimeError('Cannot handle matrix of type %d yet' % matrix_type) data = fid.read(int(bit * dims.prod())) data = np.frombuffer(data, dtype=dtype) # Note: we need the non-conjugate transpose here if matrix_type == FIFF.FIFFT_COMPLEX_FLOAT: data = data.view('>c8') elif matrix_type == FIFF.FIFFT_COMPLEX_DOUBLE: data = data.view('>c16') data.shape = dims elif matrix_coding in (_matrix_coding_CCS, _matrix_coding_RCS): # Find dimensions and return to the beginning of tag data pos = fid.tell() fid.seek(tag.size - 4, 1) ndim = int(np.frombuffer(fid.read(4), dtype='>i4')) fid.seek(-(ndim + 2) * 4, 1) dims = np.frombuffer(fid.read(4 * (ndim + 1)), dtype='>i4') if ndim != 2: raise Exception('Only two-dimensional matrices are ' 'supported at this time') # Back to where the data start fid.seek(pos, 0) nnz = int(dims[0]) nrow = int(dims[1]) ncol = int(dims[2]) data = np.frombuffer(fid.read(4 * nnz), dtype='>f4') shape = (dims[1], dims[2]) if matrix_coding == _matrix_coding_CCS: # CCS tmp_indices = fid.read(4 * nnz) indices = np.frombuffer(tmp_indices, dtype='>i4') tmp_ptr = fid.read(4 * (ncol + 1)) indptr = np.frombuffer(tmp_ptr, dtype='>i4') if indptr[-1] > len(indices) or np.any(indptr < 0): # There was a bug in MNE-C that caused some data to be # stored without byte swapping indices = np.concatenate( (np.frombuffer(tmp_indices[:4 * (nrow + 1)], dtype='>i4'), np.frombuffer(tmp_indices[4 * (nrow + 1):], dtype='<i4'))) indptr = np.frombuffer(tmp_ptr, dtype='<i4') data = sparse.csc_matrix((data, indices, indptr), shape=shape) else: # RCS tmp_indices = fid.read(4 * nnz) indices = np.frombuffer(tmp_indices, dtype='>i4') tmp_ptr = fid.read(4 * (nrow + 1)) indptr = np.frombuffer(tmp_ptr, dtype='>i4') if indptr[-1] > len(indices) or np.any(indptr < 0): # There was a bug in MNE-C that caused some data to be # stored without byte swapping indices = np.concatenate( (np.frombuffer(tmp_indices[:4 * (ncol + 1)], dtype='>i4'), np.frombuffer(tmp_indices[4 * (ncol + 1):], dtype='<i4'))) indptr = np.frombuffer(tmp_ptr, dtype='<i4') data = sparse.csr_matrix((data, indices, indptr), shape=shape) else: raise Exception('Cannot handle other than dense or sparse ' 'matrices yet') return data def _read_simple(fid, tag, shape, rlims, dtype): """Read simple datatypes from tag (typically used with partial).""" return _frombuffer_rows(fid, tag.size, dtype=dtype, shape=shape, rlims=rlims) def _read_string(fid, tag, shape, rlims): """Read a string tag.""" # Always decode to ISO 8859-1 / latin1 (FIFF standard). d = _frombuffer_rows(fid, tag.size, dtype='>c', shape=shape, rlims=rlims) return str(d.tobytes().decode('latin1', 'ignore')) def _read_complex_float(fid, tag, shape, rlims): """Read complex float tag.""" # data gets stored twice as large if shape is not None: shape = (shape[0], shape[1] * 2) d = _frombuffer_rows(fid, tag.size, dtype=">f4", shape=shape, rlims=rlims) d = d.view(">c8") return d def _read_complex_double(fid, tag, shape, rlims): """Read complex double tag.""" # data gets stored twice as large if shape is not None: shape = (shape[0], shape[1] * 2) d = _frombuffer_rows(fid, tag.size, dtype=">f8", shape=shape, rlims=rlims) d = d.view(">c16") return d def _read_id_struct(fid, tag, shape, rlims): """Read ID struct tag.""" return dict( version=int(np.frombuffer(fid.read(4), dtype=">i4")), machid=np.frombuffer(fid.read(8), dtype=">i4"), secs=int(np.frombuffer(fid.read(4), dtype=">i4")), usecs=int(np.frombuffer(fid.read(4), dtype=">i4"))) def _read_dig_point_struct(fid, tag, shape, rlims): """Read dig point struct tag.""" kind = int(np.frombuffer(fid.read(4), dtype=">i4")) kind = _dig_kind_named.get(kind, kind) ident = int(np.frombuffer(fid.read(4), dtype=">i4")) if kind == FIFF.FIFFV_POINT_CARDINAL: ident = _dig_cardinal_named.get(ident, ident) return dict( kind=kind, ident=ident, r=np.frombuffer(fid.read(12), dtype=">f4"), coord_frame=FIFF.FIFFV_COORD_UNKNOWN) def _read_coord_trans_struct(fid, tag, shape, rlims): """Read coord trans struct tag.""" from ..transforms import Transform fro = int(np.frombuffer(fid.read(4), dtype=">i4")) to = int(np.frombuffer(fid.read(4), dtype=">i4")) rot = np.frombuffer(fid.read(36), dtype=">f4").reshape(3, 3) move = np.frombuffer(fid.read(12), dtype=">f4") trans = np.r_[np.c_[rot, move], np.array([[0], [0], [0], [1]]).T] data = Transform(fro, to, trans) fid.seek(48, 1) # Skip over the inverse transformation return data _ch_coord_dict = { FIFF.FIFFV_MEG_CH: FIFF.FIFFV_COORD_DEVICE, FIFF.FIFFV_REF_MEG_CH: FIFF.FIFFV_COORD_DEVICE, FIFF.FIFFV_EEG_CH: FIFF.FIFFV_COORD_HEAD, } def _read_ch_info_struct(fid, tag, shape, rlims): """Read channel info struct tag.""" d = dict( scanno=int(np.frombuffer(fid.read(4), dtype=">i4")), logno=int(np.frombuffer(fid.read(4), dtype=">i4")), kind=int(np.frombuffer(fid.read(4), dtype=">i4")), range=float(np.frombuffer(fid.read(4), dtype=">f4")), cal=float(np.frombuffer(fid.read(4), dtype=">f4")), coil_type=int(np.frombuffer(fid.read(4), dtype=">i4")), # deal with really old OSX Anaconda bug by casting to float64 loc=np.frombuffer(fid.read(48), dtype=">f4").astype(np.float64), # unit and exponent unit=int(np.frombuffer(fid.read(4), dtype=">i4")), unit_mul=int(np.frombuffer(fid.read(4), dtype=">i4")), ) # channel name ch_name = np.frombuffer(fid.read(16), dtype=">c") ch_name = ch_name[:np.argmax(ch_name == b'')].tobytes() d['ch_name'] = ch_name.decode() # coil coordinate system definition _update_ch_info_named(d) return d def _update_ch_info_named(d): d['coord_frame'] = _ch_coord_dict.get(d['kind'], FIFF.FIFFV_COORD_UNKNOWN) d['kind'] = _ch_kind_named.get(d['kind'], d['kind']) d['coil_type'] = _ch_coil_type_named.get(d['coil_type'], d['coil_type']) d['unit'] = _ch_unit_named.get(d['unit'], d['unit']) d['unit_mul'] = _ch_unit_mul_named.get(d['unit_mul'], d['unit_mul']) def _read_old_pack(fid, tag, shape, rlims): """Read old pack tag.""" offset = float(np.frombuffer(fid.read(4), dtype=">f4")) scale = float(np.frombuffer(fid.read(4), dtype=">f4")) data = np.frombuffer(fid.read(tag.size - 8), dtype=">i2") data = data * scale # to float64 data += offset return data def _read_dir_entry_struct(fid, tag, shape, rlims): """Read dir entry struct tag.""" return [_read_tag_header(fid) for _ in range(tag.size // 16 - 1)] def _read_julian(fid, tag, shape, rlims): """Read julian tag.""" return _julian_to_cal(int(np.frombuffer(fid.read(4), dtype=">i4"))) # Read types call dict _call_dict = { FIFF.FIFFT_STRING: _read_string, FIFF.FIFFT_COMPLEX_FLOAT: _read_complex_float, FIFF.FIFFT_COMPLEX_DOUBLE: _read_complex_double, FIFF.FIFFT_ID_STRUCT: _read_id_struct, FIFF.FIFFT_DIG_POINT_STRUCT: _read_dig_point_struct, FIFF.FIFFT_COORD_TRANS_STRUCT: _read_coord_trans_struct, FIFF.FIFFT_CH_INFO_STRUCT: _read_ch_info_struct, FIFF.FIFFT_OLD_PACK: _read_old_pack, FIFF.FIFFT_DIR_ENTRY_STRUCT: _read_dir_entry_struct, FIFF.FIFFT_JULIAN: _read_julian, } _call_dict_names = { FIFF.FIFFT_STRING: 'str', FIFF.FIFFT_COMPLEX_FLOAT: 'c8', FIFF.FIFFT_COMPLEX_DOUBLE: 'c16', FIFF.FIFFT_ID_STRUCT: 'ids', FIFF.FIFFT_DIG_POINT_STRUCT: 'dps', FIFF.FIFFT_COORD_TRANS_STRUCT: 'cts', FIFF.FIFFT_CH_INFO_STRUCT: 'cis', FIFF.FIFFT_OLD_PACK: 'op_', FIFF.FIFFT_DIR_ENTRY_STRUCT: 'dir', FIFF.FIFFT_JULIAN: 'jul', FIFF.FIFFT_VOID: 'nul', # 0 } # Append the simple types _simple_dict = { FIFF.FIFFT_BYTE: '>B', FIFF.FIFFT_SHORT: '>i2', FIFF.FIFFT_INT: '>i4', FIFF.FIFFT_USHORT: '>u2', FIFF.FIFFT_UINT: '>u4', FIFF.FIFFT_FLOAT: '>f4', FIFF.FIFFT_DOUBLE: '>f8', FIFF.FIFFT_DAU_PACK16: '>i2', } for key, dtype in _simple_dict.items(): _call_dict[key] = partial(_read_simple, dtype=dtype) _call_dict_names[key] = dtype def read_tag(fid, pos=None, shape=None, rlims=None): """Read a Tag from a file at a given position. Parameters ---------- fid : file The open FIF file descriptor. pos : int The position of the Tag in the file. shape : tuple | None If tuple, the shape of the stored matrix. Only to be used with data stored as a vector (not implemented for matrices yet). rlims : tuple | None If tuple, the first (inclusive) and last (exclusive) rows to retrieve. Note that data are assumed to be stored row-major in the file. Only to be used with data stored as a vector (not implemented for matrices yet). Returns ------- tag : Tag The Tag read. """ if pos is not None: fid.seek(pos, 0) tag = _read_tag_header(fid) if tag.size > 0: matrix_coding = _is_matrix & tag.type if matrix_coding != 0: tag.data = _read_matrix(fid, tag, shape, rlims, matrix_coding) else: # All other data types try: fun = _call_dict[tag.type] except KeyError: raise Exception('Unimplemented tag data type %s' % tag.type) tag.data = fun(fid, tag, shape, rlims) if tag.next != FIFF.FIFFV_NEXT_SEQ: # f.seek(tag.next,0) fid.seek(tag.next, 1) # XXX : fix? pb when tag.next < 0 return tag def find_tag(fid, node, findkind): """Find Tag in an open FIF file descriptor. Parameters ---------- fid : file-like Open file. node : dict Node to search. findkind : int Tag kind to find. Returns ------- tag : instance of Tag The first tag found. """ if node['directory'] is not None: for subnode in node['directory']: if subnode.kind == findkind: return read_tag(fid, subnode.pos) return None def has_tag(node, kind): """Check if the node contains a Tag of a given kind.""" for d in node['directory']: if d.kind == kind: return True return False def _rename_list(bads, ch_names_mapping): return [ch_names_mapping.get(bad, bad) for bad in bads]
bsd-3-clause
arnavd96/Cinemiezer
myvenv/lib/python3.4/site-packages/pip/vcs/git.py
473
7898
import tempfile import re import os.path from pip.util import call_subprocess from pip.util import display_path, rmtree from pip.vcs import vcs, VersionControl from pip.log import logger from pip.backwardcompat import url2pathname, urlparse urlsplit = urlparse.urlsplit urlunsplit = urlparse.urlunsplit class Git(VersionControl): name = 'git' dirname = '.git' repo_name = 'clone' schemes = ('git', 'git+http', 'git+https', 'git+ssh', 'git+git', 'git+file') bundle_file = 'git-clone.txt' guide = ('# This was a Git repo; to make it a repo again run:\n' 'git init\ngit remote add origin %(url)s -f\ngit checkout %(rev)s\n') def __init__(self, url=None, *args, **kwargs): # Works around an apparent Git bug # (see http://article.gmane.org/gmane.comp.version-control.git/146500) if url: scheme, netloc, path, query, fragment = urlsplit(url) if scheme.endswith('file'): initial_slashes = path[:-len(path.lstrip('/'))] newpath = initial_slashes + url2pathname(path).replace('\\', '/').lstrip('/') url = urlunsplit((scheme, netloc, newpath, query, fragment)) after_plus = scheme.find('+') + 1 url = scheme[:after_plus] + urlunsplit((scheme[after_plus:], netloc, newpath, query, fragment)) super(Git, self).__init__(url, *args, **kwargs) def parse_vcs_bundle_file(self, content): url = rev = None for line in content.splitlines(): if not line.strip() or line.strip().startswith('#'): continue url_match = re.search(r'git\s*remote\s*add\s*origin(.*)\s*-f', line) if url_match: url = url_match.group(1).strip() rev_match = re.search(r'^git\s*checkout\s*-q\s*(.*)\s*', line) if rev_match: rev = rev_match.group(1).strip() if url and rev: return url, rev return None, None def export(self, location): """Export the Git repository at the url to the destination location""" temp_dir = tempfile.mkdtemp('-export', 'pip-') self.unpack(temp_dir) try: if not location.endswith('/'): location = location + '/' call_subprocess( [self.cmd, 'checkout-index', '-a', '-f', '--prefix', location], filter_stdout=self._filter, show_stdout=False, cwd=temp_dir) finally: rmtree(temp_dir) def check_rev_options(self, rev, dest, rev_options): """Check the revision options before checkout to compensate that tags and branches may need origin/ as a prefix. Returns the SHA1 of the branch or tag if found. """ revisions = self.get_refs(dest) origin_rev = 'origin/%s' % rev if origin_rev in revisions: # remote branch return [revisions[origin_rev]] elif rev in revisions: # a local tag or branch name return [revisions[rev]] else: logger.warn("Could not find a tag or branch '%s', assuming commit." % rev) return rev_options def switch(self, dest, url, rev_options): call_subprocess( [self.cmd, 'config', 'remote.origin.url', url], cwd=dest) call_subprocess( [self.cmd, 'checkout', '-q'] + rev_options, cwd=dest) self.update_submodules(dest) def update(self, dest, rev_options): # First fetch changes from the default remote call_subprocess([self.cmd, 'fetch', '-q'], cwd=dest) # Then reset to wanted revision (maby even origin/master) if rev_options: rev_options = self.check_rev_options(rev_options[0], dest, rev_options) call_subprocess([self.cmd, 'reset', '--hard', '-q'] + rev_options, cwd=dest) #: update submodules self.update_submodules(dest) def obtain(self, dest): url, rev = self.get_url_rev() if rev: rev_options = [rev] rev_display = ' (to %s)' % rev else: rev_options = ['origin/master'] rev_display = '' if self.check_destination(dest, url, rev_options, rev_display): logger.notify('Cloning %s%s to %s' % (url, rev_display, display_path(dest))) call_subprocess([self.cmd, 'clone', '-q', url, dest]) #: repo may contain submodules self.update_submodules(dest) if rev: rev_options = self.check_rev_options(rev, dest, rev_options) # Only do a checkout if rev_options differs from HEAD if not self.get_revision(dest).startswith(rev_options[0]): call_subprocess([self.cmd, 'checkout', '-q'] + rev_options, cwd=dest) def get_url(self, location): url = call_subprocess( [self.cmd, 'config', 'remote.origin.url'], show_stdout=False, cwd=location) return url.strip() def get_revision(self, location): current_rev = call_subprocess( [self.cmd, 'rev-parse', 'HEAD'], show_stdout=False, cwd=location) return current_rev.strip() def get_refs(self, location): """Return map of named refs (branches or tags) to commit hashes.""" output = call_subprocess([self.cmd, 'show-ref'], show_stdout=False, cwd=location) rv = {} for line in output.strip().splitlines(): commit, ref = line.split(' ', 1) ref = ref.strip() ref_name = None if ref.startswith('refs/remotes/'): ref_name = ref[len('refs/remotes/'):] elif ref.startswith('refs/heads/'): ref_name = ref[len('refs/heads/'):] elif ref.startswith('refs/tags/'): ref_name = ref[len('refs/tags/'):] if ref_name is not None: rv[ref_name] = commit.strip() return rv def get_src_requirement(self, dist, location, find_tags): repo = self.get_url(location) if not repo.lower().startswith('git:'): repo = 'git+' + repo egg_project_name = dist.egg_name().split('-', 1)[0] if not repo: return None current_rev = self.get_revision(location) refs = self.get_refs(location) # refs maps names to commit hashes; we need the inverse # if multiple names map to a single commit, this arbitrarily picks one names_by_commit = dict((commit, ref) for ref, commit in refs.items()) if current_rev in names_by_commit: # It's a tag full_egg_name = '%s-%s' % (egg_project_name, names_by_commit[current_rev]) else: full_egg_name = '%s-dev' % egg_project_name return '%s@%s#egg=%s' % (repo, current_rev, full_egg_name) def get_url_rev(self): """ Prefixes stub URLs like 'user@hostname:user/repo.git' with 'ssh://'. That's required because although they use SSH they sometimes doesn't work with a ssh:// scheme (e.g. Github). But we need a scheme for parsing. Hence we remove it again afterwards and return it as a stub. """ if not '://' in self.url: assert not 'file:' in self.url self.url = self.url.replace('git+', 'git+ssh://') url, rev = super(Git, self).get_url_rev() url = url.replace('ssh://', '') else: url, rev = super(Git, self).get_url_rev() return url, rev def update_submodules(self, location): if not os.path.exists(os.path.join(location, '.gitmodules')): return call_subprocess([self.cmd, 'submodule', 'update', '--init', '--recursive', '-q'], cwd=location) vcs.register(Git)
mit
harisibrahimkv/django
tests/view_tests/tests/test_defaults.py
60
5068
import datetime from django.contrib.sites.models import Site from django.http import Http404 from django.template import TemplateDoesNotExist from django.test import RequestFactory, TestCase from django.test.utils import override_settings from django.views.defaults import ( bad_request, page_not_found, permission_denied, server_error, ) from ..models import Article, Author, UrlArticle @override_settings(ROOT_URLCONF='view_tests.urls') class DefaultsTests(TestCase): """Test django views in django/views/defaults.py""" nonexistent_urls = [ '/nonexistent_url/', # this is in urls.py '/other_nonexistent_url/', # this NOT in urls.py ] @classmethod def setUpTestData(cls): Author.objects.create(name='Boris') Article.objects.create( title='Old Article', slug='old_article', author_id=1, date_created=datetime.datetime(2001, 1, 1, 21, 22, 23) ) Article.objects.create( title='Current Article', slug='current_article', author_id=1, date_created=datetime.datetime(2007, 9, 17, 21, 22, 23) ) Article.objects.create( title='Future Article', slug='future_article', author_id=1, date_created=datetime.datetime(3000, 1, 1, 21, 22, 23) ) UrlArticle.objects.create( title='Old Article', slug='old_article', author_id=1, date_created=datetime.datetime(2001, 1, 1, 21, 22, 23) ) Site(id=1, domain='testserver', name='testserver').save() def test_page_not_found(self): "A 404 status is returned by the page_not_found view" for url in self.nonexistent_urls: response = self.client.get(url) self.assertEqual(response.status_code, 404) @override_settings(TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': { 'loaders': [ ('django.template.loaders.locmem.Loader', { '404.html': '{{ csrf_token }}', }), ], }, }]) def test_csrf_token_in_404(self): """ The 404 page should have the csrf_token available in the context """ # See ticket #14565 for url in self.nonexistent_urls: response = self.client.get(url) self.assertNotEqual(response.content, b'NOTPROVIDED') self.assertNotEqual(response.content, b'') def test_server_error(self): "The server_error view raises a 500 status" response = self.client.get('/server_error/') self.assertEqual(response.status_code, 500) @override_settings(TEMPLATES=[{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': { 'loaders': [ ('django.template.loaders.locmem.Loader', { '404.html': 'This is a test template for a 404 error ' '(path: {{ request_path }}, exception: {{ exception }}).', '500.html': 'This is a test template for a 500 error.', }), ], }, }]) def test_custom_templates(self): """ 404.html and 500.html templates are picked by their respective handler. """ response = self.client.get('/server_error/') self.assertContains(response, "test template for a 500 error", status_code=500) response = self.client.get('/no_such_url/') self.assertContains(response, 'path: /no_such_url/', status_code=404) self.assertContains(response, 'exception: Resolver404', status_code=404) response = self.client.get('/technical404/') self.assertContains(response, 'exception: Testing technical 404.', status_code=404) def test_get_absolute_url_attributes(self): "A model can set attributes on the get_absolute_url method" self.assertTrue(getattr(UrlArticle.get_absolute_url, 'purge', False), 'The attributes of the original get_absolute_url must be added.') article = UrlArticle.objects.get(pk=1) self.assertTrue(getattr(article.get_absolute_url, 'purge', False), 'The attributes of the original get_absolute_url must be added.') def test_custom_templates_wrong(self): """ Default error views should raise TemplateDoesNotExist when passed a template that doesn't exist. """ rf = RequestFactory() request = rf.get('/') with self.assertRaises(TemplateDoesNotExist): bad_request(request, Exception(), template_name='nonexistent') with self.assertRaises(TemplateDoesNotExist): permission_denied(request, Exception(), template_name='nonexistent') with self.assertRaises(TemplateDoesNotExist): page_not_found(request, Http404(), template_name='nonexistent') with self.assertRaises(TemplateDoesNotExist): server_error(request, template_name='nonexistent')
bsd-3-clause
GaetanCambier/CouchPotatoServer
couchpotato/core/media/movie/providers/trailer/youtube_dl/extractor/viddler.py
25
3298
from __future__ import unicode_literals from .common import InfoExtractor from ..utils import ( float_or_none, int_or_none, ) class ViddlerIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?viddler\.com/(?:v|embed|player)/(?P<id>[a-z0-9]+)' _TEST = { "url": "http://www.viddler.com/v/43903784", 'md5': 'ae43ad7cb59431ce043f0ff7fa13cbf4', 'info_dict': { 'id': '43903784', 'ext': 'mp4', "title": "Video Made Easy", 'description': 'You don\'t need to be a professional to make high-quality video content. Viddler provides some quick and easy tips on how to produce great video content with limited resources. ', "uploader": "viddler", 'timestamp': 1335371429, 'upload_date': '20120425', "duration": 100.89, 'thumbnail': 're:^https?://.*\.jpg$', 'view_count': int, 'categories': ['video content', 'high quality video', 'video made easy', 'how to produce video with limited resources', 'viddler'], } } def _real_extract(self, url): video_id = self._match_id(url) json_url = ( 'http://api.viddler.com/api/v2/viddler.videos.getPlaybackDetails.json?video_id=%s&key=v0vhrt7bg2xq1vyxhkct' % video_id) data = self._download_json(json_url, video_id)['video'] formats = [] for filed in data['files']: if filed.get('status', 'ready') != 'ready': continue f = { 'format_id': filed['profile_id'], 'format_note': filed['profile_name'], 'url': self._proto_relative_url(filed['url']), 'width': int_or_none(filed.get('width')), 'height': int_or_none(filed.get('height')), 'filesize': int_or_none(filed.get('size')), 'ext': filed.get('ext'), 'source_preference': -1, } formats.append(f) if filed.get('cdn_url'): f = f.copy() f['url'] = self._proto_relative_url(filed['cdn_url']) f['format_id'] = filed['profile_id'] + '-cdn' f['source_preference'] = 1 formats.append(f) if filed.get('html5_video_source'): f = f.copy() f['url'] = self._proto_relative_url( filed['html5_video_source']) f['format_id'] = filed['profile_id'] + '-html5' f['source_preference'] = 0 formats.append(f) self._sort_formats(formats) categories = [ t.get('text') for t in data.get('tags', []) if 'text' in t] return { '_type': 'video', 'id': video_id, 'title': data['title'], 'formats': formats, 'description': data.get('description'), 'timestamp': int_or_none(data.get('upload_time')), 'thumbnail': self._proto_relative_url(data.get('thumbnail_url')), 'uploader': data.get('author'), 'duration': float_or_none(data.get('length')), 'view_count': int_or_none(data.get('view_count')), 'categories': categories, }
gpl-3.0
tejo-esperanto/pasportaservo
pasportaservo/settings/dev.py
1
1693
from .base import * # isort:skip import logging from django.contrib.messages import constants as message_level from debug_toolbar.settings import PANELS_DEFAULTS as DEBUG_PANEL_DEFAULTS ENVIRONMENT = 'DEV' SECRET_KEY = 'N0_s3kre7~k3Y' DEBUG = True MESSAGE_LEVEL = message_level.DEBUG ALLOWED_HOSTS = [ 'localhost', '127.0.0.1', ] logging.getLogger('PasportaServo.auth').setLevel(logging.INFO) logging.getLogger('PasportaServo.geo').setLevel(logging.DEBUG) SASS_PROCESSOR_ROOT = path.join(BASE_DIR, 'core', 'static') INSTALLED_APPS += ( 'debug_toolbar', ) MIDDLEWARE.insert( [i for i, mw in enumerate(MIDDLEWARE) if mw.startswith('django')][-1] + 1, 'debug_toolbar.middleware.DebugToolbarMiddleware' ) MIDDLEWARE += [ # 'debug_toolbar.middleware.DebugToolbarMiddleware', ] DEBUG_TOOLBAR_CONFIG = { 'JQUERY_URL': '/static/js/jquery.min.js', 'DISABLE_PANELS': { 'debug_toolbar.panels.redirects.RedirectsPanel', }, } DEBUG_TOOLBAR_PANELS = DEBUG_PANEL_DEFAULTS[:] DEBUG_TOOLBAR_PANELS[ DEBUG_TOOLBAR_PANELS.index('debug_toolbar.panels.request.RequestPanel') ] = 'pasportaservo.debug.CustomRequestPanel' DEBUG_TOOLBAR_PANELS.remove( 'debug_toolbar.panels.logging.LoggingPanel') DEBUG_TOOLBAR_PANELS.insert( DEBUG_TOOLBAR_PANELS.index('debug_toolbar.panels.sql.SQLPanel') + 1, 'pasportaservo.debug.CustomLoggingPanel') # MailDump # $ sudo pip install maildump (python 2 only) # $ maildump # http://127.0.0.1:1080/ if DEBUG: EMAIL_HOST = '127.0.0.1' EMAIL_PORT = '1025' INTERNAL_IPS = ('127.0.0.1',) EMAIL_SUBJECT_PREFIX = '[PS test] ' EMAIL_SUBJECT_PREFIX_FULL = '[Pasporta Servo][{}] '.format(ENVIRONMENT)
agpl-3.0
ARL-UTEP-OC/emubox
workshop-creator/python27-64bit-gtk3/Lib/site-packages/gi/overrides/Gtk.py
1
57878
# -*- Mode: Python; py-indent-offset: 4 -*- # vim: tabstop=4 shiftwidth=4 expandtab # # Copyright (C) 2009 Johan Dahlin <johan@gnome.org> # 2010 Simon van der Linden <svdlinden@src.gnome.org> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 # USA import collections import sys import warnings from gi.repository import GObject from ..overrides import override, strip_boolean_result, deprecated_init from ..module import get_introspection_module from gi import PyGIDeprecationWarning if sys.version_info >= (3, 0): _basestring = str _callable = lambda c: hasattr(c, '__call__') else: _basestring = basestring _callable = callable Gtk = get_introspection_module('Gtk') __all__ = [] if Gtk._version == '2.0': warn_msg = "You have imported the Gtk 2.0 module. Because Gtk 2.0 \ was not designed for use with introspection some of the \ interfaces and API will fail. As such this is not supported \ by the pygobject development team and we encourage you to \ port your app to Gtk 3 or greater. PyGTK is the recomended \ python module to use with Gtk 2.0" warnings.warn(warn_msg, RuntimeWarning) class PyGTKDeprecationWarning(PyGIDeprecationWarning): pass __all__.append('PyGTKDeprecationWarning') def _construct_target_list(targets): """Create a list of TargetEntry items from a list of tuples in the form (target, flags, info) The list can also contain existing TargetEntry items in which case the existing entry is re-used in the return list. """ target_entries = [] for entry in targets: if not isinstance(entry, Gtk.TargetEntry): entry = Gtk.TargetEntry.new(*entry) target_entries.append(entry) return target_entries __all__.append('_construct_target_list') def _extract_handler_and_args(obj_or_map, handler_name): handler = None if isinstance(obj_or_map, collections.Mapping): handler = obj_or_map.get(handler_name, None) else: handler = getattr(obj_or_map, handler_name, None) if handler is None: raise AttributeError('Handler %s not found' % handler_name) args = () if isinstance(handler, collections.Sequence): if len(handler) == 0: raise TypeError("Handler %s tuple can not be empty" % handler) args = handler[1:] handler = handler[0] elif not _callable(handler): raise TypeError('Handler %s is not a method, function or tuple' % handler) return handler, args # Exposed for unit-testing. __all__.append('_extract_handler_and_args') def _builder_connect_callback(builder, gobj, signal_name, handler_name, connect_obj, flags, obj_or_map): handler, args = _extract_handler_and_args(obj_or_map, handler_name) after = flags & GObject.ConnectFlags.AFTER if connect_obj is not None: if after: gobj.connect_object_after(signal_name, handler, connect_obj, *args) else: gobj.connect_object(signal_name, handler, connect_obj, *args) else: if after: gobj.connect_after(signal_name, handler, *args) else: gobj.connect(signal_name, handler, *args) class Widget(Gtk.Widget): translate_coordinates = strip_boolean_result(Gtk.Widget.translate_coordinates) def drag_dest_set_target_list(self, target_list): if (target_list is not None) and (not isinstance(target_list, Gtk.TargetList)): target_list = Gtk.TargetList.new(_construct_target_list(target_list)) super(Widget, self).drag_dest_set_target_list(target_list) def drag_source_set_target_list(self, target_list): if (target_list is not None) and (not isinstance(target_list, Gtk.TargetList)): target_list = Gtk.TargetList.new(_construct_target_list(target_list)) super(Widget, self).drag_source_set_target_list(target_list) def style_get_property(self, property_name, value=None): if value is None: prop = self.find_style_property(property_name) if prop is None: raise ValueError('Class "%s" does not contain style property "%s"' % (self, property_name)) value = GObject.Value(prop.value_type) Gtk.Widget.style_get_property(self, property_name, value) return value.get_value() Widget = override(Widget) __all__.append('Widget') class Container(Gtk.Container, Widget): def __len__(self): return len(self.get_children()) def __contains__(self, child): return child in self.get_children() def __iter__(self): return iter(self.get_children()) def __bool__(self): return True # alias for Python 2.x object protocol __nonzero__ = __bool__ get_focus_chain = strip_boolean_result(Gtk.Container.get_focus_chain) def child_get_property(self, child, property_name, value=None): if value is None: prop = self.find_child_property(property_name) if prop is None: raise ValueError('Class "%s" does not contain child property "%s"' % (self, property_name)) value = GObject.Value(prop.value_type) Gtk.Container.child_get_property(self, child, property_name, value) return value.get_value() def child_get(self, child, *prop_names): """Returns a list of child property values for the given names.""" return [self.child_get_property(child, name) for name in prop_names] def child_set(self, child, **kwargs): """Set a child properties on the given child to key/value pairs.""" for name, value in kwargs.items(): name = name.replace('_', '-') self.child_set_property(child, name, value) Container = override(Container) __all__.append('Container') class Editable(Gtk.Editable): def insert_text(self, text, position): return super(Editable, self).insert_text(text, -1, position) get_selection_bounds = strip_boolean_result(Gtk.Editable.get_selection_bounds, fail_ret=()) Editable = override(Editable) __all__.append("Editable") if Gtk._version in ("2.0", "3.0"): class Action(Gtk.Action): __init__ = deprecated_init(Gtk.Action.__init__, arg_names=('name', 'label', 'tooltip', 'stock_id'), category=PyGTKDeprecationWarning) Action = override(Action) __all__.append("Action") class RadioAction(Gtk.RadioAction): __init__ = deprecated_init(Gtk.RadioAction.__init__, arg_names=('name', 'label', 'tooltip', 'stock_id', 'value'), category=PyGTKDeprecationWarning) RadioAction = override(RadioAction) __all__.append("RadioAction") class ActionGroup(Gtk.ActionGroup): __init__ = deprecated_init(Gtk.ActionGroup.__init__, arg_names=('name',), category=PyGTKDeprecationWarning) def add_actions(self, entries, user_data=None): """ The add_actions() method is a convenience method that creates a number of gtk.Action objects based on the information in the list of action entry tuples contained in entries and adds them to the action group. The entry tuples can vary in size from one to six items with the following information: * The name of the action. Must be specified. * The stock id for the action. Optional with a default value of None if a label is specified. * The label for the action. This field should typically be marked for translation, see the set_translation_domain() method. Optional with a default value of None if a stock id is specified. * The accelerator for the action, in the format understood by the gtk.accelerator_parse() function. Optional with a default value of None. * The tooltip for the action. This field should typically be marked for translation, see the set_translation_domain() method. Optional with a default value of None. * The callback function invoked when the action is activated. Optional with a default value of None. The "activate" signals of the actions are connected to the callbacks and their accel paths are set to <Actions>/group-name/action-name. """ try: iter(entries) except (TypeError): raise TypeError('entries must be iterable') def _process_action(name, stock_id=None, label=None, accelerator=None, tooltip=None, callback=None): action = Action(name=name, label=label, tooltip=tooltip, stock_id=stock_id) if callback is not None: if user_data is None: action.connect('activate', callback) else: action.connect('activate', callback, user_data) self.add_action_with_accel(action, accelerator) for e in entries: # using inner function above since entries can leave out optional arguments _process_action(*e) def add_toggle_actions(self, entries, user_data=None): """ The add_toggle_actions() method is a convenience method that creates a number of gtk.ToggleAction objects based on the information in the list of action entry tuples contained in entries and adds them to the action group. The toggle action entry tuples can vary in size from one to seven items with the following information: * The name of the action. Must be specified. * The stock id for the action. Optional with a default value of None if a label is specified. * The label for the action. This field should typically be marked for translation, see the set_translation_domain() method. Optional with a default value of None if a stock id is specified. * The accelerator for the action, in the format understood by the gtk.accelerator_parse() function. Optional with a default value of None. * The tooltip for the action. This field should typically be marked for translation, see the set_translation_domain() method. Optional with a default value of None. * The callback function invoked when the action is activated. Optional with a default value of None. * A flag indicating whether the toggle action is active. Optional with a default value of False. The "activate" signals of the actions are connected to the callbacks and their accel paths are set to <Actions>/group-name/action-name. """ try: iter(entries) except (TypeError): raise TypeError('entries must be iterable') def _process_action(name, stock_id=None, label=None, accelerator=None, tooltip=None, callback=None, is_active=False): action = Gtk.ToggleAction(name=name, label=label, tooltip=tooltip, stock_id=stock_id) action.set_active(is_active) if callback is not None: if user_data is None: action.connect('activate', callback) else: action.connect('activate', callback, user_data) self.add_action_with_accel(action, accelerator) for e in entries: # using inner function above since entries can leave out optional arguments _process_action(*e) def add_radio_actions(self, entries, value=None, on_change=None, user_data=None): """ The add_radio_actions() method is a convenience method that creates a number of gtk.RadioAction objects based on the information in the list of action entry tuples contained in entries and adds them to the action group. The entry tuples can vary in size from one to six items with the following information: * The name of the action. Must be specified. * The stock id for the action. Optional with a default value of None if a label is specified. * The label for the action. This field should typically be marked for translation, see the set_translation_domain() method. Optional with a default value of None if a stock id is specified. * The accelerator for the action, in the format understood by the gtk.accelerator_parse() function. Optional with a default value of None. * The tooltip for the action. This field should typically be marked for translation, see the set_translation_domain() method. Optional with a default value of None. * The value to set on the radio action. Optional with a default value of 0. Should be specified in applications. The value parameter specifies the radio action that should be set active. The "changed" signal of the first radio action is connected to the on_change callback (if specified and not None) and the accel paths of the actions are set to <Actions>/group-name/action-name. """ try: iter(entries) except (TypeError): raise TypeError('entries must be iterable') first_action = None def _process_action(group_source, name, stock_id=None, label=None, accelerator=None, tooltip=None, entry_value=0): action = RadioAction(name=name, label=label, tooltip=tooltip, stock_id=stock_id, value=entry_value) # FIXME: join_group is a patch to Gtk+ 3.0 # otherwise we can't effectively add radio actions to a # group. Should we depend on 3.0 and error out here # or should we offer the functionality via a compat # C module? if hasattr(action, 'join_group'): action.join_group(group_source) if value == entry_value: action.set_active(True) self.add_action_with_accel(action, accelerator) return action for e in entries: # using inner function above since entries can leave out optional arguments action = _process_action(first_action, *e) if first_action is None: first_action = action if first_action is not None and on_change is not None: if user_data is None: first_action.connect('changed', on_change) else: first_action.connect('changed', on_change, user_data) ActionGroup = override(ActionGroup) __all__.append('ActionGroup') class UIManager(Gtk.UIManager): def add_ui_from_string(self, buffer): if not isinstance(buffer, _basestring): raise TypeError('buffer must be a string') length = len(buffer.encode('UTF-8')) return Gtk.UIManager.add_ui_from_string(self, buffer, length) def insert_action_group(self, buffer, length=-1): return Gtk.UIManager.insert_action_group(self, buffer, length) UIManager = override(UIManager) __all__.append('UIManager') class ComboBox(Gtk.ComboBox, Container): get_active_iter = strip_boolean_result(Gtk.ComboBox.get_active_iter) ComboBox = override(ComboBox) __all__.append('ComboBox') class Box(Gtk.Box): __init__ = deprecated_init(Gtk.Box.__init__, arg_names=('homogeneous', 'spacing'), category=PyGTKDeprecationWarning) Box = override(Box) __all__.append('Box') class SizeGroup(Gtk.SizeGroup): __init__ = deprecated_init(Gtk.SizeGroup.__init__, arg_names=('mode',), deprecated_defaults={'mode': Gtk.SizeGroupMode.VERTICAL}, category=PyGTKDeprecationWarning) SizeGroup = override(SizeGroup) __all__.append('SizeGroup') class MenuItem(Gtk.MenuItem): __init__ = deprecated_init(Gtk.MenuItem.__init__, arg_names=('label',), category=PyGTKDeprecationWarning) MenuItem = override(MenuItem) __all__.append('MenuItem') class Builder(Gtk.Builder): def connect_signals(self, obj_or_map): """Connect signals specified by this builder to a name, handler mapping. Connect signal, name, and handler sets specified in the builder with the given mapping "obj_or_map". The handler/value aspect of the mapping can also contain a tuple in the form of (handler [,arg1 [,argN]]) allowing for extra arguments to be passed to the handler. For example: .. code-block:: python builder.connect_signals({'on_clicked': (on_clicked, arg1, arg2)}) """ self.connect_signals_full(_builder_connect_callback, obj_or_map) def add_from_string(self, buffer): if not isinstance(buffer, _basestring): raise TypeError('buffer must be a string') length = len(buffer) return Gtk.Builder.add_from_string(self, buffer, length) def add_objects_from_string(self, buffer, object_ids): if not isinstance(buffer, _basestring): raise TypeError('buffer must be a string') length = len(buffer) return Gtk.Builder.add_objects_from_string(self, buffer, length, object_ids) Builder = override(Builder) __all__.append('Builder') # NOTE: This must come before any other Window/Dialog subclassing, to ensure # that we have a correct inheritance hierarchy. class Window(Gtk.Window): __init__ = deprecated_init(Gtk.Window.__init__, arg_names=('type',), category=PyGTKDeprecationWarning) Window = override(Window) __all__.append('Window') class Dialog(Gtk.Dialog, Container): _old_arg_names = ('title', 'parent', 'flags', 'buttons', '_buttons_property') _init = deprecated_init(Gtk.Dialog.__init__, arg_names=('title', 'transient_for', 'flags', 'add_buttons', 'buttons'), ignore=('flags', 'add_buttons'), deprecated_aliases={'transient_for': 'parent', 'buttons': '_buttons_property'}, category=PyGTKDeprecationWarning) def __init__(self, *args, **kwargs): new_kwargs = kwargs.copy() old_kwargs = dict(zip(self._old_arg_names, args)) old_kwargs.update(kwargs) # Increment the warning stacklevel for sub-classes which implement their own __init__. stacklevel = 2 if self.__class__ != Dialog and self.__class__.__init__ != Dialog.__init__: stacklevel += 1 # buttons was overloaded by PyGtk but is needed for Gtk.MessageDialog # as a pass through, so type check the argument and give a deprecation # when it is not of type Gtk.ButtonsType add_buttons = old_kwargs.get('buttons', None) if add_buttons is not None and not isinstance(add_buttons, Gtk.ButtonsType): warnings.warn('The "buttons" argument must be a Gtk.ButtonsType enum value. ' 'Please use the "add_buttons" method for adding buttons. ' 'See: https://wiki.gnome.org/PyGObject/InitializerDeprecations', PyGTKDeprecationWarning, stacklevel=stacklevel) if 'buttons' in new_kwargs: del new_kwargs['buttons'] else: add_buttons = None flags = old_kwargs.get('flags', 0) if flags: warnings.warn('The "flags" argument for dialog construction is deprecated. ' 'Please use initializer keywords: modal=True and/or destroy_with_parent=True. ' 'See: https://wiki.gnome.org/PyGObject/InitializerDeprecations', PyGTKDeprecationWarning, stacklevel=stacklevel) if flags & Gtk.DialogFlags.MODAL: new_kwargs['modal'] = True if flags & Gtk.DialogFlags.DESTROY_WITH_PARENT: new_kwargs['destroy_with_parent'] = True self._init(*args, **new_kwargs) if add_buttons: self.add_buttons(*add_buttons) action_area = property(lambda dialog: dialog.get_action_area()) vbox = property(lambda dialog: dialog.get_content_area()) def add_buttons(self, *args): """ The add_buttons() method adds several buttons to the Gtk.Dialog using the button data passed as arguments to the method. This method is the same as calling the Gtk.Dialog.add_button() repeatedly. The button data pairs - button text (or stock ID) and a response ID integer are passed individually. For example: .. code-block:: python dialog.add_buttons(Gtk.STOCK_OPEN, 42, "Close", Gtk.ResponseType.CLOSE) will add "Open" and "Close" buttons to dialog. """ def _button(b): while b: t, r = b[0:2] b = b[2:] yield t, r try: for text, response in _button(args): self.add_button(text, response) except (IndexError): raise TypeError('Must pass an even number of arguments') Dialog = override(Dialog) __all__.append('Dialog') class MessageDialog(Gtk.MessageDialog, Dialog): __init__ = deprecated_init(Gtk.MessageDialog.__init__, arg_names=('parent', 'flags', 'message_type', 'buttons', 'message_format'), deprecated_aliases={'text': 'message_format', 'message_type': 'type'}, category=PyGTKDeprecationWarning) def format_secondary_text(self, message_format): self.set_property('secondary-use-markup', False) self.set_property('secondary-text', message_format) def format_secondary_markup(self, message_format): self.set_property('secondary-use-markup', True) self.set_property('secondary-text', message_format) MessageDialog = override(MessageDialog) __all__.append('MessageDialog') if Gtk._version in ("2.0", "3.0"): class ColorSelectionDialog(Gtk.ColorSelectionDialog): __init__ = deprecated_init(Gtk.ColorSelectionDialog.__init__, arg_names=('title',), category=PyGTKDeprecationWarning) ColorSelectionDialog = override(ColorSelectionDialog) __all__.append('ColorSelectionDialog') class FileChooserDialog(Gtk.FileChooserDialog): __init__ = deprecated_init(Gtk.FileChooserDialog.__init__, arg_names=('title', 'parent', 'action', 'buttons'), category=PyGTKDeprecationWarning) FileChooserDialog = override(FileChooserDialog) __all__.append('FileChooserDialog') if Gtk._version in ("2.0", "3.0"): class FontSelectionDialog(Gtk.FontSelectionDialog): __init__ = deprecated_init(Gtk.FontSelectionDialog.__init__, arg_names=('title',), category=PyGTKDeprecationWarning) FontSelectionDialog = override(FontSelectionDialog) __all__.append('FontSelectionDialog') class RecentChooserDialog(Gtk.RecentChooserDialog): # Note, the "manager" keyword must work across the entire 3.x series because # "recent_manager" is not backwards compatible with PyGObject versions prior to 3.10. __init__ = deprecated_init(Gtk.RecentChooserDialog.__init__, arg_names=('title', 'parent', 'recent_manager', 'buttons'), deprecated_aliases={'recent_manager': 'manager'}, category=PyGTKDeprecationWarning) RecentChooserDialog = override(RecentChooserDialog) __all__.append('RecentChooserDialog') class IconView(Gtk.IconView): __init__ = deprecated_init(Gtk.IconView.__init__, arg_names=('model',), category=PyGTKDeprecationWarning) get_item_at_pos = strip_boolean_result(Gtk.IconView.get_item_at_pos) get_visible_range = strip_boolean_result(Gtk.IconView.get_visible_range) get_dest_item_at_pos = strip_boolean_result(Gtk.IconView.get_dest_item_at_pos) IconView = override(IconView) __all__.append('IconView') class ToolButton(Gtk.ToolButton): __init__ = deprecated_init(Gtk.ToolButton.__init__, arg_names=('stock_id',), category=PyGTKDeprecationWarning) ToolButton = override(ToolButton) __all__.append('ToolButton') class IMContext(Gtk.IMContext): get_surrounding = strip_boolean_result(Gtk.IMContext.get_surrounding) IMContext = override(IMContext) __all__.append('IMContext') class RecentInfo(Gtk.RecentInfo): get_application_info = strip_boolean_result(Gtk.RecentInfo.get_application_info) RecentInfo = override(RecentInfo) __all__.append('RecentInfo') class TextBuffer(Gtk.TextBuffer): def _get_or_create_tag_table(self): table = self.get_tag_table() if table is None: table = Gtk.TextTagTable() self.set_tag_table(table) return table def create_tag(self, tag_name=None, **properties): """Creates a tag and adds it to the tag table of the TextBuffer. :param str tag_name: Name of the new tag, or None :param **properties: Keyword list of properties and their values This is equivalent to creating a Gtk.TextTag and then adding the tag to the buffer's tag table. The returned tag is owned by the buffer's tag table. If ``tag_name`` is None, the tag is anonymous. If ``tag_name`` is not None, a tag called ``tag_name`` must not already exist in the tag table for this buffer. Properties are passed as a keyword list of names and values (e.g. foreground='DodgerBlue', weight=Pango.Weight.BOLD) :returns: A new tag. """ tag = Gtk.TextTag(name=tag_name, **properties) self._get_or_create_tag_table().add(tag) return tag def create_mark(self, mark_name, where, left_gravity=False): return Gtk.TextBuffer.create_mark(self, mark_name, where, left_gravity) def set_text(self, text, length=-1): Gtk.TextBuffer.set_text(self, text, length) def insert(self, iter, text, length=-1): if not isinstance(text, _basestring): raise TypeError('text must be a string, not %s' % type(text)) Gtk.TextBuffer.insert(self, iter, text, length) def insert_with_tags(self, iter, text, *tags): start_offset = iter.get_offset() self.insert(iter, text) if not tags: return start = self.get_iter_at_offset(start_offset) for tag in tags: self.apply_tag(tag, start, iter) def insert_with_tags_by_name(self, iter, text, *tags): if not tags: return tag_objs = [] for tag in tags: tag_obj = self.get_tag_table().lookup(tag) if not tag_obj: raise ValueError('unknown text tag: %s' % tag) tag_objs.append(tag_obj) self.insert_with_tags(iter, text, *tag_objs) def insert_at_cursor(self, text, length=-1): if not isinstance(text, _basestring): raise TypeError('text must be a string, not %s' % type(text)) Gtk.TextBuffer.insert_at_cursor(self, text, length) get_selection_bounds = strip_boolean_result(Gtk.TextBuffer.get_selection_bounds, fail_ret=()) TextBuffer = override(TextBuffer) __all__.append('TextBuffer') class TextIter(Gtk.TextIter): forward_search = strip_boolean_result(Gtk.TextIter.forward_search) backward_search = strip_boolean_result(Gtk.TextIter.backward_search) TextIter = override(TextIter) __all__.append('TextIter') class TreeModel(Gtk.TreeModel): def __len__(self): return self.iter_n_children(None) def __bool__(self): return True # alias for Python 2.x object protocol __nonzero__ = __bool__ def _getiter(self, key): if isinstance(key, Gtk.TreeIter): return key elif isinstance(key, int) and key < 0: index = len(self) + key if index < 0: raise IndexError("row index is out of bounds: %d" % key) try: aiter = self.get_iter(index) except ValueError: raise IndexError("could not find tree path '%s'" % key) return aiter else: try: aiter = self.get_iter(key) except ValueError: raise IndexError("could not find tree path '%s'" % key) return aiter def _coerce_path(self, path): if isinstance(path, Gtk.TreePath): return path else: return TreePath(path) def __getitem__(self, key): aiter = self._getiter(key) return TreeModelRow(self, aiter) def __setitem__(self, key, value): row = self[key] self.set_row(row.iter, value) def __delitem__(self, key): aiter = self._getiter(key) self.remove(aiter) def __iter__(self): return TreeModelRowIter(self, self.get_iter_first()) get_iter_first = strip_boolean_result(Gtk.TreeModel.get_iter_first) iter_children = strip_boolean_result(Gtk.TreeModel.iter_children) iter_nth_child = strip_boolean_result(Gtk.TreeModel.iter_nth_child) iter_parent = strip_boolean_result(Gtk.TreeModel.iter_parent) get_iter_from_string = strip_boolean_result(Gtk.TreeModel.get_iter_from_string, ValueError, 'invalid tree path') def get_iter(self, path): path = self._coerce_path(path) success, aiter = super(TreeModel, self).get_iter(path) if not success: raise ValueError("invalid tree path '%s'" % path) return aiter def iter_next(self, aiter): next_iter = aiter.copy() success = super(TreeModel, self).iter_next(next_iter) if success: return next_iter def iter_previous(self, aiter): prev_iter = aiter.copy() success = super(TreeModel, self).iter_previous(prev_iter) if success: return prev_iter def _convert_row(self, row): # TODO: Accept a dictionary for row # model.append(None,{COLUMN_ICON: icon, COLUMN_NAME: name}) if isinstance(row, str): raise TypeError('Expected a list or tuple, but got str') n_columns = self.get_n_columns() if len(row) != n_columns: raise ValueError('row sequence has the incorrect number of elements') result = [] columns = [] for cur_col, value in enumerate(row): # do not try to set None values, they are causing warnings if value is None: continue result.append(self._convert_value(cur_col, value)) columns.append(cur_col) return (result, columns) def set_row(self, treeiter, row): converted_row, columns = self._convert_row(row) for column in columns: value = row[column] if value is None: continue # None means skip this row self.set_value(treeiter, column, value) def _convert_value(self, column, value): '''Convert value to a GObject.Value of the expected type''' if isinstance(value, GObject.Value): return value return GObject.Value(self.get_column_type(column), value) def get(self, treeiter, *columns): n_columns = self.get_n_columns() values = [] for col in columns: if not isinstance(col, int): raise TypeError("column numbers must be ints") if col < 0 or col >= n_columns: raise ValueError("column number is out of range") values.append(self.get_value(treeiter, col)) return tuple(values) # # Signals supporting python iterables as tree paths # def row_changed(self, path, iter): return super(TreeModel, self).row_changed(self._coerce_path(path), iter) def row_inserted(self, path, iter): return super(TreeModel, self).row_inserted(self._coerce_path(path), iter) def row_has_child_toggled(self, path, iter): return super(TreeModel, self).row_has_child_toggled(self._coerce_path(path), iter) def row_deleted(self, path): return super(TreeModel, self).row_deleted(self._coerce_path(path)) def rows_reordered(self, path, iter, new_order): return super(TreeModel, self).rows_reordered(self._coerce_path(path), iter, new_order) TreeModel = override(TreeModel) __all__.append('TreeModel') class TreeSortable(Gtk.TreeSortable, ): get_sort_column_id = strip_boolean_result(Gtk.TreeSortable.get_sort_column_id, fail_ret=(None, None)) def set_sort_func(self, sort_column_id, sort_func, user_data=None): super(TreeSortable, self).set_sort_func(sort_column_id, sort_func, user_data) def set_default_sort_func(self, sort_func, user_data=None): super(TreeSortable, self).set_default_sort_func(sort_func, user_data) TreeSortable = override(TreeSortable) __all__.append('TreeSortable') class TreeModelSort(Gtk.TreeModelSort): __init__ = deprecated_init(Gtk.TreeModelSort.__init__, arg_names=('model',), category=PyGTKDeprecationWarning) TreeModelSort = override(TreeModelSort) __all__.append('TreeModelSort') class ListStore(Gtk.ListStore, TreeModel, TreeSortable): def __init__(self, *column_types): Gtk.ListStore.__init__(self) self.set_column_types(column_types) def _do_insert(self, position, row): if row is not None: row, columns = self._convert_row(row) treeiter = self.insert_with_valuesv(position, columns, row) else: treeiter = Gtk.ListStore.insert(self, position) return treeiter def append(self, row=None): if row: return self._do_insert(-1, row) # gtk_list_store_insert() does not know about the "position == -1" # case, so use append() here else: return Gtk.ListStore.append(self) def prepend(self, row=None): return self._do_insert(0, row) def insert(self, position, row=None): return self._do_insert(position, row) # FIXME: sends two signals; check if this can use an atomic # insert_with_valuesv() def insert_before(self, sibling, row=None): treeiter = Gtk.ListStore.insert_before(self, sibling) if row is not None: self.set_row(treeiter, row) return treeiter # FIXME: sends two signals; check if this can use an atomic # insert_with_valuesv() def insert_after(self, sibling, row=None): treeiter = Gtk.ListStore.insert_after(self, sibling) if row is not None: self.set_row(treeiter, row) return treeiter def set_value(self, treeiter, column, value): value = self._convert_value(column, value) Gtk.ListStore.set_value(self, treeiter, column, value) def set(self, treeiter, *args): def _set_lists(columns, values): if len(columns) != len(values): raise TypeError('The number of columns do not match the number of values') for col_num, val in zip(columns, values): if not isinstance(col_num, int): raise TypeError('TypeError: Expected integer argument for column.') self.set_value(treeiter, col_num, val) if args: if isinstance(args[0], int): columns = args[::2] values = args[1::2] _set_lists(columns, values) elif isinstance(args[0], (tuple, list)): if len(args) != 2: raise TypeError('Too many arguments') _set_lists(args[0], args[1]) elif isinstance(args[0], dict): columns = args[0].keys() values = args[0].values() _set_lists(columns, values) else: raise TypeError('Argument list must be in the form of (column, value, ...), ((columns,...), (values, ...)) or {column: value}. No -1 termination is needed.') ListStore = override(ListStore) __all__.append('ListStore') class TreeModelRow(object): def __init__(self, model, iter_or_path): if not isinstance(model, Gtk.TreeModel): raise TypeError("expected Gtk.TreeModel, %s found" % type(model).__name__) self.model = model if isinstance(iter_or_path, Gtk.TreePath): self.iter = model.get_iter(iter_or_path) elif isinstance(iter_or_path, Gtk.TreeIter): self.iter = iter_or_path else: raise TypeError("expected Gtk.TreeIter or Gtk.TreePath, \ %s found" % type(iter_or_path).__name__) @property def path(self): return self.model.get_path(self.iter) @property def next(self): return self.get_next() @property def previous(self): return self.get_previous() @property def parent(self): return self.get_parent() def get_next(self): next_iter = self.model.iter_next(self.iter) if next_iter: return TreeModelRow(self.model, next_iter) def get_previous(self): prev_iter = self.model.iter_previous(self.iter) if prev_iter: return TreeModelRow(self.model, prev_iter) def get_parent(self): parent_iter = self.model.iter_parent(self.iter) if parent_iter: return TreeModelRow(self.model, parent_iter) def __getitem__(self, key): if isinstance(key, int): if key >= self.model.get_n_columns(): raise IndexError("column index is out of bounds: %d" % key) elif key < 0: key = self._convert_negative_index(key) return self.model.get_value(self.iter, key) elif isinstance(key, slice): start, stop, step = key.indices(self.model.get_n_columns()) alist = [] for i in range(start, stop, step): alist.append(self.model.get_value(self.iter, i)) return alist elif isinstance(key, tuple): return [self[k] for k in key] else: raise TypeError("indices must be integers, slice or tuple, not %s" % type(key).__name__) def __setitem__(self, key, value): if isinstance(key, int): if key >= self.model.get_n_columns(): raise IndexError("column index is out of bounds: %d" % key) elif key < 0: key = self._convert_negative_index(key) self.model.set_value(self.iter, key, value) elif isinstance(key, slice): start, stop, step = key.indices(self.model.get_n_columns()) indexList = range(start, stop, step) if len(indexList) != len(value): raise ValueError( "attempt to assign sequence of size %d to slice of size %d" % (len(value), len(indexList))) for i, v in enumerate(indexList): self.model.set_value(self.iter, v, value[i]) elif isinstance(key, tuple): if len(key) != len(value): raise ValueError( "attempt to assign sequence of size %d to sequence of size %d" % (len(value), len(key))) for k, v in zip(key, value): self[k] = v else: raise TypeError("indices must be an integer, slice or tuple, not %s" % type(key).__name__) def _convert_negative_index(self, index): new_index = self.model.get_n_columns() + index if new_index < 0: raise IndexError("column index is out of bounds: %d" % index) return new_index def iterchildren(self): child_iter = self.model.iter_children(self.iter) return TreeModelRowIter(self.model, child_iter) __all__.append('TreeModelRow') class TreeModelRowIter(object): def __init__(self, model, aiter): self.model = model self.iter = aiter def __next__(self): if not self.iter: raise StopIteration row = TreeModelRow(self.model, self.iter) self.iter = self.model.iter_next(self.iter) return row # alias for Python 2.x object protocol next = __next__ def __iter__(self): return self __all__.append('TreeModelRowIter') class TreePath(Gtk.TreePath): def __new__(cls, path=0): if isinstance(path, int): path = str(path) elif not isinstance(path, _basestring): path = ":".join(str(val) for val in path) if len(path) == 0: raise TypeError("could not parse subscript '%s' as a tree path" % path) try: return TreePath.new_from_string(path) except TypeError: raise TypeError("could not parse subscript '%s' as a tree path" % path) def __init__(self, *args, **kwargs): super(TreePath, self).__init__() def __str__(self): return self.to_string() def __lt__(self, other): return other is not None and self.compare(other) < 0 def __le__(self, other): return other is not None and self.compare(other) <= 0 def __eq__(self, other): return other is not None and self.compare(other) == 0 def __ne__(self, other): return other is None or self.compare(other) != 0 def __gt__(self, other): return other is None or self.compare(other) > 0 def __ge__(self, other): return other is None or self.compare(other) >= 0 def __iter__(self): return iter(self.get_indices()) def __len__(self): return self.get_depth() def __getitem__(self, index): return self.get_indices()[index] TreePath = override(TreePath) __all__.append('TreePath') class TreeStore(Gtk.TreeStore, TreeModel, TreeSortable): def __init__(self, *column_types): Gtk.TreeStore.__init__(self) self.set_column_types(column_types) def _do_insert(self, parent, position, row): if row is not None: row, columns = self._convert_row(row) treeiter = self.insert_with_values(parent, position, columns, row) else: treeiter = Gtk.TreeStore.insert(self, parent, position) return treeiter def append(self, parent, row=None): return self._do_insert(parent, -1, row) def prepend(self, parent, row=None): return self._do_insert(parent, 0, row) def insert(self, parent, position, row=None): return self._do_insert(parent, position, row) # FIXME: sends two signals; check if this can use an atomic # insert_with_valuesv() def insert_before(self, parent, sibling, row=None): treeiter = Gtk.TreeStore.insert_before(self, parent, sibling) if row is not None: self.set_row(treeiter, row) return treeiter # FIXME: sends two signals; check if this can use an atomic # insert_with_valuesv() def insert_after(self, parent, sibling, row=None): treeiter = Gtk.TreeStore.insert_after(self, parent, sibling) if row is not None: self.set_row(treeiter, row) return treeiter def set_value(self, treeiter, column, value): value = self._convert_value(column, value) Gtk.TreeStore.set_value(self, treeiter, column, value) def set(self, treeiter, *args): def _set_lists(columns, values): if len(columns) != len(values): raise TypeError('The number of columns do not match the number of values') for col_num, val in zip(columns, values): if not isinstance(col_num, int): raise TypeError('TypeError: Expected integer argument for column.') self.set_value(treeiter, col_num, val) if args: if isinstance(args[0], int): columns = args[::2] values = args[1::2] _set_lists(columns, values) elif isinstance(args[0], (tuple, list)): if len(args) != 2: raise TypeError('Too many arguments') _set_lists(args[0], args[1]) elif isinstance(args[0], dict): columns = args[0].keys() values = args[0].values() _set_lists(columns, values) else: raise TypeError('Argument list must be in the form of (column, value, ...), ((columns,...), (values, ...)) or {column: value}. No -1 termination is needed.') TreeStore = override(TreeStore) __all__.append('TreeStore') class TreeView(Gtk.TreeView, Container): __init__ = deprecated_init(Gtk.TreeView.__init__, arg_names=('model',), category=PyGTKDeprecationWarning) get_path_at_pos = strip_boolean_result(Gtk.TreeView.get_path_at_pos) get_visible_range = strip_boolean_result(Gtk.TreeView.get_visible_range) get_dest_row_at_pos = strip_boolean_result(Gtk.TreeView.get_dest_row_at_pos) def enable_model_drag_source(self, start_button_mask, targets, actions): target_entries = _construct_target_list(targets) super(TreeView, self).enable_model_drag_source(start_button_mask, target_entries, actions) def enable_model_drag_dest(self, targets, actions): target_entries = _construct_target_list(targets) super(TreeView, self).enable_model_drag_dest(target_entries, actions) def scroll_to_cell(self, path, column=None, use_align=False, row_align=0.0, col_align=0.0): if not isinstance(path, Gtk.TreePath): path = TreePath(path) super(TreeView, self).scroll_to_cell(path, column, use_align, row_align, col_align) def set_cursor(self, path, column=None, start_editing=False): if not isinstance(path, Gtk.TreePath): path = TreePath(path) super(TreeView, self).set_cursor(path, column, start_editing) def get_cell_area(self, path, column=None): if not isinstance(path, Gtk.TreePath): path = TreePath(path) return super(TreeView, self).get_cell_area(path, column) def insert_column_with_attributes(self, position, title, cell, **kwargs): column = TreeViewColumn() column.set_title(title) column.pack_start(cell, False) self.insert_column(column, position) column.set_attributes(cell, **kwargs) TreeView = override(TreeView) __all__.append('TreeView') class TreeViewColumn(Gtk.TreeViewColumn): def __init__(self, title='', cell_renderer=None, **attributes): Gtk.TreeViewColumn.__init__(self, title=title) if cell_renderer: self.pack_start(cell_renderer, True) for (name, value) in attributes.items(): self.add_attribute(cell_renderer, name, value) cell_get_position = strip_boolean_result(Gtk.TreeViewColumn.cell_get_position) def set_cell_data_func(self, cell_renderer, func, func_data=None): super(TreeViewColumn, self).set_cell_data_func(cell_renderer, func, func_data) def set_attributes(self, cell_renderer, **attributes): Gtk.CellLayout.clear_attributes(self, cell_renderer) for (name, value) in attributes.items(): Gtk.CellLayout.add_attribute(self, cell_renderer, name, value) TreeViewColumn = override(TreeViewColumn) __all__.append('TreeViewColumn') class TreeSelection(Gtk.TreeSelection): def select_path(self, path): if not isinstance(path, Gtk.TreePath): path = TreePath(path) super(TreeSelection, self).select_path(path) def get_selected(self): success, model, aiter = super(TreeSelection, self).get_selected() if success: return (model, aiter) else: return (model, None) # for compatibility with PyGtk def get_selected_rows(self): rows, model = super(TreeSelection, self).get_selected_rows() return (model, rows) TreeSelection = override(TreeSelection) __all__.append('TreeSelection') class Button(Gtk.Button, Container): _init = deprecated_init(Gtk.Button.__init__, arg_names=('label', 'stock', 'use_stock', 'use_underline'), ignore=('stock',), category=PyGTKDeprecationWarning, stacklevel=3) def __init__(self, *args, **kwargs): # Doubly deprecated initializer, the stock keyword is non-standard. # Simply give a warning that stock items are deprecated even though # we want to deprecate the non-standard keyword as well here from # the overrides. if 'stock' in kwargs and kwargs['stock']: warnings.warn('Stock items are deprecated. ' 'Please use: Gtk.Button.new_with_mnemonic(label)', PyGTKDeprecationWarning, stacklevel=2) new_kwargs = kwargs.copy() new_kwargs['label'] = new_kwargs['stock'] new_kwargs['use_stock'] = True new_kwargs['use_underline'] = True del new_kwargs['stock'] Gtk.Button.__init__(self, **new_kwargs) else: self._init(*args, **kwargs) Button = override(Button) __all__.append('Button') class LinkButton(Gtk.LinkButton): __init__ = deprecated_init(Gtk.LinkButton.__init__, arg_names=('uri', 'label'), category=PyGTKDeprecationWarning) LinkButton = override(LinkButton) __all__.append('LinkButton') class Label(Gtk.Label): __init__ = deprecated_init(Gtk.Label.__init__, arg_names=('label',), category=PyGTKDeprecationWarning) Label = override(Label) __all__.append('Label') class Adjustment(Gtk.Adjustment): _init = deprecated_init(Gtk.Adjustment.__init__, arg_names=('value', 'lower', 'upper', 'step_increment', 'page_increment', 'page_size'), deprecated_aliases={'page_increment': 'page_incr', 'step_increment': 'step_incr'}, category=PyGTKDeprecationWarning, stacklevel=3) def __init__(self, *args, **kwargs): self._init(*args, **kwargs) # The value property is set between lower and (upper - page_size). # Just in case lower, upper or page_size was still 0 when value # was set, we set it again here. if 'value' in kwargs: self.set_value(kwargs['value']) Adjustment = override(Adjustment) __all__.append('Adjustment') if Gtk._version in ("2.0", "3.0"): class Table(Gtk.Table, Container): __init__ = deprecated_init(Gtk.Table.__init__, arg_names=('n_rows', 'n_columns', 'homogeneous'), deprecated_aliases={'n_rows': 'rows', 'n_columns': 'columns'}, category=PyGTKDeprecationWarning) def attach(self, child, left_attach, right_attach, top_attach, bottom_attach, xoptions=Gtk.AttachOptions.EXPAND | Gtk.AttachOptions.FILL, yoptions=Gtk.AttachOptions.EXPAND | Gtk.AttachOptions.FILL, xpadding=0, ypadding=0): Gtk.Table.attach(self, child, left_attach, right_attach, top_attach, bottom_attach, xoptions, yoptions, xpadding, ypadding) Table = override(Table) __all__.append('Table') class ScrolledWindow(Gtk.ScrolledWindow): __init__ = deprecated_init(Gtk.ScrolledWindow.__init__, arg_names=('hadjustment', 'vadjustment'), category=PyGTKDeprecationWarning) ScrolledWindow = override(ScrolledWindow) __all__.append('ScrolledWindow') if Gtk._version in ("2.0", "3.0"): class HScrollbar(Gtk.HScrollbar): __init__ = deprecated_init(Gtk.HScrollbar.__init__, arg_names=('adjustment',), category=PyGTKDeprecationWarning) HScrollbar = override(HScrollbar) __all__.append('HScrollbar') class VScrollbar(Gtk.VScrollbar): __init__ = deprecated_init(Gtk.VScrollbar.__init__, arg_names=('adjustment',), category=PyGTKDeprecationWarning) VScrollbar = override(VScrollbar) __all__.append('VScrollbar') class Paned(Gtk.Paned): def pack1(self, child, resize=False, shrink=True): super(Paned, self).pack1(child, resize, shrink) def pack2(self, child, resize=True, shrink=True): super(Paned, self).pack2(child, resize, shrink) Paned = override(Paned) __all__.append('Paned') if Gtk._version in ("2.0", "3.0"): class Arrow(Gtk.Arrow): __init__ = deprecated_init(Gtk.Arrow.__init__, arg_names=('arrow_type', 'shadow_type'), category=PyGTKDeprecationWarning) Arrow = override(Arrow) __all__.append('Arrow') class IconSet(Gtk.IconSet): def __new__(cls, pixbuf=None): if pixbuf is not None: warnings.warn('Gtk.IconSet(pixbuf) has been deprecated. Please use: ' 'Gtk.IconSet.new_from_pixbuf(pixbuf)', PyGTKDeprecationWarning, stacklevel=2) iconset = Gtk.IconSet.new_from_pixbuf(pixbuf) else: iconset = Gtk.IconSet.__new__(cls) return iconset def __init__(self, *args, **kwargs): return super(IconSet, self).__init__() IconSet = override(IconSet) __all__.append('IconSet') class Viewport(Gtk.Viewport): __init__ = deprecated_init(Gtk.Viewport.__init__, arg_names=('hadjustment', 'vadjustment'), category=PyGTKDeprecationWarning) Viewport = override(Viewport) __all__.append('Viewport') class TreeModelFilter(Gtk.TreeModelFilter): def set_visible_func(self, func, data=None): super(TreeModelFilter, self).set_visible_func(func, data) def set_value(self, iter, column, value): # Delegate to child model iter = self.convert_iter_to_child_iter(iter) self.get_model().set_value(iter, column, value) TreeModelFilter = override(TreeModelFilter) __all__.append('TreeModelFilter') if Gtk._version != '2.0': class Menu(Gtk.Menu): def popup(self, parent_menu_shell, parent_menu_item, func, data, button, activate_time): self.popup_for_device(None, parent_menu_shell, parent_menu_item, func, data, button, activate_time) Menu = override(Menu) __all__.append('Menu') _Gtk_main_quit = Gtk.main_quit @override(Gtk.main_quit) def main_quit(*args): _Gtk_main_quit() if Gtk._version in ("2.0", "3.0"): stock_lookup = strip_boolean_result(Gtk.stock_lookup) __all__.append('stock_lookup') if Gtk._version == "4.0": Gtk.init_check() else: initialized, argv = Gtk.init_check(sys.argv) sys.argv = list(argv)
gpl-2.0
eueung/svg-edit-mirror
extras/topo.py
48
1292
import sys, json, codecs infile = json.load(codecs.open(sys.argv[1], "r", "utf-8")) outfile = codecs.open(sys.argv[1] + ".po", "w", "utf-8") out = [] out.append("""# LANGUAGE FILE FOR SVG-EDIT, AUTOGENERATED BY TOPO.PY msgid "" msgstr "" "Content-Type: text/plain; charset=utf-8\\n" "Content-Transfer-Encoding: 8bit\\n" # --- """) def printstr(flag, i, s): out.append('\n') if flag == '-x-svg-edit-both': out.append("# Enter the title first, then the contents, seperated by a pipe char (|)\n") out.append("#, " + flag + '\n') out.append("msgid \"" + i + "\"" + '\n') out.append("msgstr \"" + s.replace('\n', '\\n') + "\"" + '\n') for line in infile: if line.has_key('title') and line.has_key('textContent'): printstr('-x-svg-edit-both', line['id'], "|".join(((line['title'], line['textContent'])))) elif line.has_key('title'): printstr('-x-svg-edit-title', line['id'], line['title']) elif line.has_key('textContent'): printstr('-x-svg-edit-textContent', line['id'], line['textContent']) elif line.has_key('js_strings'): for i, s in line['js_strings'].items(): printstr('-x-svg-edit-js_strings', i, s) else: pass # The line wasn't really a string outfile.writelines(out) outfile.close()
mit
rhinstaller/initial-setup
tests/pylint/intl.py
12
2668
# I18N-related pylint module # # Copyright (C) 2013 Red Hat, Inc. # # This copyrighted material is made available to anyone wishing to use, # modify, copy, or redistribute it subject to the terms and conditions of # the GNU General Public License v.2, or (at your option) any later version. # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY expressed or implied, including the implied warranties of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General # Public License for more details. You should have received a copy of the # GNU General Public License along with this program; if not, write to the # Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA # 02110-1301, USA. Any Red Hat trademarks that are incorporated in the # source code or documentation are not subject to the GNU General Public # License and may only be used or replicated with the express permission of # Red Hat, Inc. # # Red Hat Author(s): Chris Lumens <clumens@redhat.com> # import astroid from pylint.checkers import BaseChecker from pylint.checkers.utils import check_messages from pylint.interfaces import IAstroidChecker translationMethods = ["_", "N_", "P_", "C_", "CN_", "CP_"] class IntlChecker(BaseChecker): __implements__ = (IAstroidChecker, ) name = "internationalization" msgs = {"W9901": ("Found % in a call to a _() method", "found-percent-in-_", "% in a call to one of the _() methods results in incorrect translations"), "W9902": ("Found _ call at module/class level", "found-_-in-module-class", "Calling _ at the module or class level results in translations to the wrong language") } @check_messages("W9901") def visit_binop(self, node): if node.op != "%": return curr = node while curr.parent: if isinstance(curr.parent, astroid.CallFunc) and getattr(curr.parent.func, "name", "") in translationMethods: self.add_message("W9901", node=node) break curr = curr.parent @check_messages("W9902") def visit_callfunc(self, node): # The first test skips internal functions like getattr. if isinstance(node.func, astroid.Name) and node.func.name == "_": if isinstance(node.scope(), astroid.Module) or isinstance(node.scope(), astroid.Class): self.add_message("W9902", node=node) def register(linter): """required method to auto register this checker """ linter.register_checker(IntlChecker(linter))
gpl-2.0
Brocade-OpenSource/OpenStack-DNRM-Nova
nova/db/sqlalchemy/migrate_repo/versions/176_add_availability_zone_to_volume_usage_cache.py
16
2048
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright 2013 OpenStack Foundation # # 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. # # This migration adds the availability_zone to the volume_usage_cache table. # # This table keeps a cache of the volume usage. Every minute (or what ever # is configured for volume_usage_poll_interval value) one row in this table # gets updated for each attached volume. After this patch is applied, for # any currently attached volumes, the value will immediately be null, but # will get updated to the correct value on the next tick of the volume # usage poll. # # The volume usage poll function is the only code to access this table. The # sequence of operation in that function is to first update the field with # the correct value and then to pass the updated data to the consumer. # # Hence this new column does not need to be pre-populated. # from sqlalchemy import MetaData, String, Table, Column from nova.openstack.common import log as logging LOG = logging.getLogger(__name__) def upgrade(migrate_engine): meta = MetaData() meta.bind = migrate_engine volume_usage_cache = Table('volume_usage_cache', meta, autoload=True) availability_zone = Column('availability_zone', String(255)) volume_usage_cache.create_column(availability_zone) def downgrade(migrate_engine): meta = MetaData() meta.bind = migrate_engine volume_usage_cache = Table('volume_usage_cache', meta, autoload=True) volume_usage_cache.drop_column('availability_zone')
apache-2.0
rainaashutosh/MyTestRekall
rekall-core/rekall/plugins/common/bovine.py
6
4865
# Rekall Memory Forensics # Copyright 2014 Google Inc. All Rights Reserved. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or (at # your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # """The plugins in this module are mainly used to visually test renderers.""" __author__ = "Adam Sindelar <adamsh@google.com>" import itertools from rekall import plugin from rekall import algo from rekall import utils from rekall.plugins.renderers import visual_aides class RekallBovineExperience3000(plugin.Command): """Renders Bessy the cow and some beer. This is a text renderer stress-test. It uses multiple features at the same time: - Multiple coloring rules per line (this was a doozy). - Two columns with colors next to each other. - Text with its own newlines isn't rewrapped. - It still wraps if it overflows the cell. - Bovine readiness and international spirit. """ __name = "moo" def render(self, renderer): renderer.table_header([ dict(name="Dogma", width=35, style="full"), dict(name="Bessy", width=65, type="bool", style="cow"), dict(name="Pilsner", width=50, style="full"), dict(name="Nowrap", width=10, nowrap=True)]) fixtures = self.session.LoadProfile("tests/fixtures") beer = fixtures.data["ascii_art"]["beer"] phys_map = fixtures.data["fixtures"]["phys_map"] renderer.table_row( ("This is a renderer stress-test. The flags should have correct" " colors, the beer should be yellow and the cell on the left" " should not bleed into the cell on the right.\n" "This is a really " "long column of text with its own newlines in it!\n" "This bovine experience has been brought to you by Rekall."), True, utils.AttributedString("\n".join(beer["ascii"]), beer["highlights"]), ("This is a fairly long line that shouldn't get wrapped.\n" "The same row has another line that shouldn't get wrapped.")) renderer.section("Heatmap test:") cells = [] for digit in itertools.islice(algo.EulersDecimals(), 0xff): cells.append(dict(heat=float(digit + 1) * .1, value=digit)) randomized = visual_aides.Heatmap( caption="Offset (p)", # Some of the below xs stand for eXtreme. The other ones just # look cool. column_headers=["%0.2x" % x for x in xrange(0, 0xff, 0x10)], row_headers=["0x%0.6x" % x for x in xrange(0x0, 0xfffff, 0x10000)], cells=cells, greyscale=False) gradual = visual_aides.Heatmap( caption="Offset (v)", column_headers=["%0.2x" % x for x in xrange(0, 0xff, 0x10)], row_headers=["0x%0.6x" % x for x in xrange(0x0, 0xfffff, 0x10000)], cells=[dict(value="%x" % x, heat=x / 255.0) for x in xrange(256)], greyscale=False) ranges_legend = visual_aides.MapLegend(phys_map["ranges_legend"]) ranges = visual_aides.RunBasedMap( caption="Offset (p)", legend=ranges_legend, runs=phys_map["runs"]) renderer.table_header([dict(name="Random Heatmap", style="full", width=60, align="c"), dict(name="Gradual Heatmap", style="full", width=60, align="c"), dict(name="Legend", style="full", orientation="horizontal")]) renderer.table_row(randomized, gradual, visual_aides.HeatmapLegend()) renderer.table_header([dict(name="Greyscale Random", style="full", width=60, align="c"), dict(name="Memory Ranges", style="full", width=80, align="c"), dict(name="Ranges Legend", style="full", width=30, orientation="vertical")]) randomized.greyscale = True renderer.table_row(randomized, ranges, ranges_legend)
gpl-2.0
tersmitten/ansible
lib/ansible/modules/cloud/azure/azure_rm_availabilityset_facts.py
7
4695
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2016, Julien Stroheker <juliens@microsoft.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: azure_rm_availabilityset_facts version_added: "2.4" short_description: Get availability set facts. description: - Get facts for a specific availability set or all availability sets. options: name: description: - Limit results to a specific availability set resource_group: description: - The resource group to search for the desired availability set tags: description: - List of tags to be matched extends_documentation_fragment: - azure author: - "Julien Stroheker (@julienstroheker)" ''' EXAMPLES = ''' - name: Get facts for one availability set azure_rm_availabilityset_facts: name: Testing resource_group: myResourceGroup - name: Get facts for all availability sets in a specific resource group azure_rm_availabilityset_facts: resource_group: myResourceGroup ''' RETURN = ''' azure_availabilityset: description: List of availability sets dicts. returned: always type: list example: [{ "location": "eastus2", "name": "myAvailabilitySet", "properties": { "platformFaultDomainCount": 3, "platformUpdateDomainCount": 2, "virtualMachines": [] }, "sku": "Aligned", "type": "Microsoft.Compute/availabilitySets" }] ''' from ansible.module_utils.azure_rm_common import AzureRMModuleBase try: from msrestazure.azure_exceptions import CloudError except Exception: # handled in azure_rm_common pass AZURE_OBJECT_CLASS = 'AvailabilitySet' class AzureRMAvailabilitySetFacts(AzureRMModuleBase): """Utility class to get availability set facts""" def __init__(self): self.module_args = dict( name=dict(type='str'), resource_group=dict(type='str'), tags=dict(type='list') ) self.results = dict( changed=False, ansible_facts=dict( azure_availabilitysets=[] ) ) self.name = None self.resource_group = None self.tags = None super(AzureRMAvailabilitySetFacts, self).__init__( derived_arg_spec=self.module_args, supports_tags=False, facts_module=True ) def exec_module(self, **kwargs): for key in self.module_args: setattr(self, key, kwargs[key]) if self.name and not self.resource_group: self.fail("Parameter error: resource group required when filtering by name.") if self.name: self.results['ansible_facts']['azure_availabilitysets'] = self.get_item() else: self.results['ansible_facts']['azure_availabilitysets'] = self.list_items() return self.results def get_item(self): """Get a single availability set""" self.log('Get properties for {0}'.format(self.name)) item = None result = [] try: item = self.compute_client.availability_sets.get(self.resource_group, self.name) except CloudError: pass if item and self.has_tags(item.tags, self.tags): avase = self.serialize_obj(item, AZURE_OBJECT_CLASS) avase['name'] = item.name avase['type'] = item.type avase['sku'] = item.sku.name result = [avase] return result def list_items(self): """Get all availability sets""" self.log('List all availability sets') try: response = self.compute_client.availability_sets.list(self.resource_group) except CloudError as exc: self.fail('Failed to list all items - {0}'.format(str(exc))) results = [] for item in response: if self.has_tags(item.tags, self.tags): avase = self.serialize_obj(item, AZURE_OBJECT_CLASS) avase['name'] = item.name avase['type'] = item.type avase['sku'] = item.sku.name results.append(avase) return results def main(): """Main module execution code path""" AzureRMAvailabilitySetFacts() if __name__ == '__main__': main()
gpl-3.0
xq262144/hue
desktop/core/ext-py/Django-1.6.10/tests/model_inheritance_regress/models.py
49
4981
from __future__ import unicode_literals import datetime from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) class Meta: ordering = ('name',) def __str__(self): return "%s the place" % self.name @python_2_unicode_compatible class Restaurant(Place): serves_hot_dogs = models.BooleanField(default=False) serves_pizza = models.BooleanField(default=False) def __str__(self): return "%s the restaurant" % self.name @python_2_unicode_compatible class ItalianRestaurant(Restaurant): serves_gnocchi = models.BooleanField(default=False) def __str__(self): return "%s the italian restaurant" % self.name @python_2_unicode_compatible class ParkingLot(Place): # An explicit link to the parent (we can control the attribute name). parent = models.OneToOneField(Place, primary_key=True, parent_link=True) capacity = models.IntegerField() def __str__(self): return "%s the parking lot" % self.name class ParkingLot2(Place): # In lieu of any other connector, an existing OneToOneField will be # promoted to the primary key. parent = models.OneToOneField(Place) class ParkingLot3(Place): # The parent_link connector need not be the pk on the model. primary_key = models.AutoField(primary_key=True) parent = models.OneToOneField(Place, parent_link=True) class Supplier(models.Model): restaurant = models.ForeignKey(Restaurant) class Wholesaler(Supplier): retailer = models.ForeignKey(Supplier,related_name='wholesale_supplier') class Parent(models.Model): created = models.DateTimeField(default=datetime.datetime.now) class Child(Parent): name = models.CharField(max_length=10) class SelfRefParent(models.Model): parent_data = models.IntegerField() self_data = models.ForeignKey('self', null=True) class SelfRefChild(SelfRefParent): child_data = models.IntegerField() @python_2_unicode_compatible class Article(models.Model): headline = models.CharField(max_length=100) pub_date = models.DateTimeField() class Meta: ordering = ('-pub_date', 'headline') def __str__(self): return self.headline class ArticleWithAuthor(Article): author = models.CharField(max_length=100) class M2MBase(models.Model): articles = models.ManyToManyField(Article) class M2MChild(M2MBase): name = models.CharField(max_length=50) class Evaluation(Article): quality = models.IntegerField() class Meta: abstract = True class QualityControl(Evaluation): assignee = models.CharField(max_length=50) @python_2_unicode_compatible class BaseM(models.Model): base_name = models.CharField(max_length=100) def __str__(self): return self.base_name @python_2_unicode_compatible class DerivedM(BaseM): customPK = models.IntegerField(primary_key=True) derived_name = models.CharField(max_length=100) def __str__(self): return "PK = %d, base_name = %s, derived_name = %s" \ % (self.customPK, self.base_name, self.derived_name) class AuditBase(models.Model): planned_date = models.DateField() class Meta: abstract = True verbose_name_plural = 'Audits' class CertificationAudit(AuditBase): class Meta(AuditBase.Meta): abstract = True class InternalCertificationAudit(CertificationAudit): auditing_dept = models.CharField(max_length=20) # Check that abstract classes don't get m2m tables autocreated. @python_2_unicode_compatible class Person(models.Model): name = models.CharField(max_length=100) class Meta: ordering = ('name',) def __str__(self): return self.name @python_2_unicode_compatible class AbstractEvent(models.Model): name = models.CharField(max_length=100) attendees = models.ManyToManyField(Person, related_name="%(class)s_set") class Meta: abstract = True ordering = ('name',) def __str__(self): return self.name class BirthdayParty(AbstractEvent): pass class BachelorParty(AbstractEvent): pass class MessyBachelorParty(BachelorParty): pass # Check concrete -> abstract -> concrete inheritance class SearchableLocation(models.Model): keywords = models.CharField(max_length=256) class Station(SearchableLocation): name = models.CharField(max_length=128) class Meta: abstract = True class BusStation(Station): bus_routes = models.CommaSeparatedIntegerField(max_length=128) inbound = models.BooleanField(default=False) class TrainStation(Station): zone = models.IntegerField() class User(models.Model): username = models.CharField(max_length=30, unique=True) class Profile(User): profile_id = models.AutoField(primary_key=True) extra = models.CharField(max_length=30, blank=True)
apache-2.0
ckuethe/gnuradio
gr-blocks/python/blocks/qa_file_metadata.py
40
6783
#!/usr/bin/env python # # Copyright 2012,2013 Free Software Foundation, Inc. # # This file is part of GNU Radio # # GNU Radio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # GNU Radio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with GNU Radio; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, # Boston, MA 02110-1301, USA. # import os, math from gnuradio import gr, gr_unittest, blocks import pmt import parse_file_metadata def sig_source_c(samp_rate, freq, amp, N): t = map(lambda x: float(x)/samp_rate, xrange(N)) y = map(lambda x: amp*math.cos(2.*math.pi*freq*x) + \ 1j*amp*math.sin(2.*math.pi*freq*x), t) return y class test_file_metadata(gr_unittest.TestCase): def setUp(self): os.environ['GR_CONF_CONTROLPORT_ON'] = 'False' self.tb = gr.top_block() def tearDown(self): self.tb = None def test_001(self): N = 1000 outfile = "test_out.dat" detached = False samp_rate = 200000 key = pmt.intern("samp_rate") val = pmt.from_double(samp_rate) extras = pmt.make_dict() extras = pmt.dict_add(extras, key, val) extras_str = pmt.serialize_str(extras) data = sig_source_c(samp_rate, 1000, 1, N) src = blocks.vector_source_c(data) fsnk = blocks.file_meta_sink(gr.sizeof_gr_complex, outfile, samp_rate, 1, blocks.GR_FILE_FLOAT, True, 1000000, extras_str, detached) fsnk.set_unbuffered(True) self.tb.connect(src, fsnk) self.tb.run() fsnk.close() handle = open(outfile, "rb") header_str = handle.read(parse_file_metadata.HEADER_LENGTH) if(len(header_str) == 0): self.assertFalse() try: header = pmt.deserialize_str(header_str) except RuntimeError: self.assertFalse() info = parse_file_metadata.parse_header(header, False) extra_str = handle.read(info["extra_len"]) self.assertEqual(len(extra_str) > 0, True) handle.close() try: extra = pmt.deserialize_str(extra_str) except RuntimeError: self.assertFalse() extra_info = parse_file_metadata.parse_extra_dict(extra, info, False) self.assertEqual(info['rx_rate'], samp_rate) self.assertEqual(pmt.to_double(extra_info['samp_rate']), samp_rate) # Test file metadata source src.rewind() fsrc = blocks.file_meta_source(outfile, False) vsnk = blocks.vector_sink_c() tsnk = blocks.tag_debug(gr.sizeof_gr_complex, "QA") ssnk = blocks.vector_sink_c() self.tb.disconnect(src, fsnk) self.tb.connect(fsrc, vsnk) self.tb.connect(fsrc, tsnk) self.tb.connect(src, ssnk) self.tb.run() # Test to make sure tags with 'samp_rate' and 'rx_rate' keys # were generated and received correctly. tags = tsnk.current_tags() for t in tags: if(pmt.eq(t.key, pmt.intern("samp_rate"))): self.assertEqual(pmt.to_double(t.value), samp_rate) elif(pmt.eq(t.key, pmt.intern("rx_rate"))): self.assertEqual(pmt.to_double(t.value), samp_rate) # Test that the data portion was extracted and received correctly. self.assertComplexTuplesAlmostEqual(vsnk.data(), ssnk.data(), 5) os.remove(outfile) def test_002(self): N = 1000 outfile = "test_out.dat" outfile_hdr = "test_out.dat.hdr" detached = True samp_rate = 200000 key = pmt.intern("samp_rate") val = pmt.from_double(samp_rate) extras = pmt.make_dict() extras = pmt.dict_add(extras, key, val) extras_str = pmt.serialize_str(extras) data = sig_source_c(samp_rate, 1000, 1, N) src = blocks.vector_source_c(data) fsnk = blocks.file_meta_sink(gr.sizeof_gr_complex, outfile, samp_rate, 1, blocks.GR_FILE_FLOAT, True, 1000000, extras_str, detached) fsnk.set_unbuffered(True) self.tb.connect(src, fsnk) self.tb.run() fsnk.close() # Open detached header for reading handle = open(outfile_hdr, "rb") header_str = handle.read(parse_file_metadata.HEADER_LENGTH) if(len(header_str) == 0): self.assertFalse() try: header = pmt.deserialize_str(header_str) except RuntimeError: self.assertFalse() info = parse_file_metadata.parse_header(header, False) extra_str = handle.read(info["extra_len"]) self.assertEqual(len(extra_str) > 0, True) handle.close() try: extra = pmt.deserialize_str(extra_str) except RuntimeError: self.assertFalse() extra_info = parse_file_metadata.parse_extra_dict(extra, info, False) self.assertEqual(info['rx_rate'], samp_rate) self.assertEqual(pmt.to_double(extra_info['samp_rate']), samp_rate) # Test file metadata source src.rewind() fsrc = blocks.file_meta_source(outfile, False, detached, outfile_hdr) vsnk = blocks.vector_sink_c() tsnk = blocks.tag_debug(gr.sizeof_gr_complex, "QA") ssnk = blocks.vector_sink_c() self.tb.disconnect(src, fsnk) self.tb.connect(fsrc, vsnk) self.tb.connect(fsrc, tsnk) self.tb.connect(src, ssnk) self.tb.run() # Test to make sure tags with 'samp_rate' and 'rx_rate' keys # were generated and received correctly. tags = tsnk.current_tags() for t in tags: if(pmt.eq(t.key, pmt.intern("samp_rate"))): self.assertEqual(pmt.to_double(t.value), samp_rate) elif(pmt.eq(t.key, pmt.intern("rx_rate"))): self.assertEqual(pmt.to_double(t.value), samp_rate) # Test that the data portion was extracted and received correctly. self.assertComplexTuplesAlmostEqual(vsnk.data(), ssnk.data(), 5) os.remove(outfile) os.remove(outfile_hdr) if __name__ == '__main__': gr_unittest.run(test_file_metadata, "test_file_metadata.xml")
gpl-3.0
clips/pattern
pattern/vector/stemmer.py
1
12662
##### PATTERN | VECTOR | PORTER STEMMER ############################################################ # Copyright (c) 2010 University of Antwerp, Belgium # Author: Tom De Smedt <tom@organisms.be> # License: BSD (see LICENSE.txt for details). # http://www.clips.ua.ac.be/pages/pattern #################################################################################################### # The Porter2 stemming algorithm (or "Porter stemmer") is a process for removing the commoner # morphological and inflexional endings from words in English. # Its main use is as part of a term normalisation process that is usually done # when setting up Information Retrieval systems. # Reference: # C.J. van Rijsbergen, S.E. Robertson and M.F. Porter, 1980. # "New models in probabilistic information retrieval." # London: British Library. (British Library Research and Development Report, no. 5587). # # http://tartarus.org/~martin/PorterStemmer/ # Comments throughout the source code were taken from: # http://snowball.tartarus.org/algorithms/english/stemmer.html from __future__ import unicode_literals from __future__ import division import re from builtins import str, bytes, dict, int from builtins import object, range #--------------------------------------------------------------------------------------------------- # Note: this module is optimized for performance. # There is little gain in using more regular expressions. VOWELS = ["a", "e", "i", "o", "u", "y"] DOUBLE = ["bb", "dd", "ff", "gg", "mm", "nn", "pp", "rr", "tt"] VALID_LI = ["b", "c", "d", "e", "g", "h", "k", "m", "n", "r", "t"] def is_vowel(s): return s in VOWELS def is_consonant(s): return s not in VOWELS def is_double_consonant(s): return s in DOUBLE def is_short_syllable(w, before=None): """ A short syllable in a word is either: - a vowel followed by a non-vowel other than w, x or Y and preceded by a non-vowel - a vowel at the beginning of the word followed by a non-vowel. Checks the three characters before the given index in the word (or entire word if None). """ if before is not None: i = before < 0 and len(w) + before or before return is_short_syllable(w[max(0, i - 3):i]) if len(w) == 3 and is_consonant(w[0]) and is_vowel(w[1]) and is_consonant(w[2]) and w[2] not in "wxY": return True if len(w) == 2 and is_vowel(w[0]) and is_consonant(w[1]): return True return False def is_short(w): """ A word is called short if it consists of a short syllable preceded by zero or more consonants. """ return is_short_syllable(w[-3:]) and len([ch for ch in w[:-3] if ch in VOWELS]) == 0 # A point made at least twice in the literature is that words beginning with gener- # are overstemmed by the Porter stemmer: # generate => gener, generically => gener # Moving the region one vowel-consonant pair to the right fixes this: # generate => generat, generically => generic overstemmed = ("gener", "commun", "arsen") RE_R1 = re.compile(r"[aeiouy][^aeiouy]") def R1(w): """ R1 is the region after the first non-vowel following a vowel, or the end of the word if there is no such non-vowel. """ m = RE_R1.search(w) if m: return w[m.end():] return "" def R2(w): """ R2 is the region after the first non-vowel following a vowel in R1, or the end of the word if there is no such non-vowel. """ if w.startswith(tuple(overstemmed)): return R1(R1(R1(w))) return R1(R1(w)) def find_vowel(w): """ Returns the index of the first vowel in the word. When no vowel is found, returns len(word). """ for i, ch in enumerate(w): if ch in VOWELS: return i return len(w) def has_vowel(w): """ Returns True if there is a vowel in the given string. """ for ch in w: if ch in VOWELS: return True return False def vowel_consonant_pairs(w, max=None): """ Returns the number of consecutive vowel-consonant pairs in the word. """ m = 0 for i, ch in enumerate(w): if is_vowel(ch) and i < len(w) - 1 and is_consonant(w[i + 1]): m += 1 # An optimisation to stop searching once we reach the amount of <vc> pairs we need. if m == max: break return m #--- REPLACEMENT RULES ----------------------------------------------------------------------------- def step_1a(w): """ Step 1a handles -s suffixes. """ if w.endswith("s"): if w.endswith("sses"): return w[:-2] if w.endswith("ies"): # Replace by -ie if preceded by just one letter, # otherwise by -i (so ties => tie, cries => cri). return len(w) == 4 and w[:-1] or w[:-2] if w.endswith(("us", "ss")): return w if find_vowel(w) < len(w) - 2: # Delete -s if the preceding part contains a vowel not immediately before the -s # (so gas and this retain the -s, gaps and kiwis lose it). return w[:-1] return w def step_1b(w): """ Step 1b handles -ed and -ing suffixes (or -edly and -ingly). Removes double consonants at the end of the stem and adds -e to some words. """ if w.endswith("y") and w.endswith(("edly", "ingly")): w = w[:-2] # Strip -ly for next step. if w.endswith(("ed", "ing")): if w.endswith("ied"): # See -ies in step 1a. return len(w) == 4 and w[:-1] or w[:-2] if w.endswith("eed"): # Replace by -ee if preceded by at least one vowel-consonant pair. return R1(w).endswith("eed") and w[:-1] or w for suffix in ("ed", "ing"): # Delete if the preceding word part contains a vowel. # - If the word ends -at, -bl or -iz add -e (luxuriat => luxuriate). # - If the word ends with a double remove the last letter (hopp => hop). # - If the word is short, add e (hop => hope). if w.endswith(suffix) and has_vowel(w[:-len(suffix)]): w = w[:-len(suffix)] if w.endswith(("at", "bl", "iz")): return w + "e" if is_double_consonant(w[-2:]): return w[:-1] if is_short(w): return w + "e" return w def step_1c(w): """ Step 1c replaces suffix -y or -Y by -i if preceded by a non-vowel which is not the first letter of the word (cry => cri, by => by, say => say). """ if len(w) > 2 and w.endswith(("y", "Y")) and is_consonant(w[-2]): return w[:-1] + "i" return w suffixes2 = [ ("al", (("ational", "ate"), ("tional", "tion"))), ("ci", (("enci", "ence"), ("anci", "ance"))), ("er", (("izer", "ize"),)), ("li", (("bli", "ble"), ("alli", "al"), ("entli", "ent"), ("eli", "e"), ("ousli", "ous"))), ("on", (("ization", "ize"), ("isation", "ize"), ("ation", "ate"))), ("or", (("ator", "ate"),)), ("ss", (("iveness", "ive"), ("fulness", "ful"), ("ousness", "ous"))), ("sm", (("alism", "al"),)), ("ti", (("aliti", "al"), ("iviti", "ive"), ("biliti", "ble"))), ("gi", (("logi", "log"),)) ] def step_2(w): """ Step 2 replaces double suffixes (singularization => singularize). This only happens if there is at least one vowel-consonant pair before the suffix. """ for suffix, rules in suffixes2: if w.endswith(suffix): for A, B in rules: if w.endswith(A): return R1(w).endswith(A) and w[:-len(A)] + B or w if w.endswith("li") and R1(w)[-3:-2] in VALID_LI: # Delete -li if preceded by a valid li-ending. return w[:-2] return w suffixes3 = [ ("e", (("icate", "ic"), ("ative", ""), ("alize", "al"))), ("i", (("iciti", "ic"),)), ("l", (("ical", "ic"), ("ful", ""))), ("s", (("ness", ""),)) ] def step_3(w): """ Step 3 replaces -ic, -ful, -ness etc. suffixes. This only happens if there is at least one vowel-consonant pair before the suffix. """ for suffix, rules in suffixes3: if w.endswith(suffix): for A, B in rules: if w.endswith(A): return R1(w).endswith(A) and w[:-len(A)] + B or w return w suffixes4 = [ ("al", ("al",)), ("ce", ("ance", "ence")), ("er", ("er",)), ("ic", ("ic",)), ("le", ("able", "ible")), ("nt", ("ant", "ement", "ment", "ent")), ("e", ("ate", "ive", "ize")), (("m", "i", "s"), ("ism", "iti", "ous")) ] def step_4(w): """ Step 4 strips -ant, -ent etc. suffixes. This only happens if there is more than one vowel-consonant pair before the suffix. """ for suffix, rules in suffixes4: if w.endswith(suffix): for A in rules: if w.endswith(A): return R2(w).endswith(A) and w[:-len(A)] or w if R2(w).endswith("ion") and w[:-3].endswith(("s", "t")): # Delete -ion if preceded by s or t. return w[:-3] return w def step_5a(w): """ Step 5a strips suffix -e if preceded by multiple vowel-consonant pairs, or one vowel-consonant pair that is not a short syllable. """ if w.endswith("e"): if R2(w).endswith("e") or R1(w).endswith("e") and not is_short_syllable(w, before=-1): return w[:-1] return w def step_5b(w): """ Step 5b strips suffix -l if preceded by l and multiple vowel-consonant pairs, bell => bell, rebell => rebel. """ if w.endswith("ll") and R2(w).endswith("l"): return w[:-1] return w #--- EXCEPTIONS ------------------------------------------------------------------------------------ # Exceptions: # - in, out and can stems could be seen as stop words later on. # - Special -ly cases. exceptions = { "skis": "ski", "skies": "sky", "dying": "die", "lying": "lie", "tying": "tie", "innings": "inning", "outings": "outing", "cannings": "canning", "idly": "idl", "gently": "gentl", "ugly": "ugli", "early": "earli", "only": "onli", "singly": "singl" } # Words that are never stemmed: uninflected = dict.fromkeys([ "sky", "news", "howe", "inning", "outing", "canning", "proceed", "exceed", "succeed", "atlas", "cosmos", "bias", "andes" # not plural forms ], True) #--- STEMMER --------------------------------------------------------------------------------------- def case_sensitive(stem, word): """ Applies the letter case of the word to the stem: Ponies => Poni """ ch = [] for i in range(len(stem)): if word[i] == word[i].upper(): ch.append(stem[i].upper()) else: ch.append(stem[i]) return "".join(ch) def upper_consonant_y(w): """ Sets the initial y, or y after a vowel, to Y. Of course, y is interpreted as a vowel and Y as a consonant. """ a = [] p = None for ch in w: if ch == "y" and (p is None or p in VOWELS): a.append("Y") else: a.append(ch) p = ch return "".join(a) # If we stemmed a word once, we can cache the result and reuse it. # By default, keep a history of a 10000 entries (<500KB). cache = {} def stem(word, cached=True, history=10000, **kwargs): """ Returns the stem of the given word: ponies => poni. Note: it is often taken to be a crude error that a stemming algorithm does not leave a real word after removing the stem. But the purpose of stemming is to bring variant forms of a word together, not to map a word onto its "paradigm" form. """ stem = word.lower() if cached and stem in cache: return case_sensitive(cache[stem], word) if cached and len(cache) > history: # Empty cache every now and then. cache.clear() if len(stem) <= 2: # If the word has two letters or less, leave it as it is. return case_sensitive(stem, word) if stem in exceptions: return case_sensitive(exceptions[stem], word) if stem in uninflected: return case_sensitive(stem, word) # Mark y treated as a consonant as Y. stem = upper_consonant_y(stem) for f in (step_1a, step_1b, step_1c, step_2, step_3, step_4, step_5a, step_5b): stem = f(stem) # Turn any remaining Y letters in the stem back into lower case. # Apply the case of the original word to the stem. stem = stem.lower() stem = case_sensitive(stem, word) if cached: cache[word.lower()] = stem.lower() return stem
bsd-3-clause
Khilo84/PyQt4
examples/dbus/pingpong/ping.py
8
3136
#!/usr/bin/env python ############################################################################# ## ## Copyright (C) 2011 Riverbank Computing Limited. ## Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ## All rights reserved. ## ## This file is part of the examples of PyQt. ## ## $QT_BEGIN_LICENSE:BSD$ ## You may use this file under the terms of the BSD license as follows: ## ## "Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above copyright ## notice, this list of conditions and the following disclaimer in ## the documentation and/or other materials provided with the ## distribution. ## * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor ## the names of its contributors may be used to endorse or promote ## products derived from this software without specific prior written ## permission. ## ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ## $QT_END_LICENSE$ ## ############################################################################# # This is only needed for Python v2 but is harmless for Python v3. import sip sip.setapi('QString', 2) sip.setapi('QVariant', 2) import sys from PyQt4 import QtCore, QtDBus if __name__ == '__main__': app = QtCore.QCoreApplication(sys.argv) if not QtDBus.QDBusConnection.sessionBus().isConnected(): sys.stderr.write("Cannot connect to the D-Bus session bus.\n" "To start it, run:\n" "\teval `dbus-launch --auto-syntax`\n"); sys.exit(1) iface = QtDBus.QDBusInterface('com.trolltech.QtDBus.PingExample', '/', '', QtDBus.QDBusConnection.sessionBus()) if iface.isValid(): msg = iface.call('ping', sys.argv[1] if len(sys.argv) > 1 else "") reply = QtDBus.QDBusReply(msg) if reply.isValid(): sys.stdout.write("Reply was: %s\n" % reply.value()) sys.exit() sys.stderr.write("Call failed: %s\n" % reply.error().message()) sys.exit(1) sys.stderr.write("%s\n" % QtDBus.QDBusConnection.sessionBus().lastError().message()) sys.exit(1)
gpl-2.0
mpetyx/palmdrop
venv/lib/python2.7/site-packages/south/management/commands/convert_to_south.py
129
3725
""" Quick conversion command module. """ from __future__ import print_function from optparse import make_option import sys from django.core.management.base import BaseCommand from django.core.management.color import no_style from django.conf import settings from django.db import models from django.core import management from django.core.exceptions import ImproperlyConfigured from south.migration import Migrations from south.hacks import hacks from south.exceptions import NoMigrations class Command(BaseCommand): option_list = BaseCommand.option_list if '--verbosity' not in [opt.get_opt_string() for opt in BaseCommand.option_list]: option_list += ( make_option('--verbosity', action='store', dest='verbosity', default='1', type='choice', choices=['0', '1', '2'], help='Verbosity level; 0=minimal output, 1=normal output, 2=all output'), ) option_list += ( make_option('--delete-ghost-migrations', action='store_true', dest='delete_ghosts', default=False, help="Tells South to delete any 'ghost' migrations (ones in the database but not on disk)."), make_option('--ignore-ghost-migrations', action='store_true', dest='ignore_ghosts', default=False, help="Tells South to ignore any 'ghost' migrations (ones in the database but not on disk) and continue to apply new migrations."), ) help = "Quickly converts the named application to use South if it is currently using syncdb." def handle(self, app=None, *args, **options): # Make sure we have an app if not app: print("Please specify an app to convert.") return # See if the app exists app = app.split(".")[-1] try: app_module = models.get_app(app) except ImproperlyConfigured: print("There is no enabled application matching '%s'." % app) return # Try to get its list of models model_list = models.get_models(app_module) if not model_list: print("This application has no models; this command is for applications that already have models syncdb'd.") print("Make some models, and then use ./manage.py schemamigration %s --initial instead." % app) return # Ask South if it thinks it's already got migrations try: Migrations(app) except NoMigrations: pass else: print("This application is already managed by South.") return # Finally! It seems we've got a candidate, so do the two-command trick verbosity = int(options.get('verbosity', 0)) management.call_command("schemamigration", app, initial=True, verbosity=verbosity) # Now, we need to re-clean and sanitise appcache hacks.clear_app_cache() hacks.repopulate_app_cache() # And also clear our cached Migration classes Migrations._clear_cache() # Now, migrate management.call_command( "migrate", app, "0001", fake=True, verbosity=verbosity, ignore_ghosts=options.get("ignore_ghosts", False), delete_ghosts=options.get("delete_ghosts", False), ) print() print("App '%s' converted. Note that South assumed the application's models matched the database" % app) print("(i.e. you haven't changed it since last syncdb); if you have, you should delete the %s/migrations" % app) print("directory, revert models.py so it matches the database, and try again.")
apache-2.0
shyamalschandra/catkin
test/unit_tests/test_builder.py
9
3354
# -*- coding: utf-8 -*- import os import unittest try: import catkin.builder except ImportError as e: raise ImportError( 'Please adjust your pythonpath before running this test: %s' % str(e) ) class BuilderTest(unittest.TestCase): # TODO: Add tests for catkin_make and catkin_make_isolated def test_run_command_unicode_string(self): backup_Popen = catkin.builder.subprocess.Popen class StdOut(object): def __init__(self, popen): self.__popen = popen def readline(self): self.__popen.returncode = 0 try: # for Python 2 compatibility only return unichr(2018) except NameError: return chr(2018) class MockPopen(object): def __init__(self, *args, **kwargs): self.returncode = None self.stdout = StdOut(self) def wait(self): return True try: catkin.builder.subprocess.Popen = MockPopen catkin.builder.run_command(['false'], os.getcwd(), True, True) finally: catkin.builder.subprocess.Popen = backup_Popen def test_run_command_unicode_bytes(self): backup_Popen = catkin.builder.subprocess.Popen class StdOut(object): def __init__(self, popen): self.__popen = popen def readline(self): self.__popen.returncode = 0 try: # for Python 2 compatibility only s = unichr(2018) except NameError: s = chr(2018) return s.encode('utf8') class MockPopen(object): def __init__(self, *args, **kwargs): self.returncode = None self.stdout = StdOut(self) def wait(self): return True try: catkin.builder.subprocess.Popen = MockPopen catkin.builder.run_command(['false'], os.getcwd(), True, True) finally: catkin.builder.subprocess.Popen = backup_Popen def test_extract_jobs_flags(self): valid_mflags = [ '-j8 -l8', 'j8 ', '-j', 'j', '-l8', 'l8', '-l', 'l', '-j18', ' -j8 l9', '-j1 -l1', '--jobs=8', '--jobs 8', '--jobs', '--load-average', '--load-average=8', '--load-average 8', '--jobs=8 -l9' ] results = [ '-j8 -l8', 'j8', '-j', 'j', '-l8', 'l8', '-l', 'l', '-j18', '-j8 l9', '-j1 -l1', '--jobs=8', '--jobs 8', '--jobs', '--load-average', '--load-average=8', '--load-average 8', '--jobs=8 -l9' ] for mflag, result in zip(valid_mflags, results): match = catkin.builder.extract_jobs_flags(mflag) assert match == result, "should match '{0}'".format(mflag) print('--') print("input: '{0}'".format(mflag)) print("matched: '{0}'".format(match)) print("expected: '{0}'".format(result)) invalid_mflags = ['', '--jobs= 8', '--jobs8'] for mflag in invalid_mflags: match = catkin.builder.extract_jobs_flags(mflag) assert match is None, "should not match '{0}'".format(mflag)
bsd-3-clause
lseyesl/phantomjs
src/breakpad/src/tools/gyp/pylib/gyp/input.py
137
84791
#!/usr/bin/python # Copyright (c) 2009 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from compiler.ast import Const from compiler.ast import Dict from compiler.ast import Discard from compiler.ast import List from compiler.ast import Module from compiler.ast import Node from compiler.ast import Stmt import compiler import copy import gyp.common import optparse import os.path import re import shlex import subprocess import sys # A list of types that are treated as linkable. linkable_types = ['executable', 'shared_library', 'loadable_module'] # A list of sections that contain links to other targets. dependency_sections = ['dependencies', 'export_dependent_settings'] # base_path_sections is a list of sections defined by GYP that contain # pathnames. The generators can provide more keys, the two lists are merged # into path_sections, but you should call IsPathSection instead of using either # list directly. base_path_sections = [ 'destination', 'files', 'include_dirs', 'inputs', 'libraries', 'outputs', 'sources', ] path_sections = [] def IsPathSection(section): if section in path_sections or \ section.endswith('_dir') or section.endswith('_dirs') or \ section.endswith('_file') or section.endswith('_files') or \ section.endswith('_path') or section.endswith('_paths'): return True return False # base_non_configuraiton_keys is a list of key names that belong in the target # itself and should not be propagated into its configurations. It is merged # with a list that can come from the generator to # create non_configuration_keys. base_non_configuration_keys = [ # Sections that must exist inside targets and not configurations. 'actions', 'configurations', 'copies', 'default_configuration', 'dependencies', 'dependencies_original', 'link_languages', 'libraries', 'postbuilds', 'product_dir', 'product_extension', 'product_name', 'rules', 'run_as', 'sources', 'suppress_wildcard', 'target_name', 'test', 'toolset', 'toolsets', 'type', 'variants', # Sections that can be found inside targets or configurations, but that # should not be propagated from targets into their configurations. 'variables', ] non_configuration_keys = [] # Controls how the generator want the build file paths. absolute_build_file_paths = False # Controls whether or not the generator supports multiple toolsets. multiple_toolsets = False def GetIncludedBuildFiles(build_file_path, aux_data, included=None): """Return a list of all build files included into build_file_path. The returned list will contain build_file_path as well as all other files that it included, either directly or indirectly. Note that the list may contain files that were included into a conditional section that evaluated to false and was not merged into build_file_path's dict. aux_data is a dict containing a key for each build file or included build file. Those keys provide access to dicts whose "included" keys contain lists of all other files included by the build file. included should be left at its default None value by external callers. It is used for recursion. The returned list will not contain any duplicate entries. Each build file in the list will be relative to the current directory. """ if included == None: included = [] if build_file_path in included: return included included.append(build_file_path) for included_build_file in aux_data[build_file_path].get('included', []): GetIncludedBuildFiles(included_build_file, aux_data, included) return included def CheckedEval(file_contents): """Return the eval of a gyp file. The gyp file is restricted to dictionaries and lists only, and repeated keys are not allowed. Note that this is slower than eval() is. """ ast = compiler.parse(file_contents) assert isinstance(ast, Module) c1 = ast.getChildren() assert c1[0] is None assert isinstance(c1[1], Stmt) c2 = c1[1].getChildren() assert isinstance(c2[0], Discard) c3 = c2[0].getChildren() assert len(c3) == 1 return CheckNode(c3[0],0) def CheckNode(node, level): if isinstance(node, Dict): c = node.getChildren() dict = {} for n in range(0, len(c), 2): assert isinstance(c[n], Const) key = c[n].getChildren()[0] if key in dict: raise KeyError, "Key '" + key + "' repeated at level " + \ repr(level) dict[key] = CheckNode(c[n + 1], level + 1) return dict elif isinstance(node, List): c = node.getChildren() list = [] for child in c: list.append(CheckNode(child, level + 1)) return list elif isinstance(node, Const): return node.getChildren()[0] else: raise TypeError, "Unknown AST node " + repr(node) def LoadOneBuildFile(build_file_path, data, aux_data, variables, includes, is_target, check): if build_file_path in data: return data[build_file_path] if os.path.exists(build_file_path): build_file_contents = open(build_file_path).read() else: raise Exception("%s not found (cwd: %s)" % (build_file_path, os.getcwd())) build_file_data = None try: if check: build_file_data = CheckedEval(build_file_contents) else: build_file_data = eval(build_file_contents, {'__builtins__': None}, None) except SyntaxError, e: e.filename = build_file_path raise except Exception, e: gyp.common.ExceptionAppend(e, 'while reading ' + build_file_path) raise data[build_file_path] = build_file_data aux_data[build_file_path] = {} # Scan for includes and merge them in. try: if is_target: LoadBuildFileIncludesIntoDict(build_file_data, build_file_path, data, aux_data, variables, includes, check) else: LoadBuildFileIncludesIntoDict(build_file_data, build_file_path, data, aux_data, variables, None, check) except Exception, e: gyp.common.ExceptionAppend(e, 'while reading includes of ' + build_file_path) raise return build_file_data def LoadBuildFileIncludesIntoDict(subdict, subdict_path, data, aux_data, variables, includes, check): includes_list = [] if includes != None: includes_list.extend(includes) if 'includes' in subdict: for include in subdict['includes']: # "include" is specified relative to subdict_path, so compute the real # path to include by appending the provided "include" to the directory # in which subdict_path resides. relative_include = \ os.path.normpath(os.path.join(os.path.dirname(subdict_path), include)) includes_list.append(relative_include) # Unhook the includes list, it's no longer needed. del subdict['includes'] # Merge in the included files. for include in includes_list: if not 'included' in aux_data[subdict_path]: aux_data[subdict_path]['included'] = [] aux_data[subdict_path]['included'].append(include) gyp.DebugOutput(gyp.DEBUG_INCLUDES, "Loading Included File: '%s'" % include) MergeDicts(subdict, LoadOneBuildFile(include, data, aux_data, variables, None, False, check), subdict_path, include) # Recurse into subdictionaries. for k, v in subdict.iteritems(): if v.__class__ == dict: LoadBuildFileIncludesIntoDict(v, subdict_path, data, aux_data, variables, None, check) elif v.__class__ == list: LoadBuildFileIncludesIntoList(v, subdict_path, data, aux_data, variables, check) # This recurses into lists so that it can look for dicts. def LoadBuildFileIncludesIntoList(sublist, sublist_path, data, aux_data, variables, check): for item in sublist: if item.__class__ == dict: LoadBuildFileIncludesIntoDict(item, sublist_path, data, aux_data, variables, None, check) elif item.__class__ == list: LoadBuildFileIncludesIntoList(item, sublist_path, data, aux_data, variables, check) # Processes toolsets in all the targets. This recurses into condition entries # since they can contain toolsets as well. def ProcessToolsetsInDict(data): if 'targets' in data: target_list = data['targets'] new_target_list = [] for target in target_list: global multiple_toolsets if multiple_toolsets: toolsets = target.get('toolsets', ['target']) else: toolsets = ['target'] if len(toolsets) > 0: # Optimization: only do copies if more than one toolset is specified. for build in toolsets[1:]: new_target = copy.deepcopy(target) new_target['toolset'] = build new_target_list.append(new_target) target['toolset'] = toolsets[0] new_target_list.append(target) data['targets'] = new_target_list if 'conditions' in data: for condition in data['conditions']: if isinstance(condition, list): for condition_dict in condition[1:]: ProcessToolsetsInDict(condition_dict) # TODO(mark): I don't love this name. It just means that it's going to load # a build file that contains targets and is expected to provide a targets dict # that contains the targets... def LoadTargetBuildFile(build_file_path, data, aux_data, variables, includes, depth, check): global absolute_build_file_paths # If depth is set, predefine the DEPTH variable to be a relative path from # this build file's directory to the directory identified by depth. if depth: d = gyp.common.RelativePath(depth, os.path.dirname(build_file_path)) if d == '': variables['DEPTH'] = '.' else: variables['DEPTH'] = d # If the generator needs absolue paths, then do so. if absolute_build_file_paths: build_file_path = os.path.abspath(build_file_path) if build_file_path in data['target_build_files']: # Already loaded. return data['target_build_files'].add(build_file_path) gyp.DebugOutput(gyp.DEBUG_INCLUDES, "Loading Target Build File '%s'" % build_file_path) build_file_data = LoadOneBuildFile(build_file_path, data, aux_data, variables, includes, True, check) # Store DEPTH for later use in generators. build_file_data['_DEPTH'] = depth # Set up the included_files key indicating which .gyp files contributed to # this target dict. if 'included_files' in build_file_data: raise KeyError, build_file_path + ' must not contain included_files key' included = GetIncludedBuildFiles(build_file_path, aux_data) build_file_data['included_files'] = [] for included_file in included: # included_file is relative to the current directory, but it needs to # be made relative to build_file_path's directory. included_relative = \ gyp.common.RelativePath(included_file, os.path.dirname(build_file_path)) build_file_data['included_files'].append(included_relative) ProcessToolsetsInDict(build_file_data) # Apply "pre"/"early" variable expansions and condition evaluations. ProcessVariablesAndConditionsInDict(build_file_data, False, variables, build_file_path) # Look at each project's target_defaults dict, and merge settings into # targets. if 'target_defaults' in build_file_data: index = 0 if 'targets' in build_file_data: while index < len(build_file_data['targets']): # This procedure needs to give the impression that target_defaults is # used as defaults, and the individual targets inherit from that. # The individual targets need to be merged into the defaults. Make # a deep copy of the defaults for each target, merge the target dict # as found in the input file into that copy, and then hook up the # copy with the target-specific data merged into it as the replacement # target dict. old_target_dict = build_file_data['targets'][index] new_target_dict = copy.deepcopy(build_file_data['target_defaults']) MergeDicts(new_target_dict, old_target_dict, build_file_path, build_file_path) build_file_data['targets'][index] = new_target_dict index = index + 1 else: raise Exception, \ "Unable to find targets in build file %s" % build_file_path # No longer needed. del build_file_data['target_defaults'] # Look for dependencies. This means that dependency resolution occurs # after "pre" conditionals and variable expansion, but before "post" - # in other words, you can't put a "dependencies" section inside a "post" # conditional within a target. if 'targets' in build_file_data: for target_dict in build_file_data['targets']: if 'dependencies' not in target_dict: continue for dependency in target_dict['dependencies']: other_build_file = \ gyp.common.ResolveTarget(build_file_path, dependency, None)[0] try: LoadTargetBuildFile(other_build_file, data, aux_data, variables, includes, depth, check) except Exception, e: gyp.common.ExceptionAppend( e, 'while loading dependencies of %s' % build_file_path) raise return data # Look for the bracket that matches the first bracket seen in a # string, and return the start and end as a tuple. For example, if # the input is something like "<(foo <(bar)) blah", then it would # return (1, 13), indicating the entire string except for the leading # "<" and trailing " blah". def FindEnclosingBracketGroup(input): brackets = { '}': '{', ']': '[', ')': '(', } stack = [] count = 0 start = -1 for char in input: if char in brackets.values(): stack.append(char) if start == -1: start = count if char in brackets.keys(): try: last_bracket = stack.pop() except IndexError: return (-1, -1) if last_bracket != brackets[char]: return (-1, -1) if len(stack) == 0: return (start, count + 1) count = count + 1 return (-1, -1) canonical_int_re = re.compile('^(0|-?[1-9][0-9]*)$') def IsStrCanonicalInt(string): """Returns True if |string| is in its canonical integer form. The canonical form is such that str(int(string)) == string. """ if not isinstance(string, str) or not canonical_int_re.match(string): return False return True early_variable_re = re.compile('(?P<replace>(?P<type><!?@?)' '\((?P<is_array>\s*\[?)' '(?P<content>.*?)(\]?)\))') late_variable_re = re.compile('(?P<replace>(?P<type>>!?@?)' '\((?P<is_array>\s*\[?)' '(?P<content>.*?)(\]?)\))') # Global cache of results from running commands so they don't have to be run # more then once. cached_command_results = {} def ExpandVariables(input, is_late, variables, build_file): # Look for the pattern that gets expanded into variables if not is_late: variable_re = early_variable_re else: variable_re = late_variable_re input_str = str(input) # Get the entire list of matches as a list of MatchObject instances. # (using findall here would return strings, and we want # MatchObjects). matches = [match for match in variable_re.finditer(input_str)] output = input_str if matches: # Reverse the list of matches so that replacements are done right-to-left. # That ensures that earlier replacements won't mess up the string in a # way that causes later calls to find the earlier substituted text instead # of what's intended for replacement. matches.reverse() for match_group in matches: match = match_group.groupdict() gyp.DebugOutput(gyp.DEBUG_VARIABLES, "Matches: %s" % repr(match)) # match['replace'] is the substring to look for, match['type'] # is the character code for the replacement type (< > <! >! <@ # >@ <!@ >!@), match['is_array'] contains a '[' for command # arrays, and match['content'] is the name of the variable (< >) # or command to run (<! >!). # run_command is true if a ! variant is used. run_command = '!' in match['type'] # Capture these now so we can adjust them later. replace_start = match_group.start('replace') replace_end = match_group.end('replace') # Find the ending paren, and re-evaluate the contained string. (c_start, c_end) = FindEnclosingBracketGroup(input_str[replace_start:]) # Adjust the replacement range to match the entire command # found by FindEnclosingBracketGroup (since the variable_re # probably doesn't match the entire command if it contained # nested variables). replace_end = replace_start + c_end # Find the "real" replacement, matching the appropriate closing # paren, and adjust the replacement start and end. replacement = input_str[replace_start:replace_end] # Figure out what the contents of the variable parens are. contents_start = replace_start + c_start + 1 contents_end = replace_end - 1 contents = input_str[contents_start:contents_end] # Recurse to expand variables in the contents contents = ExpandVariables(contents, is_late, variables, build_file) # Strip off leading/trailing whitespace so that variable matches are # simpler below (and because they are rarely needed). contents = contents.strip() # expand_to_list is true if an @ variant is used. In that case, # the expansion should result in a list. Note that the caller # is to be expecting a list in return, and not all callers do # because not all are working in list context. Also, for list # expansions, there can be no other text besides the variable # expansion in the input string. expand_to_list = '@' in match['type'] and input_str == replacement if run_command: # Run the command in the build file's directory. build_file_dir = os.path.dirname(build_file) if build_file_dir == '': # If build_file is just a leaf filename indicating a file in the # current directory, build_file_dir might be an empty string. Set # it to None to signal to subprocess.Popen that it should run the # command in the current directory. build_file_dir = None use_shell = True if match['is_array']: contents = eval(contents) use_shell = False # Check for a cached value to avoid executing commands more than once. # TODO(http://code.google.com/p/gyp/issues/detail?id=112): It is # possible that the command being invoked depends on the current # directory. For that case the syntax needs to be extended so that the # directory is also used in cache_key (it becomes a tuple). # TODO(http://code.google.com/p/gyp/issues/detail?id=111): In theory, # someone could author a set of GYP files where each time the command # is invoked it produces different output by design. When the need # arises, the syntax should be extended to support no caching off a # command's output so it is run every time. cache_key = str(contents) cached_value = cached_command_results.get(cache_key, None) if cached_value is None: gyp.DebugOutput(gyp.DEBUG_VARIABLES, "Executing command '%s' in directory '%s'" % (contents,build_file_dir)) p = subprocess.Popen(contents, shell=use_shell, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, cwd=build_file_dir) (p_stdout, p_stderr) = p.communicate('') if p.wait() != 0 or p_stderr: sys.stderr.write(p_stderr) # Simulate check_call behavior, since check_call only exists # in python 2.5 and later. raise Exception("Call to '%s' returned exit status %d." % (contents, p.returncode)) replacement = p_stdout.rstrip() cached_command_results[cache_key] = replacement else: gyp.DebugOutput(gyp.DEBUG_VARIABLES, "Had cache value for command '%s' in directory '%s'" % (contents,build_file_dir)) replacement = cached_value else: if not contents in variables: raise KeyError, 'Undefined variable ' + contents + \ ' in ' + build_file replacement = variables[contents] if isinstance(replacement, list): for item in replacement: if not isinstance(item, str) and not isinstance(item, int): raise TypeError, 'Variable ' + contents + \ ' must expand to a string or list of strings; ' + \ 'list contains a ' + \ item.__class__.__name__ # Run through the list and handle variable expansions in it. Since # the list is guaranteed not to contain dicts, this won't do anything # with conditions sections. ProcessVariablesAndConditionsInList(replacement, is_late, variables, build_file) elif not isinstance(replacement, str) and \ not isinstance(replacement, int): raise TypeError, 'Variable ' + contents + \ ' must expand to a string or list of strings; ' + \ 'found a ' + replacement.__class__.__name__ if expand_to_list: # Expanding in list context. It's guaranteed that there's only one # replacement to do in |input_str| and that it's this replacement. See # above. if isinstance(replacement, list): # If it's already a list, make a copy. output = replacement[:] else: # Split it the same way sh would split arguments. output = shlex.split(str(replacement)) else: # Expanding in string context. encoded_replacement = '' if isinstance(replacement, list): # When expanding a list into string context, turn the list items # into a string in a way that will work with a subprocess call. # # TODO(mark): This isn't completely correct. This should # call a generator-provided function that observes the # proper list-to-argument quoting rules on a specific # platform instead of just calling the POSIX encoding # routine. encoded_replacement = gyp.common.EncodePOSIXShellList(replacement) else: encoded_replacement = replacement output = output[:replace_start] + str(encoded_replacement) + \ output[replace_end:] # Prepare for the next match iteration. input_str = output # Look for more matches now that we've replaced some, to deal with # expanding local variables (variables defined in the same # variables block as this one). gyp.DebugOutput(gyp.DEBUG_VARIABLES, "Found output %s, recursing." % repr(output)) if isinstance(output, list): new_output = [] for item in output: new_output.append(ExpandVariables(item, is_late, variables, build_file)) output = new_output else: output = ExpandVariables(output, is_late, variables, build_file) # Convert all strings that are canonically-represented integers into integers. if isinstance(output, list): for index in xrange(0, len(output)): if IsStrCanonicalInt(output[index]): output[index] = int(output[index]) elif IsStrCanonicalInt(output): output = int(output) gyp.DebugOutput(gyp.DEBUG_VARIABLES, "Expanding %s to %s" % (repr(input), repr(output))) return output def ProcessConditionsInDict(the_dict, is_late, variables, build_file): # Process a 'conditions' or 'target_conditions' section in the_dict, # depending on is_late. If is_late is False, 'conditions' is used. # # Each item in a conditions list consists of cond_expr, a string expression # evaluated as the condition, and true_dict, a dict that will be merged into # the_dict if cond_expr evaluates to true. Optionally, a third item, # false_dict, may be present. false_dict is merged into the_dict if # cond_expr evaluates to false. # # Any dict merged into the_dict will be recursively processed for nested # conditionals and other expansions, also according to is_late, immediately # prior to being merged. if not is_late: conditions_key = 'conditions' else: conditions_key = 'target_conditions' if not conditions_key in the_dict: return conditions_list = the_dict[conditions_key] # Unhook the conditions list, it's no longer needed. del the_dict[conditions_key] for condition in conditions_list: if not isinstance(condition, list): raise TypeError, conditions_key + ' must be a list' if len(condition) != 2 and len(condition) != 3: # It's possible that condition[0] won't work in which case this # attempt will raise its own IndexError. That's probably fine. raise IndexError, conditions_key + ' ' + condition[0] + \ ' must be length 2 or 3, not ' + len(condition) [cond_expr, true_dict] = condition[0:2] false_dict = None if len(condition) == 3: false_dict = condition[2] # Do expansions on the condition itself. Since the conditon can naturally # contain variable references without needing to resort to GYP expansion # syntax, this is of dubious value for variables, but someone might want to # use a command expansion directly inside a condition. cond_expr_expanded = ExpandVariables(cond_expr, is_late, variables, build_file) if not isinstance(cond_expr_expanded, str) and \ not isinstance(cond_expr_expanded, int): raise ValueError, \ 'Variable expansion in this context permits str and int ' + \ 'only, found ' + expanded.__class__.__name__ try: ast_code = compile(cond_expr_expanded, '<string>', 'eval') if eval(ast_code, {'__builtins__': None}, variables): merge_dict = true_dict else: merge_dict = false_dict except SyntaxError, e: syntax_error = SyntaxError('%s while evaluating condition \'%s\' in %s ' 'at character %d.' % (str(e.args[0]), e.text, build_file, e.offset), e.filename, e.lineno, e.offset, e.text) raise syntax_error except NameError, e: gyp.common.ExceptionAppend(e, 'while evaluating condition \'%s\' in %s' % (cond_expr_expanded, build_file)) raise if merge_dict != None: # Expand variables and nested conditinals in the merge_dict before # merging it. ProcessVariablesAndConditionsInDict(merge_dict, is_late, variables, build_file) MergeDicts(the_dict, merge_dict, build_file, build_file) def LoadAutomaticVariablesFromDict(variables, the_dict): # Any keys with plain string values in the_dict become automatic variables. # The variable name is the key name with a "_" character prepended. for key, value in the_dict.iteritems(): if isinstance(value, str) or isinstance(value, int) or \ isinstance(value, list): variables['_' + key] = value def LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key): # Any keys in the_dict's "variables" dict, if it has one, becomes a # variable. The variable name is the key name in the "variables" dict. # Variables that end with the % character are set only if they are unset in # the variables dict. the_dict_key is the name of the key that accesses # the_dict in the_dict's parent dict. If the_dict's parent is not a dict # (it could be a list or it could be parentless because it is a root dict), # the_dict_key will be None. for key, value in the_dict.get('variables', {}).iteritems(): if not isinstance(value, str) and not isinstance(value, int) and \ not isinstance(value, list): continue if key.endswith('%'): variable_name = key[:-1] if variable_name in variables: # If the variable is already set, don't set it. continue if the_dict_key is 'variables' and variable_name in the_dict: # If the variable is set without a % in the_dict, and the_dict is a # variables dict (making |variables| a varaibles sub-dict of a # variables dict), use the_dict's definition. value = the_dict[variable_name] else: variable_name = key variables[variable_name] = value def ProcessVariablesAndConditionsInDict(the_dict, is_late, variables_in, build_file, the_dict_key=None): """Handle all variable and command expansion and conditional evaluation. This function is the public entry point for all variable expansions and conditional evaluations. The variables_in dictionary will not be modified by this function. """ # Make a copy of the variables_in dict that can be modified during the # loading of automatics and the loading of the variables dict. variables = variables_in.copy() LoadAutomaticVariablesFromDict(variables, the_dict) if 'variables' in the_dict: # Make sure all the local variables are added to the variables # list before we process them so that you can reference one # variable from another. They will be fully expanded by recursion # in ExpandVariables. for key, value in the_dict['variables'].iteritems(): variables[key] = value # Handle the associated variables dict first, so that any variable # references within can be resolved prior to using them as variables. # Pass a copy of the variables dict to avoid having it be tainted. # Otherwise, it would have extra automatics added for everything that # should just be an ordinary variable in this scope. ProcessVariablesAndConditionsInDict(the_dict['variables'], is_late, variables, build_file, 'variables') LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key) for key, value in the_dict.iteritems(): # Skip "variables", which was already processed if present. if key != 'variables' and isinstance(value, str): expanded = ExpandVariables(value, is_late, variables, build_file) if not isinstance(expanded, str) and not isinstance(expanded, int): raise ValueError, \ 'Variable expansion in this context permits str and int ' + \ 'only, found ' + expanded.__class__.__name__ + ' for ' + key the_dict[key] = expanded # Variable expansion may have resulted in changes to automatics. Reload. # TODO(mark): Optimization: only reload if no changes were made. variables = variables_in.copy() LoadAutomaticVariablesFromDict(variables, the_dict) LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key) # Process conditions in this dict. This is done after variable expansion # so that conditions may take advantage of expanded variables. For example, # if the_dict contains: # {'type': '<(library_type)', # 'conditions': [['_type=="static_library"', { ... }]]}, # _type, as used in the condition, will only be set to the value of # library_type if variable expansion is performed before condition # processing. However, condition processing should occur prior to recursion # so that variables (both automatic and "variables" dict type) may be # adjusted by conditions sections, merged into the_dict, and have the # intended impact on contained dicts. # # This arrangement means that a "conditions" section containing a "variables" # section will only have those variables effective in subdicts, not in # the_dict. The workaround is to put a "conditions" section within a # "variables" section. For example: # {'conditions': [['os=="mac"', {'variables': {'define': 'IS_MAC'}}]], # 'defines': ['<(define)'], # 'my_subdict': {'defines': ['<(define)']}}, # will not result in "IS_MAC" being appended to the "defines" list in the # current scope but would result in it being appended to the "defines" list # within "my_subdict". By comparison: # {'variables': {'conditions': [['os=="mac"', {'define': 'IS_MAC'}]]}, # 'defines': ['<(define)'], # 'my_subdict': {'defines': ['<(define)']}}, # will append "IS_MAC" to both "defines" lists. # Evaluate conditions sections, allowing variable expansions within them # as well as nested conditionals. This will process a 'conditions' or # 'target_conditions' section, perform appropriate merging and recursive # conditional and variable processing, and then remove the conditions section # from the_dict if it is present. ProcessConditionsInDict(the_dict, is_late, variables, build_file) # Conditional processing may have resulted in changes to automatics or the # variables dict. Reload. variables = variables_in.copy() LoadAutomaticVariablesFromDict(variables, the_dict) LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key) # Recurse into child dicts, or process child lists which may result in # further recursion into descendant dicts. for key, value in the_dict.iteritems(): # Skip "variables" and string values, which were already processed if # present. if key == 'variables' or isinstance(value, str): continue if isinstance(value, dict): # Pass a copy of the variables dict so that subdicts can't influence # parents. ProcessVariablesAndConditionsInDict(value, is_late, variables, build_file, key) elif isinstance(value, list): # The list itself can't influence the variables dict, and # ProcessVariablesAndConditionsInList will make copies of the variables # dict if it needs to pass it to something that can influence it. No # copy is necessary here. ProcessVariablesAndConditionsInList(value, is_late, variables, build_file) elif not isinstance(value, int): raise TypeError, 'Unknown type ' + value.__class__.__name__ + \ ' for ' + key def ProcessVariablesAndConditionsInList(the_list, is_late, variables, build_file): # Iterate using an index so that new values can be assigned into the_list. index = 0 while index < len(the_list): item = the_list[index] if isinstance(item, dict): # Make a copy of the variables dict so that it won't influence anything # outside of its own scope. ProcessVariablesAndConditionsInDict(item, is_late, variables, build_file) elif isinstance(item, list): ProcessVariablesAndConditionsInList(item, is_late, variables, build_file) elif isinstance(item, str): expanded = ExpandVariables(item, is_late, variables, build_file) if isinstance(expanded, str) or isinstance(expanded, int): the_list[index] = expanded elif isinstance(expanded, list): del the_list[index] for expanded_item in expanded: the_list.insert(index, expanded_item) index = index + 1 # index now identifies the next item to examine. Continue right now # without falling into the index increment below. continue else: raise ValueError, \ 'Variable expansion in this context permits strings and ' + \ 'lists only, found ' + expanded.__class__.__name__ + ' at ' + \ index elif not isinstance(item, int): raise TypeError, 'Unknown type ' + item.__class__.__name__ + \ ' at index ' + index index = index + 1 def BuildTargetsDict(data): """Builds a dict mapping fully-qualified target names to their target dicts. |data| is a dict mapping loaded build files by pathname relative to the current directory. Values in |data| are build file contents. For each |data| value with a "targets" key, the value of the "targets" key is taken as a list containing target dicts. Each target's fully-qualified name is constructed from the pathname of the build file (|data| key) and its "target_name" property. These fully-qualified names are used as the keys in the returned dict. These keys provide access to the target dicts, the dicts in the "targets" lists. """ targets = {} for build_file in data['target_build_files']: for target in data[build_file].get('targets', []): target_name = gyp.common.QualifiedTarget(build_file, target['target_name'], target['toolset']) if target_name in targets: raise KeyError, 'Duplicate target definitions for ' + target_name targets[target_name] = target return targets def QualifyDependencies(targets): """Make dependency links fully-qualified relative to the current directory. |targets| is a dict mapping fully-qualified target names to their target dicts. For each target in this dict, keys known to contain dependency links are examined, and any dependencies referenced will be rewritten so that they are fully-qualified and relative to the current directory. All rewritten dependencies are suitable for use as keys to |targets| or a similar dict. """ for target, target_dict in targets.iteritems(): target_build_file = gyp.common.BuildFile(target) toolset = target_dict['toolset'] for dependency_key in dependency_sections: dependencies = target_dict.get(dependency_key, []) for index in xrange(0, len(dependencies)): dep_file, dep_target, dep_toolset = gyp.common.ResolveTarget( target_build_file, dependencies[index], toolset) global multiple_toolsets if not multiple_toolsets: # Ignore toolset specification in the dependency if it is specified. dep_toolset = toolset dependency = gyp.common.QualifiedTarget(dep_file, dep_target, dep_toolset) dependencies[index] = dependency # Make sure anything appearing in a list other than "dependencies" also # appears in the "dependencies" list. if dependency_key != 'dependencies' and \ dependency not in target_dict['dependencies']: raise KeyError, 'Found ' + dependency + ' in ' + dependency_key + \ ' of ' + target + ', but not in dependencies' def ExpandWildcardDependencies(targets, data): """Expands dependencies specified as build_file:*. For each target in |targets|, examines sections containing links to other targets. If any such section contains a link of the form build_file:*, it is taken as a wildcard link, and is expanded to list each target in build_file. The |data| dict provides access to build file dicts. Any target that does not wish to be included by wildcard can provide an optional "suppress_wildcard" key in its target dict. When present and true, a wildcard dependency link will not include such targets. All dependency names, including the keys to |targets| and the values in each dependency list, must be qualified when this function is called. """ for target, target_dict in targets.iteritems(): toolset = target_dict['toolset'] target_build_file = gyp.common.BuildFile(target) for dependency_key in dependency_sections: dependencies = target_dict.get(dependency_key, []) # Loop this way instead of "for dependency in" or "for index in xrange" # because the dependencies list will be modified within the loop body. index = 0 while index < len(dependencies): (dependency_build_file, dependency_target, dependency_toolset) = \ gyp.common.ParseQualifiedTarget(dependencies[index]) if dependency_target != '*' and dependency_toolset != '*': # Not a wildcard. Keep it moving. index = index + 1 continue if dependency_build_file == target_build_file: # It's an error for a target to depend on all other targets in # the same file, because a target cannot depend on itself. raise KeyError, 'Found wildcard in ' + dependency_key + ' of ' + \ target + ' referring to same build file' # Take the wildcard out and adjust the index so that the next # dependency in the list will be processed the next time through the # loop. del dependencies[index] index = index - 1 # Loop through the targets in the other build file, adding them to # this target's list of dependencies in place of the removed # wildcard. dependency_target_dicts = data[dependency_build_file]['targets'] for dependency_target_dict in dependency_target_dicts: if int(dependency_target_dict.get('suppress_wildcard', False)): continue dependency_target_name = dependency_target_dict['target_name'] if (dependency_target != '*' and dependency_target != dependency_target_name): continue dependency_target_toolset = dependency_target_dict['toolset'] if (dependency_toolset != '*' and dependency_toolset != dependency_target_toolset): continue dependency = gyp.common.QualifiedTarget(dependency_build_file, dependency_target_name, dependency_target_toolset) index = index + 1 dependencies.insert(index, dependency) index = index + 1 class DependencyGraphNode(object): """ Attributes: ref: A reference to an object that this DependencyGraphNode represents. dependencies: List of DependencyGraphNodes on which this one depends. dependents: List of DependencyGraphNodes that depend on this one. """ class CircularException(Exception): pass def __init__(self, ref): self.ref = ref self.dependencies = [] self.dependents = [] def FlattenToList(self): # flat_list is the sorted list of dependencies - actually, the list items # are the "ref" attributes of DependencyGraphNodes. Every target will # appear in flat_list after all of its dependencies, and before all of its # dependents. flat_list = [] # in_degree_zeros is the list of DependencyGraphNodes that have no # dependencies not in flat_list. Initially, it is a copy of the children # of this node, because when the graph was built, nodes with no # dependencies were made implicit dependents of the root node. in_degree_zeros = self.dependents[:] while in_degree_zeros: # Nodes in in_degree_zeros have no dependencies not in flat_list, so they # can be appended to flat_list. Take these nodes out of in_degree_zeros # as work progresses, so that the next node to process from the list can # always be accessed at a consistent position. node = in_degree_zeros.pop(0) flat_list.append(node.ref) # Look at dependents of the node just added to flat_list. Some of them # may now belong in in_degree_zeros. for node_dependent in node.dependents: is_in_degree_zero = True for node_dependent_dependency in node_dependent.dependencies: if not node_dependent_dependency.ref in flat_list: # The dependent one or more dependencies not in flat_list. There # will be more chances to add it to flat_list when examining # it again as a dependent of those other dependencies, provided # that there are no cycles. is_in_degree_zero = False break if is_in_degree_zero: # All of the dependent's dependencies are already in flat_list. Add # it to in_degree_zeros where it will be processed in a future # iteration of the outer loop. in_degree_zeros.append(node_dependent) return flat_list def DirectDependencies(self, dependencies=None): """Returns a list of just direct dependencies.""" if dependencies == None: dependencies = [] for dependency in self.dependencies: # Check for None, corresponding to the root node. if dependency.ref != None and dependency.ref not in dependencies: dependencies.append(dependency.ref) return dependencies def _AddImportedDependencies(self, targets, dependencies=None): """Given a list of direct dependencies, adds indirect dependencies that other dependencies have declared to export their settings. This method does not operate on self. Rather, it operates on the list of dependencies in the |dependencies| argument. For each dependency in that list, if any declares that it exports the settings of one of its own dependencies, those dependencies whose settings are "passed through" are added to the list. As new items are added to the list, they too will be processed, so it is possible to import settings through multiple levels of dependencies. This method is not terribly useful on its own, it depends on being "primed" with a list of direct dependencies such as one provided by DirectDependencies. DirectAndImportedDependencies is intended to be the public entry point. """ if dependencies == None: dependencies = [] index = 0 while index < len(dependencies): dependency = dependencies[index] dependency_dict = targets[dependency] # Add any dependencies whose settings should be imported to the list # if not already present. Newly-added items will be checked for # their own imports when the list iteration reaches them. # Rather than simply appending new items, insert them after the # dependency that exported them. This is done to more closely match # the depth-first method used by DeepDependencies. add_index = 1 for imported_dependency in \ dependency_dict.get('export_dependent_settings', []): if imported_dependency not in dependencies: dependencies.insert(index + add_index, imported_dependency) add_index = add_index + 1 index = index + 1 return dependencies def DirectAndImportedDependencies(self, targets, dependencies=None): """Returns a list of a target's direct dependencies and all indirect dependencies that a dependency has advertised settings should be exported through the dependency for. """ dependencies = self.DirectDependencies(dependencies) return self._AddImportedDependencies(targets, dependencies) def DeepDependencies(self, dependencies=None): """Returns a list of all of a target's dependencies, recursively.""" if dependencies == None: dependencies = [] for dependency in self.dependencies: # Check for None, corresponding to the root node. if dependency.ref != None and dependency.ref not in dependencies: dependencies.append(dependency.ref) dependency.DeepDependencies(dependencies) return dependencies def LinkDependencies(self, targets, dependencies=None, initial=True): """Returns a list of dependency targets that are linked into this target. This function has a split personality, depending on the setting of |initial|. Outside callers should always leave |initial| at its default setting. When adding a target to the list of dependencies, this function will recurse into itself with |initial| set to False, to collect depenedencies that are linked into the linkable target for which the list is being built. """ if dependencies == None: dependencies = [] # Check for None, corresponding to the root node. if self.ref == None: return dependencies # It's kind of sucky that |targets| has to be passed into this function, # but that's presently the easiest way to access the target dicts so that # this function can find target types. if not 'target_name' in targets[self.ref]: raise Exception("Missing 'target_name' field in target.") try: target_type = targets[self.ref]['type'] except KeyError, e: raise Exception("Missing 'type' field in target %s" % targets[self.ref]['target_name']) is_linkable = target_type in linkable_types if initial and not is_linkable: # If this is the first target being examined and it's not linkable, # return an empty list of link dependencies, because the link # dependencies are intended to apply to the target itself (initial is # True) and this target won't be linked. return dependencies # Executables and loadable modules are already fully and finally linked. # Nothing else can be a link dependency of them, there can only be # dependencies in the sense that a dependent target might run an # executable or load the loadable_module. if not initial and target_type in ('executable', 'loadable_module'): return dependencies # The target is linkable, add it to the list of link dependencies. if self.ref not in dependencies: if target_type != 'none': # Special case: "none" type targets don't produce any linkable products # and shouldn't be exposed as link dependencies, although dependencies # of "none" type targets may still be link dependencies. dependencies.append(self.ref) if initial or not is_linkable: # If this is a subsequent target and it's linkable, don't look any # further for linkable dependencies, as they'll already be linked into # this target linkable. Always look at dependencies of the initial # target, and always look at dependencies of non-linkables. for dependency in self.dependencies: dependency.LinkDependencies(targets, dependencies, False) return dependencies def BuildDependencyList(targets): # Create a DependencyGraphNode for each target. Put it into a dict for easy # access. dependency_nodes = {} for target, spec in targets.iteritems(): if not target in dependency_nodes: dependency_nodes[target] = DependencyGraphNode(target) # Set up the dependency links. Targets that have no dependencies are treated # as dependent on root_node. root_node = DependencyGraphNode(None) for target, spec in targets.iteritems(): target_node = dependency_nodes[target] target_build_file = gyp.common.BuildFile(target) if not 'dependencies' in spec or len(spec['dependencies']) == 0: target_node.dependencies = [root_node] root_node.dependents.append(target_node) else: dependencies = spec['dependencies'] for index in xrange(0, len(dependencies)): try: dependency = dependencies[index] dependency_node = dependency_nodes[dependency] target_node.dependencies.append(dependency_node) dependency_node.dependents.append(target_node) except KeyError, e: gyp.common.ExceptionAppend(e, 'while trying to load target %s' % target) raise flat_list = root_node.FlattenToList() # If there's anything left unvisited, there must be a circular dependency # (cycle). If you need to figure out what's wrong, look for elements of # targets that are not in flat_list. if len(flat_list) != len(targets): raise DependencyGraphNode.CircularException, \ 'Some targets not reachable, cycle in dependency graph detected' return [dependency_nodes, flat_list] def DoDependentSettings(key, flat_list, targets, dependency_nodes): # key should be one of all_dependent_settings, direct_dependent_settings, # or link_settings. for target in flat_list: target_dict = targets[target] build_file = gyp.common.BuildFile(target) if key == 'all_dependent_settings': dependencies = dependency_nodes[target].DeepDependencies() elif key == 'direct_dependent_settings': dependencies = \ dependency_nodes[target].DirectAndImportedDependencies(targets) elif key == 'link_settings': dependencies = dependency_nodes[target].LinkDependencies(targets) else: raise KeyError, "DoDependentSettings doesn't know how to determine " + \ 'dependencies for ' + key for dependency in dependencies: dependency_dict = targets[dependency] if not key in dependency_dict: continue dependency_build_file = gyp.common.BuildFile(dependency) MergeDicts(target_dict, dependency_dict[key], build_file, dependency_build_file) def AdjustStaticLibraryDependencies(flat_list, targets, dependency_nodes): # Recompute target "dependencies" properties. For each static library # target, remove "dependencies" entries referring to other static libraries, # unless the dependency has the "hard_dependency" attribute set. For each # linkable target, add a "dependencies" entry referring to all of the # target's computed list of link dependencies (including static libraries # if no such entry is already present. for target in flat_list: target_dict = targets[target] target_type = target_dict['type'] if target_type == 'static_library': if not 'dependencies' in target_dict: continue target_dict['dependencies_original'] = target_dict.get( 'dependencies', [])[:] index = 0 while index < len(target_dict['dependencies']): dependency = target_dict['dependencies'][index] dependency_dict = targets[dependency] if dependency_dict['type'] == 'static_library' and \ (not 'hard_dependency' in dependency_dict or \ not dependency_dict['hard_dependency']): # A static library should not depend on another static library unless # the dependency relationship is "hard," which should only be done # when a dependent relies on some side effect other than just the # build product, like a rule or action output. Take the dependency # out of the list, and don't increment index because the next # dependency to analyze will shift into the index formerly occupied # by the one being removed. del target_dict['dependencies'][index] else: index = index + 1 # If the dependencies list is empty, it's not needed, so unhook it. if len(target_dict['dependencies']) == 0: del target_dict['dependencies'] elif target_type in linkable_types: # Get a list of dependency targets that should be linked into this # target. Add them to the dependencies list if they're not already # present. link_dependencies = dependency_nodes[target].LinkDependencies(targets) for dependency in link_dependencies: if dependency == target: continue if not 'dependencies' in target_dict: target_dict['dependencies'] = [] if not dependency in target_dict['dependencies']: target_dict['dependencies'].append(dependency) # Initialize this here to speed up MakePathRelative. exception_re = re.compile(r'''["']?[-/$<>]''') def MakePathRelative(to_file, fro_file, item): # If item is a relative path, it's relative to the build file dict that it's # coming from. Fix it up to make it relative to the build file dict that # it's going into. # Exception: any |item| that begins with these special characters is # returned without modification. # / Used when a path is already absolute (shortcut optimization; # such paths would be returned as absolute anyway) # $ Used for build environment variables # - Used for some build environment flags (such as -lapr-1 in a # "libraries" section) # < Used for our own variable and command expansions (see ExpandVariables) # > Used for our own variable and command expansions (see ExpandVariables) # # "/' Used when a value is quoted. If these are present, then we # check the second character instead. # if to_file == fro_file or exception_re.match(item): return item else: # TODO(dglazkov) The backslash/forward-slash replacement at the end is a # temporary measure. This should really be addressed by keeping all paths # in POSIX until actual project generation. return os.path.normpath(os.path.join( gyp.common.RelativePath(os.path.dirname(fro_file), os.path.dirname(to_file)), item)).replace('\\', '/') def MergeLists(to, fro, to_file, fro_file, is_paths=False, append=True): prepend_index = 0 for item in fro: singleton = False if isinstance(item, str) or isinstance(item, int): # The cheap and easy case. if is_paths: to_item = MakePathRelative(to_file, fro_file, item) else: to_item = item if not isinstance(item, str) or not item.startswith('-'): # Any string that doesn't begin with a "-" is a singleton - it can # only appear once in a list, to be enforced by the list merge append # or prepend. singleton = True elif isinstance(item, dict): # Make a copy of the dictionary, continuing to look for paths to fix. # The other intelligent aspects of merge processing won't apply because # item is being merged into an empty dict. to_item = {} MergeDicts(to_item, item, to_file, fro_file) elif isinstance(item, list): # Recurse, making a copy of the list. If the list contains any # descendant dicts, path fixing will occur. Note that here, custom # values for is_paths and append are dropped; those are only to be # applied to |to| and |fro|, not sublists of |fro|. append shouldn't # matter anyway because the new |to_item| list is empty. to_item = [] MergeLists(to_item, item, to_file, fro_file) else: raise TypeError, \ 'Attempt to merge list item of unsupported type ' + \ item.__class__.__name__ if append: # If appending a singleton that's already in the list, don't append. # This ensures that the earliest occurrence of the item will stay put. if not singleton or not to_item in to: to.append(to_item) else: # If prepending a singleton that's already in the list, remove the # existing instance and proceed with the prepend. This ensures that the # item appears at the earliest possible position in the list. while singleton and to_item in to: to.remove(to_item) # Don't just insert everything at index 0. That would prepend the new # items to the list in reverse order, which would be an unwelcome # surprise. to.insert(prepend_index, to_item) prepend_index = prepend_index + 1 def MergeDicts(to, fro, to_file, fro_file): # I wanted to name the parameter "from" but it's a Python keyword... for k, v in fro.iteritems(): # It would be nice to do "if not k in to: to[k] = v" but that wouldn't give # copy semantics. Something else may want to merge from the |fro| dict # later, and having the same dict ref pointed to twice in the tree isn't # what anyone wants considering that the dicts may subsequently be # modified. if k in to: bad_merge = False if isinstance(v, str) or isinstance(v, int): if not (isinstance(to[k], str) or isinstance(to[k], int)): bad_merge = True elif v.__class__ != to[k].__class__: bad_merge = True if bad_merge: raise TypeError, \ 'Attempt to merge dict value of type ' + v.__class__.__name__ + \ ' into incompatible type ' + to[k].__class__.__name__ + \ ' for key ' + k if isinstance(v, str) or isinstance(v, int): # Overwrite the existing value, if any. Cheap and easy. is_path = IsPathSection(k) if is_path: to[k] = MakePathRelative(to_file, fro_file, v) else: to[k] = v elif isinstance(v, dict): # Recurse, guaranteeing copies will be made of objects that require it. if not k in to: to[k] = {} MergeDicts(to[k], v, to_file, fro_file) elif isinstance(v, list): # Lists in dicts can be merged with different policies, depending on # how the key in the "from" dict (k, the from-key) is written. # # If the from-key has ...the to-list will have this action # this character appended:... applied when receiving the from-list: # = replace # + prepend # ? set, only if to-list does not yet exist # (none) append # # This logic is list-specific, but since it relies on the associated # dict key, it's checked in this dict-oriented function. ext = k[-1] append = True if ext == '=': list_base = k[:-1] lists_incompatible = [list_base, list_base + '?'] to[list_base] = [] elif ext == '+': list_base = k[:-1] lists_incompatible = [list_base + '=', list_base + '?'] append = False elif ext == '?': list_base = k[:-1] lists_incompatible = [list_base, list_base + '=', list_base + '+'] else: list_base = k lists_incompatible = [list_base + '=', list_base + '?'] # Some combinations of merge policies appearing together are meaningless. # It's stupid to replace and append simultaneously, for example. Append # and prepend are the only policies that can coexist. for list_incompatible in lists_incompatible: if list_incompatible in fro: raise KeyError, 'Incompatible list policies ' + k + ' and ' + \ list_incompatible if list_base in to: if ext == '?': # If the key ends in "?", the list will only be merged if it doesn't # already exist. continue if not isinstance(to[list_base], list): # This may not have been checked above if merging in a list with an # extension character. raise TypeError, \ 'Attempt to merge dict value of type ' + v.__class__.__name__ + \ ' into incompatible type ' + to[list_base].__class__.__name__ + \ ' for key ' + list_base + '(' + k + ')' else: to[list_base] = [] # Call MergeLists, which will make copies of objects that require it. # MergeLists can recurse back into MergeDicts, although this will be # to make copies of dicts (with paths fixed), there will be no # subsequent dict "merging" once entering a list because lists are # always replaced, appended to, or prepended to. is_paths = IsPathSection(list_base) MergeLists(to[list_base], v, to_file, fro_file, is_paths, append) else: raise TypeError, \ 'Attempt to merge dict value of unsupported type ' + \ v.__class__.__name__ + ' for key ' + k def MergeConfigWithInheritance(new_configuration_dict, build_file, target_dict, configuration, visited): # Skip if previously visted. if configuration in visited: return # Look at this configuration. configuration_dict = target_dict['configurations'][configuration] # Merge in parents. for parent in configuration_dict.get('inherit_from', []): MergeConfigWithInheritance(new_configuration_dict, build_file, target_dict, parent, visited + [configuration]) # Merge it into the new config. MergeDicts(new_configuration_dict, configuration_dict, build_file, build_file) # Drop abstract. if 'abstract' in new_configuration_dict: del new_configuration_dict['abstract'] def SetUpConfigurations(target, target_dict): global non_configuration_keys # key_suffixes is a list of key suffixes that might appear on key names. # These suffixes are handled in conditional evaluations (for =, +, and ?) # and rules/exclude processing (for ! and /). Keys with these suffixes # should be treated the same as keys without. key_suffixes = ['=', '+', '?', '!', '/'] build_file = gyp.common.BuildFile(target) # Provide a single configuration by default if none exists. # TODO(mark): Signal an error if default_configurations exists but # configurations does not. if not 'configurations' in target_dict: target_dict['configurations'] = {'Default': {}} if not 'default_configuration' in target_dict: concrete = [i for i in target_dict['configurations'].keys() if not target_dict['configurations'][i].get('abstract')] target_dict['default_configuration'] = sorted(concrete)[0] for configuration in target_dict['configurations'].keys(): old_configuration_dict = target_dict['configurations'][configuration] # Skip abstract configurations (saves work only). if old_configuration_dict.get('abstract'): continue # Configurations inherit (most) settings from the enclosing target scope. # Get the inheritance relationship right by making a copy of the target # dict. new_configuration_dict = copy.deepcopy(target_dict) # Take out the bits that don't belong in a "configurations" section. # Since configuration setup is done before conditional, exclude, and rules # processing, be careful with handling of the suffix characters used in # those phases. delete_keys = [] for key in new_configuration_dict: key_ext = key[-1:] if key_ext in key_suffixes: key_base = key[:-1] else: key_base = key if key_base in non_configuration_keys: delete_keys.append(key) for key in delete_keys: del new_configuration_dict[key] # Merge in configuration (with all its parents first). MergeConfigWithInheritance(new_configuration_dict, build_file, target_dict, configuration, []) # Put the new result back into the target dict as a configuration. target_dict['configurations'][configuration] = new_configuration_dict # Now drop all the abstract ones. for configuration in target_dict['configurations'].keys(): old_configuration_dict = target_dict['configurations'][configuration] if old_configuration_dict.get('abstract'): del target_dict['configurations'][configuration] # Now that all of the target's configurations have been built, go through # the target dict's keys and remove everything that's been moved into a # "configurations" section. delete_keys = [] for key in target_dict: key_ext = key[-1:] if key_ext in key_suffixes: key_base = key[:-1] else: key_base = key if not key_base in non_configuration_keys: delete_keys.append(key) for key in delete_keys: del target_dict[key] def ProcessListFiltersInDict(name, the_dict): """Process regular expression and exclusion-based filters on lists. An exclusion list is in a dict key named with a trailing "!", like "sources!". Every item in such a list is removed from the associated main list, which in this example, would be "sources". Removed items are placed into a "sources_excluded" list in the dict. Regular expression (regex) filters are contained in dict keys named with a trailing "/", such as "sources/" to operate on the "sources" list. Regex filters in a dict take the form: 'sources/': [ ['exclude', '_(linux|mac|win)\\.cc$'] ], ['include', '_mac\\.cc$'] ], The first filter says to exclude all files ending in _linux.cc, _mac.cc, and _win.cc. The second filter then includes all files ending in _mac.cc that are now or were once in the "sources" list. Items matching an "exclude" filter are subject to the same processing as would occur if they were listed by name in an exclusion list (ending in "!"). Items matching an "include" filter are brought back into the main list if previously excluded by an exclusion list or exclusion regex filter. Subsequent matching "exclude" patterns can still cause items to be excluded after matching an "include". """ # Look through the dictionary for any lists whose keys end in "!" or "/". # These are lists that will be treated as exclude lists and regular # expression-based exclude/include lists. Collect the lists that are # needed first, looking for the lists that they operate on, and assemble # then into |lists|. This is done in a separate loop up front, because # the _included and _excluded keys need to be added to the_dict, and that # can't be done while iterating through it. lists = [] del_lists = [] for key, value in the_dict.iteritems(): operation = key[-1] if operation != '!' and operation != '/': continue if not isinstance(value, list): raise ValueError, name + ' key ' + key + ' must be list, not ' + \ value.__class__.__name__ list_key = key[:-1] if list_key not in the_dict: # This happens when there's a list like "sources!" but no corresponding # "sources" list. Since there's nothing for it to operate on, queue up # the "sources!" list for deletion now. del_lists.append(key) continue if not isinstance(the_dict[list_key], list): raise ValueError, name + ' key ' + list_key + \ ' must be list, not ' + \ value.__class__.__name__ + ' when applying ' + \ {'!': 'exclusion', '/': 'regex'}[operation] if not list_key in lists: lists.append(list_key) # Delete the lists that are known to be unneeded at this point. for del_list in del_lists: del the_dict[del_list] for list_key in lists: the_list = the_dict[list_key] # Initialize the list_actions list, which is parallel to the_list. Each # item in list_actions identifies whether the corresponding item in # the_list should be excluded, unconditionally preserved (included), or # whether no exclusion or inclusion has been applied. Items for which # no exclusion or inclusion has been applied (yet) have value -1, items # excluded have value 0, and items included have value 1. Includes and # excludes override previous actions. All items in list_actions are # initialized to -1 because no excludes or includes have been processed # yet. list_actions = list((-1,) * len(the_list)) exclude_key = list_key + '!' if exclude_key in the_dict: for exclude_item in the_dict[exclude_key]: for index in xrange(0, len(the_list)): if exclude_item == the_list[index]: # This item matches the exclude_item, so set its action to 0 # (exclude). list_actions[index] = 0 # The "whatever!" list is no longer needed, dump it. del the_dict[exclude_key] regex_key = list_key + '/' if regex_key in the_dict: for regex_item in the_dict[regex_key]: [action, pattern] = regex_item pattern_re = re.compile(pattern) for index in xrange(0, len(the_list)): list_item = the_list[index] if pattern_re.search(list_item): # Regular expression match. if action == 'exclude': # This item matches an exclude regex, so set its value to 0 # (exclude). list_actions[index] = 0 elif action == 'include': # This item matches an include regex, so set its value to 1 # (include). list_actions[index] = 1 else: # This is an action that doesn't make any sense. raise ValueError, 'Unrecognized action ' + action + ' in ' + \ name + ' key ' + key # The "whatever/" list is no longer needed, dump it. del the_dict[regex_key] # Add excluded items to the excluded list. # # Note that exclude_key ("sources!") is different from excluded_key # ("sources_excluded"). The exclude_key list is input and it was already # processed and deleted; the excluded_key list is output and it's about # to be created. excluded_key = list_key + '_excluded' if excluded_key in the_dict: raise KeyError, \ name + ' key ' + excluded_key + ' must not be present prior ' + \ ' to applying exclusion/regex filters for ' + list_key excluded_list = [] # Go backwards through the list_actions list so that as items are deleted, # the indices of items that haven't been seen yet don't shift. That means # that things need to be prepended to excluded_list to maintain them in the # same order that they existed in the_list. for index in xrange(len(list_actions) - 1, -1, -1): if list_actions[index] == 0: # Dump anything with action 0 (exclude). Keep anything with action 1 # (include) or -1 (no include or exclude seen for the item). excluded_list.insert(0, the_list[index]) del the_list[index] # If anything was excluded, put the excluded list into the_dict at # excluded_key. if len(excluded_list) > 0: the_dict[excluded_key] = excluded_list # Now recurse into subdicts and lists that may contain dicts. for key, value in the_dict.iteritems(): if isinstance(value, dict): ProcessListFiltersInDict(key, value) elif isinstance(value, list): ProcessListFiltersInList(key, value) def ProcessListFiltersInList(name, the_list): for item in the_list: if isinstance(item, dict): ProcessListFiltersInDict(name, item) elif isinstance(item, list): ProcessListFiltersInList(name, item) def ValidateRulesInTarget(target, target_dict, extra_sources_for_rules): """Ensures that the rules sections in target_dict are valid and consistent, and determines which sources they apply to. Arguments: target: string, name of target. target_dict: dict, target spec containing "rules" and "sources" lists. extra_sources_for_rules: a list of keys to scan for rule matches in addition to 'sources'. """ # Dicts to map between values found in rules' 'rule_name' and 'extension' # keys and the rule dicts themselves. rule_names = {} rule_extensions = {} rules = target_dict.get('rules', []) for rule in rules: # Make sure that there's no conflict among rule names and extensions. rule_name = rule['rule_name'] if rule_name in rule_names: raise KeyError, 'rule %s exists in duplicate, target %s' % \ (rule_name, target) rule_names[rule_name] = rule rule_extension = rule['extension'] if rule_extension in rule_extensions: raise KeyError, ('extension %s associated with multiple rules, ' + 'target %s rules %s and %s') % \ (rule_extension, target, rule_extensions[rule_extension]['rule_name'], rule_name) rule_extensions[rule_extension] = rule # Make sure rule_sources isn't already there. It's going to be # created below if needed. if 'rule_sources' in rule: raise KeyError, \ 'rule_sources must not exist in input, target %s rule %s' % \ (target, rule_name) extension = rule['extension'] rule_sources = [] source_keys = ['sources'] source_keys.extend(extra_sources_for_rules) for source_key in source_keys: for source in target_dict.get(source_key, []): (source_root, source_extension) = os.path.splitext(source) if source_extension.startswith('.'): source_extension = source_extension[1:] if source_extension == extension: rule_sources.append(source) if len(rule_sources) > 0: rule['rule_sources'] = rule_sources def ValidateActionsInTarget(target, target_dict, build_file): '''Validates the inputs to the actions in a target.''' target_name = target_dict.get('target_name') actions = target_dict.get('actions', []) for action in actions: action_name = action.get('action_name') if not action_name: raise Exception("Anonymous action in target %s. " "An action must have an 'action_name' field." % target_name) inputs = action.get('inputs', []) def ValidateRunAsInTarget(target, target_dict, build_file): target_name = target_dict.get('target_name') run_as = target_dict.get('run_as') if not run_as: return if not isinstance(run_as, dict): raise Exception("The 'run_as' in target %s from file %s should be a " "dictionary." % (target_name, build_file)) action = run_as.get('action') if not action: raise Exception("The 'run_as' in target %s from file %s must have an " "'action' section." % (target_name, build_file)) if not isinstance(action, list): raise Exception("The 'action' for 'run_as' in target %s from file %s " "must be a list." % (target_name, build_file)) working_directory = run_as.get('working_directory') if working_directory and not isinstance(working_directory, str): raise Exception("The 'working_directory' for 'run_as' in target %s " "in file %s should be a string." % (target_name, build_file)) environment = run_as.get('environment') if environment and not isinstance(environment, dict): raise Exception("The 'environment' for 'run_as' in target %s " "in file %s should be a dictionary." % (target_name, build_file)) def TurnIntIntoStrInDict(the_dict): """Given dict the_dict, recursively converts all integers into strings. """ # Use items instead of iteritems because there's no need to try to look at # reinserted keys and their associated values. for k, v in the_dict.items(): if isinstance(v, int): v = str(v) the_dict[k] = v elif isinstance(v, dict): TurnIntIntoStrInDict(v) elif isinstance(v, list): TurnIntIntoStrInList(v) if isinstance(k, int): the_dict[str(k)] = v del the_dict[k] def TurnIntIntoStrInList(the_list): """Given list the_list, recursively converts all integers into strings. """ for index in xrange(0, len(the_list)): item = the_list[index] if isinstance(item, int): the_list[index] = str(item) elif isinstance(item, dict): TurnIntIntoStrInDict(item) elif isinstance(item, list): TurnIntIntoStrInList(item) def Load(build_files, variables, includes, depth, generator_input_info, check): # Set up path_sections and non_configuration_keys with the default data plus # the generator-specifc data. global path_sections path_sections = base_path_sections[:] path_sections.extend(generator_input_info['path_sections']) global non_configuration_keys non_configuration_keys = base_non_configuration_keys[:] non_configuration_keys.extend(generator_input_info['non_configuration_keys']) # TODO(mark) handle variants if the generator doesn't want them directly. generator_handles_variants = \ generator_input_info['generator_handles_variants'] global absolute_build_file_paths absolute_build_file_paths = \ generator_input_info['generator_wants_absolute_build_file_paths'] global multiple_toolsets multiple_toolsets = generator_input_info[ 'generator_supports_multiple_toolsets'] # A generator can have other lists (in addition to sources) be processed # for rules. extra_sources_for_rules = generator_input_info['extra_sources_for_rules'] # Load build files. This loads every target-containing build file into # the |data| dictionary such that the keys to |data| are build file names, # and the values are the entire build file contents after "early" or "pre" # processing has been done and includes have been resolved. # NOTE: data contains both "target" files (.gyp) and "includes" (.gypi), as # well as meta-data (e.g. 'included_files' key). 'target_build_files' keeps # track of the keys corresponding to "target" files. data = {'target_build_files': set()} aux_data = {} for build_file in build_files: # Normalize paths everywhere. This is important because paths will be # used as keys to the data dict and for references between input files. build_file = os.path.normpath(build_file) try: LoadTargetBuildFile(build_file, data, aux_data, variables, includes, depth, check) except Exception, e: gyp.common.ExceptionAppend(e, 'while trying to load %s' % build_file) raise # Build a dict to access each target's subdict by qualified name. targets = BuildTargetsDict(data) # Fully qualify all dependency links. QualifyDependencies(targets) # Expand dependencies specified as build_file:*. ExpandWildcardDependencies(targets, data) [dependency_nodes, flat_list] = BuildDependencyList(targets) # Handle dependent settings of various types. for settings_type in ['all_dependent_settings', 'direct_dependent_settings', 'link_settings']: DoDependentSettings(settings_type, flat_list, targets, dependency_nodes) # Take out the dependent settings now that they've been published to all # of the targets that require them. for target in flat_list: if settings_type in targets[target]: del targets[target][settings_type] # Make sure static libraries don't declare dependencies on other static # libraries, but that linkables depend on all unlinked static libraries # that they need so that their link steps will be correct. AdjustStaticLibraryDependencies(flat_list, targets, dependency_nodes) # Apply "post"/"late"/"target" variable expansions and condition evaluations. for target in flat_list: target_dict = targets[target] build_file = gyp.common.BuildFile(target) ProcessVariablesAndConditionsInDict(target_dict, True, variables, build_file) # Move everything that can go into a "configurations" section into one. for target in flat_list: target_dict = targets[target] SetUpConfigurations(target, target_dict) # Apply exclude (!) and regex (/) list filters. for target in flat_list: target_dict = targets[target] ProcessListFiltersInDict(target, target_dict) # Make sure that the rules make sense, and build up rule_sources lists as # needed. Not all generators will need to use the rule_sources lists, but # some may, and it seems best to build the list in a common spot. # Also validate actions and run_as elements in targets. for target in flat_list: target_dict = targets[target] build_file = gyp.common.BuildFile(target) ValidateRulesInTarget(target, target_dict, extra_sources_for_rules) ValidateRunAsInTarget(target, target_dict, build_file) ValidateActionsInTarget(target, target_dict, build_file) # Generators might not expect ints. Turn them into strs. TurnIntIntoStrInDict(data) # TODO(mark): Return |data| for now because the generator needs a list of # build files that came in. In the future, maybe it should just accept # a list, and not the whole data dict. return [flat_list, targets, data]
bsd-3-clause
auduny/home-assistant
tests/components/api/test_init.py
9
18834
"""The tests for the Home Assistant API component.""" # pylint: disable=protected-access import asyncio import json from unittest.mock import patch from aiohttp import web import pytest import voluptuous as vol from homeassistant import const from homeassistant.bootstrap import DATA_LOGGING import homeassistant.core as ha from homeassistant.setup import async_setup_component from tests.common import async_mock_service @pytest.fixture def mock_api_client(hass, hass_client): """Start the Hass HTTP component and return admin API client.""" hass.loop.run_until_complete(async_setup_component(hass, 'api', {})) return hass.loop.run_until_complete(hass_client()) @asyncio.coroutine def test_api_list_state_entities(hass, mock_api_client): """Test if the debug interface allows us to list state entities.""" hass.states.async_set('test.entity', 'hello') resp = yield from mock_api_client.get(const.URL_API_STATES) assert resp.status == 200 json = yield from resp.json() remote_data = [ha.State.from_dict(item) for item in json] assert remote_data == hass.states.async_all() @asyncio.coroutine def test_api_get_state(hass, mock_api_client): """Test if the debug interface allows us to get a state.""" hass.states.async_set('hello.world', 'nice', { 'attr': 1, }) resp = yield from mock_api_client.get( const.URL_API_STATES_ENTITY.format("hello.world")) assert resp.status == 200 json = yield from resp.json() data = ha.State.from_dict(json) state = hass.states.get("hello.world") assert data.state == state.state assert data.last_changed == state.last_changed assert data.attributes == state.attributes @asyncio.coroutine def test_api_get_non_existing_state(hass, mock_api_client): """Test if the debug interface allows us to get a state.""" resp = yield from mock_api_client.get( const.URL_API_STATES_ENTITY.format("does_not_exist")) assert resp.status == 404 @asyncio.coroutine def test_api_state_change(hass, mock_api_client): """Test if we can change the state of an entity that exists.""" hass.states.async_set("test.test", "not_to_be_set") yield from mock_api_client.post( const.URL_API_STATES_ENTITY.format("test.test"), json={"state": "debug_state_change2"}) assert hass.states.get("test.test").state == "debug_state_change2" # pylint: disable=invalid-name @asyncio.coroutine def test_api_state_change_of_non_existing_entity(hass, mock_api_client): """Test if changing a state of a non existing entity is possible.""" new_state = "debug_state_change" resp = yield from mock_api_client.post( const.URL_API_STATES_ENTITY.format("test_entity.that_does_not_exist"), json={'state': new_state}) assert resp.status == 201 assert hass.states.get("test_entity.that_does_not_exist").state == \ new_state # pylint: disable=invalid-name @asyncio.coroutine def test_api_state_change_with_bad_data(hass, mock_api_client): """Test if API sends appropriate error if we omit state.""" resp = yield from mock_api_client.post( const.URL_API_STATES_ENTITY.format("test_entity.that_does_not_exist"), json={}) assert resp.status == 400 # pylint: disable=invalid-name @asyncio.coroutine def test_api_state_change_to_zero_value(hass, mock_api_client): """Test if changing a state to a zero value is possible.""" resp = yield from mock_api_client.post( const.URL_API_STATES_ENTITY.format("test_entity.with_zero_state"), json={'state': 0}) assert resp.status == 201 resp = yield from mock_api_client.post( const.URL_API_STATES_ENTITY.format("test_entity.with_zero_state"), json={'state': 0.}) assert resp.status == 200 # pylint: disable=invalid-name @asyncio.coroutine def test_api_state_change_push(hass, mock_api_client): """Test if we can push a change the state of an entity.""" hass.states.async_set("test.test", "not_to_be_set") events = [] @ha.callback def event_listener(event): """Track events.""" events.append(event) hass.bus.async_listen(const.EVENT_STATE_CHANGED, event_listener) yield from mock_api_client.post( const.URL_API_STATES_ENTITY.format("test.test"), json={"state": "not_to_be_set"}) yield from hass.async_block_till_done() assert len(events) == 0 yield from mock_api_client.post( const.URL_API_STATES_ENTITY.format("test.test"), json={"state": "not_to_be_set", "force_update": True}) yield from hass.async_block_till_done() assert len(events) == 1 # pylint: disable=invalid-name @asyncio.coroutine def test_api_fire_event_with_no_data(hass, mock_api_client): """Test if the API allows us to fire an event.""" test_value = [] @ha.callback def listener(event): """Record that our event got called.""" test_value.append(1) hass.bus.async_listen_once("test.event_no_data", listener) yield from mock_api_client.post( const.URL_API_EVENTS_EVENT.format("test.event_no_data")) yield from hass.async_block_till_done() assert len(test_value) == 1 # pylint: disable=invalid-name @asyncio.coroutine def test_api_fire_event_with_data(hass, mock_api_client): """Test if the API allows us to fire an event.""" test_value = [] @ha.callback def listener(event): """Record that our event got called. Also test if our data came through. """ if "test" in event.data: test_value.append(1) hass.bus.async_listen_once("test_event_with_data", listener) yield from mock_api_client.post( const.URL_API_EVENTS_EVENT.format("test_event_with_data"), json={"test": 1}) yield from hass.async_block_till_done() assert len(test_value) == 1 # pylint: disable=invalid-name @asyncio.coroutine def test_api_fire_event_with_invalid_json(hass, mock_api_client): """Test if the API allows us to fire an event.""" test_value = [] @ha.callback def listener(event): """Record that our event got called.""" test_value.append(1) hass.bus.async_listen_once("test_event_bad_data", listener) resp = yield from mock_api_client.post( const.URL_API_EVENTS_EVENT.format("test_event_bad_data"), data=json.dumps('not an object')) yield from hass.async_block_till_done() assert resp.status == 400 assert len(test_value) == 0 # Try now with valid but unusable JSON resp = yield from mock_api_client.post( const.URL_API_EVENTS_EVENT.format("test_event_bad_data"), data=json.dumps([1, 2, 3])) yield from hass.async_block_till_done() assert resp.status == 400 assert len(test_value) == 0 @asyncio.coroutine def test_api_get_config(hass, mock_api_client): """Test the return of the configuration.""" resp = yield from mock_api_client.get(const.URL_API_CONFIG) result = yield from resp.json() if 'components' in result: result['components'] = set(result['components']) if 'whitelist_external_dirs' in result: result['whitelist_external_dirs'] = \ set(result['whitelist_external_dirs']) assert hass.config.as_dict() == result @asyncio.coroutine def test_api_get_components(hass, mock_api_client): """Test the return of the components.""" resp = yield from mock_api_client.get(const.URL_API_COMPONENTS) result = yield from resp.json() assert set(result) == hass.config.components @asyncio.coroutine def test_api_get_event_listeners(hass, mock_api_client): """Test if we can get the list of events being listened for.""" resp = yield from mock_api_client.get(const.URL_API_EVENTS) data = yield from resp.json() local = hass.bus.async_listeners() for event in data: assert local.pop(event["event"]) == event["listener_count"] assert len(local) == 0 @asyncio.coroutine def test_api_get_services(hass, mock_api_client): """Test if we can get a dict describing current services.""" resp = yield from mock_api_client.get(const.URL_API_SERVICES) data = yield from resp.json() local_services = hass.services.async_services() for serv_domain in data: local = local_services.pop(serv_domain["domain"]) assert serv_domain["services"] == local @asyncio.coroutine def test_api_call_service_no_data(hass, mock_api_client): """Test if the API allows us to call a service.""" test_value = [] @ha.callback def listener(service_call): """Record that our service got called.""" test_value.append(1) hass.services.async_register("test_domain", "test_service", listener) yield from mock_api_client.post( const.URL_API_SERVICES_SERVICE.format( "test_domain", "test_service")) yield from hass.async_block_till_done() assert len(test_value) == 1 @asyncio.coroutine def test_api_call_service_with_data(hass, mock_api_client): """Test if the API allows us to call a service.""" test_value = [] @ha.callback def listener(service_call): """Record that our service got called. Also test if our data came through. """ if "test" in service_call.data: test_value.append(1) hass.services.async_register("test_domain", "test_service", listener) yield from mock_api_client.post( const.URL_API_SERVICES_SERVICE.format("test_domain", "test_service"), json={"test": 1}) yield from hass.async_block_till_done() assert len(test_value) == 1 @asyncio.coroutine def test_api_template(hass, mock_api_client): """Test the template API.""" hass.states.async_set('sensor.temperature', 10) resp = yield from mock_api_client.post( const.URL_API_TEMPLATE, json={"template": '{{ states.sensor.temperature.state }}'}) body = yield from resp.text() assert body == '10' @asyncio.coroutine def test_api_template_error(hass, mock_api_client): """Test the template API.""" hass.states.async_set('sensor.temperature', 10) resp = yield from mock_api_client.post( const.URL_API_TEMPLATE, json={"template": '{{ states.sensor.temperature.state'}) assert resp.status == 400 @asyncio.coroutine def test_stream(hass, mock_api_client): """Test the stream.""" listen_count = _listen_count(hass) resp = yield from mock_api_client.get(const.URL_API_STREAM) assert resp.status == 200 assert listen_count + 1 == _listen_count(hass) hass.bus.async_fire('test_event') data = yield from _stream_next_event(resp.content) assert data['event_type'] == 'test_event' @asyncio.coroutine def test_stream_with_restricted(hass, mock_api_client): """Test the stream with restrictions.""" listen_count = _listen_count(hass) resp = yield from mock_api_client.get( '{}?restrict=test_event1,test_event3'.format(const.URL_API_STREAM)) assert resp.status == 200 assert listen_count + 1 == _listen_count(hass) hass.bus.async_fire('test_event1') data = yield from _stream_next_event(resp.content) assert data['event_type'] == 'test_event1' hass.bus.async_fire('test_event2') hass.bus.async_fire('test_event3') data = yield from _stream_next_event(resp.content) assert data['event_type'] == 'test_event3' @asyncio.coroutine def _stream_next_event(stream): """Read the stream for next event while ignoring ping.""" while True: last_new_line = False data = b'' while True: dat = yield from stream.read(1) if dat == b'\n' and last_new_line: break data += dat last_new_line = dat == b'\n' conv = data.decode('utf-8').strip()[6:] if conv != 'ping': break return json.loads(conv) def _listen_count(hass): """Return number of event listeners.""" return sum(hass.bus.async_listeners().values()) async def test_api_error_log(hass, aiohttp_client, hass_access_token, hass_admin_user): """Test if we can fetch the error log.""" hass.data[DATA_LOGGING] = '/some/path' await async_setup_component(hass, 'api', {}) client = await aiohttp_client(hass.http.app) resp = await client.get(const.URL_API_ERROR_LOG) # Verify auth required assert resp.status == 401 with patch( 'aiohttp.web.FileResponse', return_value=web.Response(status=200, text='Hello') ) as mock_file: resp = await client.get(const.URL_API_ERROR_LOG, headers={ 'Authorization': 'Bearer {}'.format(hass_access_token) }) assert len(mock_file.mock_calls) == 1 assert mock_file.mock_calls[0][1][0] == hass.data[DATA_LOGGING] assert resp.status == 200 assert await resp.text() == 'Hello' # Verify we require admin user hass_admin_user.groups = [] resp = await client.get(const.URL_API_ERROR_LOG, headers={ 'Authorization': 'Bearer {}'.format(hass_access_token) }) assert resp.status == 401 async def test_api_fire_event_context(hass, mock_api_client, hass_access_token): """Test if the API sets right context if we fire an event.""" test_value = [] @ha.callback def listener(event): """Record that our event got called.""" test_value.append(event) hass.bus.async_listen("test.event", listener) await mock_api_client.post( const.URL_API_EVENTS_EVENT.format("test.event"), headers={ 'authorization': 'Bearer {}'.format(hass_access_token) }) await hass.async_block_till_done() refresh_token = await hass.auth.async_validate_access_token( hass_access_token) assert len(test_value) == 1 assert test_value[0].context.user_id == refresh_token.user.id async def test_api_call_service_context(hass, mock_api_client, hass_access_token): """Test if the API sets right context if we call a service.""" calls = async_mock_service(hass, 'test_domain', 'test_service') await mock_api_client.post( '/api/services/test_domain/test_service', headers={ 'authorization': 'Bearer {}'.format(hass_access_token) }) await hass.async_block_till_done() refresh_token = await hass.auth.async_validate_access_token( hass_access_token) assert len(calls) == 1 assert calls[0].context.user_id == refresh_token.user.id async def test_api_set_state_context(hass, mock_api_client, hass_access_token): """Test if the API sets right context if we set state.""" await mock_api_client.post( '/api/states/light.kitchen', json={ 'state': 'on' }, headers={ 'authorization': 'Bearer {}'.format(hass_access_token) }) refresh_token = await hass.auth.async_validate_access_token( hass_access_token) state = hass.states.get('light.kitchen') assert state.context.user_id == refresh_token.user.id async def test_event_stream_requires_admin(hass, mock_api_client, hass_admin_user): """Test user needs to be admin to access event stream.""" hass_admin_user.groups = [] resp = await mock_api_client.get('/api/stream') assert resp.status == 401 async def test_states_view_filters(hass, mock_api_client, hass_admin_user): """Test filtering only visible states.""" hass_admin_user.mock_policy({ 'entities': { 'entity_ids': { 'test.entity': True } } }) hass.states.async_set('test.entity', 'hello') hass.states.async_set('test.not_visible_entity', 'invisible') resp = await mock_api_client.get(const.URL_API_STATES) assert resp.status == 200 json = await resp.json() assert len(json) == 1 assert json[0]['entity_id'] == 'test.entity' async def test_get_entity_state_read_perm(hass, mock_api_client, hass_admin_user): """Test getting a state requires read permission.""" hass_admin_user.mock_policy({}) resp = await mock_api_client.get('/api/states/light.test') assert resp.status == 401 async def test_post_entity_state_admin(hass, mock_api_client, hass_admin_user): """Test updating state requires admin.""" hass_admin_user.groups = [] resp = await mock_api_client.post('/api/states/light.test') assert resp.status == 401 async def test_delete_entity_state_admin(hass, mock_api_client, hass_admin_user): """Test deleting entity requires admin.""" hass_admin_user.groups = [] resp = await mock_api_client.delete('/api/states/light.test') assert resp.status == 401 async def test_post_event_admin(hass, mock_api_client, hass_admin_user): """Test sending event requires admin.""" hass_admin_user.groups = [] resp = await mock_api_client.post('/api/events/state_changed') assert resp.status == 401 async def test_rendering_template_admin(hass, mock_api_client, hass_admin_user): """Test rendering a template requires admin.""" hass_admin_user.groups = [] resp = await mock_api_client.post(const.URL_API_TEMPLATE) assert resp.status == 401 async def test_rendering_template_legacy_user( hass, mock_api_client, aiohttp_client, legacy_auth): """Test rendering a template with legacy API password.""" hass.states.async_set('sensor.temperature', 10) client = await aiohttp_client(hass.http.app) resp = await client.post( const.URL_API_TEMPLATE, json={"template": '{{ states.sensor.temperature.state }}'} ) assert resp.status == 401 async def test_api_call_service_not_found(hass, mock_api_client): """Test if the API failes 400 if unknown service.""" resp = await mock_api_client.post( const.URL_API_SERVICES_SERVICE.format( "test_domain", "test_service")) assert resp.status == 400 async def test_api_call_service_bad_data(hass, mock_api_client): """Test if the API failes 400 if unknown service.""" test_value = [] @ha.callback def listener(service_call): """Record that our service got called.""" test_value.append(1) hass.services.async_register("test_domain", "test_service", listener, schema=vol.Schema({'hello': str})) resp = await mock_api_client.post( const.URL_API_SERVICES_SERVICE.format( "test_domain", "test_service"), json={'hello': 5}) assert resp.status == 400
apache-2.0
philsong/p2pool
p2pool/data.py
63
38817
from __future__ import division import hashlib import os import random import sys import time from twisted.python import log import p2pool from p2pool.bitcoin import data as bitcoin_data, script, sha256 from p2pool.util import math, forest, pack # hashlink hash_link_type = pack.ComposedType([ ('state', pack.FixedStrType(32)), ('extra_data', pack.FixedStrType(0)), # bit of a hack, but since the donation script is at the end, const_ending is long enough to always make this empty ('length', pack.VarIntType()), ]) def prefix_to_hash_link(prefix, const_ending=''): assert prefix.endswith(const_ending), (prefix, const_ending) x = sha256.sha256(prefix) return dict(state=x.state, extra_data=x.buf[:max(0, len(x.buf)-len(const_ending))], length=x.length//8) def check_hash_link(hash_link, data, const_ending=''): extra_length = hash_link['length'] % (512//8) assert len(hash_link['extra_data']) == max(0, extra_length - len(const_ending)) extra = (hash_link['extra_data'] + const_ending)[len(hash_link['extra_data']) + len(const_ending) - extra_length:] assert len(extra) == extra_length return pack.IntType(256).unpack(hashlib.sha256(sha256.sha256(data, (hash_link['state'], extra, 8*hash_link['length'])).digest()).digest()) # shares share_type = pack.ComposedType([ ('type', pack.VarIntType()), ('contents', pack.VarStrType()), ]) def load_share(share, net, peer_addr): assert peer_addr is None or isinstance(peer_addr, tuple) if share['type'] < Share.VERSION: from p2pool import p2p raise p2p.PeerMisbehavingError('sent an obsolete share') elif share['type'] == Share.VERSION: return Share(net, peer_addr, Share.share_type.unpack(share['contents'])) else: raise ValueError('unknown share type: %r' % (share['type'],)) DONATION_SCRIPT = '4104ffd03de44a6e11b9917f3a29f9443283d9871c9d743ef30d5eddcd37094b64d1b3d8090496b53256786bf5c82932ec23c3b74d9f05a6f95a8b5529352656664bac'.decode('hex') class Share(object): VERSION = 13 VOTING_VERSION = 13 SUCCESSOR = None small_block_header_type = pack.ComposedType([ ('version', pack.VarIntType()), ('previous_block', pack.PossiblyNoneType(0, pack.IntType(256))), ('timestamp', pack.IntType(32)), ('bits', bitcoin_data.FloatingIntegerType()), ('nonce', pack.IntType(32)), ]) share_info_type = pack.ComposedType([ ('share_data', pack.ComposedType([ ('previous_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))), ('coinbase', pack.VarStrType()), ('nonce', pack.IntType(32)), ('pubkey_hash', pack.IntType(160)), ('subsidy', pack.IntType(64)), ('donation', pack.IntType(16)), ('stale_info', pack.EnumType(pack.IntType(8), dict((k, {0: None, 253: 'orphan', 254: 'doa'}.get(k, 'unk%i' % (k,))) for k in xrange(256)))), ('desired_version', pack.VarIntType()), ])), ('new_transaction_hashes', pack.ListType(pack.IntType(256))), ('transaction_hash_refs', pack.ListType(pack.VarIntType(), 2)), # pairs of share_count, tx_count ('far_share_hash', pack.PossiblyNoneType(0, pack.IntType(256))), ('max_bits', bitcoin_data.FloatingIntegerType()), ('bits', bitcoin_data.FloatingIntegerType()), ('timestamp', pack.IntType(32)), ('absheight', pack.IntType(32)), ('abswork', pack.IntType(128)), ]) share_type = pack.ComposedType([ ('min_header', small_block_header_type), ('share_info', share_info_type), ('ref_merkle_link', pack.ComposedType([ ('branch', pack.ListType(pack.IntType(256))), ('index', pack.IntType(0)), ])), ('last_txout_nonce', pack.IntType(64)), ('hash_link', hash_link_type), ('merkle_link', pack.ComposedType([ ('branch', pack.ListType(pack.IntType(256))), ('index', pack.IntType(0)), # it will always be 0 ])), ]) ref_type = pack.ComposedType([ ('identifier', pack.FixedStrType(64//8)), ('share_info', share_info_type), ]) gentx_before_refhash = pack.VarStrType().pack(DONATION_SCRIPT) + pack.IntType(64).pack(0) + pack.VarStrType().pack('\x6a\x28' + pack.IntType(256).pack(0) + pack.IntType(64).pack(0))[:3] @classmethod def generate_transaction(cls, tracker, share_data, block_target, desired_timestamp, desired_target, ref_merkle_link, desired_other_transaction_hashes_and_fees, net, known_txs=None, last_txout_nonce=0, base_subsidy=None): previous_share = tracker.items[share_data['previous_share_hash']] if share_data['previous_share_hash'] is not None else None height, last = tracker.get_height_and_last(share_data['previous_share_hash']) assert height >= net.REAL_CHAIN_LENGTH or last is None if height < net.TARGET_LOOKBEHIND: pre_target3 = net.MAX_TARGET else: attempts_per_second = get_pool_attempts_per_second(tracker, share_data['previous_share_hash'], net.TARGET_LOOKBEHIND, min_work=True, integer=True) pre_target = 2**256//(net.SHARE_PERIOD*attempts_per_second) - 1 if attempts_per_second else 2**256-1 pre_target2 = math.clip(pre_target, (previous_share.max_target*9//10, previous_share.max_target*11//10)) pre_target3 = math.clip(pre_target2, (net.MIN_TARGET, net.MAX_TARGET)) max_bits = bitcoin_data.FloatingInteger.from_target_upper_bound(pre_target3) bits = bitcoin_data.FloatingInteger.from_target_upper_bound(math.clip(desired_target, (pre_target3//30, pre_target3))) new_transaction_hashes = [] new_transaction_size = 0 transaction_hash_refs = [] other_transaction_hashes = [] past_shares = list(tracker.get_chain(share_data['previous_share_hash'], min(height, 100))) tx_hash_to_this = {} for i, share in enumerate(past_shares): for j, tx_hash in enumerate(share.new_transaction_hashes): if tx_hash not in tx_hash_to_this: tx_hash_to_this[tx_hash] = [1+i, j] # share_count, tx_count for tx_hash, fee in desired_other_transaction_hashes_and_fees: if tx_hash in tx_hash_to_this: this = tx_hash_to_this[tx_hash] else: if known_txs is not None: this_size = bitcoin_data.tx_type.packed_size(known_txs[tx_hash]) if new_transaction_size + this_size > 50000: # only allow 50 kB of new txns/share break new_transaction_size += this_size new_transaction_hashes.append(tx_hash) this = [0, len(new_transaction_hashes)-1] transaction_hash_refs.extend(this) other_transaction_hashes.append(tx_hash) included_transactions = set(other_transaction_hashes) removed_fees = [fee for tx_hash, fee in desired_other_transaction_hashes_and_fees if tx_hash not in included_transactions] definite_fees = sum(0 if fee is None else fee for tx_hash, fee in desired_other_transaction_hashes_and_fees if tx_hash in included_transactions) if None not in removed_fees: share_data = dict(share_data, subsidy=share_data['subsidy'] - sum(removed_fees)) else: assert base_subsidy is not None share_data = dict(share_data, subsidy=base_subsidy + definite_fees) weights, total_weight, donation_weight = tracker.get_cumulative_weights(previous_share.share_data['previous_share_hash'] if previous_share is not None else None, max(0, min(height, net.REAL_CHAIN_LENGTH) - 1), 65535*net.SPREAD*bitcoin_data.target_to_average_attempts(block_target), ) assert total_weight == sum(weights.itervalues()) + donation_weight, (total_weight, sum(weights.itervalues()) + donation_weight) amounts = dict((script, share_data['subsidy']*(199*weight)//(200*total_weight)) for script, weight in weights.iteritems()) # 99.5% goes according to weights prior to this share this_script = bitcoin_data.pubkey_hash_to_script2(share_data['pubkey_hash']) amounts[this_script] = amounts.get(this_script, 0) + share_data['subsidy']//200 # 0.5% goes to block finder amounts[DONATION_SCRIPT] = amounts.get(DONATION_SCRIPT, 0) + share_data['subsidy'] - sum(amounts.itervalues()) # all that's left over is the donation weight and some extra satoshis due to rounding if sum(amounts.itervalues()) != share_data['subsidy'] or any(x < 0 for x in amounts.itervalues()): raise ValueError() dests = sorted(amounts.iterkeys(), key=lambda script: (script == DONATION_SCRIPT, amounts[script], script))[-4000:] # block length limit, unlikely to ever be hit share_info = dict( share_data=share_data, far_share_hash=None if last is None and height < 99 else tracker.get_nth_parent_hash(share_data['previous_share_hash'], 99), max_bits=max_bits, bits=bits, timestamp=math.clip(desired_timestamp, ( (previous_share.timestamp + net.SHARE_PERIOD) - (net.SHARE_PERIOD - 1), # = previous_share.timestamp + 1 (previous_share.timestamp + net.SHARE_PERIOD) + (net.SHARE_PERIOD - 1), )) if previous_share is not None else desired_timestamp, new_transaction_hashes=new_transaction_hashes, transaction_hash_refs=transaction_hash_refs, absheight=((previous_share.absheight if previous_share is not None else 0) + 1) % 2**32, abswork=((previous_share.abswork if previous_share is not None else 0) + bitcoin_data.target_to_average_attempts(bits.target)) % 2**128, ) gentx = dict( version=1, tx_ins=[dict( previous_output=None, sequence=None, script=share_data['coinbase'], )], tx_outs=[dict(value=amounts[script], script=script) for script in dests if amounts[script] or script == DONATION_SCRIPT] + [dict( value=0, script='\x6a\x28' + cls.get_ref_hash(net, share_info, ref_merkle_link) + pack.IntType(64).pack(last_txout_nonce), )], lock_time=0, ) def get_share(header, last_txout_nonce=last_txout_nonce): min_header = dict(header); del min_header['merkle_root'] share = cls(net, None, dict( min_header=min_header, share_info=share_info, ref_merkle_link=dict(branch=[], index=0), last_txout_nonce=last_txout_nonce, hash_link=prefix_to_hash_link(bitcoin_data.tx_type.pack(gentx)[:-32-8-4], cls.gentx_before_refhash), merkle_link=bitcoin_data.calculate_merkle_link([None] + other_transaction_hashes, 0), )) assert share.header == header # checks merkle_root return share return share_info, gentx, other_transaction_hashes, get_share @classmethod def get_ref_hash(cls, net, share_info, ref_merkle_link): return pack.IntType(256).pack(bitcoin_data.check_merkle_link(bitcoin_data.hash256(cls.ref_type.pack(dict( identifier=net.IDENTIFIER, share_info=share_info, ))), ref_merkle_link)) __slots__ = 'net peer_addr contents min_header share_info hash_link merkle_link hash share_data max_target target timestamp previous_hash new_script desired_version gentx_hash header pow_hash header_hash new_transaction_hashes time_seen absheight abswork'.split(' ') def __init__(self, net, peer_addr, contents): self.net = net self.peer_addr = peer_addr self.contents = contents self.min_header = contents['min_header'] self.share_info = contents['share_info'] self.hash_link = contents['hash_link'] self.merkle_link = contents['merkle_link'] if not (2 <= len(self.share_info['share_data']['coinbase']) <= 100): raise ValueError('''bad coinbase size! %i bytes''' % (len(self.share_info['share_data']['coinbase']),)) if len(self.merkle_link['branch']) > 16: raise ValueError('merkle branch too long!') assert not self.hash_link['extra_data'], repr(self.hash_link['extra_data']) self.share_data = self.share_info['share_data'] self.max_target = self.share_info['max_bits'].target self.target = self.share_info['bits'].target self.timestamp = self.share_info['timestamp'] self.previous_hash = self.share_data['previous_share_hash'] self.new_script = bitcoin_data.pubkey_hash_to_script2(self.share_data['pubkey_hash']) self.desired_version = self.share_data['desired_version'] self.absheight = self.share_info['absheight'] self.abswork = self.share_info['abswork'] n = set() for share_count, tx_count in self.iter_transaction_hash_refs(): assert share_count < 110 if share_count == 0: n.add(tx_count) assert n == set(range(len(self.share_info['new_transaction_hashes']))) self.gentx_hash = check_hash_link( self.hash_link, self.get_ref_hash(net, self.share_info, contents['ref_merkle_link']) + pack.IntType(64).pack(self.contents['last_txout_nonce']) + pack.IntType(32).pack(0), self.gentx_before_refhash, ) merkle_root = bitcoin_data.check_merkle_link(self.gentx_hash, self.merkle_link) self.header = dict(self.min_header, merkle_root=merkle_root) self.pow_hash = net.PARENT.POW_FUNC(bitcoin_data.block_header_type.pack(self.header)) self.hash = self.header_hash = bitcoin_data.hash256(bitcoin_data.block_header_type.pack(self.header)) if self.target > net.MAX_TARGET: from p2pool import p2p raise p2p.PeerMisbehavingError('share target invalid') if self.pow_hash > self.target: from p2pool import p2p raise p2p.PeerMisbehavingError('share PoW invalid') self.new_transaction_hashes = self.share_info['new_transaction_hashes'] # XXX eww self.time_seen = time.time() def __repr__(self): return 'Share' + repr((self.net, self.peer_addr, self.contents)) def as_share(self): return dict(type=self.VERSION, contents=self.share_type.pack(self.contents)) def iter_transaction_hash_refs(self): return zip(self.share_info['transaction_hash_refs'][::2], self.share_info['transaction_hash_refs'][1::2]) def check(self, tracker): from p2pool import p2p if self.share_data['previous_share_hash'] is not None: previous_share = tracker.items[self.share_data['previous_share_hash']] if type(self) is type(previous_share): pass elif type(self) is type(previous_share).SUCCESSOR: if tracker.get_height(previous_share.hash) < self.net.CHAIN_LENGTH: from p2pool import p2p raise p2p.PeerMisbehavingError('switch without enough history') # switch only valid if 85% of hashes in [self.net.CHAIN_LENGTH*9//10, self.net.CHAIN_LENGTH] for new version counts = get_desired_version_counts(tracker, tracker.get_nth_parent_hash(previous_share.hash, self.net.CHAIN_LENGTH*9//10), self.net.CHAIN_LENGTH//10) if counts.get(self.VERSION, 0) < sum(counts.itervalues())*85//100: raise p2p.PeerMisbehavingError('switch without enough hash power upgraded') else: raise p2p.PeerMisbehavingError('''%s can't follow %s''' % (type(self).__name__, type(previous_share).__name__)) other_tx_hashes = [tracker.items[tracker.get_nth_parent_hash(self.hash, share_count)].share_info['new_transaction_hashes'][tx_count] for share_count, tx_count in self.iter_transaction_hash_refs()] share_info, gentx, other_tx_hashes2, get_share = self.generate_transaction(tracker, self.share_info['share_data'], self.header['bits'].target, self.share_info['timestamp'], self.share_info['bits'].target, self.contents['ref_merkle_link'], [(h, None) for h in other_tx_hashes], self.net, last_txout_nonce=self.contents['last_txout_nonce']) assert other_tx_hashes2 == other_tx_hashes if share_info != self.share_info: raise ValueError('share_info invalid') if bitcoin_data.hash256(bitcoin_data.tx_type.pack(gentx)) != self.gentx_hash: raise ValueError('''gentx doesn't match hash_link''') if bitcoin_data.calculate_merkle_link([None] + other_tx_hashes, 0) != self.merkle_link: raise ValueError('merkle_link and other_tx_hashes do not match') return gentx # only used by as_block def get_other_tx_hashes(self, tracker): parents_needed = max(share_count for share_count, tx_count in self.iter_transaction_hash_refs()) if self.share_info['transaction_hash_refs'] else 0 parents = tracker.get_height(self.hash) - 1 if parents < parents_needed: return None last_shares = list(tracker.get_chain(self.hash, parents_needed + 1)) return [last_shares[share_count].share_info['new_transaction_hashes'][tx_count] for share_count, tx_count in self.iter_transaction_hash_refs()] def _get_other_txs(self, tracker, known_txs): other_tx_hashes = self.get_other_tx_hashes(tracker) if other_tx_hashes is None: return None # not all parents present if not all(tx_hash in known_txs for tx_hash in other_tx_hashes): return None # not all txs present return [known_txs[tx_hash] for tx_hash in other_tx_hashes] def should_punish_reason(self, previous_block, bits, tracker, known_txs): if (self.header['previous_block'], self.header['bits']) != (previous_block, bits) and self.header_hash != previous_block and self.peer_addr is not None: return True, 'Block-stale detected! height(%x) < height(%x) or %08x != %08x' % (self.header['previous_block'], previous_block, self.header['bits'].bits, bits.bits) if self.pow_hash <= self.header['bits'].target: return -1, 'block solution' other_txs = self._get_other_txs(tracker, known_txs) if other_txs is None: pass else: all_txs_size = sum(bitcoin_data.tx_type.packed_size(tx) for tx in other_txs) if all_txs_size > 1000000: return True, 'txs over block size limit' new_txs_size = sum(bitcoin_data.tx_type.packed_size(known_txs[tx_hash]) for tx_hash in self.share_info['new_transaction_hashes']) if new_txs_size > 50000: return True, 'new txs over limit' return False, None def as_block(self, tracker, known_txs): other_txs = self._get_other_txs(tracker, known_txs) if other_txs is None: return None # not all txs present return dict(header=self.header, txs=[self.check(tracker)] + other_txs) class WeightsSkipList(forest.TrackerSkipList): # share_count, weights, total_weight def get_delta(self, element): from p2pool.bitcoin import data as bitcoin_data share = self.tracker.items[element] att = bitcoin_data.target_to_average_attempts(share.target) return 1, {share.new_script: att*(65535-share.share_data['donation'])}, att*65535, att*share.share_data['donation'] def combine_deltas(self, (share_count1, weights1, total_weight1, total_donation_weight1), (share_count2, weights2, total_weight2, total_donation_weight2)): return share_count1 + share_count2, math.add_dicts(weights1, weights2), total_weight1 + total_weight2, total_donation_weight1 + total_donation_weight2 def initial_solution(self, start, (max_shares, desired_weight)): assert desired_weight % 65535 == 0, divmod(desired_weight, 65535) return 0, None, 0, 0 def apply_delta(self, (share_count1, weights_list, total_weight1, total_donation_weight1), (share_count2, weights2, total_weight2, total_donation_weight2), (max_shares, desired_weight)): if total_weight1 + total_weight2 > desired_weight and share_count2 == 1: assert (desired_weight - total_weight1) % 65535 == 0 script, = weights2.iterkeys() new_weights = {script: (desired_weight - total_weight1)//65535*weights2[script]//(total_weight2//65535)} return share_count1 + share_count2, (weights_list, new_weights), desired_weight, total_donation_weight1 + (desired_weight - total_weight1)//65535*total_donation_weight2//(total_weight2//65535) return share_count1 + share_count2, (weights_list, weights2), total_weight1 + total_weight2, total_donation_weight1 + total_donation_weight2 def judge(self, (share_count, weights_list, total_weight, total_donation_weight), (max_shares, desired_weight)): if share_count > max_shares or total_weight > desired_weight: return 1 elif share_count == max_shares or total_weight == desired_weight: return 0 else: return -1 def finalize(self, (share_count, weights_list, total_weight, total_donation_weight), (max_shares, desired_weight)): assert share_count <= max_shares and total_weight <= desired_weight assert share_count == max_shares or total_weight == desired_weight return math.add_dicts(*math.flatten_linked_list(weights_list)), total_weight, total_donation_weight class OkayTracker(forest.Tracker): def __init__(self, net): forest.Tracker.__init__(self, delta_type=forest.get_attributedelta_type(dict(forest.AttributeDelta.attrs, work=lambda share: bitcoin_data.target_to_average_attempts(share.target), min_work=lambda share: bitcoin_data.target_to_average_attempts(share.max_target), ))) self.net = net self.verified = forest.SubsetTracker(delta_type=forest.get_attributedelta_type(dict(forest.AttributeDelta.attrs, work=lambda share: bitcoin_data.target_to_average_attempts(share.target), )), subset_of=self) self.get_cumulative_weights = WeightsSkipList(self) def attempt_verify(self, share): if share.hash in self.verified.items: return True height, last = self.get_height_and_last(share.hash) if height < self.net.CHAIN_LENGTH + 1 and last is not None: raise AssertionError() try: share.check(self) except: log.err(None, 'Share check failed: %064x -> %064x' % (share.hash, share.previous_hash if share.previous_hash is not None else 0)) return False else: self.verified.add(share) return True def think(self, block_rel_height_func, previous_block, bits, known_txs): desired = set() bad_peer_addresses = set() # O(len(self.heads)) # make 'unverified heads' set? # for each overall head, attempt verification # if it fails, attempt on parent, and repeat # if no successful verification because of lack of parents, request parent bads = [] for head in set(self.heads) - set(self.verified.heads): head_height, last = self.get_height_and_last(head) for share in self.get_chain(head, head_height if last is None else min(5, max(0, head_height - self.net.CHAIN_LENGTH))): if self.attempt_verify(share): break bads.append(share.hash) else: if last is not None: desired.add(( self.items[random.choice(list(self.reverse[last]))].peer_addr, last, max(x.timestamp for x in self.get_chain(head, min(head_height, 5))), min(x.target for x in self.get_chain(head, min(head_height, 5))), )) for bad in bads: assert bad not in self.verified.items #assert bad in self.heads bad_share = self.items[bad] if bad_share.peer_addr is not None: bad_peer_addresses.add(bad_share.peer_addr) if p2pool.DEBUG: print "BAD", bad try: self.remove(bad) except NotImplementedError: pass # try to get at least CHAIN_LENGTH height for each verified head, requesting parents if needed for head in list(self.verified.heads): head_height, last_hash = self.verified.get_height_and_last(head) last_height, last_last_hash = self.get_height_and_last(last_hash) # XXX review boundary conditions want = max(self.net.CHAIN_LENGTH - head_height, 0) can = max(last_height - 1 - self.net.CHAIN_LENGTH, 0) if last_last_hash is not None else last_height get = min(want, can) #print 'Z', head_height, last_hash is None, last_height, last_last_hash is None, want, can, get for share in self.get_chain(last_hash, get): if not self.attempt_verify(share): break if head_height < self.net.CHAIN_LENGTH and last_last_hash is not None: desired.add(( self.items[random.choice(list(self.verified.reverse[last_hash]))].peer_addr, last_last_hash, max(x.timestamp for x in self.get_chain(head, min(head_height, 5))), min(x.target for x in self.get_chain(head, min(head_height, 5))), )) # decide best tree decorated_tails = sorted((self.score(max(self.verified.tails[tail_hash], key=self.verified.get_work), block_rel_height_func), tail_hash) for tail_hash in self.verified.tails) if p2pool.DEBUG: print len(decorated_tails), 'tails:' for score, tail_hash in decorated_tails: print format_hash(tail_hash), score best_tail_score, best_tail = decorated_tails[-1] if decorated_tails else (None, None) # decide best verified head decorated_heads = sorted((( self.verified.get_work(self.verified.get_nth_parent_hash(h, min(5, self.verified.get_height(h)))), #self.items[h].peer_addr is None, -self.items[h].should_punish_reason(previous_block, bits, self, known_txs)[0], -self.items[h].time_seen, ), h) for h in self.verified.tails.get(best_tail, [])) if p2pool.DEBUG: print len(decorated_heads), 'heads. Top 10:' for score, head_hash in decorated_heads[-10:]: print ' ', format_hash(head_hash), format_hash(self.items[head_hash].previous_hash), score best_head_score, best = decorated_heads[-1] if decorated_heads else (None, None) if best is not None: best_share = self.items[best] punish, punish_reason = best_share.should_punish_reason(previous_block, bits, self, known_txs) if punish > 0: print 'Punishing share for %r! Jumping from %s to %s!' % (punish_reason, format_hash(best), format_hash(best_share.previous_hash)) best = best_share.previous_hash timestamp_cutoff = min(int(time.time()), best_share.timestamp) - 3600 target_cutoff = int(2**256//(self.net.SHARE_PERIOD*best_tail_score[1] + 1) * 2 + .5) if best_tail_score[1] is not None else 2**256-1 else: timestamp_cutoff = int(time.time()) - 24*60*60 target_cutoff = 2**256-1 if p2pool.DEBUG: print 'Desire %i shares. Cutoff: %s old diff>%.2f' % (len(desired), math.format_dt(time.time() - timestamp_cutoff), bitcoin_data.target_to_difficulty(target_cutoff)) for peer_addr, hash, ts, targ in desired: print ' ', None if peer_addr is None else '%s:%i' % peer_addr, format_hash(hash), math.format_dt(time.time() - ts), bitcoin_data.target_to_difficulty(targ), ts >= timestamp_cutoff, targ <= target_cutoff return best, [(peer_addr, hash) for peer_addr, hash, ts, targ in desired if ts >= timestamp_cutoff], decorated_heads, bad_peer_addresses def score(self, share_hash, block_rel_height_func): # returns approximate lower bound on chain's hashrate in the last self.net.CHAIN_LENGTH*15//16*self.net.SHARE_PERIOD time head_height = self.verified.get_height(share_hash) if head_height < self.net.CHAIN_LENGTH: return head_height, None end_point = self.verified.get_nth_parent_hash(share_hash, self.net.CHAIN_LENGTH*15//16) block_height = max(block_rel_height_func(share.header['previous_block']) for share in self.verified.get_chain(end_point, self.net.CHAIN_LENGTH//16)) return self.net.CHAIN_LENGTH, self.verified.get_delta(share_hash, end_point).work/((0 - block_height + 1)*self.net.PARENT.BLOCK_PERIOD) def get_pool_attempts_per_second(tracker, previous_share_hash, dist, min_work=False, integer=False): assert dist >= 2 near = tracker.items[previous_share_hash] far = tracker.items[tracker.get_nth_parent_hash(previous_share_hash, dist - 1)] attempts = tracker.get_delta(near.hash, far.hash).work if not min_work else tracker.get_delta(near.hash, far.hash).min_work time = near.timestamp - far.timestamp if time <= 0: time = 1 if integer: return attempts//time return attempts/time def get_average_stale_prop(tracker, share_hash, lookbehind): stales = sum(1 for share in tracker.get_chain(share_hash, lookbehind) if share.share_data['stale_info'] is not None) return stales/(lookbehind + stales) def get_stale_counts(tracker, share_hash, lookbehind, rates=False): res = {} for share in tracker.get_chain(share_hash, lookbehind - 1): res['good'] = res.get('good', 0) + bitcoin_data.target_to_average_attempts(share.target) s = share.share_data['stale_info'] if s is not None: res[s] = res.get(s, 0) + bitcoin_data.target_to_average_attempts(share.target) if rates: dt = tracker.items[share_hash].timestamp - tracker.items[tracker.get_nth_parent_hash(share_hash, lookbehind - 1)].timestamp res = dict((k, v/dt) for k, v in res.iteritems()) return res def get_user_stale_props(tracker, share_hash, lookbehind): res = {} for share in tracker.get_chain(share_hash, lookbehind - 1): stale, total = res.get(share.share_data['pubkey_hash'], (0, 0)) total += 1 if share.share_data['stale_info'] is not None: stale += 1 total += 1 res[share.share_data['pubkey_hash']] = stale, total return dict((pubkey_hash, stale/total) for pubkey_hash, (stale, total) in res.iteritems()) def get_expected_payouts(tracker, best_share_hash, block_target, subsidy, net): weights, total_weight, donation_weight = tracker.get_cumulative_weights(best_share_hash, min(tracker.get_height(best_share_hash), net.REAL_CHAIN_LENGTH), 65535*net.SPREAD*bitcoin_data.target_to_average_attempts(block_target)) res = dict((script, subsidy*weight//total_weight) for script, weight in weights.iteritems()) res[DONATION_SCRIPT] = res.get(DONATION_SCRIPT, 0) + subsidy - sum(res.itervalues()) return res def get_desired_version_counts(tracker, best_share_hash, dist): res = {} for share in tracker.get_chain(best_share_hash, dist): res[share.desired_version] = res.get(share.desired_version, 0) + bitcoin_data.target_to_average_attempts(share.target) return res def get_warnings(tracker, best_share, net, bitcoind_getinfo, bitcoind_work_value): res = [] desired_version_counts = get_desired_version_counts(tracker, best_share, min(net.CHAIN_LENGTH, 60*60//net.SHARE_PERIOD, tracker.get_height(best_share))) majority_desired_version = max(desired_version_counts, key=lambda k: desired_version_counts[k]) if majority_desired_version > (Share.SUCCESSOR if Share.SUCCESSOR is not None else Share).VOTING_VERSION and desired_version_counts[majority_desired_version] > sum(desired_version_counts.itervalues())/2: res.append('A MAJORITY OF SHARES CONTAIN A VOTE FOR AN UNSUPPORTED SHARE IMPLEMENTATION! (v%i with %i%% support)\n' 'An upgrade is likely necessary. Check http://p2pool.forre.st/ for more information.' % ( majority_desired_version, 100*desired_version_counts[majority_desired_version]/sum(desired_version_counts.itervalues()))) if bitcoind_getinfo['errors'] != '': if 'This is a pre-release test build' not in bitcoind_getinfo['errors']: res.append('(from bitcoind) %s' % (bitcoind_getinfo['errors'],)) version_warning = getattr(net, 'VERSION_WARNING', lambda v: None)(bitcoind_getinfo['version']) if version_warning is not None: res.append(version_warning) if time.time() > bitcoind_work_value['last_update'] + 60: res.append('''LOST CONTACT WITH BITCOIND for %s! Check that it isn't frozen or dead!''' % (math.format_dt(time.time() - bitcoind_work_value['last_update']),)) return res def format_hash(x): if x is None: return 'xxxxxxxx' return '%08x' % (x % 2**32) class ShareStore(object): def __init__(self, prefix, net, share_cb, verified_hash_cb): self.dirname = os.path.dirname(os.path.abspath(prefix)) self.filename = os.path.basename(os.path.abspath(prefix)) self.net = net known = {} filenames, next = self.get_filenames_and_next() for filename in filenames: share_hashes, verified_hashes = known.setdefault(filename, (set(), set())) with open(filename, 'rb') as f: for line in f: try: type_id_str, data_hex = line.strip().split(' ') type_id = int(type_id_str) if type_id == 0: pass elif type_id == 1: pass elif type_id == 2: verified_hash = int(data_hex, 16) verified_hash_cb(verified_hash) verified_hashes.add(verified_hash) elif type_id == 5: raw_share = share_type.unpack(data_hex.decode('hex')) if raw_share['type'] < Share.VERSION: continue share = load_share(raw_share, self.net, None) share_cb(share) share_hashes.add(share.hash) else: raise NotImplementedError("share type %i" % (type_id,)) except Exception: log.err(None, "HARMLESS error while reading saved shares, continuing where left off:") self.known = known # filename -> (set of share hashes, set of verified hashes) self.known_desired = dict((k, (set(a), set(b))) for k, (a, b) in known.iteritems()) def _add_line(self, line): filenames, next = self.get_filenames_and_next() if filenames and os.path.getsize(filenames[-1]) < 10e6: filename = filenames[-1] else: filename = next with open(filename, 'ab') as f: f.write(line + '\n') return filename def add_share(self, share): for filename, (share_hashes, verified_hashes) in self.known.iteritems(): if share.hash in share_hashes: break else: filename = self._add_line("%i %s" % (5, share_type.pack(share.as_share()).encode('hex'))) share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set())) share_hashes.add(share.hash) share_hashes, verified_hashes = self.known_desired.setdefault(filename, (set(), set())) share_hashes.add(share.hash) def add_verified_hash(self, share_hash): for filename, (share_hashes, verified_hashes) in self.known.iteritems(): if share_hash in verified_hashes: break else: filename = self._add_line("%i %x" % (2, share_hash)) share_hashes, verified_hashes = self.known.setdefault(filename, (set(), set())) verified_hashes.add(share_hash) share_hashes, verified_hashes = self.known_desired.setdefault(filename, (set(), set())) verified_hashes.add(share_hash) def get_filenames_and_next(self): suffixes = sorted(int(x[len(self.filename):]) for x in os.listdir(self.dirname) if x.startswith(self.filename) and x[len(self.filename):].isdigit()) return [os.path.join(self.dirname, self.filename + str(suffix)) for suffix in suffixes], os.path.join(self.dirname, self.filename + (str(suffixes[-1] + 1) if suffixes else str(0))) def forget_share(self, share_hash): for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems(): if share_hash in share_hashes: share_hashes.remove(share_hash) self.check_remove() def forget_verified_share(self, share_hash): for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems(): if share_hash in verified_hashes: verified_hashes.remove(share_hash) self.check_remove() def check_remove(self): to_remove = set() for filename, (share_hashes, verified_hashes) in self.known_desired.iteritems(): #print filename, len(share_hashes) + len(verified_hashes) if not share_hashes and not verified_hashes: to_remove.add(filename) for filename in to_remove: self.known.pop(filename) self.known_desired.pop(filename) os.remove(filename) print "REMOVED", filename
gpl-3.0
freeflightsim/fg-flying-club
google_appengine/lib/yaml/lib/yaml/cyaml.py
125
3233
__all__ = ['CBaseLoader', 'CSafeLoader', 'CLoader', 'CBaseDumper', 'CSafeDumper', 'CDumper'] from _yaml import CParser, CEmitter from constructor import * from serializer import * from representer import * from resolver import * class CBaseLoader(CParser, BaseConstructor, BaseResolver): def __init__(self, stream): CParser.__init__(self, stream) BaseConstructor.__init__(self) BaseResolver.__init__(self) class CSafeLoader(CParser, SafeConstructor, Resolver): def __init__(self, stream): CParser.__init__(self, stream) SafeConstructor.__init__(self) Resolver.__init__(self) class CLoader(CParser, Constructor, Resolver): def __init__(self, stream): CParser.__init__(self, stream) Constructor.__init__(self) Resolver.__init__(self) class CBaseDumper(CEmitter, BaseRepresenter, BaseResolver): def __init__(self, stream, default_style=None, default_flow_style=None, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None, encoding=None, explicit_start=None, explicit_end=None, version=None, tags=None): CEmitter.__init__(self, stream, canonical=canonical, indent=indent, width=width, allow_unicode=allow_unicode, line_break=line_break, explicit_start=explicit_start, explicit_end=explicit_end, version=version, tags=tags) Representer.__init__(self, default_style=default_style, default_flow_style=default_flow_style) Resolver.__init__(self) class CSafeDumper(CEmitter, SafeRepresenter, Resolver): def __init__(self, stream, default_style=None, default_flow_style=None, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None, encoding=None, explicit_start=None, explicit_end=None, version=None, tags=None): CEmitter.__init__(self, stream, canonical=canonical, indent=indent, width=width, allow_unicode=allow_unicode, line_break=line_break, explicit_start=explicit_start, explicit_end=explicit_end, version=version, tags=tags) SafeRepresenter.__init__(self, default_style=default_style, default_flow_style=default_flow_style) Resolver.__init__(self) class CDumper(CEmitter, Serializer, Representer, Resolver): def __init__(self, stream, default_style=None, default_flow_style=None, canonical=None, indent=None, width=None, allow_unicode=None, line_break=None, encoding=None, explicit_start=None, explicit_end=None, version=None, tags=None): CEmitter.__init__(self, stream, canonical=canonical, indent=indent, width=width, allow_unicode=allow_unicode, line_break=line_break, explicit_start=explicit_start, explicit_end=explicit_end, version=version, tags=tags) Representer.__init__(self, default_style=default_style, default_flow_style=default_flow_style) Resolver.__init__(self)
gpl-2.0
0x90sled/catapult
third_party/Paste/paste/exceptions/formatter.py
49
19468
# (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org) # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php """ Formatters for the exception data that comes from ExceptionCollector. """ # @@: TODO: # Use this: http://www.zope.org/Members/tino/VisualTraceback/VisualTracebackNews import cgi import six import re from paste.util import PySourceColor def html_quote(s): return cgi.escape(str(s), True) class AbstractFormatter(object): general_data_order = ['object', 'source_url'] def __init__(self, show_hidden_frames=False, include_reusable=True, show_extra_data=True, trim_source_paths=()): self.show_hidden_frames = show_hidden_frames self.trim_source_paths = trim_source_paths self.include_reusable = include_reusable self.show_extra_data = show_extra_data def format_collected_data(self, exc_data): general_data = {} if self.show_extra_data: for name, value_list in exc_data.extra_data.items(): if isinstance(name, tuple): importance, title = name else: importance, title = 'normal', name for value in value_list: general_data[(importance, name)] = self.format_extra_data( importance, title, value) lines = [] frames = self.filter_frames(exc_data.frames) for frame in frames: sup = frame.supplement if sup: if sup.object: general_data[('important', 'object')] = self.format_sup_object( sup.object) if sup.source_url: general_data[('important', 'source_url')] = self.format_sup_url( sup.source_url) if sup.line: lines.append(self.format_sup_line_pos(sup.line, sup.column)) if sup.expression: lines.append(self.format_sup_expression(sup.expression)) if sup.warnings: for warning in sup.warnings: lines.append(self.format_sup_warning(warning)) if sup.info: lines.extend(self.format_sup_info(sup.info)) if frame.supplement_exception: lines.append('Exception in supplement:') lines.append(self.quote_long(frame.supplement_exception)) if frame.traceback_info: lines.append(self.format_traceback_info(frame.traceback_info)) filename = frame.filename if filename and self.trim_source_paths: for path, repl in self.trim_source_paths: if filename.startswith(path): filename = repl + filename[len(path):] break lines.append(self.format_source_line(filename or '?', frame)) source = frame.get_source_line() long_source = frame.get_source_line(2) if source: lines.append(self.format_long_source( source, long_source)) etype = exc_data.exception_type if not isinstance(etype, six.string_types): etype = etype.__name__ exc_info = self.format_exception_info( etype, exc_data.exception_value) data_by_importance = {'important': [], 'normal': [], 'supplemental': [], 'extra': []} for (importance, name), value in general_data.items(): data_by_importance[importance].append( (name, value)) for value in data_by_importance.values(): value.sort() return self.format_combine(data_by_importance, lines, exc_info) def filter_frames(self, frames): """ Removes any frames that should be hidden, according to the values of traceback_hide, self.show_hidden_frames, and the hidden status of the final frame. """ if self.show_hidden_frames: return frames new_frames = [] hidden = False for frame in frames: hide = frame.traceback_hide # @@: It would be nice to signal a warning if an unknown # hide string was used, but I'm not sure where to put # that warning. if hide == 'before': new_frames = [] hidden = False elif hide == 'before_and_this': new_frames = [] hidden = False continue elif hide == 'reset': hidden = False elif hide == 'reset_and_this': hidden = False continue elif hide == 'after': hidden = True elif hide == 'after_and_this': hidden = True continue elif hide: continue elif hidden: continue new_frames.append(frame) if frames[-1] not in new_frames: # We must include the last frame; that we don't indicates # that the error happened where something was "hidden", # so we just have to show everything return frames return new_frames def pretty_string_repr(self, s): """ Formats the string as a triple-quoted string when it contains newlines. """ if '\n' in s: s = repr(s) s = s[0]*3 + s[1:-1] + s[-1]*3 s = s.replace('\\n', '\n') return s else: return repr(s) def long_item_list(self, lst): """ Returns true if the list contains items that are long, and should be more nicely formatted. """ how_many = 0 for item in lst: if len(repr(item)) > 40: how_many += 1 if how_many >= 3: return True return False class TextFormatter(AbstractFormatter): def quote(self, s): return s def quote_long(self, s): return s def emphasize(self, s): return s def format_sup_object(self, obj): return 'In object: %s' % self.emphasize(self.quote(repr(obj))) def format_sup_url(self, url): return 'URL: %s' % self.quote(url) def format_sup_line_pos(self, line, column): if column: return self.emphasize('Line %i, Column %i' % (line, column)) else: return self.emphasize('Line %i' % line) def format_sup_expression(self, expr): return self.emphasize('In expression: %s' % self.quote(expr)) def format_sup_warning(self, warning): return 'Warning: %s' % self.quote(warning) def format_sup_info(self, info): return [self.quote_long(info)] def format_source_line(self, filename, frame): return 'File %r, line %s in %s' % ( filename, frame.lineno or '?', frame.name or '?') def format_long_source(self, source, long_source): return self.format_source(source) def format_source(self, source_line): return ' ' + self.quote(source_line.strip()) def format_exception_info(self, etype, evalue): return self.emphasize( '%s: %s' % (self.quote(etype), self.quote(evalue))) def format_traceback_info(self, info): return info def format_combine(self, data_by_importance, lines, exc_info): lines[:0] = [value for n, value in data_by_importance['important']] lines.append(exc_info) for name in 'normal', 'supplemental', 'extra': lines.extend([value for n, value in data_by_importance[name]]) return self.format_combine_lines(lines) def format_combine_lines(self, lines): return '\n'.join(lines) def format_extra_data(self, importance, title, value): if isinstance(value, str): s = self.pretty_string_repr(value) if '\n' in s: return '%s:\n%s' % (title, s) else: return '%s: %s' % (title, s) elif isinstance(value, dict): lines = ['\n', title, '-'*len(title)] items = value.items() items.sort() for n, v in items: try: v = repr(v) except Exception as e: v = 'Cannot display: %s' % e v = truncate(v) lines.append(' %s: %s' % (n, v)) return '\n'.join(lines) elif (isinstance(value, (list, tuple)) and self.long_item_list(value)): parts = [truncate(repr(v)) for v in value] return '%s: [\n %s]' % ( title, ',\n '.join(parts)) else: return '%s: %s' % (title, truncate(repr(value))) class HTMLFormatter(TextFormatter): def quote(self, s): return html_quote(s) def quote_long(self, s): return '<pre>%s</pre>' % self.quote(s) def emphasize(self, s): return '<b>%s</b>' % s def format_sup_url(self, url): return 'URL: <a href="%s">%s</a>' % (url, url) def format_combine_lines(self, lines): return '<br>\n'.join(lines) def format_source_line(self, filename, frame): name = self.quote(frame.name or '?') return 'Module <span class="module" title="%s">%s</span>:<b>%s</b> in <code>%s</code>' % ( filename, frame.modname or '?', frame.lineno or '?', name) return 'File %r, line %s in <tt>%s</tt>' % ( filename, frame.lineno, name) def format_long_source(self, source, long_source): q_long_source = str2html(long_source, False, 4, True) q_source = str2html(source, True, 0, False) return ('<code style="display: none" class="source" source-type="long"><a class="switch_source" onclick="return switch_source(this, \'long\')" href="#">&lt;&lt;&nbsp; </a>%s</code>' '<code class="source" source-type="short"><a onclick="return switch_source(this, \'short\')" class="switch_source" href="#">&gt;&gt;&nbsp; </a>%s</code>' % (q_long_source, q_source)) def format_source(self, source_line): return '&nbsp;&nbsp;<code class="source">%s</code>' % self.quote(source_line.strip()) def format_traceback_info(self, info): return '<pre>%s</pre>' % self.quote(info) def format_extra_data(self, importance, title, value): if isinstance(value, str): s = self.pretty_string_repr(value) if '\n' in s: return '%s:<br><pre>%s</pre>' % (title, self.quote(s)) else: return '%s: <tt>%s</tt>' % (title, self.quote(s)) elif isinstance(value, dict): return self.zebra_table(title, value) elif (isinstance(value, (list, tuple)) and self.long_item_list(value)): return '%s: <tt>[<br>\n&nbsp; &nbsp; %s]</tt>' % ( title, ',<br>&nbsp; &nbsp; '.join(map(self.quote, map(repr, value)))) else: return '%s: <tt>%s</tt>' % (title, self.quote(repr(value))) def format_combine(self, data_by_importance, lines, exc_info): lines[:0] = [value for n, value in data_by_importance['important']] lines.append(exc_info) for name in 'normal', 'supplemental': lines.extend([value for n, value in data_by_importance[name]]) if data_by_importance['extra']: lines.append( '<script type="text/javascript">\nshow_button(\'extra_data\', \'extra data\');\n</script>\n' + '<div id="extra_data" class="hidden-data">\n') lines.extend([value for n, value in data_by_importance['extra']]) lines.append('</div>') text = self.format_combine_lines(lines) if self.include_reusable: return error_css + hide_display_js + text else: # Usually because another error is already on this page, # and so the js & CSS are unneeded return text def zebra_table(self, title, rows, table_class="variables"): if isinstance(rows, dict): rows = rows.items() rows.sort() table = ['<table class="%s">' % table_class, '<tr class="header"><th colspan="2">%s</th></tr>' % self.quote(title)] odd = False for name, value in rows: try: value = repr(value) except Exception as e: value = 'Cannot print: %s' % e odd = not odd table.append( '<tr class="%s"><td>%s</td>' % (odd and 'odd' or 'even', self.quote(name))) table.append( '<td><tt>%s</tt></td></tr>' % make_wrappable(self.quote(truncate(value)))) table.append('</table>') return '\n'.join(table) hide_display_js = r''' <script type="text/javascript"> function hide_display(id) { var el = document.getElementById(id); if (el.className == "hidden-data") { el.className = ""; return true; } else { el.className = "hidden-data"; return false; } } document.write('<style type="text/css">\n'); document.write('.hidden-data {display: none}\n'); document.write('</style>\n'); function show_button(toggle_id, name) { document.write('<a href="#' + toggle_id + '" onclick="javascript:hide_display(\'' + toggle_id + '\')" class="button">' + name + '</a><br>'); } function switch_source(el, hide_type) { while (el) { if (el.getAttribute && el.getAttribute('source-type') == hide_type) { break; } el = el.parentNode; } if (! el) { return false; } el.style.display = 'none'; if (hide_type == 'long') { while (el) { if (el.getAttribute && el.getAttribute('source-type') == 'short') { break; } el = el.nextSibling; } } else { while (el) { if (el.getAttribute && el.getAttribute('source-type') == 'long') { break; } el = el.previousSibling; } } if (el) { el.style.display = ''; } return false; } </script>''' error_css = """ <style type="text/css"> body { font-family: Helvetica, sans-serif; } table { width: 100%; } tr.header { background-color: #006; color: #fff; } tr.even { background-color: #ddd; } table.variables td { vertical-align: top; overflow: auto; } a.button { background-color: #ccc; border: 2px outset #aaa; color: #000; text-decoration: none; } a.button:hover { background-color: #ddd; } code.source { color: #006; } a.switch_source { color: #090; text-decoration: none; } a.switch_source:hover { background-color: #ddd; } .source-highlight { background-color: #ff9; } </style> """ def format_html(exc_data, include_hidden_frames=False, **ops): if not include_hidden_frames: return HTMLFormatter(**ops).format_collected_data(exc_data) short_er = format_html(exc_data, show_hidden_frames=False, **ops) # @@: This should have a way of seeing if the previous traceback # was actually trimmed at all ops['include_reusable'] = False ops['show_extra_data'] = False long_er = format_html(exc_data, show_hidden_frames=True, **ops) text_er = format_text(exc_data, show_hidden_frames=True, **ops) return """ %s <br> <script type="text/javascript"> show_button('full_traceback', 'full traceback') </script> <div id="full_traceback" class="hidden-data"> %s </div> <br> <script type="text/javascript"> show_button('text_version', 'text version') </script> <div id="text_version" class="hidden-data"> <textarea style="width: 100%%" rows=10 cols=60>%s</textarea> </div> """ % (short_er, long_er, cgi.escape(text_er)) def format_text(exc_data, **ops): return TextFormatter(**ops).format_collected_data(exc_data) whitespace_re = re.compile(r' +') pre_re = re.compile(r'</?pre.*?>') error_re = re.compile(r'<h3>ERROR: .*?</h3>') def str2html(src, strip=False, indent_subsequent=0, highlight_inner=False): """ Convert a string to HTML. Try to be really safe about it, returning a quoted version of the string if nothing else works. """ try: return _str2html(src, strip=strip, indent_subsequent=indent_subsequent, highlight_inner=highlight_inner) except: return html_quote(src) def _str2html(src, strip=False, indent_subsequent=0, highlight_inner=False): if strip: src = src.strip() orig_src = src try: src = PySourceColor.str2html(src, form='snip') src = error_re.sub('', src) src = pre_re.sub('', src) src = re.sub(r'^[\n\r]{0,1}', '', src) src = re.sub(r'[\n\r]{0,1}$', '', src) except: src = html_quote(orig_src) lines = src.splitlines() if len(lines) == 1: return lines[0] indent = ' '*indent_subsequent for i in range(1, len(lines)): lines[i] = indent+lines[i] if highlight_inner and i == len(lines)/2: lines[i] = '<span class="source-highlight">%s</span>' % lines[i] src = '<br>\n'.join(lines) src = whitespace_re.sub( lambda m: '&nbsp;'*(len(m.group(0))-1) + ' ', src) return src def truncate(string, limit=1000): """ Truncate the string to the limit number of characters """ if len(string) > limit: return string[:limit-20]+'...'+string[-17:] else: return string def make_wrappable(html, wrap_limit=60, split_on=';?&@!$#-/\\"\''): # Currently using <wbr>, maybe should use &#8203; # http://www.cs.tut.fi/~jkorpela/html/nobr.html if len(html) <= wrap_limit: return html words = html.split() new_words = [] for word in words: wrapped_word = '' while len(word) > wrap_limit: for char in split_on: if char in word: first, rest = word.split(char, 1) wrapped_word += first+char+'<wbr>' word = rest break else: for i in range(0, len(word), wrap_limit): wrapped_word += word[i:i+wrap_limit]+'<wbr>' word = '' wrapped_word += word new_words.append(wrapped_word) return ' '.join(new_words) def make_pre_wrappable(html, wrap_limit=60, split_on=';?&@!$#-/\\"\''): """ Like ``make_wrappable()`` but intended for text that will go in a ``<pre>`` block, so wrap on a line-by-line basis. """ lines = html.splitlines() new_lines = [] for line in lines: if len(line) > wrap_limit: for char in split_on: if char in line: parts = line.split(char) line = '<wbr>'.join(parts) break new_lines.append(line) return '\n'.join(lines)
bsd-3-clause
fitermay/intellij-community
python/lib/Lib/site-packages/django/db/models/expressions.py
229
4992
import datetime from django.utils import tree from django.utils.copycompat import deepcopy class ExpressionNode(tree.Node): """ Base class for all query expressions. """ # Arithmetic connectors ADD = '+' SUB = '-' MUL = '*' DIV = '/' MOD = '%%' # This is a quoted % operator - it is quoted # because it can be used in strings that also # have parameter substitution. # Bitwise operators AND = '&' OR = '|' def __init__(self, children=None, connector=None, negated=False): if children is not None and len(children) > 1 and connector is None: raise TypeError('You have to specify a connector.') super(ExpressionNode, self).__init__(children, connector, negated) def _combine(self, other, connector, reversed, node=None): if isinstance(other, datetime.timedelta): return DateModifierNode([self, other], connector) if reversed: obj = ExpressionNode([other], connector) obj.add(node or self, connector) else: obj = node or ExpressionNode([self], connector) obj.add(other, connector) return obj ################### # VISITOR METHODS # ################### def prepare(self, evaluator, query, allow_joins): return evaluator.prepare_node(self, query, allow_joins) def evaluate(self, evaluator, qn, connection): return evaluator.evaluate_node(self, qn, connection) ############# # OPERATORS # ############# def __add__(self, other): return self._combine(other, self.ADD, False) def __sub__(self, other): return self._combine(other, self.SUB, False) def __mul__(self, other): return self._combine(other, self.MUL, False) def __div__(self, other): return self._combine(other, self.DIV, False) def __mod__(self, other): return self._combine(other, self.MOD, False) def __and__(self, other): return self._combine(other, self.AND, False) def __or__(self, other): return self._combine(other, self.OR, False) def __radd__(self, other): return self._combine(other, self.ADD, True) def __rsub__(self, other): return self._combine(other, self.SUB, True) def __rmul__(self, other): return self._combine(other, self.MUL, True) def __rdiv__(self, other): return self._combine(other, self.DIV, True) def __rmod__(self, other): return self._combine(other, self.MOD, True) def __rand__(self, other): return self._combine(other, self.AND, True) def __ror__(self, other): return self._combine(other, self.OR, True) def prepare_database_save(self, unused): return self class F(ExpressionNode): """ An expression representing the value of the given field. """ def __init__(self, name): super(F, self).__init__(None, None, False) self.name = name def __deepcopy__(self, memodict): obj = super(F, self).__deepcopy__(memodict) obj.name = self.name return obj def prepare(self, evaluator, query, allow_joins): return evaluator.prepare_leaf(self, query, allow_joins) def evaluate(self, evaluator, qn, connection): return evaluator.evaluate_leaf(self, qn, connection) class DateModifierNode(ExpressionNode): """ Node that implements the following syntax: filter(end_date__gt=F('start_date') + datetime.timedelta(days=3, seconds=200)) which translates into: POSTGRES: WHERE end_date > (start_date + INTERVAL '3 days 200 seconds') MYSQL: WHERE end_date > (start_date + INTERVAL '3 0:0:200:0' DAY_MICROSECOND) ORACLE: WHERE end_date > (start_date + INTERVAL '3 00:03:20.000000' DAY(1) TO SECOND(6)) SQLITE: WHERE end_date > django_format_dtdelta(start_date, "+" "3", "200", "0") (A custom function is used in order to preserve six digits of fractional second information on sqlite, and to format both date and datetime values.) Note that microsecond comparisons are not well supported with MySQL, since MySQL does not store microsecond information. Only adding and subtracting timedeltas is supported, attempts to use other operations raise a TypeError. """ def __init__(self, children, connector, negated=False): if len(children) != 2: raise TypeError('Must specify a node and a timedelta.') if not isinstance(children[1], datetime.timedelta): raise TypeError('Second child must be a timedelta.') if connector not in (self.ADD, self.SUB): raise TypeError('Connector must be + or -, not %s' % connector) super(DateModifierNode, self).__init__(children, connector, negated) def evaluate(self, evaluator, qn, connection): return evaluator.evaluate_date_modifier_node(self, qn, connection)
apache-2.0
holmes/intellij-community
python/helpers/profiler/thrift/protocol/TBase.py
208
2637
# # 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. # from thrift.Thrift import * from thrift.protocol import TBinaryProtocol from thrift.transport import TTransport try: from thrift.protocol import fastbinary except: fastbinary = None class TBase(object): __slots__ = [] def __repr__(self): L = ['%s=%r' % (key, getattr(self, key)) for key in self.__slots__] return '%s(%s)' % (self.__class__.__name__, ', '.join(L)) def __eq__(self, other): if not isinstance(other, self.__class__): return False for attr in self.__slots__: my_val = getattr(self, attr) other_val = getattr(other, attr) if my_val != other_val: return False return True def __ne__(self, other): return not (self == other) def read(self, iprot): if (iprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None and fastbinary is not None): fastbinary.decode_binary(self, iprot.trans, (self.__class__, self.thrift_spec)) return iprot.readStruct(self, self.thrift_spec) def write(self, oprot): if (oprot.__class__ == TBinaryProtocol.TBinaryProtocolAccelerated and self.thrift_spec is not None and fastbinary is not None): oprot.trans.write( fastbinary.encode_binary(self, (self.__class__, self.thrift_spec))) return oprot.writeStruct(self, self.thrift_spec) class TExceptionBase(Exception): # old style class so python2.4 can raise exceptions derived from this # This can't inherit from TBase because of that limitation. __slots__ = [] __repr__ = TBase.__repr__.im_func __eq__ = TBase.__eq__.im_func __ne__ = TBase.__ne__.im_func read = TBase.read.im_func write = TBase.write.im_func
apache-2.0
dsarlis/SAD-Spring-2016-Project-Team4
ApacheCMDA-Backend/project/target/node-modules/webjars/npm/node_modules/node-gyp/gyp/pylib/gyp/xcodeproj_file.py
505
118664
# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Xcode project file generator. This module is both an Xcode project file generator and a documentation of the Xcode project file format. Knowledge of the project file format was gained based on extensive experience with Xcode, and by making changes to projects in Xcode.app and observing the resultant changes in the associated project files. XCODE PROJECT FILES The generator targets the file format as written by Xcode 3.2 (specifically, 3.2.6), but past experience has taught that the format has not changed significantly in the past several years, and future versions of Xcode are able to read older project files. Xcode project files are "bundled": the project "file" from an end-user's perspective is actually a directory with an ".xcodeproj" extension. The project file from this module's perspective is actually a file inside this directory, always named "project.pbxproj". This file contains a complete description of the project and is all that is needed to use the xcodeproj. Other files contained in the xcodeproj directory are simply used to store per-user settings, such as the state of various UI elements in the Xcode application. The project.pbxproj file is a property list, stored in a format almost identical to the NeXTstep property list format. The file is able to carry Unicode data, and is encoded in UTF-8. The root element in the property list is a dictionary that contains several properties of minimal interest, and two properties of immense interest. The most important property is a dictionary named "objects". The entire structure of the project is represented by the children of this property. The objects dictionary is keyed by unique 96-bit values represented by 24 uppercase hexadecimal characters. Each value in the objects dictionary is itself a dictionary, describing an individual object. Each object in the dictionary is a member of a class, which is identified by the "isa" property of each object. A variety of classes are represented in a project file. Objects can refer to other objects by ID, using the 24-character hexadecimal object key. A project's objects form a tree, with a root object of class PBXProject at the root. As an example, the PBXProject object serves as parent to an XCConfigurationList object defining the build configurations used in the project, a PBXGroup object serving as a container for all files referenced in the project, and a list of target objects, each of which defines a target in the project. There are several different types of target object, such as PBXNativeTarget and PBXAggregateTarget. In this module, this relationship is expressed by having each target type derive from an abstract base named XCTarget. The project.pbxproj file's root dictionary also contains a property, sibling to the "objects" dictionary, named "rootObject". The value of rootObject is a 24-character object key referring to the root PBXProject object in the objects dictionary. In Xcode, every file used as input to a target or produced as a final product of a target must appear somewhere in the hierarchy rooted at the PBXGroup object referenced by the PBXProject's mainGroup property. A PBXGroup is generally represented as a folder in the Xcode application. PBXGroups can contain other PBXGroups as well as PBXFileReferences, which are pointers to actual files. Each XCTarget contains a list of build phases, represented in this module by the abstract base XCBuildPhase. Examples of concrete XCBuildPhase derivations are PBXSourcesBuildPhase and PBXFrameworksBuildPhase, which correspond to the "Compile Sources" and "Link Binary With Libraries" phases displayed in the Xcode application. Files used as input to these phases (for example, source files in the former case and libraries and frameworks in the latter) are represented by PBXBuildFile objects, referenced by elements of "files" lists in XCTarget objects. Each PBXBuildFile object refers to a PBXBuildFile object as a "weak" reference: it does not "own" the PBXBuildFile, which is owned by the root object's mainGroup or a descendant group. In most cases, the layer of indirection between an XCBuildPhase and a PBXFileReference via a PBXBuildFile appears extraneous, but there's actually one reason for this: file-specific compiler flags are added to the PBXBuildFile object so as to allow a single file to be a member of multiple targets while having distinct compiler flags for each. These flags can be modified in the Xcode applciation in the "Build" tab of a File Info window. When a project is open in the Xcode application, Xcode will rewrite it. As such, this module is careful to adhere to the formatting used by Xcode, to avoid insignificant changes appearing in the file when it is used in the Xcode application. This will keep version control repositories happy, and makes it possible to compare a project file used in Xcode to one generated by this module to determine if any significant changes were made in the application. Xcode has its own way of assigning 24-character identifiers to each object, which is not duplicated here. Because the identifier only is only generated once, when an object is created, and is then left unchanged, there is no need to attempt to duplicate Xcode's behavior in this area. The generator is free to select any identifier, even at random, to refer to the objects it creates, and Xcode will retain those identifiers and use them when subsequently rewriting the project file. However, the generator would choose new random identifiers each time the project files are generated, leading to difficulties comparing "used" project files to "pristine" ones produced by this module, and causing the appearance of changes as every object identifier is changed when updated projects are checked in to a version control repository. To mitigate this problem, this module chooses identifiers in a more deterministic way, by hashing a description of each object as well as its parent and ancestor objects. This strategy should result in minimal "shift" in IDs as successive generations of project files are produced. THIS MODULE This module introduces several classes, all derived from the XCObject class. Nearly all of the "brains" are built into the XCObject class, which understands how to create and modify objects, maintain the proper tree structure, compute identifiers, and print objects. For the most part, classes derived from XCObject need only provide a _schema class object, a dictionary that expresses what properties objects of the class may contain. Given this structure, it's possible to build a minimal project file by creating objects of the appropriate types and making the proper connections: config_list = XCConfigurationList() group = PBXGroup() project = PBXProject({'buildConfigurationList': config_list, 'mainGroup': group}) With the project object set up, it can be added to an XCProjectFile object. XCProjectFile is a pseudo-class in the sense that it is a concrete XCObject subclass that does not actually correspond to a class type found in a project file. Rather, it is used to represent the project file's root dictionary. Printing an XCProjectFile will print the entire project file, including the full "objects" dictionary. project_file = XCProjectFile({'rootObject': project}) project_file.ComputeIDs() project_file.Print() Xcode project files are always encoded in UTF-8. This module will accept strings of either the str class or the unicode class. Strings of class str are assumed to already be encoded in UTF-8. Obviously, if you're just using ASCII, you won't encounter difficulties because ASCII is a UTF-8 subset. Strings of class unicode are handled properly and encoded in UTF-8 when a project file is output. """ import gyp.common import posixpath import re import struct import sys # hashlib is supplied as of Python 2.5 as the replacement interface for sha # and other secure hashes. In 2.6, sha is deprecated. Import hashlib if # available, avoiding a deprecation warning under 2.6. Import sha otherwise, # preserving 2.4 compatibility. try: import hashlib _new_sha1 = hashlib.sha1 except ImportError: import sha _new_sha1 = sha.new # See XCObject._EncodeString. This pattern is used to determine when a string # can be printed unquoted. Strings that match this pattern may be printed # unquoted. Strings that do not match must be quoted and may be further # transformed to be properly encoded. Note that this expression matches the # characters listed with "+", for 1 or more occurrences: if a string is empty, # it must not match this pattern, because it needs to be encoded as "". _unquoted = re.compile('^[A-Za-z0-9$./_]+$') # Strings that match this pattern are quoted regardless of what _unquoted says. # Oddly, Xcode will quote any string with a run of three or more underscores. _quoted = re.compile('___') # This pattern should match any character that needs to be escaped by # XCObject._EncodeString. See that function. _escaped = re.compile('[\\\\"]|[\x00-\x1f]') # Used by SourceTreeAndPathFromPath _path_leading_variable = re.compile('^\$\((.*?)\)(/(.*))?$') def SourceTreeAndPathFromPath(input_path): """Given input_path, returns a tuple with sourceTree and path values. Examples: input_path (source_tree, output_path) '$(VAR)/path' ('VAR', 'path') '$(VAR)' ('VAR', None) 'path' (None, 'path') """ source_group_match = _path_leading_variable.match(input_path) if source_group_match: source_tree = source_group_match.group(1) output_path = source_group_match.group(3) # This may be None. else: source_tree = None output_path = input_path return (source_tree, output_path) def ConvertVariablesToShellSyntax(input_string): return re.sub('\$\((.*?)\)', '${\\1}', input_string) class XCObject(object): """The abstract base of all class types used in Xcode project files. Class variables: _schema: A dictionary defining the properties of this class. The keys to _schema are string property keys as used in project files. Values are a list of four or five elements: [ is_list, property_type, is_strong, is_required, default ] is_list: True if the property described is a list, as opposed to a single element. property_type: The type to use as the value of the property, or if is_list is True, the type to use for each element of the value's list. property_type must be an XCObject subclass, or one of the built-in types str, int, or dict. is_strong: If property_type is an XCObject subclass, is_strong is True to assert that this class "owns," or serves as parent, to the property value (or, if is_list is True, values). is_strong must be False if property_type is not an XCObject subclass. is_required: True if the property is required for the class. Note that is_required being True does not preclude an empty string ("", in the case of property_type str) or list ([], in the case of is_list True) from being set for the property. default: Optional. If is_requried is True, default may be set to provide a default value for objects that do not supply their own value. If is_required is True and default is not provided, users of the class must supply their own value for the property. Note that although the values of the array are expressed in boolean terms, subclasses provide values as integers to conserve horizontal space. _should_print_single_line: False in XCObject. Subclasses whose objects should be written to the project file in the alternate single-line format, such as PBXFileReference and PBXBuildFile, should set this to True. _encode_transforms: Used by _EncodeString to encode unprintable characters. The index into this list is the ordinal of the character to transform; each value is a string used to represent the character in the output. XCObject provides an _encode_transforms list suitable for most XCObject subclasses. _alternate_encode_transforms: Provided for subclasses that wish to use the alternate encoding rules. Xcode seems to use these rules when printing objects in single-line format. Subclasses that desire this behavior should set _encode_transforms to _alternate_encode_transforms. _hashables: A list of XCObject subclasses that can be hashed by ComputeIDs to construct this object's ID. Most classes that need custom hashing behavior should do it by overriding Hashables, but in some cases an object's parent may wish to push a hashable value into its child, and it can do so by appending to _hashables. Attributes: id: The object's identifier, a 24-character uppercase hexadecimal string. Usually, objects being created should not set id until the entire project file structure is built. At that point, UpdateIDs() should be called on the root object to assign deterministic values for id to each object in the tree. parent: The object's parent. This is set by a parent XCObject when a child object is added to it. _properties: The object's property dictionary. An object's properties are described by its class' _schema variable. """ _schema = {} _should_print_single_line = False # See _EncodeString. _encode_transforms = [] i = 0 while i < ord(' '): _encode_transforms.append('\\U%04x' % i) i = i + 1 _encode_transforms[7] = '\\a' _encode_transforms[8] = '\\b' _encode_transforms[9] = '\\t' _encode_transforms[10] = '\\n' _encode_transforms[11] = '\\v' _encode_transforms[12] = '\\f' _encode_transforms[13] = '\\n' _alternate_encode_transforms = list(_encode_transforms) _alternate_encode_transforms[9] = chr(9) _alternate_encode_transforms[10] = chr(10) _alternate_encode_transforms[11] = chr(11) def __init__(self, properties=None, id=None, parent=None): self.id = id self.parent = parent self._properties = {} self._hashables = [] self._SetDefaultsFromSchema() self.UpdateProperties(properties) def __repr__(self): try: name = self.Name() except NotImplementedError: return '<%s at 0x%x>' % (self.__class__.__name__, id(self)) return '<%s %r at 0x%x>' % (self.__class__.__name__, name, id(self)) def Copy(self): """Make a copy of this object. The new object will have its own copy of lists and dicts. Any XCObject objects owned by this object (marked "strong") will be copied in the new object, even those found in lists. If this object has any weak references to other XCObjects, the same references are added to the new object without making a copy. """ that = self.__class__(id=self.id, parent=self.parent) for key, value in self._properties.iteritems(): is_strong = self._schema[key][2] if isinstance(value, XCObject): if is_strong: new_value = value.Copy() new_value.parent = that that._properties[key] = new_value else: that._properties[key] = value elif isinstance(value, str) or isinstance(value, unicode) or \ isinstance(value, int): that._properties[key] = value elif isinstance(value, list): if is_strong: # If is_strong is True, each element is an XCObject, so it's safe to # call Copy. that._properties[key] = [] for item in value: new_item = item.Copy() new_item.parent = that that._properties[key].append(new_item) else: that._properties[key] = value[:] elif isinstance(value, dict): # dicts are never strong. if is_strong: raise TypeError, 'Strong dict for key ' + key + ' in ' + \ self.__class__.__name__ else: that._properties[key] = value.copy() else: raise TypeError, 'Unexpected type ' + value.__class__.__name__ + \ ' for key ' + key + ' in ' + self.__class__.__name__ return that def Name(self): """Return the name corresponding to an object. Not all objects necessarily need to be nameable, and not all that do have a "name" property. Override as needed. """ # If the schema indicates that "name" is required, try to access the # property even if it doesn't exist. This will result in a KeyError # being raised for the property that should be present, which seems more # appropriate than NotImplementedError in this case. if 'name' in self._properties or \ ('name' in self._schema and self._schema['name'][3]): return self._properties['name'] raise NotImplementedError, \ self.__class__.__name__ + ' must implement Name' def Comment(self): """Return a comment string for the object. Most objects just use their name as the comment, but PBXProject uses different values. The returned comment is not escaped and does not have any comment marker strings applied to it. """ return self.Name() def Hashables(self): hashables = [self.__class__.__name__] name = self.Name() if name != None: hashables.append(name) hashables.extend(self._hashables) return hashables def HashablesForChild(self): return None def ComputeIDs(self, recursive=True, overwrite=True, seed_hash=None): """Set "id" properties deterministically. An object's "id" property is set based on a hash of its class type and name, as well as the class type and name of all ancestor objects. As such, it is only advisable to call ComputeIDs once an entire project file tree is built. If recursive is True, recurse into all descendant objects and update their hashes. If overwrite is True, any existing value set in the "id" property will be replaced. """ def _HashUpdate(hash, data): """Update hash with data's length and contents. If the hash were updated only with the value of data, it would be possible for clowns to induce collisions by manipulating the names of their objects. By adding the length, it's exceedingly less likely that ID collisions will be encountered, intentionally or not. """ hash.update(struct.pack('>i', len(data))) hash.update(data) if seed_hash is None: seed_hash = _new_sha1() hash = seed_hash.copy() hashables = self.Hashables() assert len(hashables) > 0 for hashable in hashables: _HashUpdate(hash, hashable) if recursive: hashables_for_child = self.HashablesForChild() if hashables_for_child is None: child_hash = hash else: assert len(hashables_for_child) > 0 child_hash = seed_hash.copy() for hashable in hashables_for_child: _HashUpdate(child_hash, hashable) for child in self.Children(): child.ComputeIDs(recursive, overwrite, child_hash) if overwrite or self.id is None: # Xcode IDs are only 96 bits (24 hex characters), but a SHA-1 digest is # is 160 bits. Instead of throwing out 64 bits of the digest, xor them # into the portion that gets used. assert hash.digest_size % 4 == 0 digest_int_count = hash.digest_size / 4 digest_ints = struct.unpack('>' + 'I' * digest_int_count, hash.digest()) id_ints = [0, 0, 0] for index in xrange(0, digest_int_count): id_ints[index % 3] ^= digest_ints[index] self.id = '%08X%08X%08X' % tuple(id_ints) def EnsureNoIDCollisions(self): """Verifies that no two objects have the same ID. Checks all descendants. """ ids = {} descendants = self.Descendants() for descendant in descendants: if descendant.id in ids: other = ids[descendant.id] raise KeyError, \ 'Duplicate ID %s, objects "%s" and "%s" in "%s"' % \ (descendant.id, str(descendant._properties), str(other._properties), self._properties['rootObject'].Name()) ids[descendant.id] = descendant def Children(self): """Returns a list of all of this object's owned (strong) children.""" children = [] for property, attributes in self._schema.iteritems(): (is_list, property_type, is_strong) = attributes[0:3] if is_strong and property in self._properties: if not is_list: children.append(self._properties[property]) else: children.extend(self._properties[property]) return children def Descendants(self): """Returns a list of all of this object's descendants, including this object. """ children = self.Children() descendants = [self] for child in children: descendants.extend(child.Descendants()) return descendants def PBXProjectAncestor(self): # The base case for recursion is defined at PBXProject.PBXProjectAncestor. if self.parent: return self.parent.PBXProjectAncestor() return None def _EncodeComment(self, comment): """Encodes a comment to be placed in the project file output, mimicing Xcode behavior. """ # This mimics Xcode behavior by wrapping the comment in "/*" and "*/". If # the string already contains a "*/", it is turned into "(*)/". This keeps # the file writer from outputting something that would be treated as the # end of a comment in the middle of something intended to be entirely a # comment. return '/* ' + comment.replace('*/', '(*)/') + ' */' def _EncodeTransform(self, match): # This function works closely with _EncodeString. It will only be called # by re.sub with match.group(0) containing a character matched by the # the _escaped expression. char = match.group(0) # Backslashes (\) and quotation marks (") are always replaced with a # backslash-escaped version of the same. Everything else gets its # replacement from the class' _encode_transforms array. if char == '\\': return '\\\\' if char == '"': return '\\"' return self._encode_transforms[ord(char)] def _EncodeString(self, value): """Encodes a string to be placed in the project file output, mimicing Xcode behavior. """ # Use quotation marks when any character outside of the range A-Z, a-z, 0-9, # $ (dollar sign), . (period), and _ (underscore) is present. Also use # quotation marks to represent empty strings. # # Escape " (double-quote) and \ (backslash) by preceding them with a # backslash. # # Some characters below the printable ASCII range are encoded specially: # 7 ^G BEL is encoded as "\a" # 8 ^H BS is encoded as "\b" # 11 ^K VT is encoded as "\v" # 12 ^L NP is encoded as "\f" # 127 ^? DEL is passed through as-is without escaping # - In PBXFileReference and PBXBuildFile objects: # 9 ^I HT is passed through as-is without escaping # 10 ^J NL is passed through as-is without escaping # 13 ^M CR is passed through as-is without escaping # - In other objects: # 9 ^I HT is encoded as "\t" # 10 ^J NL is encoded as "\n" # 13 ^M CR is encoded as "\n" rendering it indistinguishable from # 10 ^J NL # All other characters within the ASCII control character range (0 through # 31 inclusive) are encoded as "\U001f" referring to the Unicode code point # in hexadecimal. For example, character 14 (^N SO) is encoded as "\U000e". # Characters above the ASCII range are passed through to the output encoded # as UTF-8 without any escaping. These mappings are contained in the # class' _encode_transforms list. if _unquoted.search(value) and not _quoted.search(value): return value return '"' + _escaped.sub(self._EncodeTransform, value) + '"' def _XCPrint(self, file, tabs, line): file.write('\t' * tabs + line) def _XCPrintableValue(self, tabs, value, flatten_list=False): """Returns a representation of value that may be printed in a project file, mimicing Xcode's behavior. _XCPrintableValue can handle str and int values, XCObjects (which are made printable by returning their id property), and list and dict objects composed of any of the above types. When printing a list or dict, and _should_print_single_line is False, the tabs parameter is used to determine how much to indent the lines corresponding to the items in the list or dict. If flatten_list is True, single-element lists will be transformed into strings. """ printable = '' comment = None if self._should_print_single_line: sep = ' ' element_tabs = '' end_tabs = '' else: sep = '\n' element_tabs = '\t' * (tabs + 1) end_tabs = '\t' * tabs if isinstance(value, XCObject): printable += value.id comment = value.Comment() elif isinstance(value, str): printable += self._EncodeString(value) elif isinstance(value, unicode): printable += self._EncodeString(value.encode('utf-8')) elif isinstance(value, int): printable += str(value) elif isinstance(value, list): if flatten_list and len(value) <= 1: if len(value) == 0: printable += self._EncodeString('') else: printable += self._EncodeString(value[0]) else: printable = '(' + sep for item in value: printable += element_tabs + \ self._XCPrintableValue(tabs + 1, item, flatten_list) + \ ',' + sep printable += end_tabs + ')' elif isinstance(value, dict): printable = '{' + sep for item_key, item_value in sorted(value.iteritems()): printable += element_tabs + \ self._XCPrintableValue(tabs + 1, item_key, flatten_list) + ' = ' + \ self._XCPrintableValue(tabs + 1, item_value, flatten_list) + ';' + \ sep printable += end_tabs + '}' else: raise TypeError, "Can't make " + value.__class__.__name__ + ' printable' if comment != None: printable += ' ' + self._EncodeComment(comment) return printable def _XCKVPrint(self, file, tabs, key, value): """Prints a key and value, members of an XCObject's _properties dictionary, to file. tabs is an int identifying the indentation level. If the class' _should_print_single_line variable is True, tabs is ignored and the key-value pair will be followed by a space insead of a newline. """ if self._should_print_single_line: printable = '' after_kv = ' ' else: printable = '\t' * tabs after_kv = '\n' # Xcode usually prints remoteGlobalIDString values in PBXContainerItemProxy # objects without comments. Sometimes it prints them with comments, but # the majority of the time, it doesn't. To avoid unnecessary changes to # the project file after Xcode opens it, don't write comments for # remoteGlobalIDString. This is a sucky hack and it would certainly be # cleaner to extend the schema to indicate whether or not a comment should # be printed, but since this is the only case where the problem occurs and # Xcode itself can't seem to make up its mind, the hack will suffice. # # Also see PBXContainerItemProxy._schema['remoteGlobalIDString']. if key == 'remoteGlobalIDString' and isinstance(self, PBXContainerItemProxy): value_to_print = value.id else: value_to_print = value # PBXBuildFile's settings property is represented in the output as a dict, # but a hack here has it represented as a string. Arrange to strip off the # quotes so that it shows up in the output as expected. if key == 'settings' and isinstance(self, PBXBuildFile): strip_value_quotes = True else: strip_value_quotes = False # In another one-off, let's set flatten_list on buildSettings properties # of XCBuildConfiguration objects, because that's how Xcode treats them. if key == 'buildSettings' and isinstance(self, XCBuildConfiguration): flatten_list = True else: flatten_list = False try: printable_key = self._XCPrintableValue(tabs, key, flatten_list) printable_value = self._XCPrintableValue(tabs, value_to_print, flatten_list) if strip_value_quotes and len(printable_value) > 1 and \ printable_value[0] == '"' and printable_value[-1] == '"': printable_value = printable_value[1:-1] printable += printable_key + ' = ' + printable_value + ';' + after_kv except TypeError, e: gyp.common.ExceptionAppend(e, 'while printing key "%s"' % key) raise self._XCPrint(file, 0, printable) def Print(self, file=sys.stdout): """Prints a reprentation of this object to file, adhering to Xcode output formatting. """ self.VerifyHasRequiredProperties() if self._should_print_single_line: # When printing an object in a single line, Xcode doesn't put any space # between the beginning of a dictionary (or presumably a list) and the # first contained item, so you wind up with snippets like # ...CDEF = {isa = PBXFileReference; fileRef = 0123... # If it were me, I would have put a space in there after the opening # curly, but I guess this is just another one of those inconsistencies # between how Xcode prints PBXFileReference and PBXBuildFile objects as # compared to other objects. Mimic Xcode's behavior here by using an # empty string for sep. sep = '' end_tabs = 0 else: sep = '\n' end_tabs = 2 # Start the object. For example, '\t\tPBXProject = {\n'. self._XCPrint(file, 2, self._XCPrintableValue(2, self) + ' = {' + sep) # "isa" isn't in the _properties dictionary, it's an intrinsic property # of the class which the object belongs to. Xcode always outputs "isa" # as the first element of an object dictionary. self._XCKVPrint(file, 3, 'isa', self.__class__.__name__) # The remaining elements of an object dictionary are sorted alphabetically. for property, value in sorted(self._properties.iteritems()): self._XCKVPrint(file, 3, property, value) # End the object. self._XCPrint(file, end_tabs, '};\n') def UpdateProperties(self, properties, do_copy=False): """Merge the supplied properties into the _properties dictionary. The input properties must adhere to the class schema or a KeyError or TypeError exception will be raised. If adding an object of an XCObject subclass and the schema indicates a strong relationship, the object's parent will be set to this object. If do_copy is True, then lists, dicts, strong-owned XCObjects, and strong-owned XCObjects in lists will be copied instead of having their references added. """ if properties is None: return for property, value in properties.iteritems(): # Make sure the property is in the schema. if not property in self._schema: raise KeyError, property + ' not in ' + self.__class__.__name__ # Make sure the property conforms to the schema. (is_list, property_type, is_strong) = self._schema[property][0:3] if is_list: if value.__class__ != list: raise TypeError, \ property + ' of ' + self.__class__.__name__ + \ ' must be list, not ' + value.__class__.__name__ for item in value: if not isinstance(item, property_type) and \ not (item.__class__ == unicode and property_type == str): # Accept unicode where str is specified. str is treated as # UTF-8-encoded. raise TypeError, \ 'item of ' + property + ' of ' + self.__class__.__name__ + \ ' must be ' + property_type.__name__ + ', not ' + \ item.__class__.__name__ elif not isinstance(value, property_type) and \ not (value.__class__ == unicode and property_type == str): # Accept unicode where str is specified. str is treated as # UTF-8-encoded. raise TypeError, \ property + ' of ' + self.__class__.__name__ + ' must be ' + \ property_type.__name__ + ', not ' + value.__class__.__name__ # Checks passed, perform the assignment. if do_copy: if isinstance(value, XCObject): if is_strong: self._properties[property] = value.Copy() else: self._properties[property] = value elif isinstance(value, str) or isinstance(value, unicode) or \ isinstance(value, int): self._properties[property] = value elif isinstance(value, list): if is_strong: # If is_strong is True, each element is an XCObject, so it's safe # to call Copy. self._properties[property] = [] for item in value: self._properties[property].append(item.Copy()) else: self._properties[property] = value[:] elif isinstance(value, dict): self._properties[property] = value.copy() else: raise TypeError, "Don't know how to copy a " + \ value.__class__.__name__ + ' object for ' + \ property + ' in ' + self.__class__.__name__ else: self._properties[property] = value # Set up the child's back-reference to this object. Don't use |value| # any more because it may not be right if do_copy is true. if is_strong: if not is_list: self._properties[property].parent = self else: for item in self._properties[property]: item.parent = self def HasProperty(self, key): return key in self._properties def GetProperty(self, key): return self._properties[key] def SetProperty(self, key, value): self.UpdateProperties({key: value}) def DelProperty(self, key): if key in self._properties: del self._properties[key] def AppendProperty(self, key, value): # TODO(mark): Support ExtendProperty too (and make this call that)? # Schema validation. if not key in self._schema: raise KeyError, key + ' not in ' + self.__class__.__name__ (is_list, property_type, is_strong) = self._schema[key][0:3] if not is_list: raise TypeError, key + ' of ' + self.__class__.__name__ + ' must be list' if not isinstance(value, property_type): raise TypeError, 'item of ' + key + ' of ' + self.__class__.__name__ + \ ' must be ' + property_type.__name__ + ', not ' + \ value.__class__.__name__ # If the property doesn't exist yet, create a new empty list to receive the # item. if not key in self._properties: self._properties[key] = [] # Set up the ownership link. if is_strong: value.parent = self # Store the item. self._properties[key].append(value) def VerifyHasRequiredProperties(self): """Ensure that all properties identified as required by the schema are set. """ # TODO(mark): A stronger verification mechanism is needed. Some # subclasses need to perform validation beyond what the schema can enforce. for property, attributes in self._schema.iteritems(): (is_list, property_type, is_strong, is_required) = attributes[0:4] if is_required and not property in self._properties: raise KeyError, self.__class__.__name__ + ' requires ' + property def _SetDefaultsFromSchema(self): """Assign object default values according to the schema. This will not overwrite properties that have already been set.""" defaults = {} for property, attributes in self._schema.iteritems(): (is_list, property_type, is_strong, is_required) = attributes[0:4] if is_required and len(attributes) >= 5 and \ not property in self._properties: default = attributes[4] defaults[property] = default if len(defaults) > 0: # Use do_copy=True so that each new object gets its own copy of strong # objects, lists, and dicts. self.UpdateProperties(defaults, do_copy=True) class XCHierarchicalElement(XCObject): """Abstract base for PBXGroup and PBXFileReference. Not represented in a project file.""" # TODO(mark): Do name and path belong here? Probably so. # If path is set and name is not, name may have a default value. Name will # be set to the basename of path, if the basename of path is different from # the full value of path. If path is already just a leaf name, name will # not be set. _schema = XCObject._schema.copy() _schema.update({ 'comments': [0, str, 0, 0], 'fileEncoding': [0, str, 0, 0], 'includeInIndex': [0, int, 0, 0], 'indentWidth': [0, int, 0, 0], 'lineEnding': [0, int, 0, 0], 'sourceTree': [0, str, 0, 1, '<group>'], 'tabWidth': [0, int, 0, 0], 'usesTabs': [0, int, 0, 0], 'wrapsLines': [0, int, 0, 0], }) def __init__(self, properties=None, id=None, parent=None): # super XCObject.__init__(self, properties, id, parent) if 'path' in self._properties and not 'name' in self._properties: path = self._properties['path'] name = posixpath.basename(path) if name != '' and path != name: self.SetProperty('name', name) if 'path' in self._properties and \ (not 'sourceTree' in self._properties or \ self._properties['sourceTree'] == '<group>'): # If the pathname begins with an Xcode variable like "$(SDKROOT)/", take # the variable out and make the path be relative to that variable by # assigning the variable name as the sourceTree. (source_tree, path) = SourceTreeAndPathFromPath(self._properties['path']) if source_tree != None: self._properties['sourceTree'] = source_tree if path != None: self._properties['path'] = path if source_tree != None and path is None and \ not 'name' in self._properties: # The path was of the form "$(SDKROOT)" with no path following it. # This object is now relative to that variable, so it has no path # attribute of its own. It does, however, keep a name. del self._properties['path'] self._properties['name'] = source_tree def Name(self): if 'name' in self._properties: return self._properties['name'] elif 'path' in self._properties: return self._properties['path'] else: # This happens in the case of the root PBXGroup. return None def Hashables(self): """Custom hashables for XCHierarchicalElements. XCHierarchicalElements are special. Generally, their hashes shouldn't change if the paths don't change. The normal XCObject implementation of Hashables adds a hashable for each object, which means that if the hierarchical structure changes (possibly due to changes caused when TakeOverOnlyChild runs and encounters slight changes in the hierarchy), the hashes will change. For example, if a project file initially contains a/b/f1 and a/b becomes collapsed into a/b, f1 will have a single parent a/b. If someone later adds a/f2 to the project file, a/b can no longer be collapsed, and f1 winds up with parent b and grandparent a. That would be sufficient to change f1's hash. To counteract this problem, hashables for all XCHierarchicalElements except for the main group (which has neither a name nor a path) are taken to be just the set of path components. Because hashables are inherited from parents, this provides assurance that a/b/f1 has the same set of hashables whether its parent is b or a/b. The main group is a special case. As it is permitted to have no name or path, it is permitted to use the standard XCObject hash mechanism. This is not considered a problem because there can be only one main group. """ if self == self.PBXProjectAncestor()._properties['mainGroup']: # super return XCObject.Hashables(self) hashables = [] # Put the name in first, ensuring that if TakeOverOnlyChild collapses # children into a top-level group like "Source", the name always goes # into the list of hashables without interfering with path components. if 'name' in self._properties: # Make it less likely for people to manipulate hashes by following the # pattern of always pushing an object type value onto the list first. hashables.append(self.__class__.__name__ + '.name') hashables.append(self._properties['name']) # NOTE: This still has the problem that if an absolute path is encountered, # including paths with a sourceTree, they'll still inherit their parents' # hashables, even though the paths aren't relative to their parents. This # is not expected to be much of a problem in practice. path = self.PathFromSourceTreeAndPath() if path != None: components = path.split(posixpath.sep) for component in components: hashables.append(self.__class__.__name__ + '.path') hashables.append(component) hashables.extend(self._hashables) return hashables def Compare(self, other): # Allow comparison of these types. PBXGroup has the highest sort rank; # PBXVariantGroup is treated as equal to PBXFileReference. valid_class_types = { PBXFileReference: 'file', PBXGroup: 'group', PBXVariantGroup: 'file', } self_type = valid_class_types[self.__class__] other_type = valid_class_types[other.__class__] if self_type == other_type: # If the two objects are of the same sort rank, compare their names. return cmp(self.Name(), other.Name()) # Otherwise, sort groups before everything else. if self_type == 'group': return -1 return 1 def CompareRootGroup(self, other): # This function should be used only to compare direct children of the # containing PBXProject's mainGroup. These groups should appear in the # listed order. # TODO(mark): "Build" is used by gyp.generator.xcode, perhaps the # generator should have a way of influencing this list rather than having # to hardcode for the generator here. order = ['Source', 'Intermediates', 'Projects', 'Frameworks', 'Products', 'Build'] # If the groups aren't in the listed order, do a name comparison. # Otherwise, groups in the listed order should come before those that # aren't. self_name = self.Name() other_name = other.Name() self_in = isinstance(self, PBXGroup) and self_name in order other_in = isinstance(self, PBXGroup) and other_name in order if not self_in and not other_in: return self.Compare(other) if self_name in order and not other_name in order: return -1 if other_name in order and not self_name in order: return 1 # If both groups are in the listed order, go by the defined order. self_index = order.index(self_name) other_index = order.index(other_name) if self_index < other_index: return -1 if self_index > other_index: return 1 return 0 def PathFromSourceTreeAndPath(self): # Turn the object's sourceTree and path properties into a single flat # string of a form comparable to the path parameter. If there's a # sourceTree property other than "<group>", wrap it in $(...) for the # comparison. components = [] if self._properties['sourceTree'] != '<group>': components.append('$(' + self._properties['sourceTree'] + ')') if 'path' in self._properties: components.append(self._properties['path']) if len(components) > 0: return posixpath.join(*components) return None def FullPath(self): # Returns a full path to self relative to the project file, or relative # to some other source tree. Start with self, and walk up the chain of # parents prepending their paths, if any, until no more parents are # available (project-relative path) or until a path relative to some # source tree is found. xche = self path = None while isinstance(xche, XCHierarchicalElement) and \ (path is None or \ (not path.startswith('/') and not path.startswith('$'))): this_path = xche.PathFromSourceTreeAndPath() if this_path != None and path != None: path = posixpath.join(this_path, path) elif this_path != None: path = this_path xche = xche.parent return path class PBXGroup(XCHierarchicalElement): """ Attributes: _children_by_path: Maps pathnames of children of this PBXGroup to the actual child XCHierarchicalElement objects. _variant_children_by_name_and_path: Maps (name, path) tuples of PBXVariantGroup children to the actual child PBXVariantGroup objects. """ _schema = XCHierarchicalElement._schema.copy() _schema.update({ 'children': [1, XCHierarchicalElement, 1, 1, []], 'name': [0, str, 0, 0], 'path': [0, str, 0, 0], }) def __init__(self, properties=None, id=None, parent=None): # super XCHierarchicalElement.__init__(self, properties, id, parent) self._children_by_path = {} self._variant_children_by_name_and_path = {} for child in self._properties.get('children', []): self._AddChildToDicts(child) def Hashables(self): # super hashables = XCHierarchicalElement.Hashables(self) # It is not sufficient to just rely on name and parent to build a unique # hashable : a node could have two child PBXGroup sharing a common name. # To add entropy the hashable is enhanced with the names of all its # children. for child in self._properties.get('children', []): child_name = child.Name() if child_name != None: hashables.append(child_name) return hashables def HashablesForChild(self): # To avoid a circular reference the hashables used to compute a child id do # not include the child names. return XCHierarchicalElement.Hashables(self) def _AddChildToDicts(self, child): # Sets up this PBXGroup object's dicts to reference the child properly. child_path = child.PathFromSourceTreeAndPath() if child_path: if child_path in self._children_by_path: raise ValueError, 'Found multiple children with path ' + child_path self._children_by_path[child_path] = child if isinstance(child, PBXVariantGroup): child_name = child._properties.get('name', None) key = (child_name, child_path) if key in self._variant_children_by_name_and_path: raise ValueError, 'Found multiple PBXVariantGroup children with ' + \ 'name ' + str(child_name) + ' and path ' + \ str(child_path) self._variant_children_by_name_and_path[key] = child def AppendChild(self, child): # Callers should use this instead of calling # AppendProperty('children', child) directly because this function # maintains the group's dicts. self.AppendProperty('children', child) self._AddChildToDicts(child) def GetChildByName(self, name): # This is not currently optimized with a dict as GetChildByPath is because # it has few callers. Most callers probably want GetChildByPath. This # function is only useful to get children that have names but no paths, # which is rare. The children of the main group ("Source", "Products", # etc.) is pretty much the only case where this likely to come up. # # TODO(mark): Maybe this should raise an error if more than one child is # present with the same name. if not 'children' in self._properties: return None for child in self._properties['children']: if child.Name() == name: return child return None def GetChildByPath(self, path): if not path: return None if path in self._children_by_path: return self._children_by_path[path] return None def GetChildByRemoteObject(self, remote_object): # This method is a little bit esoteric. Given a remote_object, which # should be a PBXFileReference in another project file, this method will # return this group's PBXReferenceProxy object serving as a local proxy # for the remote PBXFileReference. # # This function might benefit from a dict optimization as GetChildByPath # for some workloads, but profiling shows that it's not currently a # problem. if not 'children' in self._properties: return None for child in self._properties['children']: if not isinstance(child, PBXReferenceProxy): continue container_proxy = child._properties['remoteRef'] if container_proxy._properties['remoteGlobalIDString'] == remote_object: return child return None def AddOrGetFileByPath(self, path, hierarchical): """Returns an existing or new file reference corresponding to path. If hierarchical is True, this method will create or use the necessary hierarchical group structure corresponding to path. Otherwise, it will look in and create an item in the current group only. If an existing matching reference is found, it is returned, otherwise, a new one will be created, added to the correct group, and returned. If path identifies a directory by virtue of carrying a trailing slash, this method returns a PBXFileReference of "folder" type. If path identifies a variant, by virtue of it identifying a file inside a directory with an ".lproj" extension, this method returns a PBXVariantGroup containing the variant named by path, and possibly other variants. For all other paths, a "normal" PBXFileReference will be returned. """ # Adding or getting a directory? Directories end with a trailing slash. is_dir = False if path.endswith('/'): is_dir = True path = posixpath.normpath(path) if is_dir: path = path + '/' # Adding or getting a variant? Variants are files inside directories # with an ".lproj" extension. Xcode uses variants for localization. For # a variant path/to/Language.lproj/MainMenu.nib, put a variant group named # MainMenu.nib inside path/to, and give it a variant named Language. In # this example, grandparent would be set to path/to and parent_root would # be set to Language. variant_name = None parent = posixpath.dirname(path) grandparent = posixpath.dirname(parent) parent_basename = posixpath.basename(parent) (parent_root, parent_ext) = posixpath.splitext(parent_basename) if parent_ext == '.lproj': variant_name = parent_root if grandparent == '': grandparent = None # Putting a directory inside a variant group is not currently supported. assert not is_dir or variant_name is None path_split = path.split(posixpath.sep) if len(path_split) == 1 or \ ((is_dir or variant_name != None) and len(path_split) == 2) or \ not hierarchical: # The PBXFileReference or PBXVariantGroup will be added to or gotten from # this PBXGroup, no recursion necessary. if variant_name is None: # Add or get a PBXFileReference. file_ref = self.GetChildByPath(path) if file_ref != None: assert file_ref.__class__ == PBXFileReference else: file_ref = PBXFileReference({'path': path}) self.AppendChild(file_ref) else: # Add or get a PBXVariantGroup. The variant group name is the same # as the basename (MainMenu.nib in the example above). grandparent # specifies the path to the variant group itself, and path_split[-2:] # is the path of the specific variant relative to its group. variant_group_name = posixpath.basename(path) variant_group_ref = self.AddOrGetVariantGroupByNameAndPath( variant_group_name, grandparent) variant_path = posixpath.sep.join(path_split[-2:]) variant_ref = variant_group_ref.GetChildByPath(variant_path) if variant_ref != None: assert variant_ref.__class__ == PBXFileReference else: variant_ref = PBXFileReference({'name': variant_name, 'path': variant_path}) variant_group_ref.AppendChild(variant_ref) # The caller is interested in the variant group, not the specific # variant file. file_ref = variant_group_ref return file_ref else: # Hierarchical recursion. Add or get a PBXGroup corresponding to the # outermost path component, and then recurse into it, chopping off that # path component. next_dir = path_split[0] group_ref = self.GetChildByPath(next_dir) if group_ref != None: assert group_ref.__class__ == PBXGroup else: group_ref = PBXGroup({'path': next_dir}) self.AppendChild(group_ref) return group_ref.AddOrGetFileByPath(posixpath.sep.join(path_split[1:]), hierarchical) def AddOrGetVariantGroupByNameAndPath(self, name, path): """Returns an existing or new PBXVariantGroup for name and path. If a PBXVariantGroup identified by the name and path arguments is already present as a child of this object, it is returned. Otherwise, a new PBXVariantGroup with the correct properties is created, added as a child, and returned. This method will generally be called by AddOrGetFileByPath, which knows when to create a variant group based on the structure of the pathnames passed to it. """ key = (name, path) if key in self._variant_children_by_name_and_path: variant_group_ref = self._variant_children_by_name_and_path[key] assert variant_group_ref.__class__ == PBXVariantGroup return variant_group_ref variant_group_properties = {'name': name} if path != None: variant_group_properties['path'] = path variant_group_ref = PBXVariantGroup(variant_group_properties) self.AppendChild(variant_group_ref) return variant_group_ref def TakeOverOnlyChild(self, recurse=False): """If this PBXGroup has only one child and it's also a PBXGroup, take it over by making all of its children this object's children. This function will continue to take over only children when those children are groups. If there are three PBXGroups representing a, b, and c, with c inside b and b inside a, and a and b have no other children, this will result in a taking over both b and c, forming a PBXGroup for a/b/c. If recurse is True, this function will recurse into children and ask them to collapse themselves by taking over only children as well. Assuming an example hierarchy with files at a/b/c/d1, a/b/c/d2, and a/b/c/d3/e/f (d1, d2, and f are files, the rest are groups), recursion will result in a group for a/b/c containing a group for d3/e. """ # At this stage, check that child class types are PBXGroup exactly, # instead of using isinstance. The only subclass of PBXGroup, # PBXVariantGroup, should not participate in reparenting in the same way: # reparenting by merging different object types would be wrong. while len(self._properties['children']) == 1 and \ self._properties['children'][0].__class__ == PBXGroup: # Loop to take over the innermost only-child group possible. child = self._properties['children'][0] # Assume the child's properties, including its children. Save a copy # of this object's old properties, because they'll still be needed. # This object retains its existing id and parent attributes. old_properties = self._properties self._properties = child._properties self._children_by_path = child._children_by_path if not 'sourceTree' in self._properties or \ self._properties['sourceTree'] == '<group>': # The child was relative to its parent. Fix up the path. Note that # children with a sourceTree other than "<group>" are not relative to # their parents, so no path fix-up is needed in that case. if 'path' in old_properties: if 'path' in self._properties: # Both the original parent and child have paths set. self._properties['path'] = posixpath.join(old_properties['path'], self._properties['path']) else: # Only the original parent has a path, use it. self._properties['path'] = old_properties['path'] if 'sourceTree' in old_properties: # The original parent had a sourceTree set, use it. self._properties['sourceTree'] = old_properties['sourceTree'] # If the original parent had a name set, keep using it. If the original # parent didn't have a name but the child did, let the child's name # live on. If the name attribute seems unnecessary now, get rid of it. if 'name' in old_properties and old_properties['name'] != None and \ old_properties['name'] != self.Name(): self._properties['name'] = old_properties['name'] if 'name' in self._properties and 'path' in self._properties and \ self._properties['name'] == self._properties['path']: del self._properties['name'] # Notify all children of their new parent. for child in self._properties['children']: child.parent = self # If asked to recurse, recurse. if recurse: for child in self._properties['children']: if child.__class__ == PBXGroup: child.TakeOverOnlyChild(recurse) def SortGroup(self): self._properties['children'] = \ sorted(self._properties['children'], cmp=lambda x,y: x.Compare(y)) # Recurse. for child in self._properties['children']: if isinstance(child, PBXGroup): child.SortGroup() class XCFileLikeElement(XCHierarchicalElement): # Abstract base for objects that can be used as the fileRef property of # PBXBuildFile. def PathHashables(self): # A PBXBuildFile that refers to this object will call this method to # obtain additional hashables specific to this XCFileLikeElement. Don't # just use this object's hashables, they're not specific and unique enough # on their own (without access to the parent hashables.) Instead, provide # hashables that identify this object by path by getting its hashables as # well as the hashables of ancestor XCHierarchicalElement objects. hashables = [] xche = self while xche != None and isinstance(xche, XCHierarchicalElement): xche_hashables = xche.Hashables() for index in xrange(0, len(xche_hashables)): hashables.insert(index, xche_hashables[index]) xche = xche.parent return hashables class XCContainerPortal(XCObject): # Abstract base for objects that can be used as the containerPortal property # of PBXContainerItemProxy. pass class XCRemoteObject(XCObject): # Abstract base for objects that can be used as the remoteGlobalIDString # property of PBXContainerItemProxy. pass class PBXFileReference(XCFileLikeElement, XCContainerPortal, XCRemoteObject): _schema = XCFileLikeElement._schema.copy() _schema.update({ 'explicitFileType': [0, str, 0, 0], 'lastKnownFileType': [0, str, 0, 0], 'name': [0, str, 0, 0], 'path': [0, str, 0, 1], }) # Weird output rules for PBXFileReference. _should_print_single_line = True # super _encode_transforms = XCFileLikeElement._alternate_encode_transforms def __init__(self, properties=None, id=None, parent=None): # super XCFileLikeElement.__init__(self, properties, id, parent) if 'path' in self._properties and self._properties['path'].endswith('/'): self._properties['path'] = self._properties['path'][:-1] is_dir = True else: is_dir = False if 'path' in self._properties and \ not 'lastKnownFileType' in self._properties and \ not 'explicitFileType' in self._properties: # TODO(mark): This is the replacement for a replacement for a quick hack. # It is no longer incredibly sucky, but this list needs to be extended. extension_map = { 'a': 'archive.ar', 'app': 'wrapper.application', 'bdic': 'file', 'bundle': 'wrapper.cfbundle', 'c': 'sourcecode.c.c', 'cc': 'sourcecode.cpp.cpp', 'cpp': 'sourcecode.cpp.cpp', 'css': 'text.css', 'cxx': 'sourcecode.cpp.cpp', 'dart': 'sourcecode', 'dylib': 'compiled.mach-o.dylib', 'framework': 'wrapper.framework', 'gyp': 'sourcecode', 'gypi': 'sourcecode', 'h': 'sourcecode.c.h', 'hxx': 'sourcecode.cpp.h', 'icns': 'image.icns', 'java': 'sourcecode.java', 'js': 'sourcecode.javascript', 'm': 'sourcecode.c.objc', 'mm': 'sourcecode.cpp.objcpp', 'nib': 'wrapper.nib', 'o': 'compiled.mach-o.objfile', 'pdf': 'image.pdf', 'pl': 'text.script.perl', 'plist': 'text.plist.xml', 'pm': 'text.script.perl', 'png': 'image.png', 'py': 'text.script.python', 'r': 'sourcecode.rez', 'rez': 'sourcecode.rez', 's': 'sourcecode.asm', 'storyboard': 'file.storyboard', 'strings': 'text.plist.strings', 'ttf': 'file', 'xcconfig': 'text.xcconfig', 'xcdatamodel': 'wrapper.xcdatamodel', 'xib': 'file.xib', 'y': 'sourcecode.yacc', } prop_map = { 'dart': 'explicitFileType', 'gyp': 'explicitFileType', 'gypi': 'explicitFileType', } if is_dir: file_type = 'folder' prop_name = 'lastKnownFileType' else: basename = posixpath.basename(self._properties['path']) (root, ext) = posixpath.splitext(basename) # Check the map using a lowercase extension. # TODO(mark): Maybe it should try with the original case first and fall # back to lowercase, in case there are any instances where case # matters. There currently aren't. if ext != '': ext = ext[1:].lower() # TODO(mark): "text" is the default value, but "file" is appropriate # for unrecognized files not containing text. Xcode seems to choose # based on content. file_type = extension_map.get(ext, 'text') prop_name = prop_map.get(ext, 'lastKnownFileType') self._properties[prop_name] = file_type class PBXVariantGroup(PBXGroup, XCFileLikeElement): """PBXVariantGroup is used by Xcode to represent localizations.""" # No additions to the schema relative to PBXGroup. pass # PBXReferenceProxy is also an XCFileLikeElement subclass. It is defined below # because it uses PBXContainerItemProxy, defined below. class XCBuildConfiguration(XCObject): _schema = XCObject._schema.copy() _schema.update({ 'baseConfigurationReference': [0, PBXFileReference, 0, 0], 'buildSettings': [0, dict, 0, 1, {}], 'name': [0, str, 0, 1], }) def HasBuildSetting(self, key): return key in self._properties['buildSettings'] def GetBuildSetting(self, key): return self._properties['buildSettings'][key] def SetBuildSetting(self, key, value): # TODO(mark): If a list, copy? self._properties['buildSettings'][key] = value def AppendBuildSetting(self, key, value): if not key in self._properties['buildSettings']: self._properties['buildSettings'][key] = [] self._properties['buildSettings'][key].append(value) def DelBuildSetting(self, key): if key in self._properties['buildSettings']: del self._properties['buildSettings'][key] def SetBaseConfiguration(self, value): self._properties['baseConfigurationReference'] = value class XCConfigurationList(XCObject): # _configs is the default list of configurations. _configs = [ XCBuildConfiguration({'name': 'Debug'}), XCBuildConfiguration({'name': 'Release'}) ] _schema = XCObject._schema.copy() _schema.update({ 'buildConfigurations': [1, XCBuildConfiguration, 1, 1, _configs], 'defaultConfigurationIsVisible': [0, int, 0, 1, 1], 'defaultConfigurationName': [0, str, 0, 1, 'Release'], }) def Name(self): return 'Build configuration list for ' + \ self.parent.__class__.__name__ + ' "' + self.parent.Name() + '"' def ConfigurationNamed(self, name): """Convenience accessor to obtain an XCBuildConfiguration by name.""" for configuration in self._properties['buildConfigurations']: if configuration._properties['name'] == name: return configuration raise KeyError, name def DefaultConfiguration(self): """Convenience accessor to obtain the default XCBuildConfiguration.""" return self.ConfigurationNamed(self._properties['defaultConfigurationName']) def HasBuildSetting(self, key): """Determines the state of a build setting in all XCBuildConfiguration child objects. If all child objects have key in their build settings, and the value is the same in all child objects, returns 1. If no child objects have the key in their build settings, returns 0. If some, but not all, child objects have the key in their build settings, or if any children have different values for the key, returns -1. """ has = None value = None for configuration in self._properties['buildConfigurations']: configuration_has = configuration.HasBuildSetting(key) if has is None: has = configuration_has elif has != configuration_has: return -1 if configuration_has: configuration_value = configuration.GetBuildSetting(key) if value is None: value = configuration_value elif value != configuration_value: return -1 if not has: return 0 return 1 def GetBuildSetting(self, key): """Gets the build setting for key. All child XCConfiguration objects must have the same value set for the setting, or a ValueError will be raised. """ # TODO(mark): This is wrong for build settings that are lists. The list # contents should be compared (and a list copy returned?) value = None for configuration in self._properties['buildConfigurations']: configuration_value = configuration.GetBuildSetting(key) if value is None: value = configuration_value else: if value != configuration_value: raise ValueError, 'Variant values for ' + key return value def SetBuildSetting(self, key, value): """Sets the build setting for key to value in all child XCBuildConfiguration objects. """ for configuration in self._properties['buildConfigurations']: configuration.SetBuildSetting(key, value) def AppendBuildSetting(self, key, value): """Appends value to the build setting for key, which is treated as a list, in all child XCBuildConfiguration objects. """ for configuration in self._properties['buildConfigurations']: configuration.AppendBuildSetting(key, value) def DelBuildSetting(self, key): """Deletes the build setting key from all child XCBuildConfiguration objects. """ for configuration in self._properties['buildConfigurations']: configuration.DelBuildSetting(key) def SetBaseConfiguration(self, value): """Sets the build configuration in all child XCBuildConfiguration objects. """ for configuration in self._properties['buildConfigurations']: configuration.SetBaseConfiguration(value) class PBXBuildFile(XCObject): _schema = XCObject._schema.copy() _schema.update({ 'fileRef': [0, XCFileLikeElement, 0, 1], 'settings': [0, str, 0, 0], # hack, it's a dict }) # Weird output rules for PBXBuildFile. _should_print_single_line = True _encode_transforms = XCObject._alternate_encode_transforms def Name(self): # Example: "main.cc in Sources" return self._properties['fileRef'].Name() + ' in ' + self.parent.Name() def Hashables(self): # super hashables = XCObject.Hashables(self) # It is not sufficient to just rely on Name() to get the # XCFileLikeElement's name, because that is not a complete pathname. # PathHashables returns hashables unique enough that no two # PBXBuildFiles should wind up with the same set of hashables, unless # someone adds the same file multiple times to the same target. That # would be considered invalid anyway. hashables.extend(self._properties['fileRef'].PathHashables()) return hashables class XCBuildPhase(XCObject): """Abstract base for build phase classes. Not represented in a project file. Attributes: _files_by_path: A dict mapping each path of a child in the files list by path (keys) to the corresponding PBXBuildFile children (values). _files_by_xcfilelikeelement: A dict mapping each XCFileLikeElement (keys) to the corresponding PBXBuildFile children (values). """ # TODO(mark): Some build phase types, like PBXShellScriptBuildPhase, don't # actually have a "files" list. XCBuildPhase should not have "files" but # another abstract subclass of it should provide this, and concrete build # phase types that do have "files" lists should be derived from that new # abstract subclass. XCBuildPhase should only provide buildActionMask and # runOnlyForDeploymentPostprocessing, and not files or the various # file-related methods and attributes. _schema = XCObject._schema.copy() _schema.update({ 'buildActionMask': [0, int, 0, 1, 0x7fffffff], 'files': [1, PBXBuildFile, 1, 1, []], 'runOnlyForDeploymentPostprocessing': [0, int, 0, 1, 0], }) def __init__(self, properties=None, id=None, parent=None): # super XCObject.__init__(self, properties, id, parent) self._files_by_path = {} self._files_by_xcfilelikeelement = {} for pbxbuildfile in self._properties.get('files', []): self._AddBuildFileToDicts(pbxbuildfile) def FileGroup(self, path): # Subclasses must override this by returning a two-element tuple. The # first item in the tuple should be the PBXGroup to which "path" should be # added, either as a child or deeper descendant. The second item should # be a boolean indicating whether files should be added into hierarchical # groups or one single flat group. raise NotImplementedError, \ self.__class__.__name__ + ' must implement FileGroup' def _AddPathToDict(self, pbxbuildfile, path): """Adds path to the dict tracking paths belonging to this build phase. If the path is already a member of this build phase, raises an exception. """ if path in self._files_by_path: raise ValueError, 'Found multiple build files with path ' + path self._files_by_path[path] = pbxbuildfile def _AddBuildFileToDicts(self, pbxbuildfile, path=None): """Maintains the _files_by_path and _files_by_xcfilelikeelement dicts. If path is specified, then it is the path that is being added to the phase, and pbxbuildfile must contain either a PBXFileReference directly referencing that path, or it must contain a PBXVariantGroup that itself contains a PBXFileReference referencing the path. If path is not specified, either the PBXFileReference's path or the paths of all children of the PBXVariantGroup are taken as being added to the phase. If the path is already present in the phase, raises an exception. If the PBXFileReference or PBXVariantGroup referenced by pbxbuildfile are already present in the phase, referenced by a different PBXBuildFile object, raises an exception. This does not raise an exception when a PBXFileReference or PBXVariantGroup reappear and are referenced by the same PBXBuildFile that has already introduced them, because in the case of PBXVariantGroup objects, they may correspond to multiple paths that are not all added simultaneously. When this situation occurs, the path needs to be added to _files_by_path, but nothing needs to change in _files_by_xcfilelikeelement, and the caller should have avoided adding the PBXBuildFile if it is already present in the list of children. """ xcfilelikeelement = pbxbuildfile._properties['fileRef'] paths = [] if path != None: # It's best when the caller provides the path. if isinstance(xcfilelikeelement, PBXVariantGroup): paths.append(path) else: # If the caller didn't provide a path, there can be either multiple # paths (PBXVariantGroup) or one. if isinstance(xcfilelikeelement, PBXVariantGroup): for variant in xcfilelikeelement._properties['children']: paths.append(variant.FullPath()) else: paths.append(xcfilelikeelement.FullPath()) # Add the paths first, because if something's going to raise, the # messages provided by _AddPathToDict are more useful owing to its # having access to a real pathname and not just an object's Name(). for a_path in paths: self._AddPathToDict(pbxbuildfile, a_path) # If another PBXBuildFile references this XCFileLikeElement, there's a # problem. if xcfilelikeelement in self._files_by_xcfilelikeelement and \ self._files_by_xcfilelikeelement[xcfilelikeelement] != pbxbuildfile: raise ValueError, 'Found multiple build files for ' + \ xcfilelikeelement.Name() self._files_by_xcfilelikeelement[xcfilelikeelement] = pbxbuildfile def AppendBuildFile(self, pbxbuildfile, path=None): # Callers should use this instead of calling # AppendProperty('files', pbxbuildfile) directly because this function # maintains the object's dicts. Better yet, callers can just call AddFile # with a pathname and not worry about building their own PBXBuildFile # objects. self.AppendProperty('files', pbxbuildfile) self._AddBuildFileToDicts(pbxbuildfile, path) def AddFile(self, path, settings=None): (file_group, hierarchical) = self.FileGroup(path) file_ref = file_group.AddOrGetFileByPath(path, hierarchical) if file_ref in self._files_by_xcfilelikeelement and \ isinstance(file_ref, PBXVariantGroup): # There's already a PBXBuildFile in this phase corresponding to the # PBXVariantGroup. path just provides a new variant that belongs to # the group. Add the path to the dict. pbxbuildfile = self._files_by_xcfilelikeelement[file_ref] self._AddBuildFileToDicts(pbxbuildfile, path) else: # Add a new PBXBuildFile to get file_ref into the phase. if settings is None: pbxbuildfile = PBXBuildFile({'fileRef': file_ref}) else: pbxbuildfile = PBXBuildFile({'fileRef': file_ref, 'settings': settings}) self.AppendBuildFile(pbxbuildfile, path) class PBXHeadersBuildPhase(XCBuildPhase): # No additions to the schema relative to XCBuildPhase. def Name(self): return 'Headers' def FileGroup(self, path): return self.PBXProjectAncestor().RootGroupForPath(path) class PBXResourcesBuildPhase(XCBuildPhase): # No additions to the schema relative to XCBuildPhase. def Name(self): return 'Resources' def FileGroup(self, path): return self.PBXProjectAncestor().RootGroupForPath(path) class PBXSourcesBuildPhase(XCBuildPhase): # No additions to the schema relative to XCBuildPhase. def Name(self): return 'Sources' def FileGroup(self, path): return self.PBXProjectAncestor().RootGroupForPath(path) class PBXFrameworksBuildPhase(XCBuildPhase): # No additions to the schema relative to XCBuildPhase. def Name(self): return 'Frameworks' def FileGroup(self, path): (root, ext) = posixpath.splitext(path) if ext != '': ext = ext[1:].lower() if ext == 'o': # .o files are added to Xcode Frameworks phases, but conceptually aren't # frameworks, they're more like sources or intermediates. Redirect them # to show up in one of those other groups. return self.PBXProjectAncestor().RootGroupForPath(path) else: return (self.PBXProjectAncestor().FrameworksGroup(), False) class PBXShellScriptBuildPhase(XCBuildPhase): _schema = XCBuildPhase._schema.copy() _schema.update({ 'inputPaths': [1, str, 0, 1, []], 'name': [0, str, 0, 0], 'outputPaths': [1, str, 0, 1, []], 'shellPath': [0, str, 0, 1, '/bin/sh'], 'shellScript': [0, str, 0, 1], 'showEnvVarsInLog': [0, int, 0, 0], }) def Name(self): if 'name' in self._properties: return self._properties['name'] return 'ShellScript' class PBXCopyFilesBuildPhase(XCBuildPhase): _schema = XCBuildPhase._schema.copy() _schema.update({ 'dstPath': [0, str, 0, 1], 'dstSubfolderSpec': [0, int, 0, 1], 'name': [0, str, 0, 0], }) # path_tree_re matches "$(DIR)/path" or just "$(DIR)". Match group 1 is # "DIR", match group 3 is "path" or None. path_tree_re = re.compile('^\\$\\((.*)\\)(/(.*)|)$') # path_tree_to_subfolder maps names of Xcode variables to the associated # dstSubfolderSpec property value used in a PBXCopyFilesBuildPhase object. path_tree_to_subfolder = { 'BUILT_PRODUCTS_DIR': 16, # Products Directory # Other types that can be chosen via the Xcode UI. # TODO(mark): Map Xcode variable names to these. # : 1, # Wrapper # : 6, # Executables: 6 # : 7, # Resources # : 15, # Java Resources # : 10, # Frameworks # : 11, # Shared Frameworks # : 12, # Shared Support # : 13, # PlugIns } def Name(self): if 'name' in self._properties: return self._properties['name'] return 'CopyFiles' def FileGroup(self, path): return self.PBXProjectAncestor().RootGroupForPath(path) def SetDestination(self, path): """Set the dstSubfolderSpec and dstPath properties from path. path may be specified in the same notation used for XCHierarchicalElements, specifically, "$(DIR)/path". """ path_tree_match = self.path_tree_re.search(path) if path_tree_match: # Everything else needs to be relative to an Xcode variable. path_tree = path_tree_match.group(1) relative_path = path_tree_match.group(3) if path_tree in self.path_tree_to_subfolder: subfolder = self.path_tree_to_subfolder[path_tree] if relative_path is None: relative_path = '' else: # The path starts with an unrecognized Xcode variable # name like $(SRCROOT). Xcode will still handle this # as an "absolute path" that starts with the variable. subfolder = 0 relative_path = path elif path.startswith('/'): # Special case. Absolute paths are in dstSubfolderSpec 0. subfolder = 0 relative_path = path[1:] else: raise ValueError, 'Can\'t use path %s in a %s' % \ (path, self.__class__.__name__) self._properties['dstPath'] = relative_path self._properties['dstSubfolderSpec'] = subfolder class PBXBuildRule(XCObject): _schema = XCObject._schema.copy() _schema.update({ 'compilerSpec': [0, str, 0, 1], 'filePatterns': [0, str, 0, 0], 'fileType': [0, str, 0, 1], 'isEditable': [0, int, 0, 1, 1], 'outputFiles': [1, str, 0, 1, []], 'script': [0, str, 0, 0], }) def Name(self): # Not very inspired, but it's what Xcode uses. return self.__class__.__name__ def Hashables(self): # super hashables = XCObject.Hashables(self) # Use the hashables of the weak objects that this object refers to. hashables.append(self._properties['fileType']) if 'filePatterns' in self._properties: hashables.append(self._properties['filePatterns']) return hashables class PBXContainerItemProxy(XCObject): # When referencing an item in this project file, containerPortal is the # PBXProject root object of this project file. When referencing an item in # another project file, containerPortal is a PBXFileReference identifying # the other project file. # # When serving as a proxy to an XCTarget (in this project file or another), # proxyType is 1. When serving as a proxy to a PBXFileReference (in another # project file), proxyType is 2. Type 2 is used for references to the # producs of the other project file's targets. # # Xcode is weird about remoteGlobalIDString. Usually, it's printed without # a comment, indicating that it's tracked internally simply as a string, but # sometimes it's printed with a comment (usually when the object is initially # created), indicating that it's tracked as a project file object at least # sometimes. This module always tracks it as an object, but contains a hack # to prevent it from printing the comment in the project file output. See # _XCKVPrint. _schema = XCObject._schema.copy() _schema.update({ 'containerPortal': [0, XCContainerPortal, 0, 1], 'proxyType': [0, int, 0, 1], 'remoteGlobalIDString': [0, XCRemoteObject, 0, 1], 'remoteInfo': [0, str, 0, 1], }) def __repr__(self): props = self._properties name = '%s.gyp:%s' % (props['containerPortal'].Name(), props['remoteInfo']) return '<%s %r at 0x%x>' % (self.__class__.__name__, name, id(self)) def Name(self): # Admittedly not the best name, but it's what Xcode uses. return self.__class__.__name__ def Hashables(self): # super hashables = XCObject.Hashables(self) # Use the hashables of the weak objects that this object refers to. hashables.extend(self._properties['containerPortal'].Hashables()) hashables.extend(self._properties['remoteGlobalIDString'].Hashables()) return hashables class PBXTargetDependency(XCObject): # The "target" property accepts an XCTarget object, and obviously not # NoneType. But XCTarget is defined below, so it can't be put into the # schema yet. The definition of PBXTargetDependency can't be moved below # XCTarget because XCTarget's own schema references PBXTargetDependency. # Python doesn't deal well with this circular relationship, and doesn't have # a real way to do forward declarations. To work around, the type of # the "target" property is reset below, after XCTarget is defined. # # At least one of "name" and "target" is required. _schema = XCObject._schema.copy() _schema.update({ 'name': [0, str, 0, 0], 'target': [0, None.__class__, 0, 0], 'targetProxy': [0, PBXContainerItemProxy, 1, 1], }) def __repr__(self): name = self._properties.get('name') or self._properties['target'].Name() return '<%s %r at 0x%x>' % (self.__class__.__name__, name, id(self)) def Name(self): # Admittedly not the best name, but it's what Xcode uses. return self.__class__.__name__ def Hashables(self): # super hashables = XCObject.Hashables(self) # Use the hashables of the weak objects that this object refers to. hashables.extend(self._properties['targetProxy'].Hashables()) return hashables class PBXReferenceProxy(XCFileLikeElement): _schema = XCFileLikeElement._schema.copy() _schema.update({ 'fileType': [0, str, 0, 1], 'path': [0, str, 0, 1], 'remoteRef': [0, PBXContainerItemProxy, 1, 1], }) class XCTarget(XCRemoteObject): # An XCTarget is really just an XCObject, the XCRemoteObject thing is just # to allow PBXProject to be used in the remoteGlobalIDString property of # PBXContainerItemProxy. # # Setting a "name" property at instantiation may also affect "productName", # which may in turn affect the "PRODUCT_NAME" build setting in children of # "buildConfigurationList". See __init__ below. _schema = XCRemoteObject._schema.copy() _schema.update({ 'buildConfigurationList': [0, XCConfigurationList, 1, 1, XCConfigurationList()], 'buildPhases': [1, XCBuildPhase, 1, 1, []], 'dependencies': [1, PBXTargetDependency, 1, 1, []], 'name': [0, str, 0, 1], 'productName': [0, str, 0, 1], }) def __init__(self, properties=None, id=None, parent=None, force_outdir=None, force_prefix=None, force_extension=None): # super XCRemoteObject.__init__(self, properties, id, parent) # Set up additional defaults not expressed in the schema. If a "name" # property was supplied, set "productName" if it is not present. Also set # the "PRODUCT_NAME" build setting in each configuration, but only if # the setting is not present in any build configuration. if 'name' in self._properties: if not 'productName' in self._properties: self.SetProperty('productName', self._properties['name']) if 'productName' in self._properties: if 'buildConfigurationList' in self._properties: configs = self._properties['buildConfigurationList'] if configs.HasBuildSetting('PRODUCT_NAME') == 0: configs.SetBuildSetting('PRODUCT_NAME', self._properties['productName']) def AddDependency(self, other): pbxproject = self.PBXProjectAncestor() other_pbxproject = other.PBXProjectAncestor() if pbxproject == other_pbxproject: # Add a dependency to another target in the same project file. container = PBXContainerItemProxy({'containerPortal': pbxproject, 'proxyType': 1, 'remoteGlobalIDString': other, 'remoteInfo': other.Name()}) dependency = PBXTargetDependency({'target': other, 'targetProxy': container}) self.AppendProperty('dependencies', dependency) else: # Add a dependency to a target in a different project file. other_project_ref = \ pbxproject.AddOrGetProjectReference(other_pbxproject)[1] container = PBXContainerItemProxy({ 'containerPortal': other_project_ref, 'proxyType': 1, 'remoteGlobalIDString': other, 'remoteInfo': other.Name(), }) dependency = PBXTargetDependency({'name': other.Name(), 'targetProxy': container}) self.AppendProperty('dependencies', dependency) # Proxy all of these through to the build configuration list. def ConfigurationNamed(self, name): return self._properties['buildConfigurationList'].ConfigurationNamed(name) def DefaultConfiguration(self): return self._properties['buildConfigurationList'].DefaultConfiguration() def HasBuildSetting(self, key): return self._properties['buildConfigurationList'].HasBuildSetting(key) def GetBuildSetting(self, key): return self._properties['buildConfigurationList'].GetBuildSetting(key) def SetBuildSetting(self, key, value): return self._properties['buildConfigurationList'].SetBuildSetting(key, \ value) def AppendBuildSetting(self, key, value): return self._properties['buildConfigurationList'].AppendBuildSetting(key, \ value) def DelBuildSetting(self, key): return self._properties['buildConfigurationList'].DelBuildSetting(key) # Redefine the type of the "target" property. See PBXTargetDependency._schema # above. PBXTargetDependency._schema['target'][1] = XCTarget class PBXNativeTarget(XCTarget): # buildPhases is overridden in the schema to be able to set defaults. # # NOTE: Contrary to most objects, it is advisable to set parent when # constructing PBXNativeTarget. A parent of an XCTarget must be a PBXProject # object. A parent reference is required for a PBXNativeTarget during # construction to be able to set up the target defaults for productReference, # because a PBXBuildFile object must be created for the target and it must # be added to the PBXProject's mainGroup hierarchy. _schema = XCTarget._schema.copy() _schema.update({ 'buildPhases': [1, XCBuildPhase, 1, 1, [PBXSourcesBuildPhase(), PBXFrameworksBuildPhase()]], 'buildRules': [1, PBXBuildRule, 1, 1, []], 'productReference': [0, PBXFileReference, 0, 1], 'productType': [0, str, 0, 1], }) # Mapping from Xcode product-types to settings. The settings are: # filetype : used for explicitFileType in the project file # prefix : the prefix for the file name # suffix : the suffix for the filen ame _product_filetypes = { 'com.apple.product-type.application': ['wrapper.application', '', '.app'], 'com.apple.product-type.bundle': ['wrapper.cfbundle', '', '.bundle'], 'com.apple.product-type.framework': ['wrapper.framework', '', '.framework'], 'com.apple.product-type.library.dynamic': ['compiled.mach-o.dylib', 'lib', '.dylib'], 'com.apple.product-type.library.static': ['archive.ar', 'lib', '.a'], 'com.apple.product-type.tool': ['compiled.mach-o.executable', '', ''], 'com.apple.product-type.bundle.unit-test': ['wrapper.cfbundle', '', '.xctest'], 'com.googlecode.gyp.xcode.bundle': ['compiled.mach-o.dylib', '', '.so'], } def __init__(self, properties=None, id=None, parent=None, force_outdir=None, force_prefix=None, force_extension=None): # super XCTarget.__init__(self, properties, id, parent) if 'productName' in self._properties and \ 'productType' in self._properties and \ not 'productReference' in self._properties and \ self._properties['productType'] in self._product_filetypes: products_group = None pbxproject = self.PBXProjectAncestor() if pbxproject != None: products_group = pbxproject.ProductsGroup() if products_group != None: (filetype, prefix, suffix) = \ self._product_filetypes[self._properties['productType']] # Xcode does not have a distinct type for loadable modules that are # pure BSD targets (not in a bundle wrapper). GYP allows such modules # to be specified by setting a target type to loadable_module without # having mac_bundle set. These are mapped to the pseudo-product type # com.googlecode.gyp.xcode.bundle. # # By picking up this special type and converting it to a dynamic # library (com.apple.product-type.library.dynamic) with fix-ups, # single-file loadable modules can be produced. # # MACH_O_TYPE is changed to mh_bundle to produce the proper file type # (as opposed to mh_dylib). In order for linking to succeed, # DYLIB_CURRENT_VERSION and DYLIB_COMPATIBILITY_VERSION must be # cleared. They are meaningless for type mh_bundle. # # Finally, the .so extension is forcibly applied over the default # (.dylib), unless another forced extension is already selected. # .dylib is plainly wrong, and .bundle is used by loadable_modules in # bundle wrappers (com.apple.product-type.bundle). .so seems an odd # choice because it's used as the extension on many other systems that # don't distinguish between linkable shared libraries and non-linkable # loadable modules, but there's precedent: Python loadable modules on # Mac OS X use an .so extension. if self._properties['productType'] == 'com.googlecode.gyp.xcode.bundle': self._properties['productType'] = \ 'com.apple.product-type.library.dynamic' self.SetBuildSetting('MACH_O_TYPE', 'mh_bundle') self.SetBuildSetting('DYLIB_CURRENT_VERSION', '') self.SetBuildSetting('DYLIB_COMPATIBILITY_VERSION', '') if force_extension is None: force_extension = suffix[1:] if self._properties['productType'] == \ 'com.apple.product-type-bundle.unit.test': if force_extension is None: force_extension = suffix[1:] if force_extension is not None: # If it's a wrapper (bundle), set WRAPPER_EXTENSION. if filetype.startswith('wrapper.'): self.SetBuildSetting('WRAPPER_EXTENSION', force_extension) else: # Extension override. suffix = '.' + force_extension self.SetBuildSetting('EXECUTABLE_EXTENSION', force_extension) if filetype.startswith('compiled.mach-o.executable'): product_name = self._properties['productName'] product_name += suffix suffix = '' self.SetProperty('productName', product_name) self.SetBuildSetting('PRODUCT_NAME', product_name) # Xcode handles most prefixes based on the target type, however there # are exceptions. If a "BSD Dynamic Library" target is added in the # Xcode UI, Xcode sets EXECUTABLE_PREFIX. This check duplicates that # behavior. if force_prefix is not None: prefix = force_prefix if filetype.startswith('wrapper.'): self.SetBuildSetting('WRAPPER_PREFIX', prefix) else: self.SetBuildSetting('EXECUTABLE_PREFIX', prefix) if force_outdir is not None: self.SetBuildSetting('TARGET_BUILD_DIR', force_outdir) # TODO(tvl): Remove the below hack. # http://code.google.com/p/gyp/issues/detail?id=122 # Some targets include the prefix in the target_name. These targets # really should just add a product_name setting that doesn't include # the prefix. For example: # target_name = 'libevent', product_name = 'event' # This check cleans up for them. product_name = self._properties['productName'] prefix_len = len(prefix) if prefix_len and (product_name[:prefix_len] == prefix): product_name = product_name[prefix_len:] self.SetProperty('productName', product_name) self.SetBuildSetting('PRODUCT_NAME', product_name) ref_props = { 'explicitFileType': filetype, 'includeInIndex': 0, 'path': prefix + product_name + suffix, 'sourceTree': 'BUILT_PRODUCTS_DIR', } file_ref = PBXFileReference(ref_props) products_group.AppendChild(file_ref) self.SetProperty('productReference', file_ref) def GetBuildPhaseByType(self, type): if not 'buildPhases' in self._properties: return None the_phase = None for phase in self._properties['buildPhases']: if isinstance(phase, type): # Some phases may be present in multiples in a well-formed project file, # but phases like PBXSourcesBuildPhase may only be present singly, and # this function is intended as an aid to GetBuildPhaseByType. Loop # over the entire list of phases and assert if more than one of the # desired type is found. assert the_phase is None the_phase = phase return the_phase def HeadersPhase(self): headers_phase = self.GetBuildPhaseByType(PBXHeadersBuildPhase) if headers_phase is None: headers_phase = PBXHeadersBuildPhase() # The headers phase should come before the resources, sources, and # frameworks phases, if any. insert_at = len(self._properties['buildPhases']) for index in xrange(0, len(self._properties['buildPhases'])): phase = self._properties['buildPhases'][index] if isinstance(phase, PBXResourcesBuildPhase) or \ isinstance(phase, PBXSourcesBuildPhase) or \ isinstance(phase, PBXFrameworksBuildPhase): insert_at = index break self._properties['buildPhases'].insert(insert_at, headers_phase) headers_phase.parent = self return headers_phase def ResourcesPhase(self): resources_phase = self.GetBuildPhaseByType(PBXResourcesBuildPhase) if resources_phase is None: resources_phase = PBXResourcesBuildPhase() # The resources phase should come before the sources and frameworks # phases, if any. insert_at = len(self._properties['buildPhases']) for index in xrange(0, len(self._properties['buildPhases'])): phase = self._properties['buildPhases'][index] if isinstance(phase, PBXSourcesBuildPhase) or \ isinstance(phase, PBXFrameworksBuildPhase): insert_at = index break self._properties['buildPhases'].insert(insert_at, resources_phase) resources_phase.parent = self return resources_phase def SourcesPhase(self): sources_phase = self.GetBuildPhaseByType(PBXSourcesBuildPhase) if sources_phase is None: sources_phase = PBXSourcesBuildPhase() self.AppendProperty('buildPhases', sources_phase) return sources_phase def FrameworksPhase(self): frameworks_phase = self.GetBuildPhaseByType(PBXFrameworksBuildPhase) if frameworks_phase is None: frameworks_phase = PBXFrameworksBuildPhase() self.AppendProperty('buildPhases', frameworks_phase) return frameworks_phase def AddDependency(self, other): # super XCTarget.AddDependency(self, other) static_library_type = 'com.apple.product-type.library.static' shared_library_type = 'com.apple.product-type.library.dynamic' framework_type = 'com.apple.product-type.framework' if isinstance(other, PBXNativeTarget) and \ 'productType' in self._properties and \ self._properties['productType'] != static_library_type and \ 'productType' in other._properties and \ (other._properties['productType'] == static_library_type or \ ((other._properties['productType'] == shared_library_type or \ other._properties['productType'] == framework_type) and \ ((not other.HasBuildSetting('MACH_O_TYPE')) or other.GetBuildSetting('MACH_O_TYPE') != 'mh_bundle'))): file_ref = other.GetProperty('productReference') pbxproject = self.PBXProjectAncestor() other_pbxproject = other.PBXProjectAncestor() if pbxproject != other_pbxproject: other_project_product_group = \ pbxproject.AddOrGetProjectReference(other_pbxproject)[0] file_ref = other_project_product_group.GetChildByRemoteObject(file_ref) self.FrameworksPhase().AppendProperty('files', PBXBuildFile({'fileRef': file_ref})) class PBXAggregateTarget(XCTarget): pass class PBXProject(XCContainerPortal): # A PBXProject is really just an XCObject, the XCContainerPortal thing is # just to allow PBXProject to be used in the containerPortal property of # PBXContainerItemProxy. """ Attributes: path: "sample.xcodeproj". TODO(mark) Document me! _other_pbxprojects: A dictionary, keyed by other PBXProject objects. Each value is a reference to the dict in the projectReferences list associated with the keyed PBXProject. """ _schema = XCContainerPortal._schema.copy() _schema.update({ 'attributes': [0, dict, 0, 0], 'buildConfigurationList': [0, XCConfigurationList, 1, 1, XCConfigurationList()], 'compatibilityVersion': [0, str, 0, 1, 'Xcode 3.2'], 'hasScannedForEncodings': [0, int, 0, 1, 1], 'mainGroup': [0, PBXGroup, 1, 1, PBXGroup()], 'projectDirPath': [0, str, 0, 1, ''], 'projectReferences': [1, dict, 0, 0], 'projectRoot': [0, str, 0, 1, ''], 'targets': [1, XCTarget, 1, 1, []], }) def __init__(self, properties=None, id=None, parent=None, path=None): self.path = path self._other_pbxprojects = {} # super return XCContainerPortal.__init__(self, properties, id, parent) def Name(self): name = self.path if name[-10:] == '.xcodeproj': name = name[:-10] return posixpath.basename(name) def Path(self): return self.path def Comment(self): return 'Project object' def Children(self): # super children = XCContainerPortal.Children(self) # Add children that the schema doesn't know about. Maybe there's a more # elegant way around this, but this is the only case where we need to own # objects in a dictionary (that is itself in a list), and three lines for # a one-off isn't that big a deal. if 'projectReferences' in self._properties: for reference in self._properties['projectReferences']: children.append(reference['ProductGroup']) return children def PBXProjectAncestor(self): return self def _GroupByName(self, name): if not 'mainGroup' in self._properties: self.SetProperty('mainGroup', PBXGroup()) main_group = self._properties['mainGroup'] group = main_group.GetChildByName(name) if group is None: group = PBXGroup({'name': name}) main_group.AppendChild(group) return group # SourceGroup and ProductsGroup are created by default in Xcode's own # templates. def SourceGroup(self): return self._GroupByName('Source') def ProductsGroup(self): return self._GroupByName('Products') # IntermediatesGroup is used to collect source-like files that are generated # by rules or script phases and are placed in intermediate directories such # as DerivedSources. def IntermediatesGroup(self): return self._GroupByName('Intermediates') # FrameworksGroup and ProjectsGroup are top-level groups used to collect # frameworks and projects. def FrameworksGroup(self): return self._GroupByName('Frameworks') def ProjectsGroup(self): return self._GroupByName('Projects') def RootGroupForPath(self, path): """Returns a PBXGroup child of this object to which path should be added. This method is intended to choose between SourceGroup and IntermediatesGroup on the basis of whether path is present in a source directory or an intermediates directory. For the purposes of this determination, any path located within a derived file directory such as PROJECT_DERIVED_FILE_DIR is treated as being in an intermediates directory. The returned value is a two-element tuple. The first element is the PBXGroup, and the second element specifies whether that group should be organized hierarchically (True) or as a single flat list (False). """ # TODO(mark): make this a class variable and bind to self on call? # Also, this list is nowhere near exhaustive. # INTERMEDIATE_DIR and SHARED_INTERMEDIATE_DIR are used by # gyp.generator.xcode. There should probably be some way for that module # to push the names in, rather than having to hard-code them here. source_tree_groups = { 'DERIVED_FILE_DIR': (self.IntermediatesGroup, True), 'INTERMEDIATE_DIR': (self.IntermediatesGroup, True), 'PROJECT_DERIVED_FILE_DIR': (self.IntermediatesGroup, True), 'SHARED_INTERMEDIATE_DIR': (self.IntermediatesGroup, True), } (source_tree, path) = SourceTreeAndPathFromPath(path) if source_tree != None and source_tree in source_tree_groups: (group_func, hierarchical) = source_tree_groups[source_tree] group = group_func() return (group, hierarchical) # TODO(mark): make additional choices based on file extension. return (self.SourceGroup(), True) def AddOrGetFileInRootGroup(self, path): """Returns a PBXFileReference corresponding to path in the correct group according to RootGroupForPath's heuristics. If an existing PBXFileReference for path exists, it will be returned. Otherwise, one will be created and returned. """ (group, hierarchical) = self.RootGroupForPath(path) return group.AddOrGetFileByPath(path, hierarchical) def RootGroupsTakeOverOnlyChildren(self, recurse=False): """Calls TakeOverOnlyChild for all groups in the main group.""" for group in self._properties['mainGroup']._properties['children']: if isinstance(group, PBXGroup): group.TakeOverOnlyChild(recurse) def SortGroups(self): # Sort the children of the mainGroup (like "Source" and "Products") # according to their defined order. self._properties['mainGroup']._properties['children'] = \ sorted(self._properties['mainGroup']._properties['children'], cmp=lambda x,y: x.CompareRootGroup(y)) # Sort everything else by putting group before files, and going # alphabetically by name within sections of groups and files. SortGroup # is recursive. for group in self._properties['mainGroup']._properties['children']: if not isinstance(group, PBXGroup): continue if group.Name() == 'Products': # The Products group is a special case. Instead of sorting # alphabetically, sort things in the order of the targets that # produce the products. To do this, just build up a new list of # products based on the targets. products = [] for target in self._properties['targets']: if not isinstance(target, PBXNativeTarget): continue product = target._properties['productReference'] # Make sure that the product is already in the products group. assert product in group._properties['children'] products.append(product) # Make sure that this process doesn't miss anything that was already # in the products group. assert len(products) == len(group._properties['children']) group._properties['children'] = products else: group.SortGroup() def AddOrGetProjectReference(self, other_pbxproject): """Add a reference to another project file (via PBXProject object) to this one. Returns [ProductGroup, ProjectRef]. ProductGroup is a PBXGroup object in this project file that contains a PBXReferenceProxy object for each product of each PBXNativeTarget in the other project file. ProjectRef is a PBXFileReference to the other project file. If this project file already references the other project file, the existing ProductGroup and ProjectRef are returned. The ProductGroup will still be updated if necessary. """ if not 'projectReferences' in self._properties: self._properties['projectReferences'] = [] product_group = None project_ref = None if not other_pbxproject in self._other_pbxprojects: # This project file isn't yet linked to the other one. Establish the # link. product_group = PBXGroup({'name': 'Products'}) # ProductGroup is strong. product_group.parent = self # There's nothing unique about this PBXGroup, and if left alone, it will # wind up with the same set of hashables as all other PBXGroup objects # owned by the projectReferences list. Add the hashables of the # remote PBXProject that it's related to. product_group._hashables.extend(other_pbxproject.Hashables()) # The other project reports its path as relative to the same directory # that this project's path is relative to. The other project's path # is not necessarily already relative to this project. Figure out the # pathname that this project needs to use to refer to the other one. this_path = posixpath.dirname(self.Path()) projectDirPath = self.GetProperty('projectDirPath') if projectDirPath: if posixpath.isabs(projectDirPath[0]): this_path = projectDirPath else: this_path = posixpath.join(this_path, projectDirPath) other_path = gyp.common.RelativePath(other_pbxproject.Path(), this_path) # ProjectRef is weak (it's owned by the mainGroup hierarchy). project_ref = PBXFileReference({ 'lastKnownFileType': 'wrapper.pb-project', 'path': other_path, 'sourceTree': 'SOURCE_ROOT', }) self.ProjectsGroup().AppendChild(project_ref) ref_dict = {'ProductGroup': product_group, 'ProjectRef': project_ref} self._other_pbxprojects[other_pbxproject] = ref_dict self.AppendProperty('projectReferences', ref_dict) # Xcode seems to sort this list case-insensitively self._properties['projectReferences'] = \ sorted(self._properties['projectReferences'], cmp=lambda x,y: cmp(x['ProjectRef'].Name().lower(), y['ProjectRef'].Name().lower())) else: # The link already exists. Pull out the relevnt data. project_ref_dict = self._other_pbxprojects[other_pbxproject] product_group = project_ref_dict['ProductGroup'] project_ref = project_ref_dict['ProjectRef'] self._SetUpProductReferences(other_pbxproject, product_group, project_ref) return [product_group, project_ref] def _SetUpProductReferences(self, other_pbxproject, product_group, project_ref): # TODO(mark): This only adds references to products in other_pbxproject # when they don't exist in this pbxproject. Perhaps it should also # remove references from this pbxproject that are no longer present in # other_pbxproject. Perhaps it should update various properties if they # change. for target in other_pbxproject._properties['targets']: if not isinstance(target, PBXNativeTarget): continue other_fileref = target._properties['productReference'] if product_group.GetChildByRemoteObject(other_fileref) is None: # Xcode sets remoteInfo to the name of the target and not the name # of its product, despite this proxy being a reference to the product. container_item = PBXContainerItemProxy({ 'containerPortal': project_ref, 'proxyType': 2, 'remoteGlobalIDString': other_fileref, 'remoteInfo': target.Name() }) # TODO(mark): Does sourceTree get copied straight over from the other # project? Can the other project ever have lastKnownFileType here # instead of explicitFileType? (Use it if so?) Can path ever be # unset? (I don't think so.) Can other_fileref have name set, and # does it impact the PBXReferenceProxy if so? These are the questions # that perhaps will be answered one day. reference_proxy = PBXReferenceProxy({ 'fileType': other_fileref._properties['explicitFileType'], 'path': other_fileref._properties['path'], 'sourceTree': other_fileref._properties['sourceTree'], 'remoteRef': container_item, }) product_group.AppendChild(reference_proxy) def SortRemoteProductReferences(self): # For each remote project file, sort the associated ProductGroup in the # same order that the targets are sorted in the remote project file. This # is the sort order used by Xcode. def CompareProducts(x, y, remote_products): # x and y are PBXReferenceProxy objects. Go through their associated # PBXContainerItem to get the remote PBXFileReference, which will be # present in the remote_products list. x_remote = x._properties['remoteRef']._properties['remoteGlobalIDString'] y_remote = y._properties['remoteRef']._properties['remoteGlobalIDString'] x_index = remote_products.index(x_remote) y_index = remote_products.index(y_remote) # Use the order of each remote PBXFileReference in remote_products to # determine the sort order. return cmp(x_index, y_index) for other_pbxproject, ref_dict in self._other_pbxprojects.iteritems(): # Build up a list of products in the remote project file, ordered the # same as the targets that produce them. remote_products = [] for target in other_pbxproject._properties['targets']: if not isinstance(target, PBXNativeTarget): continue remote_products.append(target._properties['productReference']) # Sort the PBXReferenceProxy children according to the list of remote # products. product_group = ref_dict['ProductGroup'] product_group._properties['children'] = sorted( product_group._properties['children'], cmp=lambda x, y: CompareProducts(x, y, remote_products)) class XCProjectFile(XCObject): _schema = XCObject._schema.copy() _schema.update({ 'archiveVersion': [0, int, 0, 1, 1], 'classes': [0, dict, 0, 1, {}], 'objectVersion': [0, int, 0, 1, 45], 'rootObject': [0, PBXProject, 1, 1], }) def SetXcodeVersion(self, version): version_to_object_version = { '2.4': 45, '3.0': 45, '3.1': 45, '3.2': 46, } if not version in version_to_object_version: supported_str = ', '.join(sorted(version_to_object_version.keys())) raise Exception( 'Unsupported Xcode version %s (supported: %s)' % ( version, supported_str ) ) compatibility_version = 'Xcode %s' % version self._properties['rootObject'].SetProperty('compatibilityVersion', compatibility_version) self.SetProperty('objectVersion', version_to_object_version[version]); def ComputeIDs(self, recursive=True, overwrite=True, hash=None): # Although XCProjectFile is implemented here as an XCObject, it's not a # proper object in the Xcode sense, and it certainly doesn't have its own # ID. Pass through an attempt to update IDs to the real root object. if recursive: self._properties['rootObject'].ComputeIDs(recursive, overwrite, hash) def Print(self, file=sys.stdout): self.VerifyHasRequiredProperties() # Add the special "objects" property, which will be caught and handled # separately during printing. This structure allows a fairly standard # loop do the normal printing. self._properties['objects'] = {} self._XCPrint(file, 0, '// !$*UTF8*$!\n') if self._should_print_single_line: self._XCPrint(file, 0, '{ ') else: self._XCPrint(file, 0, '{\n') for property, value in sorted(self._properties.iteritems(), cmp=lambda x, y: cmp(x, y)): if property == 'objects': self._PrintObjects(file) else: self._XCKVPrint(file, 1, property, value) self._XCPrint(file, 0, '}\n') del self._properties['objects'] def _PrintObjects(self, file): if self._should_print_single_line: self._XCPrint(file, 0, 'objects = {') else: self._XCPrint(file, 1, 'objects = {\n') objects_by_class = {} for object in self.Descendants(): if object == self: continue class_name = object.__class__.__name__ if not class_name in objects_by_class: objects_by_class[class_name] = [] objects_by_class[class_name].append(object) for class_name in sorted(objects_by_class): self._XCPrint(file, 0, '\n') self._XCPrint(file, 0, '/* Begin ' + class_name + ' section */\n') for object in sorted(objects_by_class[class_name], cmp=lambda x, y: cmp(x.id, y.id)): object.Print(file) self._XCPrint(file, 0, '/* End ' + class_name + ' section */\n') if self._should_print_single_line: self._XCPrint(file, 0, '}; ') else: self._XCPrint(file, 1, '};\n')
mit
2014cdag10/2014cdaGG
wsgi/static/Brython2.1.0-20140419-113919/Lib/xml/dom/xmlbuilder.py
873
12377
"""Implementation of the DOM Level 3 'LS-Load' feature.""" import copy import xml.dom from xml.dom.NodeFilter import NodeFilter __all__ = ["DOMBuilder", "DOMEntityResolver", "DOMInputSource"] class Options: """Features object that has variables set for each DOMBuilder feature. The DOMBuilder class uses an instance of this class to pass settings to the ExpatBuilder class. """ # Note that the DOMBuilder class in LoadSave constrains which of these # values can be set using the DOM Level 3 LoadSave feature. namespaces = 1 namespace_declarations = True validation = False external_parameter_entities = True external_general_entities = True external_dtd_subset = True validate_if_schema = False validate = False datatype_normalization = False create_entity_ref_nodes = True entities = True whitespace_in_element_content = True cdata_sections = True comments = True charset_overrides_xml_encoding = True infoset = False supported_mediatypes_only = False errorHandler = None filter = None class DOMBuilder: entityResolver = None errorHandler = None filter = None ACTION_REPLACE = 1 ACTION_APPEND_AS_CHILDREN = 2 ACTION_INSERT_AFTER = 3 ACTION_INSERT_BEFORE = 4 _legal_actions = (ACTION_REPLACE, ACTION_APPEND_AS_CHILDREN, ACTION_INSERT_AFTER, ACTION_INSERT_BEFORE) def __init__(self): self._options = Options() def _get_entityResolver(self): return self.entityResolver def _set_entityResolver(self, entityResolver): self.entityResolver = entityResolver def _get_errorHandler(self): return self.errorHandler def _set_errorHandler(self, errorHandler): self.errorHandler = errorHandler def _get_filter(self): return self.filter def _set_filter(self, filter): self.filter = filter def setFeature(self, name, state): if self.supportsFeature(name): state = state and 1 or 0 try: settings = self._settings[(_name_xform(name), state)] except KeyError: raise xml.dom.NotSupportedErr( "unsupported feature: %r" % (name,)) else: for name, value in settings: setattr(self._options, name, value) else: raise xml.dom.NotFoundErr("unknown feature: " + repr(name)) def supportsFeature(self, name): return hasattr(self._options, _name_xform(name)) def canSetFeature(self, name, state): key = (_name_xform(name), state and 1 or 0) return key in self._settings # This dictionary maps from (feature,value) to a list of # (option,value) pairs that should be set on the Options object. # If a (feature,value) setting is not in this dictionary, it is # not supported by the DOMBuilder. # _settings = { ("namespace_declarations", 0): [ ("namespace_declarations", 0)], ("namespace_declarations", 1): [ ("namespace_declarations", 1)], ("validation", 0): [ ("validation", 0)], ("external_general_entities", 0): [ ("external_general_entities", 0)], ("external_general_entities", 1): [ ("external_general_entities", 1)], ("external_parameter_entities", 0): [ ("external_parameter_entities", 0)], ("external_parameter_entities", 1): [ ("external_parameter_entities", 1)], ("validate_if_schema", 0): [ ("validate_if_schema", 0)], ("create_entity_ref_nodes", 0): [ ("create_entity_ref_nodes", 0)], ("create_entity_ref_nodes", 1): [ ("create_entity_ref_nodes", 1)], ("entities", 0): [ ("create_entity_ref_nodes", 0), ("entities", 0)], ("entities", 1): [ ("entities", 1)], ("whitespace_in_element_content", 0): [ ("whitespace_in_element_content", 0)], ("whitespace_in_element_content", 1): [ ("whitespace_in_element_content", 1)], ("cdata_sections", 0): [ ("cdata_sections", 0)], ("cdata_sections", 1): [ ("cdata_sections", 1)], ("comments", 0): [ ("comments", 0)], ("comments", 1): [ ("comments", 1)], ("charset_overrides_xml_encoding", 0): [ ("charset_overrides_xml_encoding", 0)], ("charset_overrides_xml_encoding", 1): [ ("charset_overrides_xml_encoding", 1)], ("infoset", 0): [], ("infoset", 1): [ ("namespace_declarations", 0), ("validate_if_schema", 0), ("create_entity_ref_nodes", 0), ("entities", 0), ("cdata_sections", 0), ("datatype_normalization", 1), ("whitespace_in_element_content", 1), ("comments", 1), ("charset_overrides_xml_encoding", 1)], ("supported_mediatypes_only", 0): [ ("supported_mediatypes_only", 0)], ("namespaces", 0): [ ("namespaces", 0)], ("namespaces", 1): [ ("namespaces", 1)], } def getFeature(self, name): xname = _name_xform(name) try: return getattr(self._options, xname) except AttributeError: if name == "infoset": options = self._options return (options.datatype_normalization and options.whitespace_in_element_content and options.comments and options.charset_overrides_xml_encoding and not (options.namespace_declarations or options.validate_if_schema or options.create_entity_ref_nodes or options.entities or options.cdata_sections)) raise xml.dom.NotFoundErr("feature %s not known" % repr(name)) def parseURI(self, uri): if self.entityResolver: input = self.entityResolver.resolveEntity(None, uri) else: input = DOMEntityResolver().resolveEntity(None, uri) return self.parse(input) def parse(self, input): options = copy.copy(self._options) options.filter = self.filter options.errorHandler = self.errorHandler fp = input.byteStream if fp is None and options.systemId: import urllib.request fp = urllib.request.urlopen(input.systemId) return self._parse_bytestream(fp, options) def parseWithContext(self, input, cnode, action): if action not in self._legal_actions: raise ValueError("not a legal action") raise NotImplementedError("Haven't written this yet...") def _parse_bytestream(self, stream, options): import xml.dom.expatbuilder builder = xml.dom.expatbuilder.makeBuilder(options) return builder.parseFile(stream) def _name_xform(name): return name.lower().replace('-', '_') class DOMEntityResolver(object): __slots__ = '_opener', def resolveEntity(self, publicId, systemId): assert systemId is not None source = DOMInputSource() source.publicId = publicId source.systemId = systemId source.byteStream = self._get_opener().open(systemId) # determine the encoding if the transport provided it source.encoding = self._guess_media_encoding(source) # determine the base URI is we can import posixpath, urllib.parse parts = urllib.parse.urlparse(systemId) scheme, netloc, path, params, query, fragment = parts # XXX should we check the scheme here as well? if path and not path.endswith("/"): path = posixpath.dirname(path) + "/" parts = scheme, netloc, path, params, query, fragment source.baseURI = urllib.parse.urlunparse(parts) return source def _get_opener(self): try: return self._opener except AttributeError: self._opener = self._create_opener() return self._opener def _create_opener(self): import urllib.request return urllib.request.build_opener() def _guess_media_encoding(self, source): info = source.byteStream.info() if "Content-Type" in info: for param in info.getplist(): if param.startswith("charset="): return param.split("=", 1)[1].lower() class DOMInputSource(object): __slots__ = ('byteStream', 'characterStream', 'stringData', 'encoding', 'publicId', 'systemId', 'baseURI') def __init__(self): self.byteStream = None self.characterStream = None self.stringData = None self.encoding = None self.publicId = None self.systemId = None self.baseURI = None def _get_byteStream(self): return self.byteStream def _set_byteStream(self, byteStream): self.byteStream = byteStream def _get_characterStream(self): return self.characterStream def _set_characterStream(self, characterStream): self.characterStream = characterStream def _get_stringData(self): return self.stringData def _set_stringData(self, data): self.stringData = data def _get_encoding(self): return self.encoding def _set_encoding(self, encoding): self.encoding = encoding def _get_publicId(self): return self.publicId def _set_publicId(self, publicId): self.publicId = publicId def _get_systemId(self): return self.systemId def _set_systemId(self, systemId): self.systemId = systemId def _get_baseURI(self): return self.baseURI def _set_baseURI(self, uri): self.baseURI = uri class DOMBuilderFilter: """Element filter which can be used to tailor construction of a DOM instance. """ # There's really no need for this class; concrete implementations # should just implement the endElement() and startElement() # methods as appropriate. Using this makes it easy to only # implement one of them. FILTER_ACCEPT = 1 FILTER_REJECT = 2 FILTER_SKIP = 3 FILTER_INTERRUPT = 4 whatToShow = NodeFilter.SHOW_ALL def _get_whatToShow(self): return self.whatToShow def acceptNode(self, element): return self.FILTER_ACCEPT def startContainer(self, element): return self.FILTER_ACCEPT del NodeFilter class DocumentLS: """Mixin to create documents that conform to the load/save spec.""" async = False def _get_async(self): return False def _set_async(self, async): if async: raise xml.dom.NotSupportedErr( "asynchronous document loading is not supported") def abort(self): # What does it mean to "clear" a document? Does the # documentElement disappear? raise NotImplementedError( "haven't figured out what this means yet") def load(self, uri): raise NotImplementedError("haven't written this yet") def loadXML(self, source): raise NotImplementedError("haven't written this yet") def saveXML(self, snode): if snode is None: snode = self elif snode.ownerDocument is not self: raise xml.dom.WrongDocumentErr() return snode.toxml() class DOMImplementationLS: MODE_SYNCHRONOUS = 1 MODE_ASYNCHRONOUS = 2 def createDOMBuilder(self, mode, schemaType): if schemaType is not None: raise xml.dom.NotSupportedErr( "schemaType not yet supported") if mode == self.MODE_SYNCHRONOUS: return DOMBuilder() if mode == self.MODE_ASYNCHRONOUS: raise xml.dom.NotSupportedErr( "asynchronous builders are not supported") raise ValueError("unknown value for mode") def createDOMWriter(self): raise NotImplementedError( "the writer interface hasn't been written yet!") def createDOMInputSource(self): return DOMInputSource()
gpl-2.0
dternyak/React-Redux-Flask
tests/test_api.py
7
2804
from testing_config import BaseTestConfig from application.models import User import json from application.utils import auth class TestAPI(BaseTestConfig): some_user = { "email": "one@gmail.com", "password": "something1" } def test_get_spa_from_index(self): result = self.app.get("/") self.assertIn('<html>', result.data.decode("utf-8")) def test_create_new_user(self): self.assertIsNone(User.query.filter_by( email=self.some_user["email"] ).first()) res = self.app.post( "/api/create_user", data=json.dumps(self.some_user), content_type='application/json' ) self.assertEqual(res.status_code, 200) self.assertTrue(json.loads(res.data.decode("utf-8"))["token"]) self.assertEqual(User.query.filter_by(email=self.some_user["email"]).first().email, self.some_user["email"]) res2 = self.app.post( "/api/create_user", data=json.dumps(self.some_user), content_type='application/json' ) self.assertEqual(res2.status_code, 409) def test_get_token_and_verify_token(self): res = self.app.post( "/api/get_token", data=json.dumps(self.default_user), content_type='application/json' ) token = json.loads(res.data.decode("utf-8"))["token"] self.assertTrue(auth.verify_token(token)) self.assertEqual(res.status_code, 200) res2 = self.app.post( "/api/is_token_valid", data=json.dumps({"token": token}), content_type='application/json' ) self.assertTrue(json.loads(res2.data.decode("utf-8")), ["token_is_valid"]) res3 = self.app.post( "/api/is_token_valid", data=json.dumps({"token": token + "something-else"}), content_type='application/json' ) self.assertEqual(res3.status_code, 403) res4 = self.app.post( "/api/get_token", data=json.dumps(self.some_user), content_type='application/json' ) self.assertEqual(res4.status_code, 403) def test_protected_route(self): headers = { 'Authorization': self.token, } bad_headers = { 'Authorization': self.token + "bad", } response = self.app.get('/api/user', headers=headers) self.assertEqual(response.status_code, 200) response2 = self.app.get('/api/user') self.assertEqual(response2.status_code, 401) response3 = self.app.get('/api/user', headers=bad_headers) self.assertEqual(response3.status_code, 401)
mit
skycucumber/restful
python/venv/lib/python2.7/site-packages/flask/config.py
781
6234
# -*- coding: utf-8 -*- """ flask.config ~~~~~~~~~~~~ Implements the configuration related objects. :copyright: (c) 2011 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import imp import os import errno from werkzeug.utils import import_string from ._compat import string_types class ConfigAttribute(object): """Makes an attribute forward to the config""" def __init__(self, name, get_converter=None): self.__name__ = name self.get_converter = get_converter def __get__(self, obj, type=None): if obj is None: return self rv = obj.config[self.__name__] if self.get_converter is not None: rv = self.get_converter(rv) return rv def __set__(self, obj, value): obj.config[self.__name__] = value class Config(dict): """Works exactly like a dict but provides ways to fill it from files or special dictionaries. There are two common patterns to populate the config. Either you can fill the config from a config file:: app.config.from_pyfile('yourconfig.cfg') Or alternatively you can define the configuration options in the module that calls :meth:`from_object` or provide an import path to a module that should be loaded. It is also possible to tell it to use the same module and with that provide the configuration values just before the call:: DEBUG = True SECRET_KEY = 'development key' app.config.from_object(__name__) In both cases (loading from any Python file or loading from modules), only uppercase keys are added to the config. This makes it possible to use lowercase values in the config file for temporary values that are not added to the config or to define the config keys in the same file that implements the application. Probably the most interesting way to load configurations is from an environment variable pointing to a file:: app.config.from_envvar('YOURAPPLICATION_SETTINGS') In this case before launching the application you have to set this environment variable to the file you want to use. On Linux and OS X use the export statement:: export YOURAPPLICATION_SETTINGS='/path/to/config/file' On windows use `set` instead. :param root_path: path to which files are read relative from. When the config object is created by the application, this is the application's :attr:`~flask.Flask.root_path`. :param defaults: an optional dictionary of default values """ def __init__(self, root_path, defaults=None): dict.__init__(self, defaults or {}) self.root_path = root_path def from_envvar(self, variable_name, silent=False): """Loads a configuration from an environment variable pointing to a configuration file. This is basically just a shortcut with nicer error messages for this line of code:: app.config.from_pyfile(os.environ['YOURAPPLICATION_SETTINGS']) :param variable_name: name of the environment variable :param silent: set to `True` if you want silent failure for missing files. :return: bool. `True` if able to load config, `False` otherwise. """ rv = os.environ.get(variable_name) if not rv: if silent: return False raise RuntimeError('The environment variable %r is not set ' 'and as such configuration could not be ' 'loaded. Set this variable and make it ' 'point to a configuration file' % variable_name) return self.from_pyfile(rv, silent=silent) def from_pyfile(self, filename, silent=False): """Updates the values in the config from a Python file. This function behaves as if the file was imported as module with the :meth:`from_object` function. :param filename: the filename of the config. This can either be an absolute filename or a filename relative to the root path. :param silent: set to `True` if you want silent failure for missing files. .. versionadded:: 0.7 `silent` parameter. """ filename = os.path.join(self.root_path, filename) d = imp.new_module('config') d.__file__ = filename try: with open(filename) as config_file: exec(compile(config_file.read(), filename, 'exec'), d.__dict__) except IOError as e: if silent and e.errno in (errno.ENOENT, errno.EISDIR): return False e.strerror = 'Unable to load configuration file (%s)' % e.strerror raise self.from_object(d) return True def from_object(self, obj): """Updates the values from the given object. An object can be of one of the following two types: - a string: in this case the object with that name will be imported - an actual object reference: that object is used directly Objects are usually either modules or classes. Just the uppercase variables in that object are stored in the config. Example usage:: app.config.from_object('yourapplication.default_config') from yourapplication import default_config app.config.from_object(default_config) You should not use this function to load the actual configuration but rather configuration defaults. The actual config should be loaded with :meth:`from_pyfile` and ideally from a location not within the package because the package might be installed system wide. :param obj: an import name or object """ if isinstance(obj, string_types): obj = import_string(obj) for key in dir(obj): if key.isupper(): self[key] = getattr(obj, key) def __repr__(self): return '<%s %s>' % (self.__class__.__name__, dict.__repr__(self))
gpl-2.0
lukecwik/incubator-beam
sdks/python/apache_beam/metrics/execution_test.py
1
4617
# # 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. # # pytype: skip-file from __future__ import absolute_import import unittest from builtins import range from apache_beam.metrics.execution import MetricKey from apache_beam.metrics.execution import MetricsContainer from apache_beam.metrics.metricbase import MetricName class TestMetricKey(unittest.TestCase): def test_equality_for_key_with_labels(self): test_labels = {'label1', 'value1'} test_object = MetricKey( 'step', MetricName('namespace', 'name'), labels=test_labels) same_labels = MetricKey( 'step', MetricName('namespace', 'name'), labels={'label1', 'value1'}) same_label_reference = MetricKey( 'step', MetricName('namespace', 'name'), labels=test_labels) self.assertEqual(test_object, same_labels) self.assertEqual(test_object, same_label_reference) self.assertEqual(hash(test_object), hash(same_labels)) self.assertEqual(hash(test_object), hash(same_label_reference)) def test_inequality_for_key_with_labels(self): test_labels = {'label1', 'value1'} test_object = MetricKey( 'step', MetricName('namespace', 'name'), labels=test_labels) no_labels = MetricKey('step', MetricName('namespace', 'name')) diff_label_key = MetricKey( 'step', MetricName('namespace', 'name'), labels={'l1_diff', 'value1'}) diff_label_value = MetricKey( 'step', MetricName('namespace', 'name'), labels={'label1', 'v1_diff'}) self.assertNotEqual(test_object, no_labels) self.assertNotEqual(test_object, diff_label_key) self.assertNotEqual(test_object, diff_label_value) self.assertNotEqual(hash(test_object), hash(no_labels)) self.assertNotEqual(hash(test_object), hash(diff_label_key)) self.assertNotEqual(hash(test_object), hash(diff_label_value)) def test_equality_for_key_with_no_labels(self): test_object = MetricKey('step', MetricName('namespace', 'name')) same = MetricKey('step', MetricName('namespace', 'name')) self.assertEqual(test_object, same) self.assertEqual(hash(test_object), hash(same)) diff_step = MetricKey('step_diff', MetricName('namespace', 'name')) diff_namespace = MetricKey('step', MetricName('namespace_diff', 'name')) diff_name = MetricKey('step', MetricName('namespace', 'name_diff')) self.assertNotEqual(test_object, diff_step) self.assertNotEqual(test_object, diff_namespace) self.assertNotEqual(test_object, diff_name) self.assertNotEqual(hash(test_object), hash(diff_step)) self.assertNotEqual(hash(test_object), hash(diff_namespace)) self.assertNotEqual(hash(test_object), hash(diff_name)) class TestMetricsContainer(unittest.TestCase): def test_add_to_counter(self): mc = MetricsContainer('astep') counter = mc.get_counter(MetricName('namespace', 'name')) counter.inc() counter = mc.get_counter(MetricName('namespace', 'name')) self.assertEqual(counter.value, 1) def test_get_cumulative_or_updates(self): mc = MetricsContainer('astep') all_values = [] for i in range(1, 11): counter = mc.get_counter(MetricName('namespace', 'name{}'.format(i))) distribution = mc.get_distribution( MetricName('namespace', 'name{}'.format(i))) gauge = mc.get_gauge(MetricName('namespace', 'name{}'.format(i))) counter.inc(i) distribution.update(i) gauge.set(i) all_values.append(i) # Retrieve ALL updates. cumulative = mc.get_cumulative() self.assertEqual(len(cumulative.counters), 10) self.assertEqual(len(cumulative.distributions), 10) self.assertEqual(len(cumulative.gauges), 10) self.assertEqual( set(all_values), set([v for _, v in cumulative.counters.items()])) self.assertEqual( set(all_values), set([v.value for _, v in cumulative.gauges.items()])) if __name__ == '__main__': unittest.main()
apache-2.0
arpitparmar5739/youtube-dl
youtube_dl/extractor/vh1.py
199
9798
from __future__ import unicode_literals from .mtv import MTVIE import re from ..utils import fix_xml_ampersands class VH1IE(MTVIE): IE_NAME = 'vh1.com' _FEED_URL = 'http://www.vh1.com/player/embed/AS3/fullepisode/rss/' _TESTS = [{ 'url': 'http://www.vh1.com/video/metal-evolution/full-episodes/progressive-metal/1678612/playlist.jhtml', 'playlist': [ { 'md5': '7827a7505f59633983165bbd2c119b52', 'info_dict': { 'id': '731565', 'ext': 'mp4', 'title': 'Metal Evolution: Ep. 11 Act 1', 'description': 'Many rock academics have proclaimed that the truly progressive musicianship of the last 20 years has been found right here in the world of heavy metal, rather than obvious locales such as jazz, fusion or progressive rock. It stands to reason then, that much of this jaw-dropping virtuosity occurs within what\'s known as progressive metal, a genre that takes root with the likes of Rush in the \'70s, Queensryche and Fates Warning in the \'80s, and Dream Theater in the \'90s. Since then, the genre has exploded with creativity, spawning mind-bending, genre-defying acts such as Tool, Mastodon, Coheed And Cambria, Porcupine Tree, Meshuggah, A Perfect Circle and Opeth. Episode 12 looks at the extreme musicianship of these bands, as well as their often extreme literary prowess and conceptual strength, the end result being a rich level of respect and attention such challenging acts have brought upon the world of heavy metal, from a critical community usually dismissive of the form.' } }, { 'md5': '34fb4b7321c546b54deda2102a61821f', 'info_dict': { 'id': '731567', 'ext': 'mp4', 'title': 'Metal Evolution: Ep. 11 Act 2', 'description': 'Many rock academics have proclaimed that the truly progressive musicianship of the last 20 years has been found right here in the world of heavy metal, rather than obvious locales such as jazz, fusion or progressive rock. It stands to reason then, that much of this jaw-dropping virtuosity occurs within what\'s known as progressive metal, a genre that takes root with the likes of Rush in the \'70s, Queensryche and Fates Warning in the \'80s, and Dream Theater in the \'90s. Since then, the genre has exploded with creativity, spawning mind-bending, genre-defying acts such as Tool, Mastodon, Coheed And Cambria, Porcupine Tree, Meshuggah, A Perfect Circle and Opeth. Episode 11 looks at the extreme musicianship of these bands, as well as their often extreme literary prowess and conceptual strength, the end result being a rich level of respect and attention such challenging acts have brought upon the world of heavy metal, from a critical community usually dismissive of the form.' } }, { 'md5': '813f38dba4c1b8647196135ebbf7e048', 'info_dict': { 'id': '731568', 'ext': 'mp4', 'title': 'Metal Evolution: Ep. 11 Act 3', 'description': 'Many rock academics have proclaimed that the truly progressive musicianship of the last 20 years has been found right here in the world of heavy metal, rather than obvious locales such as jazz, fusion or progressive rock. It stands to reason then, that much of this jaw-dropping virtuosity occurs within what\'s known as progressive metal, a genre that takes root with the likes of Rush in the \'70s, Queensryche and Fates Warning in the \'80s, and Dream Theater in the \'90s. Since then, the genre has exploded with creativity, spawning mind-bending, genre-defying acts such as Tool, Mastodon, Coheed And Cambria, Porcupine Tree, Meshuggah, A Perfect Circle and Opeth. Episode 11 looks at the extreme musicianship of these bands, as well as their often extreme literary prowess and conceptual strength, the end result being a rich level of respect and attention such challenging acts have brought upon the world of heavy metal, from a critical community usually dismissive of the form.' } }, { 'md5': '51adb72439dfaed11c799115d76e497f', 'info_dict': { 'id': '731569', 'ext': 'mp4', 'title': 'Metal Evolution: Ep. 11 Act 4', 'description': 'Many rock academics have proclaimed that the truly progressive musicianship of the last 20 years has been found right here in the world of heavy metal, rather than obvious locales such as jazz, fusion or progressive rock. It stands to reason then, that much of this jaw-dropping virtuosity occurs within what\'s known as progressive metal, a genre that takes root with the likes of Rush in the \'70s, Queensryche and Fates Warning in the \'80s, and Dream Theater in the \'90s. Since then, the genre has exploded with creativity, spawning mind-bending, genre-defying acts such as Tool, Mastodon, Coheed And Cambria, Porcupine Tree, Meshuggah, A Perfect Circle and Opeth. Episode 11 looks at the extreme musicianship of these bands, as well as their often extreme literary prowess and conceptual strength, the end result being a rich level of respect and attention such challenging acts have brought upon the world of heavy metal, from a critical community usually dismissive of the form.' } }, { 'md5': '93d554aaf79320703b73a95288c76a6e', 'info_dict': { 'id': '731570', 'ext': 'mp4', 'title': 'Metal Evolution: Ep. 11 Act 5', 'description': 'Many rock academics have proclaimed that the truly progressive musicianship of the last 20 years has been found right here in the world of heavy metal, rather than obvious locales such as jazz, fusion or progressive rock. It stands to reason then, that much of this jaw-dropping virtuosity occurs within what\'s known as progressive metal, a genre that takes root with the likes of Rush in the \'70s, Queensryche and Fates Warning in the \'80s, and Dream Theater in the \'90s. Since then, the genre has exploded with creativity, spawning mind-bending, genre-defying acts such as Tool, Mastodon, Coheed And Cambria, Porcupine Tree, Meshuggah, A Perfect Circle and Opeth. Episode 11 looks at the extreme musicianship of these bands, as well as their often extreme literary prowess and conceptual strength, the end result being a rich level of respect and attention such challenging acts have brought upon the world of heavy metal, from a critical community usually dismissive of the form.' } } ], 'skip': 'Blocked outside the US', }, { # Clip 'url': 'http://www.vh1.com/video/misc/706675/metal-evolution-episode-1-pre-metal-show-clip.jhtml#id=1674118', 'md5': '7d67cf6d9cdc6b4f3d3ac97a55403844', 'info_dict': { 'id': '706675', 'ext': 'mp4', 'title': 'Metal Evolution: Episode 1 Pre-Metal Show Clip', 'description': 'The greatest documentary ever made about Heavy Metal begins as our host Sam Dunn travels the globe to seek out the origins and influences that helped create Heavy Metal. Sam speaks to legends like Kirk Hammett, Alice Cooper, Slash, Bill Ward, Geezer Butler, Tom Morello, Ace Frehley, Lemmy Kilmister, Dave Davies, and many many more. This episode is the prologue for the 11 hour series, and Sam goes back to the very beginning to reveal how Heavy Metal was created.' }, 'skip': 'Blocked outside the US', }, { # Short link 'url': 'http://www.vh1.com/video/play.jhtml?id=1678353', 'md5': '853192b87ad978732b67dd8e549b266a', 'info_dict': { 'id': '730355', 'ext': 'mp4', 'title': 'Metal Evolution: Episode 11 Progressive Metal Sneak', 'description': 'In Metal Evolution\'s finale sneak, Sam sits with Michael Giles of King Crimson and gets feedback from Metallica guitarist Kirk Hammett on why the group was influential.' }, 'skip': 'Blocked outside the US', }, { 'url': 'http://www.vh1.com/video/macklemore-ryan-lewis/900535/cant-hold-us-ft-ray-dalton.jhtml', 'md5': 'b1bcb5b4380c9d7f544065589432dee7', 'info_dict': { 'id': '900535', 'ext': 'mp4', 'title': 'Macklemore & Ryan Lewis - "Can\'t Hold Us ft. Ray Dalton"', 'description': 'The Heist' }, 'skip': 'Blocked outside the US', }] _VALID_URL = r'''(?x) https?://www\.vh1\.com/video/ (?: .+?/full-episodes/.+?/(?P<playlist_id>[^/]+)/playlist\.jhtml | (?: play.jhtml\?id=| misc/.+?/.+?\.jhtml\#id= ) (?P<video_id>[0-9]+)$ | [^/]+/(?P<music_id>[0-9]+)/[^/]+? ) ''' def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) if mobj.group('music_id'): id_field = 'vid' video_id = mobj.group('music_id') else: video_id = mobj.group('playlist_id') or mobj.group('video_id') id_field = 'id' doc_url = '%s?%s=%s' % (self._FEED_URL, id_field, video_id) idoc = self._download_xml( doc_url, video_id, 'Downloading info', transform_source=fix_xml_ampersands) return self.playlist_result( [self._get_video_info(item) for item in idoc.findall('.//item')], playlist_id=video_id, )
unlicense
MattAllmendinger/coala
coalib/parsing/StringProcessing/Match.py
18
1536
from coalib.misc.Decorators import generate_ordering, generate_repr @generate_repr("match", "range") @generate_ordering("range", "match") class Match: """ Stores information about a single textual match. """ def __init__(self, match, position): """ Instantiates a new Match. :param match: The actual matched string. :param position: The position where the match was found. Starts from zero. """ self._match = match self._position = position def __len__(self): return len(self.match) def __str__(self): return self.match @property def match(self): """ Returns the text matched. :returns: The text matched. """ return self._match @property def position(self): """ Returns the position where the text was matched (zero-based). :returns: The position. """ return self._position @property def end_position(self): """ Marks the end position of the matched text (zero-based). :returns: The end-position. """ return len(self) + self.position @property def range(self): """ Returns the position range where the text was matched. :returns: A pair indicating the position range. The first element is the start position, the second one the end position. """ return (self.position, self.end_position)
agpl-3.0
Srisai85/scipy
scipy/sparse/spfuncs.py
149
2823
""" Functions that operate on sparse matrices """ from __future__ import division, print_function, absolute_import __all__ = ['count_blocks','estimate_blocksize'] from .csr import isspmatrix_csr, csr_matrix from .csc import isspmatrix_csc from ._sparsetools import csr_count_blocks def extract_diagonal(A): raise NotImplementedError('use .diagonal() instead') #def extract_diagonal(A): # """extract_diagonal(A) returns the main diagonal of A.""" # #TODO extract k-th diagonal # if isspmatrix_csr(A) or isspmatrix_csc(A): # fn = getattr(sparsetools, A.format + "_diagonal") # y = empty( min(A.shape), dtype=upcast(A.dtype) ) # fn(A.shape[0],A.shape[1],A.indptr,A.indices,A.data,y) # return y # elif isspmatrix_bsr(A): # M,N = A.shape # R,C = A.blocksize # y = empty( min(M,N), dtype=upcast(A.dtype) ) # fn = sparsetools.bsr_diagonal(M//R, N//C, R, C, \ # A.indptr, A.indices, ravel(A.data), y) # return y # else: # return extract_diagonal(csr_matrix(A)) def estimate_blocksize(A,efficiency=0.7): """Attempt to determine the blocksize of a sparse matrix Returns a blocksize=(r,c) such that - A.nnz / A.tobsr( (r,c) ).nnz > efficiency """ if not (isspmatrix_csr(A) or isspmatrix_csc(A)): A = csr_matrix(A) if A.nnz == 0: return (1,1) if not 0 < efficiency < 1.0: raise ValueError('efficiency must satisfy 0.0 < efficiency < 1.0') high_efficiency = (1.0 + efficiency) / 2.0 nnz = float(A.nnz) M,N = A.shape if M % 2 == 0 and N % 2 == 0: e22 = nnz / (4 * count_blocks(A,(2,2))) else: e22 = 0.0 if M % 3 == 0 and N % 3 == 0: e33 = nnz / (9 * count_blocks(A,(3,3))) else: e33 = 0.0 if e22 > high_efficiency and e33 > high_efficiency: e66 = nnz / (36 * count_blocks(A,(6,6))) if e66 > efficiency: return (6,6) else: return (3,3) else: if M % 4 == 0 and N % 4 == 0: e44 = nnz / (16 * count_blocks(A,(4,4))) else: e44 = 0.0 if e44 > efficiency: return (4,4) elif e33 > efficiency: return (3,3) elif e22 > efficiency: return (2,2) else: return (1,1) def count_blocks(A,blocksize): """For a given blocksize=(r,c) count the number of occupied blocks in a sparse matrix A """ r,c = blocksize if r < 1 or c < 1: raise ValueError('r and c must be positive') if isspmatrix_csr(A): M,N = A.shape return csr_count_blocks(M,N,r,c,A.indptr,A.indices) elif isspmatrix_csc(A): return count_blocks(A.T,(c,r)) else: return count_blocks(csr_matrix(A),blocksize)
bsd-3-clause
nirmeshk/oh-mainline
vendor/packages/gdata/src/gdata/Crypto/Util/RFC1751.py
228
20114
#!/usr/local/bin/python # rfc1751.py : Converts between 128-bit strings and a human-readable # sequence of words, as defined in RFC1751: "A Convention for # Human-Readable 128-bit Keys", by Daniel L. McDonald. __revision__ = "$Id: RFC1751.py,v 1.6 2003/04/04 15:15:10 akuchling Exp $" import string, binascii binary={0:'0000', 1:'0001', 2:'0010', 3:'0011', 4:'0100', 5:'0101', 6:'0110', 7:'0111', 8:'1000', 9:'1001', 10:'1010', 11:'1011', 12:'1100', 13:'1101', 14:'1110', 15:'1111'} def _key2bin(s): "Convert a key into a string of binary digits" kl=map(lambda x: ord(x), s) kl=map(lambda x: binary[x/16]+binary[x&15], kl) return ''.join(kl) def _extract(key, start, length): """Extract a bitstring from a string of binary digits, and return its numeric value.""" k=key[start:start+length] return reduce(lambda x,y: x*2+ord(y)-48, k, 0) def key_to_english (key): """key_to_english(key:string) : string Transform an arbitrary key into a string containing English words. The key length must be a multiple of 8. """ english='' for index in range(0, len(key), 8): # Loop over 8-byte subkeys subkey=key[index:index+8] # Compute the parity of the key skbin=_key2bin(subkey) ; p=0 for i in range(0, 64, 2): p=p+_extract(skbin, i, 2) # Append parity bits to the subkey skbin=_key2bin(subkey+chr((p<<6) & 255)) for i in range(0, 64, 11): english=english+wordlist[_extract(skbin, i, 11)]+' ' return english[:-1] # Remove the trailing space def english_to_key (str): """english_to_key(string):string Transform a string into a corresponding key. The string must contain words separated by whitespace; the number of words must be a multiple of 6. """ L=string.split(string.upper(str)) ; key='' for index in range(0, len(L), 6): sublist=L[index:index+6] ; char=9*[0] ; bits=0 for i in sublist: index = wordlist.index(i) shift = (8-(bits+11)%8) %8 y = index << shift cl, cc, cr = (y>>16), (y>>8)&0xff, y & 0xff if (shift>5): char[bits/8] = char[bits/8] | cl char[bits/8+1] = char[bits/8+1] | cc char[bits/8+2] = char[bits/8+2] | cr elif shift>-3: char[bits/8] = char[bits/8] | cc char[bits/8+1] = char[bits/8+1] | cr else: char[bits/8] = char[bits/8] | cr bits=bits+11 subkey=reduce(lambda x,y:x+chr(y), char, '') # Check the parity of the resulting key skbin=_key2bin(subkey) p=0 for i in range(0, 64, 2): p=p+_extract(skbin, i, 2) if (p&3) != _extract(skbin, 64, 2): raise ValueError, "Parity error in resulting key" key=key+subkey[0:8] return key wordlist=[ "A", "ABE", "ACE", "ACT", "AD", "ADA", "ADD", "AGO", "AID", "AIM", "AIR", "ALL", "ALP", "AM", "AMY", "AN", "ANA", "AND", "ANN", "ANT", "ANY", "APE", "APS", "APT", "ARC", "ARE", "ARK", "ARM", "ART", "AS", "ASH", "ASK", "AT", "ATE", "AUG", "AUK", "AVE", "AWE", "AWK", "AWL", "AWN", "AX", "AYE", "BAD", "BAG", "BAH", "BAM", "BAN", "BAR", "BAT", "BAY", "BE", "BED", "BEE", "BEG", "BEN", "BET", "BEY", "BIB", "BID", "BIG", "BIN", "BIT", "BOB", "BOG", "BON", "BOO", "BOP", "BOW", "BOY", "BUB", "BUD", "BUG", "BUM", "BUN", "BUS", "BUT", "BUY", "BY", "BYE", "CAB", "CAL", "CAM", "CAN", "CAP", "CAR", "CAT", "CAW", "COD", "COG", "COL", "CON", "COO", "COP", "COT", "COW", "COY", "CRY", "CUB", "CUE", "CUP", "CUR", "CUT", "DAB", "DAD", "DAM", "DAN", "DAR", "DAY", "DEE", "DEL", "DEN", "DES", "DEW", "DID", "DIE", "DIG", "DIN", "DIP", "DO", "DOE", "DOG", "DON", "DOT", "DOW", "DRY", "DUB", "DUD", "DUE", "DUG", "DUN", "EAR", "EAT", "ED", "EEL", "EGG", "EGO", "ELI", "ELK", "ELM", "ELY", "EM", "END", "EST", "ETC", "EVA", "EVE", "EWE", "EYE", "FAD", "FAN", "FAR", "FAT", "FAY", "FED", "FEE", "FEW", "FIB", "FIG", "FIN", "FIR", "FIT", "FLO", "FLY", "FOE", "FOG", "FOR", "FRY", "FUM", "FUN", "FUR", "GAB", "GAD", "GAG", "GAL", "GAM", "GAP", "GAS", "GAY", "GEE", "GEL", "GEM", "GET", "GIG", "GIL", "GIN", "GO", "GOT", "GUM", "GUN", "GUS", "GUT", "GUY", "GYM", "GYP", "HA", "HAD", "HAL", "HAM", "HAN", "HAP", "HAS", "HAT", "HAW", "HAY", "HE", "HEM", "HEN", "HER", "HEW", "HEY", "HI", "HID", "HIM", "HIP", "HIS", "HIT", "HO", "HOB", "HOC", "HOE", "HOG", "HOP", "HOT", "HOW", "HUB", "HUE", "HUG", "HUH", "HUM", "HUT", "I", "ICY", "IDA", "IF", "IKE", "ILL", "INK", "INN", "IO", "ION", "IQ", "IRA", "IRE", "IRK", "IS", "IT", "ITS", "IVY", "JAB", "JAG", "JAM", "JAN", "JAR", "JAW", "JAY", "JET", "JIG", "JIM", "JO", "JOB", "JOE", "JOG", "JOT", "JOY", "JUG", "JUT", "KAY", "KEG", "KEN", "KEY", "KID", "KIM", "KIN", "KIT", "LA", "LAB", "LAC", "LAD", "LAG", "LAM", "LAP", "LAW", "LAY", "LEA", "LED", "LEE", "LEG", "LEN", "LEO", "LET", "LEW", "LID", "LIE", "LIN", "LIP", "LIT", "LO", "LOB", "LOG", "LOP", "LOS", "LOT", "LOU", "LOW", "LOY", "LUG", "LYE", "MA", "MAC", "MAD", "MAE", "MAN", "MAO", "MAP", "MAT", "MAW", "MAY", "ME", "MEG", "MEL", "MEN", "MET", "MEW", "MID", "MIN", "MIT", "MOB", "MOD", "MOE", "MOO", "MOP", "MOS", "MOT", "MOW", "MUD", "MUG", "MUM", "MY", "NAB", "NAG", "NAN", "NAP", "NAT", "NAY", "NE", "NED", "NEE", "NET", "NEW", "NIB", "NIL", "NIP", "NIT", "NO", "NOB", "NOD", "NON", "NOR", "NOT", "NOV", "NOW", "NU", "NUN", "NUT", "O", "OAF", "OAK", "OAR", "OAT", "ODD", "ODE", "OF", "OFF", "OFT", "OH", "OIL", "OK", "OLD", "ON", "ONE", "OR", "ORB", "ORE", "ORR", "OS", "OTT", "OUR", "OUT", "OVA", "OW", "OWE", "OWL", "OWN", "OX", "PA", "PAD", "PAL", "PAM", "PAN", "PAP", "PAR", "PAT", "PAW", "PAY", "PEA", "PEG", "PEN", "PEP", "PER", "PET", "PEW", "PHI", "PI", "PIE", "PIN", "PIT", "PLY", "PO", "POD", "POE", "POP", "POT", "POW", "PRO", "PRY", "PUB", "PUG", "PUN", "PUP", "PUT", "QUO", "RAG", "RAM", "RAN", "RAP", "RAT", "RAW", "RAY", "REB", "RED", "REP", "RET", "RIB", "RID", "RIG", "RIM", "RIO", "RIP", "ROB", "ROD", "ROE", "RON", "ROT", "ROW", "ROY", "RUB", "RUE", "RUG", "RUM", "RUN", "RYE", "SAC", "SAD", "SAG", "SAL", "SAM", "SAN", "SAP", "SAT", "SAW", "SAY", "SEA", "SEC", "SEE", "SEN", "SET", "SEW", "SHE", "SHY", "SIN", "SIP", "SIR", "SIS", "SIT", "SKI", "SKY", "SLY", "SO", "SOB", "SOD", "SON", "SOP", "SOW", "SOY", "SPA", "SPY", "SUB", "SUD", "SUE", "SUM", "SUN", "SUP", "TAB", "TAD", "TAG", "TAN", "TAP", "TAR", "TEA", "TED", "TEE", "TEN", "THE", "THY", "TIC", "TIE", "TIM", "TIN", "TIP", "TO", "TOE", "TOG", "TOM", "TON", "TOO", "TOP", "TOW", "TOY", "TRY", "TUB", "TUG", "TUM", "TUN", "TWO", "UN", "UP", "US", "USE", "VAN", "VAT", "VET", "VIE", "WAD", "WAG", "WAR", "WAS", "WAY", "WE", "WEB", "WED", "WEE", "WET", "WHO", "WHY", "WIN", "WIT", "WOK", "WON", "WOO", "WOW", "WRY", "WU", "YAM", "YAP", "YAW", "YE", "YEA", "YES", "YET", "YOU", "ABED", "ABEL", "ABET", "ABLE", "ABUT", "ACHE", "ACID", "ACME", "ACRE", "ACTA", "ACTS", "ADAM", "ADDS", "ADEN", "AFAR", "AFRO", "AGEE", "AHEM", "AHOY", "AIDA", "AIDE", "AIDS", "AIRY", "AJAR", "AKIN", "ALAN", "ALEC", "ALGA", "ALIA", "ALLY", "ALMA", "ALOE", "ALSO", "ALTO", "ALUM", "ALVA", "AMEN", "AMES", "AMID", "AMMO", "AMOK", "AMOS", "AMRA", "ANDY", "ANEW", "ANNA", "ANNE", "ANTE", "ANTI", "AQUA", "ARAB", "ARCH", "AREA", "ARGO", "ARID", "ARMY", "ARTS", "ARTY", "ASIA", "ASKS", "ATOM", "AUNT", "AURA", "AUTO", "AVER", "AVID", "AVIS", "AVON", "AVOW", "AWAY", "AWRY", "BABE", "BABY", "BACH", "BACK", "BADE", "BAIL", "BAIT", "BAKE", "BALD", "BALE", "BALI", "BALK", "BALL", "BALM", "BAND", "BANE", "BANG", "BANK", "BARB", "BARD", "BARE", "BARK", "BARN", "BARR", "BASE", "BASH", "BASK", "BASS", "BATE", "BATH", "BAWD", "BAWL", "BEAD", "BEAK", "BEAM", "BEAN", "BEAR", "BEAT", "BEAU", "BECK", "BEEF", "BEEN", "BEER", "BEET", "BELA", "BELL", "BELT", "BEND", "BENT", "BERG", "BERN", "BERT", "BESS", "BEST", "BETA", "BETH", "BHOY", "BIAS", "BIDE", "BIEN", "BILE", "BILK", "BILL", "BIND", "BING", "BIRD", "BITE", "BITS", "BLAB", "BLAT", "BLED", "BLEW", "BLOB", "BLOC", "BLOT", "BLOW", "BLUE", "BLUM", "BLUR", "BOAR", "BOAT", "BOCA", "BOCK", "BODE", "BODY", "BOGY", "BOHR", "BOIL", "BOLD", "BOLO", "BOLT", "BOMB", "BONA", "BOND", "BONE", "BONG", "BONN", "BONY", "BOOK", "BOOM", "BOON", "BOOT", "BORE", "BORG", "BORN", "BOSE", "BOSS", "BOTH", "BOUT", "BOWL", "BOYD", "BRAD", "BRAE", "BRAG", "BRAN", "BRAY", "BRED", "BREW", "BRIG", "BRIM", "BROW", "BUCK", "BUDD", "BUFF", "BULB", "BULK", "BULL", "BUNK", "BUNT", "BUOY", "BURG", "BURL", "BURN", "BURR", "BURT", "BURY", "BUSH", "BUSS", "BUST", "BUSY", "BYTE", "CADY", "CAFE", "CAGE", "CAIN", "CAKE", "CALF", "CALL", "CALM", "CAME", "CANE", "CANT", "CARD", "CARE", "CARL", "CARR", "CART", "CASE", "CASH", "CASK", "CAST", "CAVE", "CEIL", "CELL", "CENT", "CERN", "CHAD", "CHAR", "CHAT", "CHAW", "CHEF", "CHEN", "CHEW", "CHIC", "CHIN", "CHOU", "CHOW", "CHUB", "CHUG", "CHUM", "CITE", "CITY", "CLAD", "CLAM", "CLAN", "CLAW", "CLAY", "CLOD", "CLOG", "CLOT", "CLUB", "CLUE", "COAL", "COAT", "COCA", "COCK", "COCO", "CODA", "CODE", "CODY", "COED", "COIL", "COIN", "COKE", "COLA", "COLD", "COLT", "COMA", "COMB", "COME", "COOK", "COOL", "COON", "COOT", "CORD", "CORE", "CORK", "CORN", "COST", "COVE", "COWL", "CRAB", "CRAG", "CRAM", "CRAY", "CREW", "CRIB", "CROW", "CRUD", "CUBA", "CUBE", "CUFF", "CULL", "CULT", "CUNY", "CURB", "CURD", "CURE", "CURL", "CURT", "CUTS", "DADE", "DALE", "DAME", "DANA", "DANE", "DANG", "DANK", "DARE", "DARK", "DARN", "DART", "DASH", "DATA", "DATE", "DAVE", "DAVY", "DAWN", "DAYS", "DEAD", "DEAF", "DEAL", "DEAN", "DEAR", "DEBT", "DECK", "DEED", "DEEM", "DEER", "DEFT", "DEFY", "DELL", "DENT", "DENY", "DESK", "DIAL", "DICE", "DIED", "DIET", "DIME", "DINE", "DING", "DINT", "DIRE", "DIRT", "DISC", "DISH", "DISK", "DIVE", "DOCK", "DOES", "DOLE", "DOLL", "DOLT", "DOME", "DONE", "DOOM", "DOOR", "DORA", "DOSE", "DOTE", "DOUG", "DOUR", "DOVE", "DOWN", "DRAB", "DRAG", "DRAM", "DRAW", "DREW", "DRUB", "DRUG", "DRUM", "DUAL", "DUCK", "DUCT", "DUEL", "DUET", "DUKE", "DULL", "DUMB", "DUNE", "DUNK", "DUSK", "DUST", "DUTY", "EACH", "EARL", "EARN", "EASE", "EAST", "EASY", "EBEN", "ECHO", "EDDY", "EDEN", "EDGE", "EDGY", "EDIT", "EDNA", "EGAN", "ELAN", "ELBA", "ELLA", "ELSE", "EMIL", "EMIT", "EMMA", "ENDS", "ERIC", "EROS", "EVEN", "EVER", "EVIL", "EYED", "FACE", "FACT", "FADE", "FAIL", "FAIN", "FAIR", "FAKE", "FALL", "FAME", "FANG", "FARM", "FAST", "FATE", "FAWN", "FEAR", "FEAT", "FEED", "FEEL", "FEET", "FELL", "FELT", "FEND", "FERN", "FEST", "FEUD", "FIEF", "FIGS", "FILE", "FILL", "FILM", "FIND", "FINE", "FINK", "FIRE", "FIRM", "FISH", "FISK", "FIST", "FITS", "FIVE", "FLAG", "FLAK", "FLAM", "FLAT", "FLAW", "FLEA", "FLED", "FLEW", "FLIT", "FLOC", "FLOG", "FLOW", "FLUB", "FLUE", "FOAL", "FOAM", "FOGY", "FOIL", "FOLD", "FOLK", "FOND", "FONT", "FOOD", "FOOL", "FOOT", "FORD", "FORE", "FORK", "FORM", "FORT", "FOSS", "FOUL", "FOUR", "FOWL", "FRAU", "FRAY", "FRED", "FREE", "FRET", "FREY", "FROG", "FROM", "FUEL", "FULL", "FUME", "FUND", "FUNK", "FURY", "FUSE", "FUSS", "GAFF", "GAGE", "GAIL", "GAIN", "GAIT", "GALA", "GALE", "GALL", "GALT", "GAME", "GANG", "GARB", "GARY", "GASH", "GATE", "GAUL", "GAUR", "GAVE", "GAWK", "GEAR", "GELD", "GENE", "GENT", "GERM", "GETS", "GIBE", "GIFT", "GILD", "GILL", "GILT", "GINA", "GIRD", "GIRL", "GIST", "GIVE", "GLAD", "GLEE", "GLEN", "GLIB", "GLOB", "GLOM", "GLOW", "GLUE", "GLUM", "GLUT", "GOAD", "GOAL", "GOAT", "GOER", "GOES", "GOLD", "GOLF", "GONE", "GONG", "GOOD", "GOOF", "GORE", "GORY", "GOSH", "GOUT", "GOWN", "GRAB", "GRAD", "GRAY", "GREG", "GREW", "GREY", "GRID", "GRIM", "GRIN", "GRIT", "GROW", "GRUB", "GULF", "GULL", "GUNK", "GURU", "GUSH", "GUST", "GWEN", "GWYN", "HAAG", "HAAS", "HACK", "HAIL", "HAIR", "HALE", "HALF", "HALL", "HALO", "HALT", "HAND", "HANG", "HANK", "HANS", "HARD", "HARK", "HARM", "HART", "HASH", "HAST", "HATE", "HATH", "HAUL", "HAVE", "HAWK", "HAYS", "HEAD", "HEAL", "HEAR", "HEAT", "HEBE", "HECK", "HEED", "HEEL", "HEFT", "HELD", "HELL", "HELM", "HERB", "HERD", "HERE", "HERO", "HERS", "HESS", "HEWN", "HICK", "HIDE", "HIGH", "HIKE", "HILL", "HILT", "HIND", "HINT", "HIRE", "HISS", "HIVE", "HOBO", "HOCK", "HOFF", "HOLD", "HOLE", "HOLM", "HOLT", "HOME", "HONE", "HONK", "HOOD", "HOOF", "HOOK", "HOOT", "HORN", "HOSE", "HOST", "HOUR", "HOVE", "HOWE", "HOWL", "HOYT", "HUCK", "HUED", "HUFF", "HUGE", "HUGH", "HUGO", "HULK", "HULL", "HUNK", "HUNT", "HURD", "HURL", "HURT", "HUSH", "HYDE", "HYMN", "IBIS", "ICON", "IDEA", "IDLE", "IFFY", "INCA", "INCH", "INTO", "IONS", "IOTA", "IOWA", "IRIS", "IRMA", "IRON", "ISLE", "ITCH", "ITEM", "IVAN", "JACK", "JADE", "JAIL", "JAKE", "JANE", "JAVA", "JEAN", "JEFF", "JERK", "JESS", "JEST", "JIBE", "JILL", "JILT", "JIVE", "JOAN", "JOBS", "JOCK", "JOEL", "JOEY", "JOHN", "JOIN", "JOKE", "JOLT", "JOVE", "JUDD", "JUDE", "JUDO", "JUDY", "JUJU", "JUKE", "JULY", "JUNE", "JUNK", "JUNO", "JURY", "JUST", "JUTE", "KAHN", "KALE", "KANE", "KANT", "KARL", "KATE", "KEEL", "KEEN", "KENO", "KENT", "KERN", "KERR", "KEYS", "KICK", "KILL", "KIND", "KING", "KIRK", "KISS", "KITE", "KLAN", "KNEE", "KNEW", "KNIT", "KNOB", "KNOT", "KNOW", "KOCH", "KONG", "KUDO", "KURD", "KURT", "KYLE", "LACE", "LACK", "LACY", "LADY", "LAID", "LAIN", "LAIR", "LAKE", "LAMB", "LAME", "LAND", "LANE", "LANG", "LARD", "LARK", "LASS", "LAST", "LATE", "LAUD", "LAVA", "LAWN", "LAWS", "LAYS", "LEAD", "LEAF", "LEAK", "LEAN", "LEAR", "LEEK", "LEER", "LEFT", "LEND", "LENS", "LENT", "LEON", "LESK", "LESS", "LEST", "LETS", "LIAR", "LICE", "LICK", "LIED", "LIEN", "LIES", "LIEU", "LIFE", "LIFT", "LIKE", "LILA", "LILT", "LILY", "LIMA", "LIMB", "LIME", "LIND", "LINE", "LINK", "LINT", "LION", "LISA", "LIST", "LIVE", "LOAD", "LOAF", "LOAM", "LOAN", "LOCK", "LOFT", "LOGE", "LOIS", "LOLA", "LONE", "LONG", "LOOK", "LOON", "LOOT", "LORD", "LORE", "LOSE", "LOSS", "LOST", "LOUD", "LOVE", "LOWE", "LUCK", "LUCY", "LUGE", "LUKE", "LULU", "LUND", "LUNG", "LURA", "LURE", "LURK", "LUSH", "LUST", "LYLE", "LYNN", "LYON", "LYRA", "MACE", "MADE", "MAGI", "MAID", "MAIL", "MAIN", "MAKE", "MALE", "MALI", "MALL", "MALT", "MANA", "MANN", "MANY", "MARC", "MARE", "MARK", "MARS", "MART", "MARY", "MASH", "MASK", "MASS", "MAST", "MATE", "MATH", "MAUL", "MAYO", "MEAD", "MEAL", "MEAN", "MEAT", "MEEK", "MEET", "MELD", "MELT", "MEMO", "MEND", "MENU", "MERT", "MESH", "MESS", "MICE", "MIKE", "MILD", "MILE", "MILK", "MILL", "MILT", "MIMI", "MIND", "MINE", "MINI", "MINK", "MINT", "MIRE", "MISS", "MIST", "MITE", "MITT", "MOAN", "MOAT", "MOCK", "MODE", "MOLD", "MOLE", "MOLL", "MOLT", "MONA", "MONK", "MONT", "MOOD", "MOON", "MOOR", "MOOT", "MORE", "MORN", "MORT", "MOSS", "MOST", "MOTH", "MOVE", "MUCH", "MUCK", "MUDD", "MUFF", "MULE", "MULL", "MURK", "MUSH", "MUST", "MUTE", "MUTT", "MYRA", "MYTH", "NAGY", "NAIL", "NAIR", "NAME", "NARY", "NASH", "NAVE", "NAVY", "NEAL", "NEAR", "NEAT", "NECK", "NEED", "NEIL", "NELL", "NEON", "NERO", "NESS", "NEST", "NEWS", "NEWT", "NIBS", "NICE", "NICK", "NILE", "NINA", "NINE", "NOAH", "NODE", "NOEL", "NOLL", "NONE", "NOOK", "NOON", "NORM", "NOSE", "NOTE", "NOUN", "NOVA", "NUDE", "NULL", "NUMB", "OATH", "OBEY", "OBOE", "ODIN", "OHIO", "OILY", "OINT", "OKAY", "OLAF", "OLDY", "OLGA", "OLIN", "OMAN", "OMEN", "OMIT", "ONCE", "ONES", "ONLY", "ONTO", "ONUS", "ORAL", "ORGY", "OSLO", "OTIS", "OTTO", "OUCH", "OUST", "OUTS", "OVAL", "OVEN", "OVER", "OWLY", "OWNS", "QUAD", "QUIT", "QUOD", "RACE", "RACK", "RACY", "RAFT", "RAGE", "RAID", "RAIL", "RAIN", "RAKE", "RANK", "RANT", "RARE", "RASH", "RATE", "RAVE", "RAYS", "READ", "REAL", "REAM", "REAR", "RECK", "REED", "REEF", "REEK", "REEL", "REID", "REIN", "RENA", "REND", "RENT", "REST", "RICE", "RICH", "RICK", "RIDE", "RIFT", "RILL", "RIME", "RING", "RINK", "RISE", "RISK", "RITE", "ROAD", "ROAM", "ROAR", "ROBE", "ROCK", "RODE", "ROIL", "ROLL", "ROME", "ROOD", "ROOF", "ROOK", "ROOM", "ROOT", "ROSA", "ROSE", "ROSS", "ROSY", "ROTH", "ROUT", "ROVE", "ROWE", "ROWS", "RUBE", "RUBY", "RUDE", "RUDY", "RUIN", "RULE", "RUNG", "RUNS", "RUNT", "RUSE", "RUSH", "RUSK", "RUSS", "RUST", "RUTH", "SACK", "SAFE", "SAGE", "SAID", "SAIL", "SALE", "SALK", "SALT", "SAME", "SAND", "SANE", "SANG", "SANK", "SARA", "SAUL", "SAVE", "SAYS", "SCAN", "SCAR", "SCAT", "SCOT", "SEAL", "SEAM", "SEAR", "SEAT", "SEED", "SEEK", "SEEM", "SEEN", "SEES", "SELF", "SELL", "SEND", "SENT", "SETS", "SEWN", "SHAG", "SHAM", "SHAW", "SHAY", "SHED", "SHIM", "SHIN", "SHOD", "SHOE", "SHOT", "SHOW", "SHUN", "SHUT", "SICK", "SIDE", "SIFT", "SIGH", "SIGN", "SILK", "SILL", "SILO", "SILT", "SINE", "SING", "SINK", "SIRE", "SITE", "SITS", "SITU", "SKAT", "SKEW", "SKID", "SKIM", "SKIN", "SKIT", "SLAB", "SLAM", "SLAT", "SLAY", "SLED", "SLEW", "SLID", "SLIM", "SLIT", "SLOB", "SLOG", "SLOT", "SLOW", "SLUG", "SLUM", "SLUR", "SMOG", "SMUG", "SNAG", "SNOB", "SNOW", "SNUB", "SNUG", "SOAK", "SOAR", "SOCK", "SODA", "SOFA", "SOFT", "SOIL", "SOLD", "SOME", "SONG", "SOON", "SOOT", "SORE", "SORT", "SOUL", "SOUR", "SOWN", "STAB", "STAG", "STAN", "STAR", "STAY", "STEM", "STEW", "STIR", "STOW", "STUB", "STUN", "SUCH", "SUDS", "SUIT", "SULK", "SUMS", "SUNG", "SUNK", "SURE", "SURF", "SWAB", "SWAG", "SWAM", "SWAN", "SWAT", "SWAY", "SWIM", "SWUM", "TACK", "TACT", "TAIL", "TAKE", "TALE", "TALK", "TALL", "TANK", "TASK", "TATE", "TAUT", "TEAL", "TEAM", "TEAR", "TECH", "TEEM", "TEEN", "TEET", "TELL", "TEND", "TENT", "TERM", "TERN", "TESS", "TEST", "THAN", "THAT", "THEE", "THEM", "THEN", "THEY", "THIN", "THIS", "THUD", "THUG", "TICK", "TIDE", "TIDY", "TIED", "TIER", "TILE", "TILL", "TILT", "TIME", "TINA", "TINE", "TINT", "TINY", "TIRE", "TOAD", "TOGO", "TOIL", "TOLD", "TOLL", "TONE", "TONG", "TONY", "TOOK", "TOOL", "TOOT", "TORE", "TORN", "TOTE", "TOUR", "TOUT", "TOWN", "TRAG", "TRAM", "TRAY", "TREE", "TREK", "TRIG", "TRIM", "TRIO", "TROD", "TROT", "TROY", "TRUE", "TUBA", "TUBE", "TUCK", "TUFT", "TUNA", "TUNE", "TUNG", "TURF", "TURN", "TUSK", "TWIG", "TWIN", "TWIT", "ULAN", "UNIT", "URGE", "USED", "USER", "USES", "UTAH", "VAIL", "VAIN", "VALE", "VARY", "VASE", "VAST", "VEAL", "VEDA", "VEIL", "VEIN", "VEND", "VENT", "VERB", "VERY", "VETO", "VICE", "VIEW", "VINE", "VISE", "VOID", "VOLT", "VOTE", "WACK", "WADE", "WAGE", "WAIL", "WAIT", "WAKE", "WALE", "WALK", "WALL", "WALT", "WAND", "WANE", "WANG", "WANT", "WARD", "WARM", "WARN", "WART", "WASH", "WAST", "WATS", "WATT", "WAVE", "WAVY", "WAYS", "WEAK", "WEAL", "WEAN", "WEAR", "WEED", "WEEK", "WEIR", "WELD", "WELL", "WELT", "WENT", "WERE", "WERT", "WEST", "WHAM", "WHAT", "WHEE", "WHEN", "WHET", "WHOA", "WHOM", "WICK", "WIFE", "WILD", "WILL", "WIND", "WINE", "WING", "WINK", "WINO", "WIRE", "WISE", "WISH", "WITH", "WOLF", "WONT", "WOOD", "WOOL", "WORD", "WORE", "WORK", "WORM", "WORN", "WOVE", "WRIT", "WYNN", "YALE", "YANG", "YANK", "YARD", "YARN", "YAWL", "YAWN", "YEAH", "YEAR", "YELL", "YOGA", "YOKE" ] if __name__=='__main__': data = [('EB33F77EE73D4053', 'TIDE ITCH SLOW REIN RULE MOT'), ('CCAC2AED591056BE4F90FD441C534766', 'RASH BUSH MILK LOOK BAD BRIM AVID GAFF BAIT ROT POD LOVE'), ('EFF81F9BFBC65350920CDD7416DE8009', 'TROD MUTE TAIL WARM CHAR KONG HAAG CITY BORE O TEAL AWL') ] for key, words in data: print 'Trying key', key key=binascii.a2b_hex(key) w2=key_to_english(key) if w2!=words: print 'key_to_english fails on key', repr(key), ', producing', str(w2) k2=english_to_key(words) if k2!=key: print 'english_to_key fails on key', repr(key), ', producing', repr(k2)
agpl-3.0
nvoron23/arangodb
3rdParty/V8-4.3.61/tools/release/auto_push.py
22
3792
#!/usr/bin/env python # Copyright 2013 the V8 project authors. All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived # from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import argparse import json import os import re import sys import urllib from common_includes import * import create_release class Preparation(Step): MESSAGE = "Preparation." def RunStep(self): # Fetch unfetched revisions. self.vc.Fetch() class FetchCandidate(Step): MESSAGE = "Fetching V8 roll ref." def RunStep(self): # The roll ref points to the candidate to be rolled. self.Git("fetch origin +refs/heads/roll:refs/heads/roll") self["candidate"] = self.Git("show-ref -s refs/heads/roll").strip() class LastReleaseBailout(Step): MESSAGE = "Checking last V8 release base." def RunStep(self): last_release = self.GetLatestReleaseBase() commits = self.GitLog( format="%H", git_hash="%s..%s" % (last_release, self["candidate"])) if not commits: print "Already pushed current candidate %s" % self["candidate"] return True class CreateRelease(Step): MESSAGE = "Creating release if specified." def RunStep(self): print "Creating release for %s." % self["candidate"] args = [ "--author", self._options.author, "--reviewer", self._options.reviewer, "--revision", self["candidate"], "--force", ] if self._options.work_dir: args.extend(["--work-dir", self._options.work_dir]) if self._options.push: self._side_effect_handler.Call( create_release.CreateRelease().Run, args) class AutoPush(ScriptsBase): def _PrepareOptions(self, parser): parser.add_argument("-p", "--push", help="Create release. Dry run if unspecified.", default=False, action="store_true") def _ProcessOptions(self, options): if not options.author or not options.reviewer: # pragma: no cover print "You need to specify author and reviewer." return False options.requires_editor = False return True def _Config(self): return { "PERSISTFILE_BASENAME": "/tmp/v8-auto-push-tempfile", } def _Steps(self): return [ Preparation, FetchCandidate, LastReleaseBailout, CreateRelease, ] if __name__ == "__main__": # pragma: no cover sys.exit(AutoPush().Run())
apache-2.0
kumar303/pto-planner
apps/commons/tests/test_migrations.py
10
2015
import re from os import listdir from os.path import join, dirname import test_utils import manage class MigrationTests(test_utils.TestCase): """Sanity checks for the SQL migration scripts.""" @staticmethod def _migrations_path(): """Return the absolute path to the migration script folder.""" return manage.path('migrations') def test_unique(self): """Assert that the numeric prefixes of the DB migrations are unique.""" leading_digits = re.compile(r'^\d+') seen_numbers = set() path = self._migrations_path() for filename in listdir(path): match = leading_digits.match(filename) if match: number = match.group() if number in seen_numbers: self.fail('There is more than one migration #%s in %s.' % (number, path)) seen_numbers.add(number) def test_innodb_and_utf8(self): """Make sure each created table uses the InnoDB engine and UTF-8.""" # Heuristic: make sure there are at least as many "ENGINE=InnoDB"s as # "CREATE TABLE"s. (There might be additional "InnoDB"s in ALTER TABLE # statements, which are fine.) path = self._migrations_path() for filename in sorted(listdir(path)): with open(join(path, filename)) as f: contents = f.read() creates = contents.count('CREATE TABLE') engines = contents.count('ENGINE=InnoDB') encodings = (contents.count('CHARSET=utf8') + contents.count('CHARACTER SET utf8')) assert engines >= creates, ("There weren't as many " 'occurrences of "ENGINE=InnoDB" as of "CREATE TABLE" in ' 'migration %s.' % filename) assert encodings >= creates, ("There weren't as many " 'UTF-8 declarations as "CREATE TABLE" occurrences in ' 'migration %s.' % filename)
bsd-3-clause
ppwwyyxx/tensorflow
tensorflow/python/ops/weights_broadcast_ops.py
133
7197
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # 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. # ============================================================================== """Weight broadcasting operations. In `tf.losses` and `tf.metrics`, we support limited weight broadcasting. This file includes operations for those broadcasting rules. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import sets def _has_valid_dims(weights_shape, values_shape): with ops.name_scope( None, "has_invalid_dims", (weights_shape, values_shape)) as scope: values_shape_2d = array_ops.expand_dims(values_shape, -1) valid_dims = array_ops.concat( (values_shape_2d, array_ops.ones_like(values_shape_2d)), axis=1) weights_shape_2d = array_ops.expand_dims(weights_shape, -1) invalid_dims = sets.set_difference(weights_shape_2d, valid_dims) num_invalid_dims = array_ops.size( invalid_dims.values, name="num_invalid_dims") return math_ops.equal(0, num_invalid_dims, name=scope) def _has_valid_nonscalar_shape( weights_rank, weights_shape, values_rank, values_shape): with ops.name_scope( None, "has_valid_nonscalar_shape", (weights_rank, weights_shape, values_rank, values_shape)) as scope: is_same_rank = math_ops.equal( values_rank, weights_rank, name="is_same_rank") return control_flow_ops.cond( is_same_rank, lambda: _has_valid_dims(weights_shape, values_shape), lambda: is_same_rank, name=scope) _ASSERT_BROADCASTABLE_ERROR_PREFIX = "weights can not be broadcast to values." def assert_broadcastable(weights, values): """Asserts `weights` can be broadcast to `values`. In `tf.losses` and `tf.metrics`, we support limited weight broadcasting. We let weights be either scalar, or the same rank as the target values, with each dimension either 1, or the same as the corresponding values dimension. Args: weights: `Tensor` of weights. values: `Tensor` of values to which weights are applied. Returns: `Operation` raising `InvalidArgumentError` if `weights` has incorrect shape. `no_op` if static checks determine `weights` has correct shape. Raises: ValueError: If static checks determine `weights` has incorrect shape. """ with ops.name_scope(None, "assert_broadcastable", (weights, values)) as scope: with ops.name_scope(None, "weights", (weights,)) as weights_scope: weights = ops.convert_to_tensor(weights, name=weights_scope) weights_shape = array_ops.shape(weights, name="shape") weights_rank = array_ops.rank(weights, name="rank") weights_rank_static = tensor_util.constant_value(weights_rank) with ops.name_scope(None, "values", (values,)) as values_scope: values = ops.convert_to_tensor(values, name=values_scope) values_shape = array_ops.shape(values, name="shape") values_rank = array_ops.rank(values, name="rank") values_rank_static = tensor_util.constant_value(values_rank) # Try static checks. if weights_rank_static is not None and values_rank_static is not None: if weights_rank_static == 0: return control_flow_ops.no_op(name="static_scalar_check_success") if weights_rank_static != values_rank_static: raise ValueError( "%s values.rank=%s. weights.rank=%s." " values.shape=%s. weights.shape=%s." % ( _ASSERT_BROADCASTABLE_ERROR_PREFIX, values_rank_static, weights_rank_static, values.shape, weights.shape)) weights_shape_static = tensor_util.constant_value(weights_shape) values_shape_static = tensor_util.constant_value(values_shape) if weights_shape_static is not None and values_shape_static is not None: # Sanity check, this should always be true since we checked rank above. ndims = len(values_shape_static) assert ndims == len(weights_shape_static) for i in range(ndims): if weights_shape_static[i] not in (1, values_shape_static[i]): raise ValueError( "%s Mismatch at dim %s. values.shape=%s weights.shape=%s." % ( _ASSERT_BROADCASTABLE_ERROR_PREFIX, i, values_shape_static, weights_shape_static)) return control_flow_ops.no_op(name="static_dims_check_success") # Dynamic checks. is_scalar = math_ops.equal(0, weights_rank, name="is_scalar") data = ( _ASSERT_BROADCASTABLE_ERROR_PREFIX, "weights.shape=", weights.name, weights_shape, "values.shape=", values.name, values_shape, "is_scalar=", is_scalar, ) is_valid_shape = control_flow_ops.cond( is_scalar, lambda: is_scalar, lambda: _has_valid_nonscalar_shape( # pylint: disable=g-long-lambda weights_rank, weights_shape, values_rank, values_shape), name="is_valid_shape") return control_flow_ops.Assert(is_valid_shape, data, name=scope) def broadcast_weights(weights, values): """Broadcast `weights` to the same shape as `values`. This returns a version of `weights` following the same broadcast rules as `mul(weights, values)`, but limited to the weights shapes allowed by `assert_broadcastable`. When computing a weighted average, use this function to broadcast `weights` before summing them; e.g., `reduce_sum(w * v) / reduce_sum(_broadcast_weights(w, v))`. Args: weights: `Tensor` whose shape is broadcastable to `values` according to the rules of `assert_broadcastable`. values: `Tensor` of any shape. Returns: `weights` broadcast to `values` shape according to the rules of `assert_broadcastable`. """ with ops.name_scope(None, "broadcast_weights", (weights, values)) as scope: values = ops.convert_to_tensor(values, name="values") weights = ops.convert_to_tensor( weights, dtype=values.dtype.base_dtype, name="weights") # Try static check for exact match. weights_shape = weights.get_shape() values_shape = values.get_shape() if (weights_shape.is_fully_defined() and values_shape.is_fully_defined() and weights_shape.is_compatible_with(values_shape)): return weights with ops.control_dependencies((assert_broadcastable(weights, values),)): return math_ops.multiply( weights, array_ops.ones_like(values), name=scope)
apache-2.0
srvg/ansible
test/units/plugins/shell/test_powershell.py
31
5419
from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.plugins.shell.powershell import _parse_clixml, ShellModule def test_parse_clixml_empty(): empty = b'#< CLIXML\r\n<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04"></Objs>' expected = b'' actual = _parse_clixml(empty) assert actual == expected def test_parse_clixml_with_progress(): progress = b'#< CLIXML\r\n<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04">' \ b'<Obj S="progress" RefId="0"><TN RefId="0"><T>System.Management.Automation.PSCustomObject</T><T>System.Object</T></TN><MS>' \ b'<I64 N="SourceId">1</I64><PR N="Record"><AV>Preparing modules for first use.</AV><AI>0</AI><Nil />' \ b'<PI>-1</PI><PC>-1</PC><T>Completed</T><SR>-1</SR><SD> </SD></PR></MS></Obj></Objs>' expected = b'' actual = _parse_clixml(progress) assert actual == expected def test_parse_clixml_single_stream(): single_stream = b'#< CLIXML\r\n<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04">' \ b'<S S="Error">fake : The term \'fake\' is not recognized as the name of a cmdlet. Check _x000D__x000A_</S>' \ b'<S S="Error">the spelling of the name, or if a path was included._x000D__x000A_</S>' \ b'<S S="Error">At line:1 char:1_x000D__x000A_</S>' \ b'<S S="Error">+ fake cmdlet_x000D__x000A_</S><S S="Error">+ ~~~~_x000D__x000A_</S>' \ b'<S S="Error"> + CategoryInfo : ObjectNotFound: (fake:String) [], CommandNotFoundException_x000D__x000A_</S>' \ b'<S S="Error"> + FullyQualifiedErrorId : CommandNotFoundException_x000D__x000A_</S><S S="Error"> _x000D__x000A_</S>' \ b'</Objs>' expected = b"fake : The term 'fake' is not recognized as the name of a cmdlet. Check \r\n" \ b"the spelling of the name, or if a path was included.\r\n" \ b"At line:1 char:1\r\n" \ b"+ fake cmdlet\r\n" \ b"+ ~~~~\r\n" \ b" + CategoryInfo : ObjectNotFound: (fake:String) [], CommandNotFoundException\r\n" \ b" + FullyQualifiedErrorId : CommandNotFoundException\r\n " actual = _parse_clixml(single_stream) assert actual == expected def test_parse_clixml_multiple_streams(): multiple_stream = b'#< CLIXML\r\n<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04">' \ b'<S S="Error">fake : The term \'fake\' is not recognized as the name of a cmdlet. Check _x000D__x000A_</S>' \ b'<S S="Error">the spelling of the name, or if a path was included._x000D__x000A_</S>' \ b'<S S="Error">At line:1 char:1_x000D__x000A_</S>' \ b'<S S="Error">+ fake cmdlet_x000D__x000A_</S><S S="Error">+ ~~~~_x000D__x000A_</S>' \ b'<S S="Error"> + CategoryInfo : ObjectNotFound: (fake:String) [], CommandNotFoundException_x000D__x000A_</S>' \ b'<S S="Error"> + FullyQualifiedErrorId : CommandNotFoundException_x000D__x000A_</S><S S="Error"> _x000D__x000A_</S>' \ b'<S S="Info">hi info</S>' \ b'</Objs>' expected = b"hi info" actual = _parse_clixml(multiple_stream, stream="Info") assert actual == expected def test_parse_clixml_multiple_elements(): multiple_elements = b'#< CLIXML\r\n#< CLIXML\r\n<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04">' \ b'<Obj S="progress" RefId="0"><TN RefId="0"><T>System.Management.Automation.PSCustomObject</T><T>System.Object</T></TN><MS>' \ b'<I64 N="SourceId">1</I64><PR N="Record"><AV>Preparing modules for first use.</AV><AI>0</AI><Nil />' \ b'<PI>-1</PI><PC>-1</PC><T>Completed</T><SR>-1</SR><SD> </SD></PR></MS></Obj>' \ b'<S S="Error">Error 1</S></Objs>' \ b'<Objs Version="1.1.0.1" xmlns="http://schemas.microsoft.com/powershell/2004/04"><Obj S="progress" RefId="0">' \ b'<TN RefId="0"><T>System.Management.Automation.PSCustomObject</T><T>System.Object</T></TN><MS>' \ b'<I64 N="SourceId">1</I64><PR N="Record"><AV>Preparing modules for first use.</AV><AI>0</AI><Nil />' \ b'<PI>-1</PI><PC>-1</PC><T>Completed</T><SR>-1</SR><SD> </SD></PR></MS></Obj>' \ b'<Obj S="progress" RefId="1"><TNRef RefId="0" /><MS><I64 N="SourceId">2</I64>' \ b'<PR N="Record"><AV>Preparing modules for first use.</AV><AI>0</AI><Nil />' \ b'<PI>-1</PI><PC>-1</PC><T>Completed</T><SR>-1</SR><SD> </SD></PR></MS></Obj>' \ b'<S S="Error">Error 2</S></Objs>' expected = b"Error 1\r\nError 2" actual = _parse_clixml(multiple_elements) assert actual == expected def test_join_path_unc(): pwsh = ShellModule() unc_path_parts = ['\\\\host\\share\\dir1\\\\dir2\\', '\\dir3/dir4', 'dir5', 'dir6\\'] expected = '\\\\host\\share\\dir1\\dir2\\dir3\\dir4\\dir5\\dir6' actual = pwsh.join_path(*unc_path_parts) assert actual == expected
gpl-3.0
flakey-bit/plugin.audio.spotify
resources/libs/cherrypy/lib/cpstats.py
10
23042
"""CPStats, a package for collecting and reporting on program statistics. Overview ======== Statistics about program operation are an invaluable monitoring and debugging tool. Unfortunately, the gathering and reporting of these critical values is usually ad-hoc. This package aims to add a centralized place for gathering statistical performance data, a structure for recording that data which provides for extrapolation of that data into more useful information, and a method of serving that data to both human investigators and monitoring software. Let's examine each of those in more detail. Data Gathering -------------- Just as Python's `logging` module provides a common importable for gathering and sending messages, performance statistics would benefit from a similar common mechanism, and one that does *not* require each package which wishes to collect stats to import a third-party module. Therefore, we choose to re-use the `logging` module by adding a `statistics` object to it. That `logging.statistics` object is a nested dict. It is not a custom class, because that would: 1. require libraries and applications to import a third-party module in order to participate 2. inhibit innovation in extrapolation approaches and in reporting tools, and 3. be slow. There are, however, some specifications regarding the structure of the dict.:: { +----"SQLAlchemy": { | "Inserts": 4389745, | "Inserts per Second": | lambda s: s["Inserts"] / (time() - s["Start"]), | C +---"Table Statistics": { | o | "widgets": {-----------+ N | l | "Rows": 1.3M, | Record a | l | "Inserts": 400, | m | e | },---------------------+ e | c | "froobles": { s | t | "Rows": 7845, p | i | "Inserts": 0, a | o | }, c | n +---}, e | "Slow Queries": | [{"Query": "SELECT * FROM widgets;", | "Processing Time": 47.840923343, | }, | ], +----}, } The `logging.statistics` dict has four levels. The topmost level is nothing more than a set of names to introduce modularity, usually along the lines of package names. If the SQLAlchemy project wanted to participate, for example, it might populate the item `logging.statistics['SQLAlchemy']`, whose value would be a second-layer dict we call a "namespace". Namespaces help multiple packages to avoid collisions over key names, and make reports easier to read, to boot. The maintainers of SQLAlchemy should feel free to use more than one namespace if needed (such as 'SQLAlchemy ORM'). Note that there are no case or other syntax constraints on the namespace names; they should be chosen to be maximally readable by humans (neither too short nor too long). Each namespace, then, is a dict of named statistical values, such as 'Requests/sec' or 'Uptime'. You should choose names which will look good on a report: spaces and capitalization are just fine. In addition to scalars, values in a namespace MAY be a (third-layer) dict, or a list, called a "collection". For example, the CherryPy :class:`StatsTool` keeps track of what each request is doing (or has most recently done) in a 'Requests' collection, where each key is a thread ID; each value in the subdict MUST be a fourth dict (whew!) of statistical data about each thread. We call each subdict in the collection a "record". Similarly, the :class:`StatsTool` also keeps a list of slow queries, where each record contains data about each slow query, in order. Values in a namespace or record may also be functions, which brings us to: Extrapolation ------------- The collection of statistical data needs to be fast, as close to unnoticeable as possible to the host program. That requires us to minimize I/O, for example, but in Python it also means we need to minimize function calls. So when you are designing your namespace and record values, try to insert the most basic scalar values you already have on hand. When it comes time to report on the gathered data, however, we usually have much more freedom in what we can calculate. Therefore, whenever reporting tools (like the provided :class:`StatsPage` CherryPy class) fetch the contents of `logging.statistics` for reporting, they first call `extrapolate_statistics` (passing the whole `statistics` dict as the only argument). This makes a deep copy of the statistics dict so that the reporting tool can both iterate over it and even change it without harming the original. But it also expands any functions in the dict by calling them. For example, you might have a 'Current Time' entry in the namespace with the value "lambda scope: time.time()". The "scope" parameter is the current namespace dict (or record, if we're currently expanding one of those instead), allowing you access to existing static entries. If you're truly evil, you can even modify more than one entry at a time. However, don't try to calculate an entry and then use its value in further extrapolations; the order in which the functions are called is not guaranteed. This can lead to a certain amount of duplicated work (or a redesign of your schema), but that's better than complicating the spec. After the whole thing has been extrapolated, it's time for: Reporting --------- The :class:`StatsPage` class grabs the `logging.statistics` dict, extrapolates it all, and then transforms it to HTML for easy viewing. Each namespace gets its own header and attribute table, plus an extra table for each collection. This is NOT part of the statistics specification; other tools can format how they like. You can control which columns are output and how they are formatted by updating StatsPage.formatting, which is a dict that mirrors the keys and nesting of `logging.statistics`. The difference is that, instead of data values, it has formatting values. Use None for a given key to indicate to the StatsPage that a given column should not be output. Use a string with formatting (such as '%.3f') to interpolate the value(s), or use a callable (such as lambda v: v.isoformat()) for more advanced formatting. Any entry which is not mentioned in the formatting dict is output unchanged. Monitoring ---------- Although the HTML output takes pains to assign unique id's to each <td> with statistical data, you're probably better off fetching /cpstats/data, which outputs the whole (extrapolated) `logging.statistics` dict in JSON format. That is probably easier to parse, and doesn't have any formatting controls, so you get the "original" data in a consistently-serialized format. Note: there's no treatment yet for datetime objects. Try time.time() instead for now if you can. Nagios will probably thank you. Turning Collection Off ---------------------- It is recommended each namespace have an "Enabled" item which, if False, stops collection (but not reporting) of statistical data. Applications SHOULD provide controls to pause and resume collection by setting these entries to False or True, if present. Usage ===== To collect statistics on CherryPy applications:: from cherrypy.lib import cpstats appconfig['/']['tools.cpstats.on'] = True To collect statistics on your own code:: import logging # Initialize the repository if not hasattr(logging, 'statistics'): logging.statistics = {} # Initialize my namespace mystats = logging.statistics.setdefault('My Stuff', {}) # Initialize my namespace's scalars and collections mystats.update({ 'Enabled': True, 'Start Time': time.time(), 'Important Events': 0, 'Events/Second': lambda s: ( (s['Important Events'] / (time.time() - s['Start Time']))), }) ... for event in events: ... # Collect stats if mystats.get('Enabled', False): mystats['Important Events'] += 1 To report statistics:: root.cpstats = cpstats.StatsPage() To format statistics reports:: See 'Reporting', above. """ # ------------------------------- Statistics -------------------------------- # import logging if not hasattr(logging, 'statistics'): logging.statistics = {} def extrapolate_statistics(scope): """Return an extrapolated copy of the given scope.""" c = {} for k, v in list(scope.items()): if isinstance(v, dict): v = extrapolate_statistics(v) elif isinstance(v, (list, tuple)): v = [extrapolate_statistics(record) for record in v] elif hasattr(v, '__call__'): v = v(scope) c[k] = v return c # -------------------- CherryPy Applications Statistics --------------------- # import sys import threading import time import cherrypy appstats = logging.statistics.setdefault('CherryPy Applications', {}) appstats.update({ 'Enabled': True, 'Bytes Read/Request': lambda s: ( s['Total Requests'] and (s['Total Bytes Read'] / float(s['Total Requests'])) or 0.0 ), 'Bytes Read/Second': lambda s: s['Total Bytes Read'] / s['Uptime'](s), 'Bytes Written/Request': lambda s: ( s['Total Requests'] and (s['Total Bytes Written'] / float(s['Total Requests'])) or 0.0 ), 'Bytes Written/Second': lambda s: ( s['Total Bytes Written'] / s['Uptime'](s) ), 'Current Time': lambda s: time.time(), 'Current Requests': 0, 'Requests/Second': lambda s: float(s['Total Requests']) / s['Uptime'](s), 'Server Version': cherrypy.__version__, 'Start Time': time.time(), 'Total Bytes Read': 0, 'Total Bytes Written': 0, 'Total Requests': 0, 'Total Time': 0, 'Uptime': lambda s: time.time() - s['Start Time'], 'Requests': {}, }) proc_time = lambda s: time.time() - s['Start Time'] class ByteCountWrapper(object): """Wraps a file-like object, counting the number of bytes read.""" def __init__(self, rfile): self.rfile = rfile self.bytes_read = 0 def read(self, size=-1): data = self.rfile.read(size) self.bytes_read += len(data) return data def readline(self, size=-1): data = self.rfile.readline(size) self.bytes_read += len(data) return data def readlines(self, sizehint=0): # Shamelessly stolen from StringIO total = 0 lines = [] line = self.readline() while line: lines.append(line) total += len(line) if 0 < sizehint <= total: break line = self.readline() return lines def close(self): self.rfile.close() def __iter__(self): return self def next(self): data = self.rfile.next() self.bytes_read += len(data) return data average_uriset_time = lambda s: s['Count'] and (s['Sum'] / s['Count']) or 0 def _get_threading_ident(): if sys.version_info >= (3, 3): return threading.get_ident() return threading._get_ident() class StatsTool(cherrypy.Tool): """Record various information about the current request.""" def __init__(self): cherrypy.Tool.__init__(self, 'on_end_request', self.record_stop) def _setup(self): """Hook this tool into cherrypy.request. The standard CherryPy request object will automatically call this method when the tool is "turned on" in config. """ if appstats.get('Enabled', False): cherrypy.Tool._setup(self) self.record_start() def record_start(self): """Record the beginning of a request.""" request = cherrypy.serving.request if not hasattr(request.rfile, 'bytes_read'): request.rfile = ByteCountWrapper(request.rfile) request.body.fp = request.rfile r = request.remote appstats['Current Requests'] += 1 appstats['Total Requests'] += 1 appstats['Requests'][_get_threading_ident()] = { 'Bytes Read': None, 'Bytes Written': None, # Use a lambda so the ip gets updated by tools.proxy later 'Client': lambda s: '%s:%s' % (r.ip, r.port), 'End Time': None, 'Processing Time': proc_time, 'Request-Line': request.request_line, 'Response Status': None, 'Start Time': time.time(), } def record_stop( self, uriset=None, slow_queries=1.0, slow_queries_count=100, debug=False, **kwargs): """Record the end of a request.""" resp = cherrypy.serving.response w = appstats['Requests'][_get_threading_ident()] r = cherrypy.request.rfile.bytes_read w['Bytes Read'] = r appstats['Total Bytes Read'] += r if resp.stream: w['Bytes Written'] = 'chunked' else: cl = int(resp.headers.get('Content-Length', 0)) w['Bytes Written'] = cl appstats['Total Bytes Written'] += cl w['Response Status'] = getattr( resp, 'output_status', None) or resp.status w['End Time'] = time.time() p = w['End Time'] - w['Start Time'] w['Processing Time'] = p appstats['Total Time'] += p appstats['Current Requests'] -= 1 if debug: cherrypy.log('Stats recorded: %s' % repr(w), 'TOOLS.CPSTATS') if uriset: rs = appstats.setdefault('URI Set Tracking', {}) r = rs.setdefault(uriset, { 'Min': None, 'Max': None, 'Count': 0, 'Sum': 0, 'Avg': average_uriset_time}) if r['Min'] is None or p < r['Min']: r['Min'] = p if r['Max'] is None or p > r['Max']: r['Max'] = p r['Count'] += 1 r['Sum'] += p if slow_queries and p > slow_queries: sq = appstats.setdefault('Slow Queries', []) sq.append(w.copy()) if len(sq) > slow_queries_count: sq.pop(0) import cherrypy cherrypy.tools.cpstats = StatsTool() # ---------------------- CherryPy Statistics Reporting ---------------------- # import os thisdir = os.path.abspath(os.path.dirname(__file__)) try: import json except ImportError: try: import simplejson as json except ImportError: json = None missing = object() locale_date = lambda v: time.strftime('%c', time.gmtime(v)) iso_format = lambda v: time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(v)) def pause_resume(ns): def _pause_resume(enabled): pause_disabled = '' resume_disabled = '' if enabled: resume_disabled = 'disabled="disabled" ' else: pause_disabled = 'disabled="disabled" ' return """ <form action="pause" method="POST" style="display:inline"> <input type="hidden" name="namespace" value="%s" /> <input type="submit" value="Pause" %s/> </form> <form action="resume" method="POST" style="display:inline"> <input type="hidden" name="namespace" value="%s" /> <input type="submit" value="Resume" %s/> </form> """ % (ns, pause_disabled, ns, resume_disabled) return _pause_resume class StatsPage(object): formatting = { 'CherryPy Applications': { 'Enabled': pause_resume('CherryPy Applications'), 'Bytes Read/Request': '%.3f', 'Bytes Read/Second': '%.3f', 'Bytes Written/Request': '%.3f', 'Bytes Written/Second': '%.3f', 'Current Time': iso_format, 'Requests/Second': '%.3f', 'Start Time': iso_format, 'Total Time': '%.3f', 'Uptime': '%.3f', 'Slow Queries': { 'End Time': None, 'Processing Time': '%.3f', 'Start Time': iso_format, }, 'URI Set Tracking': { 'Avg': '%.3f', 'Max': '%.3f', 'Min': '%.3f', 'Sum': '%.3f', }, 'Requests': { 'Bytes Read': '%s', 'Bytes Written': '%s', 'End Time': None, 'Processing Time': '%.3f', 'Start Time': None, }, }, 'CherryPy WSGIServer': { 'Enabled': pause_resume('CherryPy WSGIServer'), 'Connections/second': '%.3f', 'Start time': iso_format, }, } @cherrypy.expose def index(self): # Transform the raw data into pretty output for HTML yield """ <html> <head> <title>Statistics</title> <style> th, td { padding: 0.25em 0.5em; border: 1px solid #666699; } table { border-collapse: collapse; } table.stats1 { width: 100%; } table.stats1 th { font-weight: bold; text-align: right; background-color: #CCD5DD; } table.stats2, h2 { margin-left: 50px; } table.stats2 th { font-weight: bold; text-align: center; background-color: #CCD5DD; } </style> </head> <body> """ for title, scalars, collections in self.get_namespaces(): yield """ <h1>%s</h1> <table class='stats1'> <tbody> """ % title for i, (key, value) in enumerate(scalars): colnum = i % 3 if colnum == 0: yield """ <tr>""" yield ( """ <th>%(key)s</th><td id='%(title)s-%(key)s'>%(value)s</td>""" % vars() ) if colnum == 2: yield """ </tr>""" if colnum == 0: yield """ <th></th><td></td> <th></th><td></td> </tr>""" elif colnum == 1: yield """ <th></th><td></td> </tr>""" yield """ </tbody> </table>""" for subtitle, headers, subrows in collections: yield """ <h2>%s</h2> <table class='stats2'> <thead> <tr>""" % subtitle for key in headers: yield """ <th>%s</th>""" % key yield """ </tr> </thead> <tbody>""" for subrow in subrows: yield """ <tr>""" for value in subrow: yield """ <td>%s</td>""" % value yield """ </tr>""" yield """ </tbody> </table>""" yield """ </body> </html> """ def get_namespaces(self): """Yield (title, scalars, collections) for each namespace.""" s = extrapolate_statistics(logging.statistics) for title, ns in sorted(s.items()): scalars = [] collections = [] ns_fmt = self.formatting.get(title, {}) for k, v in sorted(ns.items()): fmt = ns_fmt.get(k, {}) if isinstance(v, dict): headers, subrows = self.get_dict_collection(v, fmt) collections.append((k, ['ID'] + headers, subrows)) elif isinstance(v, (list, tuple)): headers, subrows = self.get_list_collection(v, fmt) collections.append((k, headers, subrows)) else: format = ns_fmt.get(k, missing) if format is None: # Don't output this column. continue if hasattr(format, '__call__'): v = format(v) elif format is not missing: v = format % v scalars.append((k, v)) yield title, scalars, collections def get_dict_collection(self, v, formatting): """Return ([headers], [rows]) for the given collection.""" # E.g., the 'Requests' dict. headers = [] try: # python2 vals = v.itervalues() except AttributeError: # python3 vals = v.values() for record in vals: for k3 in record: format = formatting.get(k3, missing) if format is None: # Don't output this column. continue if k3 not in headers: headers.append(k3) headers.sort() subrows = [] for k2, record in sorted(v.items()): subrow = [k2] for k3 in headers: v3 = record.get(k3, '') format = formatting.get(k3, missing) if format is None: # Don't output this column. continue if hasattr(format, '__call__'): v3 = format(v3) elif format is not missing: v3 = format % v3 subrow.append(v3) subrows.append(subrow) return headers, subrows def get_list_collection(self, v, formatting): """Return ([headers], [subrows]) for the given collection.""" # E.g., the 'Slow Queries' list. headers = [] for record in v: for k3 in record: format = formatting.get(k3, missing) if format is None: # Don't output this column. continue if k3 not in headers: headers.append(k3) headers.sort() subrows = [] for record in v: subrow = [] for k3 in headers: v3 = record.get(k3, '') format = formatting.get(k3, missing) if format is None: # Don't output this column. continue if hasattr(format, '__call__'): v3 = format(v3) elif format is not missing: v3 = format % v3 subrow.append(v3) subrows.append(subrow) return headers, subrows if json is not None: @cherrypy.expose def data(self): s = extrapolate_statistics(logging.statistics) cherrypy.response.headers['Content-Type'] = 'application/json' return json.dumps(s, sort_keys=True, indent=4) @cherrypy.expose def pause(self, namespace): logging.statistics.get(namespace, {})['Enabled'] = False raise cherrypy.HTTPRedirect('./') pause.cp_config = {'tools.allow.on': True, 'tools.allow.methods': ['POST']} @cherrypy.expose def resume(self, namespace): logging.statistics.get(namespace, {})['Enabled'] = True raise cherrypy.HTTPRedirect('./') resume.cp_config = {'tools.allow.on': True, 'tools.allow.methods': ['POST']}
gpl-3.0
jralls/gramps
gramps/gui/widgets/fanchartdesc.py
3
28101
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2001-2007 Donald N. Allingham, Martin Hawlisch # Copyright (C) 2009 Douglas S. Blank # Copyright (C) 2012 Benny Malengier # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # ## Based on the paper: ## http://www.cs.utah.edu/~draperg/research/fanchart/draperg_FHT08.pdf ## and the applet: ## http://www.cs.utah.edu/~draperg/research/fanchart/demo/ ## Found by redwood: ## http://www.gramps-project.org/bugs/view.php?id=2611 #------------------------------------------------------------------------- # # Python modules # #------------------------------------------------------------------------- from gi.repository import Pango from gi.repository import GObject from gi.repository import Gdk from gi.repository import Gtk from gi.repository import PangoCairo import cairo import math import colorsys import pickle from html import escape #------------------------------------------------------------------------- # # Gramps modules # #------------------------------------------------------------------------- from gramps.gen.display.name import displayer as name_displayer from gramps.gen.errors import WindowActiveError from ..editors import EditPerson, EditFamily from ..utils import hex_to_rgb from ..ddtargets import DdTargets from gramps.gen.utils.alive import probably_alive from gramps.gen.utils.libformatting import FormattingHelper from gramps.gen.utils.db import (find_children, find_parents, find_witnessed_people, get_age, get_timeperiod) from gramps.gen.plug.report.utils import find_spouse from .fanchart import * #------------------------------------------------------------------------- # # Constants # #------------------------------------------------------------------------- pi = math.pi PIXELS_PER_GENPERSON_RATIO = 0.55 # ratio of generation radius for person (rest for partner) PIXELS_PER_GEN_SMALL = 80 PIXELS_PER_GEN_LARGE = 160 N_GEN_SMALL = 4 PIXELS_PER_GENFAMILY = 25 # size of radius for family PIXELS_PER_RECLAIM = 4 # size of the radius of pixels taken from family to reclaim space PIXELS_PARTNER_GAP = 0 # Padding between someone and his partner PIXELS_CHILDREN_GAP = 5 # Padding between generations PARENTRING_WIDTH = 12 # width of the parent ring inside the person ANGLE_CHEQUI = 0 #Algorithm with homogeneous children distribution ANGLE_WEIGHT = 1 #Algorithm for angle computation based on nr of descendants TYPE_BOX_NORMAL = 0 TYPE_BOX_FAMILY = 1 #------------------------------------------------------------------------- # # FanChartDescWidget # #------------------------------------------------------------------------- class FanChartDescWidget(FanChartBaseWidget): """ Interactive Fan Chart Widget. """ CENTER = 50 # we require a larger center as CENTER includes the 1st partner def __init__(self, dbstate, uistate, callback_popup=None): """ Fan Chart Widget. Handles visualization of data in self.data. See main() of FanChartGramplet for example of model format. """ self.set_values(None, 9, True, True, BACKGROUND_GRAD_GEN, 'Sans', '#0000FF', '#FF0000', None, 0.5, FORM_CIRCLE, ANGLE_WEIGHT, '#888a85') FanChartBaseWidget.__init__(self, dbstate, uistate, callback_popup) def set_values(self, root_person_handle, maxgen, flipupsidedownname, twolinename, background, fontdescr, grad_start, grad_end, filter, alpha_filter, form, angle_algo, dupcolor): """ Reset the values to be used: :param root_person_handle: person to show :param maxgen: maximum generations to show :param flipupsidedownname: flip name on the left of the fanchart for the display of person's name :param background: config setting of which background procedure to use :type background: int :param fontdescr: string describing the font to use :param grad_start: colors to use for background procedure :param grad_end: colors to use for background procedure :param filter: the person filter to apply to the people in the chart :param alpha_filter: the alpha transparency value (0-1) to apply to filtered out data :param form: the ``FORM_`` constant for the fanchart :param angle_algo: alorithm to use to calculate the sizes of the boxes :param dupcolor: color to use for people or families that occur a second or more time """ self.rootpersonh = root_person_handle self.generations = maxgen self.background = background self.fontdescr = fontdescr self.grad_start = grad_start self.grad_end = grad_end self.filter = filter self.alpha_filter = alpha_filter self.form = form self.anglealgo = angle_algo self.dupcolor = hex_to_rgb(dupcolor) self.childring = False self.flipupsidedownname = flipupsidedownname self.twolinename = twolinename def set_generations(self): """ Set the generations to max, and fill data structures with initial data. """ if self.form == FORM_CIRCLE: self.rootangle_rad = [math.radians(0), math.radians(360)] elif self.form == FORM_HALFCIRCLE: self.rootangle_rad = [math.radians(90), math.radians(90 + 180)] elif self.form == FORM_QUADRANT: self.rootangle_rad = [math.radians(90), math.radians(90 + 90)] self.handle2desc = {} self.famhandle2desc = {} self.handle2fam = {} self.gen2people = {} self.gen2fam = {} self.innerring = [] self.gen2people[0] = [(None, False, 0, 2*pi, 0, 0, [], NORMAL)] #no center person self.gen2fam[0] = [] #no families self.angle = {} self.angle[-2] = [] for i in range(1, self.generations+1): self.gen2fam[i] = [] self.gen2people[i] = [] self.gen2people[self.generations] = [] #indication of more children def _fill_data_structures(self): self.set_generations() if not self.rootpersonh: return person = self.dbstate.db.get_person_from_handle(self.rootpersonh) if not person: #nothing to do, just return return # person, duplicate or not, start angle, slice size, # text, parent pos in fam, nrfam, userdata, status self.gen2people[0] = [[person, False, 0, 2*pi, 0, 0, [], NORMAL]] self.handle2desc[self.rootpersonh] = 0 # fill in data for the parents self.innerring = [] handleparents = [] family_handle_list = person.get_parent_family_handle_list() if family_handle_list: for family_handle in family_handle_list: family = self.dbstate.db.get_family_from_handle(family_handle) if not family: continue for hparent in [family.get_father_handle(), family.get_mother_handle()]: if hparent and hparent not in handleparents: parent = self.dbstate.db.get_person_from_handle(hparent) if parent: self.innerring.append((parent, [])) handleparents.append(hparent) #recursively fill in the datastructures: nrdesc = self._rec_fill_data(0, person, 0, self.generations) self.handle2desc[person.handle] += nrdesc self._compute_angles(*self.rootangle_rad) def _rec_fill_data(self, gen, person, pos, maxgen): """ Recursively fill in the data """ totdesc = 0 marriage_handle_list = person.get_family_handle_list() self.gen2people[gen][pos][5] = len(marriage_handle_list) for family_handle in marriage_handle_list: totdescfam = 0 family = self.dbstate.db.get_family_from_handle(family_handle) spouse_handle = find_spouse(person, family) if spouse_handle: spouse = self.dbstate.db.get_person_from_handle(spouse_handle) else: spouse = None # family may occur via father and via mother in the chart, only # first to show and count. fam_duplicate = family_handle in self.famhandle2desc # family, duplicate or not, start angle, slice size, # spouse pos in gen, nrchildren, userdata, parnter, status self.gen2fam[gen].append([family, fam_duplicate, 0, 0, pos, 0, [], spouse, NORMAL]) posfam = len(self.gen2fam[gen]) - 1 if not fam_duplicate and gen < maxgen-1: nrchild = len(family.get_child_ref_list()) self.gen2fam[gen][posfam][5] = nrchild for child_ref in family.get_child_ref_list(): child = self.dbstate.db.get_person_from_handle(child_ref.ref) child_dup = child_ref.ref in self.handle2desc if not child_dup: self.handle2desc[child_ref.ref] = 0 # mark this child as processed # person, duplicate or not, start angle, slice size, # parent pos in fam, nrfam, userdata, status self.gen2people[gen+1].append([child, child_dup, 0, 0, posfam, 0, [], NORMAL]) totdescfam += 1 #add this person as descendant pospers = len(self.gen2people[gen+1]) - 1 if not child_dup: nrdesc = self._rec_fill_data(gen+1, child, pospers, maxgen) self.handle2desc[child_ref.ref] += nrdesc totdescfam += nrdesc # add children of him as descendants if not fam_duplicate: self.famhandle2desc[family_handle] = totdescfam totdesc += totdescfam return totdesc def _compute_angles(self, start_rad, stop_rad): """ Compute the angles of the boxes """ #first we compute the size of the slice. #set angles root person start, slice = start_rad, stop_rad - start_rad nr_gen = len(self.gen2people)-1 # Fill in central person angles gen = 0 data = self.gen2people[gen][0] data[2] = start data[3] = slice for gen in range(0, nr_gen): prevpartnerdatahandle = None offset = 0 for data_fam in self.gen2fam[gen]: # for each partner/fam of gen-1 #obtain start and stop from the people of this partner persondata = self.gen2people[gen][data_fam[4]] dupfam = data_fam[1] if dupfam: # we don't show again the descendants here nrdescfam = 0 else: nrdescfam = self.famhandle2desc[data_fam[0].handle] nrdescperson = self.handle2desc[persondata[0].handle] nrfam = persondata[5] personstart, personslice = persondata[2:4] if prevpartnerdatahandle != persondata[0].handle: #partner of a new person: reset the offset offset = 0 prevpartnerdatahandle = persondata[0].handle slice = personslice/(nrdescperson+nrfam)*(nrdescfam+1) if data_fam[8] == COLLAPSED: slice = 0 elif data_fam[8] == EXPANDED: slice = personslice data_fam[2] = personstart + offset data_fam[3] = slice offset += slice ## if nrdescperson == 0: ## #no offspring, draw as large as fraction of ## #nr families ## nrfam = persondata[6] ## slice = personslice/nrfam ## data_fam[2] = personstart + offset ## data_fam[3] = slice ## offset += slice ## elif nrdescfam == 0: ## #no offspring this family, but there is another ## #family. We draw this as a weight of 1 ## nrfam = persondata[6] ## slice = personslice/(nrdescperson + nrfam - 1)*(nrdescfam+1) ## data_fam[2] = personstart + offset ## data_fam[3] = slice ## offset += slice ## else: ## #this family has offspring. We give it space for it's ## #weight in offspring ## nrfam = persondata[6] ## slice = personslice/(nrdescperson + nrfam - 1)*(nrdescfam+1) ## data_fam[2] = personstart + offset ## data_fam[3] = slice ## offset += slice prevfamdatahandle = None offset = 0 for persondata in self.gen2people[gen+1] if gen < nr_gen else []: #obtain start and stop of family this is child of parentfamdata = self.gen2fam[gen][persondata[4]] nrdescfam = 0 if not parentfamdata[1]: nrdescfam = self.famhandle2desc[parentfamdata[0].handle] nrdesc = 0 if not persondata[1]: nrdesc = self.handle2desc[persondata[0].handle] famstart = parentfamdata[2] famslice = parentfamdata[3] nrchild = parentfamdata[5] #now we divide this slice to the weight of children, #adding one for every child if self.anglealgo == ANGLE_CHEQUI: slice = famslice / nrchild elif self.anglealgo == ANGLE_WEIGHT: slice = famslice/(nrdescfam) * (nrdesc + 1) else: raise NotImplementedError('Unknown angle algorithm %d' % self.anglealgo) if prevfamdatahandle != parentfamdata[0].handle: #reset the offset offset = 0 prevfamdatahandle = parentfamdata[0].handle if persondata[7] == COLLAPSED: slice = 0 elif persondata[7] == EXPANDED: slice = famslice persondata[2] = famstart + offset persondata[3] = slice offset += slice def nrgen(self): #compute the number of generations present for gen in range(self.generations - 1, 0, -1): if len(self.gen2people[gen]) > 0: return gen + 1 return 1 def halfdist(self): """ Compute the half radius of the circle """ radius = PIXELS_PER_GEN_SMALL * N_GEN_SMALL + PIXELS_PER_GEN_LARGE \ * ( self.nrgen() - N_GEN_SMALL ) + self.CENTER return radius def get_radiusinout_for_generation(self,generation): radius_first_gen = self.CENTER - (1-PIXELS_PER_GENPERSON_RATIO) * PIXELS_PER_GEN_SMALL if generation < N_GEN_SMALL: radius_start = PIXELS_PER_GEN_SMALL * generation + radius_first_gen return (radius_start,radius_start + PIXELS_PER_GEN_SMALL) else: radius_start = PIXELS_PER_GEN_SMALL * N_GEN_SMALL + PIXELS_PER_GEN_LARGE \ * ( generation - N_GEN_SMALL ) + radius_first_gen return (radius_start,radius_start + PIXELS_PER_GEN_LARGE) def get_radiusinout_for_generation_pair(self,generation): radiusin, radiusout = self.get_radiusinout_for_generation(generation) radius_spread = radiusout - radiusin - PIXELS_CHILDREN_GAP - PIXELS_PARTNER_GAP radiusin_pers = radiusin + PIXELS_CHILDREN_GAP radiusout_pers = radiusin_pers + PIXELS_PER_GENPERSON_RATIO * radius_spread radiusin_partner = radiusout_pers + PIXELS_PARTNER_GAP radiusout_partner = radiusout return (radiusin_pers,radiusout_pers,radiusin_partner,radiusout_partner) def people_generator(self): """ a generator over all people outside of the core person """ for generation in range(self.generations): for data in self.gen2people[generation]: yield (data[0], data[6]) for generation in range(self.generations): for data in self.gen2fam[generation]: yield (data[7], data[6]) def innerpeople_generator(self): """ a generator over all people inside of the core person """ for parentdata in self.innerring: parent, userdata = parentdata yield (parent, userdata) def on_draw(self, widget, cr, scale=1.): """ The main method to do the drawing. If widget is given, we assume we draw in GTK3 and use the allocation. To draw raw on the cairo context cr, set widget=None. """ # first do size request of what we will need halfdist = self.halfdist() if widget: if self.form == FORM_CIRCLE: self.set_size_request(2 * halfdist, 2 * halfdist) elif self.form == FORM_HALFCIRCLE: self.set_size_request(2 * halfdist, halfdist + self.CENTER + PAD_PX) elif self.form == FORM_QUADRANT: self.set_size_request(halfdist + self.CENTER + PAD_PX, halfdist + self.CENTER + PAD_PX) cr.scale(scale, scale) # when printing, we need not recalculate if widget: self.center_xy = self.center_xy_from_delta() cr.translate(*self.center_xy) cr.save() # Draw center person: (person, dup, start, slice, parentfampos, nrfam, userdata, status) \ = self.gen2people[0][0] if person: r, g, b, a = self.background_box(person, 0, userdata) radiusin_pers,radiusout_pers,radiusin_partner,radiusout_partner = \ self.get_radiusinout_for_generation_pair(0) if not self.innerring: radiusin_pers = TRANSLATE_PX self.draw_person(cr, person, radiusin_pers, radiusout_pers, math.pi/2, math.pi/2 + 2*math.pi, 0, False, userdata, is_central_person =True) #draw center to move chart cr.set_source_rgb(0, 0, 0) # black cr.move_to(TRANSLATE_PX, 0) cr.arc(0, 0, TRANSLATE_PX, 0, 2 * math.pi) if self.innerring: # has at least one parent cr.fill() self.draw_innerring_people(cr) else: cr.stroke() #now write all the families and children cr.rotate(self.rotate_value * math.pi/180) for gen in range(self.generations): radiusin_pers,radiusout_pers,radiusin_partner,radiusout_partner = \ self.get_radiusinout_for_generation_pair(gen) if gen > 0: for pdata in self.gen2people[gen]: # person, duplicate or not, start angle, slice size, # parent pos in fam, nrfam, userdata, status pers, dup, start, slice, pospar, nrfam, userdata, status = \ pdata if status != COLLAPSED: self.draw_person(cr, pers, radiusin_pers, radiusout_pers, start, start + slice, gen, dup, userdata, thick=status != NORMAL) #if gen < self.generations-1: for famdata in self.gen2fam[gen]: # family, duplicate or not, start angle, slice size, # spouse pos in gen, nrchildren, userdata, status fam, dup, start, slice, posfam, nrchild, userdata,\ partner, status = famdata if status != COLLAPSED: more_pers_flag = (gen == self.generations - 1 and len(fam.get_child_ref_list()) > 0) self.draw_person(cr, partner, radiusin_partner, radiusout_partner, start, start + slice, gen, dup, userdata, thick = (status != NORMAL), has_moregen_indicator = more_pers_flag ) cr.restore() if self.background in [BACKGROUND_GRAD_AGE, BACKGROUND_GRAD_PERIOD]: self.draw_gradient_legend(cr, widget, halfdist) def cell_address_under_cursor(self, curx, cury): """ Determine the cell address in the fan under the cursor position x and y. None if outside of diagram """ radius, rads, raw_rads = self.cursor_to_polar(curx, cury, get_raw_rads=True) btype = TYPE_BOX_NORMAL if radius < TRANSLATE_PX: return None elif (self.innerring and self.angle[-2] and radius < CHILDRING_WIDTH + TRANSLATE_PX): generation = -2 # indication of one of the children elif radius < self.CENTER: generation = 0 else: generation = None for gen in range(self.generations): radiusin_pers,radiusout_pers,radiusin_partner,radiusout_partner \ = self.get_radiusinout_for_generation_pair(gen) if radiusin_pers <= radius <= radiusout_pers: generation, btype = gen, TYPE_BOX_NORMAL break if radiusin_partner <= radius <= radiusout_partner: generation, btype = gen, TYPE_BOX_FAMILY break # find what person is in this position: selected = None if not (generation is None) and 0 <= generation: selected = self.personpos_at_angle(generation, rads, btype) elif generation == -2: for p in range(len(self.angle[generation])): start, stop, state = self.angle[generation][p] if self.radian_in_bounds(start, raw_rads, stop): selected = p break if (generation is None or selected is None): return None return generation, selected, btype def draw_innerring_people(self, cr): cr.move_to(TRANSLATE_PX + CHILDRING_WIDTH, 0) cr.set_source_rgb(0, 0, 0) # black cr.set_line_width(1) cr.arc(0, 0, TRANSLATE_PX + CHILDRING_WIDTH, 0, 2 * math.pi) cr.stroke() nrparent = len(self.innerring) #Y axis is downward. positve angles are hence clockwise startangle = math.pi if nrparent <= 2: angleinc = math.pi elif nrparent <= 4: angleinc = math.pi/2 else: # FIXME: nrchild not set angleinc = 2 * math.pi / nrchild for data in self.innerring: self.draw_innerring(cr, data[0], data[1], startangle, angleinc) startangle += angleinc def personpos_at_angle(self, generation, rads, btype): """ returns the person in generation generation at angle. """ selected = None datas = None if btype == TYPE_BOX_NORMAL: if generation==0: return 0 # central person is always ok ! datas = self.gen2people[generation] elif btype == TYPE_BOX_FAMILY: datas = self.gen2fam[generation] else: return None for p, pdata in enumerate(datas): # person, duplicate or not, start angle, slice size, # parent pos in fam, nrfam, userdata, status start, stop = pdata[2], pdata[2] + pdata[3] if self.radian_in_bounds(start, rads, stop): selected = p break return selected def person_at(self, cell_address): """ returns the person at generation, pos, btype """ generation, pos, btype = cell_address if generation == -2: person, userdata = self.innerring[pos] elif btype == TYPE_BOX_NORMAL: # person, duplicate or not, start angle, slice size, # parent pos in fam, nrfam, userdata, status person = self.gen2people[generation][pos][0] elif btype == TYPE_BOX_FAMILY: # family, duplicate or not, start angle, slice size, # spouse pos in gen, nrchildren, userdata, person, status person = self.gen2fam[generation][pos][7] return person def family_at(self, cell_address): """ returns the family at generation, pos, btype """ generation, pos, btype = cell_address if pos is None or btype == TYPE_BOX_NORMAL or generation < 0: return None return self.gen2fam[generation][pos][0] def do_mouse_click(self): # no drag occured, expand or collapse the section self.toggle_cell_state(self._mouse_click_cell_address) self._compute_angles(*self.rootangle_rad) self._mouse_click = False self.queue_draw() def toggle_cell_state(self, cell_address): generation, selected, btype = cell_address if generation < 1: return if btype == TYPE_BOX_NORMAL: data = self.gen2people[generation][selected] parpos = data[4] status = data[7] if status == NORMAL: #should be expanded, rest collapsed for entry in self.gen2people[generation]: if entry[4] == parpos: entry[7] = COLLAPSED data[7] = EXPANDED else: #is expanded, set back to normal for entry in self.gen2people[generation]: if entry[4] == parpos: entry[7] = NORMAL if btype == TYPE_BOX_FAMILY: data = self.gen2fam[generation][selected] parpos = data[4] status = data[8] if status == NORMAL: #should be expanded, rest collapsed for entry in self.gen2fam[generation]: if entry[4] == parpos: entry[8] = COLLAPSED data[8] = EXPANDED else: #is expanded, set back to normal for entry in self.gen2fam[generation]: if entry[4] == parpos: entry[8] = NORMAL class FanChartDescGrampsGUI(FanChartGrampsGUI): """ class for functions fanchart GUI elements will need in Gramps """ def main(self): """ Fill the data structures with the active data. This initializes all data. """ root_person_handle = self.get_active('Person') self.fan.set_values(root_person_handle, self.maxgen, self.flipupsidedownname, self.twolinename, self.background, self.fonttype, self.grad_start, self.grad_end, self.generic_filter, self.alpha_filter, self.form, self.angle_algo, self.dupcolor) self.fan.reset() self.fan.queue_draw()
gpl-2.0
0x00-0x00/shemutils
src/database.py
1
7610
import sqlite3 import gevent from copy import copy from gevent.event import Event from gevent.queue import Queue from shemutils.logger import Logger from shemutils.database_errors import InvalidInitializer, InvalidSize '# Define static variables for module' INTEGER = "INTEGER" TEXT = "TEXT" NULL = "NULL" class Controller(object): """ Controller object made to control execution operations """ def __init__(self, objects): if len(objects) < 2: del self self.handle = objects[0] self.cursor = objects[1] self.logger = None self.queue = Queue() def _log(self, s): if self.logger: self.logger.debug(s) return 0 def _error(self, s): if self.logger: self.logger.error(s) return 0 def execute(self, sql): """ Function to execute a sql query generated by other methods from this module. :param sql: string containing sql query :return: void """ if type(sql) is not str: return -1 try: self._log("Executing SQL: {0}".format(sql)) self.cursor.execute(sql) # execute query passed to function d = self.cursor.fetchall() # actual data returned by the query n = len(d) # number of elements returned by the query if n > 0: self._log("Adding query result with {0} elements to queue ...".format(n)) self.queue.put(d) else: self._log("Speficied query does not returned any result.") except sqlite3.OperationalError as e: self._error("Error executing query: {0}".format(e)) raise sqlite3.OperationalError self._log("Executed SQL successfully\n") return def get(self): """ Function to get the top element of result's queue. :return: Queue top element, or -1 error """ try: if self.queue.empty() is False: return self.queue.get() else: return [] except gevent.hub.LoopExit: self._error("Error retrieving data from queue") return -1 class Database(object): def __init__(self, db_name, verbose=False): """ Database object to control data storage Procedures: 1. Database opening 2. Controller creation :param db_name: string """ '# --------------------------------------- #' '# Natural variables ' self.db_filename = self._parse_db_name(db_name) self.open = Event() # this Flag is used to get database status concerning its ability to operate. self.logger = Logger("DATABASE", logfile="%s.log" % db_name) '# --------------------------------------- #' '# Try to open database fd' handle, cursor = self._open() '# Give the handles and cursor to Controller Object' self.controller = Controller((handle, cursor)) if verbose is not False: self.controller.logger = self.logger def _open(self): try: handle = sqlite3.connect(self.db_filename) cursor = handle.cursor() self.open.set() return handle, cursor except Exception as e: self.logger.error("Error opening database: {0}".format(e)) return None @staticmethod def _parse_db_name(db_filename, extension=".db"): k = len(db_filename) if db_filename[k-3:] != extension: db_filename += extension return db_filename def save(self): return self.controller.handle.commit() def close(self): return self.controller.handle.close() if self.controller.handle is not None else None class Table(object): """ To create a table use the following syntax: t1 = Table("TableName", {"Name":TEXT, "Age":INTEGER}) """ def __init__(self, name, columns): self.name = str(name) self.columns = columns if self._validate(columns) is 0 else None self.num_col = len(self.columns) if self.columns is not None else None @staticmethod def _validate(columns): if type(columns) != dict: raise InvalidInitializer return 0 def _colstr(self): output = "" if not self.columns: return -1 for column in self.columns.keys(): p = self.columns[column] output += "{0} {1}, ".format(p[0], p[1]) return output[:-2] + ")" def create(self): """ :return: string containing SQL to construct the table """ return "CREATE TABLE IF NOT EXISTS {0} (id INTEGER PRIMARY KEY AUTOINCREMENT, {1}".format(self.name, self._colstr()) def remove_row(self, c, k): """ :param c: string containing column name :param k: string to search through table :return: string containing SQL query to do the desired operation """ return "DELETE FROM {0} WHERE {1} = '{2}'".format(self.name, c, k) def remove_rows(self, c, k): """ :param c: string containing column name :param k: string to search through table :return: string containing SQL query to do the desired operation """ return "DELETE FROM {0} WHERE {1} LIKE '%{2}%'".format(self.name, c, k) def update_row(self, c2, k, c1, v): """ :param c1: string containing column to be updated :param v: string containing new value for the row :param c2: string containing column name for the query condition :param k: string containing keyword value for the query condition :return: string containing SQL query to do the desired operation """ return "UPDATE {0} SET {1} = '{2}' WHERE {3} LIKE '%{4}%'".format(self.name, c1, k, c2, v) def search(self, t, k, c=None): """ Function to generate a sql query to retrieve information from a database. :param t: String containing column name for the query condition :param k: String containing keyword value for the query condition :param c: None or string containing a list with column names desired for information retrieval :return: string containing SQL query to do the desired operation """ if c is None: # all columns c = "*" else: # if specified any column list if type(c) is not list: raise TypeError("Variable 'c' must be 'list' type.") k = copy(c) c = str() for p in k: c += "{0},".format(p) c = c[:-1] return "SELECT {0} FROM {1} WHERE {2} LIKE '%{3}%'".format(c, self.name, t, k) def insert_data(self, data): """ :param data: list containing data in the same number of elements that this table has -1 (for id column) :return: string containing SQL query to do the desired operation """ if type(data) != list: raise TypeError return "INSERT INTO {0} VALUES (NULL, {1})".format(self.name, self._format_data(data)) def _format_data(self, data): output = "" if type(data) != list: raise TypeError if len(data) != self.num_col: raise InvalidSize for d in data: output += "'{0}', ".format(d) return output[:-2]
mit
pombredanne/plumbum
docs/conf.py
9
8308
# -*- coding: utf-8 -*- # # Plumbum Shell Combinators documentation build configuration file, created by # sphinx-quickstart on Sun Apr 29 16:24:32 2012. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os, time sys.path.insert(0, os.path.dirname(os.path.dirname(__file__))) # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Plumbum Shell Combinators' copyright = u'%d, Tomer Filiba, licensed under Attribution-ShareAlike 3.0' % (time.gmtime().tm_year,) # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. from plumbum.version import version_string, release_date version = version_string # The full version, including alpha/beta/rc tags. release = version_string + " / " + release_date autodoc_member_order = "bysource" # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build', '_news.rst', '_cheatsheet.rst'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. #html_theme = 'default' html_theme = 'haiku' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. html_theme_options = {"full_logo" : True} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". html_title = "Plumbum: Shell Combinators" # A shorter title for the navigation bar. Default is the same as html_title. html_short_title = "" # The name of an image file (relative to this directory) to place at the top # of the sidebar. html_logo = "_static/logo8.png" # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'PlumbumShellCombinatorsdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'PlumbumShellCombinators.tex', u'Plumbum Shell Combinators Documentation', u'Tomer Filiba', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'plumbumshellcombinators', u'Plumbum Shell Combinators Documentation', [u'Tomer Filiba'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'PlumbumShellCombinators', u'Plumbum Shell Combinators Documentation', u'Tomer Filiba', 'PlumbumShellCombinators', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote'
mit
amjoconn/django-zebra
docs/conf.py
4
7862
# -*- coding: utf-8 -*- # # django-zebra documentation build configuration file, created by # sphinx-quickstart on Thu Feb 16 22:57:53 2012. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.todo', 'sphinx.ext.autodoc'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'django-zebra' copyright = u'2012, Steven Skoczen & Lee Trout' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '1.0' # The full version, including alpha/beta/rc tags. release = '1.0' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'django-zebradoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'django-zebra.tex', u'django-zebra Documentation', u'Steven Skoczen \\& Lee Trout', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'django-zebra', u'django-zebra Documentation', [u'Steven Skoczen & Lee Trout'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'django-zebra', u'django-zebra Documentation', u'Steven Skoczen & Lee Trout', 'django-zebra', 'Stripe library for Django', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote'
mit
lnls-sirius/dev-packages
siriuspy/siriuspy/pwrsupply/pructrl/prucparms.py
1
6133
"""PRU Controller Parameters. These parameters are used in PRUController class to interact with BSMP devices. """ from ..bsmp.constants import ConstPSBSMP as _const from ..psctrl.psmodel import PSModelFactory as _PSModelFactory class PRUCParmsFBP: """FBP-specific PRUC parameters.""" FREQ_SCAN = 5.0 # [Hz] # PS model parms model = _PSModelFactory.create('FBP') CONST_PSBSMP = model.bsmp_constants Entities = model.entities groups = dict() # reserved variable groups (not to be used) groups[_const.G_ALL] = tuple(sorted(Entities.list_variables(0))) groups[_const.G_READONLY] = tuple(sorted(Entities.list_variables(1))) groups[_const.G_WRITE] = tuple(sorted(Entities.list_variables(2))) groups[CONST_PSBSMP.G_SOFB] = ( CONST_PSBSMP.V_PS_SETPOINT1, CONST_PSBSMP.V_PS_SETPOINT2, CONST_PSBSMP.V_PS_SETPOINT3, CONST_PSBSMP.V_PS_SETPOINT4, CONST_PSBSMP.V_PS_REFERENCE1, CONST_PSBSMP.V_PS_REFERENCE2, CONST_PSBSMP.V_PS_REFERENCE3, CONST_PSBSMP.V_PS_REFERENCE4, CONST_PSBSMP.V_I_LOAD1, CONST_PSBSMP.V_I_LOAD2, CONST_PSBSMP.V_I_LOAD3, CONST_PSBSMP.V_I_LOAD4,) class PRUCParmsFBP_DCLink: """FBP_DCLink-specific PRUC parameters.""" FREQ_SCAN = 2.0 # [Hz] # PS model parms model = _PSModelFactory.create('FBP_DCLink') CONST_PSBSMP = model.bsmp_constants Entities = model.entities groups = dict() # reserved variable groups (not to be used) groups[_const.G_ALL] = tuple(sorted(Entities.list_variables(0))) groups[_const.G_READONLY] = tuple(sorted(Entities.list_variables(1))) groups[_const.G_WRITE] = tuple(sorted(Entities.list_variables(2))) class PRUCParmsFAC_2S_DCDC: """FAC_2S specific PRUC parameters. Represent FAC_2S_DCDC psmodels. """ FREQ_SCAN = 5.0 # [Hz] # PS model parms model = _PSModelFactory.create('FAC_2S_DCDC') CONST_PSBSMP = model.bsmp_constants Entities = model.entities groups = dict() # reserved variable groups (not to be used) groups[_const.G_ALL] = tuple(sorted(Entities.list_variables(0))) groups[_const.G_READONLY] = tuple(sorted(Entities.list_variables(1))) groups[_const.G_WRITE] = tuple(sorted(Entities.list_variables(2))) class PRUCParmsFAC_2P4S_DCDC: """FAC-specific PRUC parameters. Represent FAC_2P4S psmodels. """ FREQ_SCAN = 5.0 # [Hz] # PS model parms model = _PSModelFactory.create('FAC_2P4S_DCDC') CONST_PSBSMP = model.bsmp_constants Entities = model.entities groups = dict() # reserved variable groups (not to be used) groups[_const.G_ALL] = tuple(sorted(Entities.list_variables(0))) groups[_const.G_READONLY] = tuple(sorted(Entities.list_variables(1))) groups[_const.G_WRITE] = tuple(sorted(Entities.list_variables(2))) class PRUCParmsFAC_DCDC: """FAC-specific PRUC parameters. Represent FAC, FAC_2S, FAC_2P4S psmodels. """ FREQ_SCAN = 5.0 # [Hz] # PS model parms model = _PSModelFactory.create('FAC_DCDC') CONST_PSBSMP = model.bsmp_constants Entities = model.entities groups = dict() # reserved variable groups (not to be used) groups[_const.G_ALL] = tuple(sorted(Entities.list_variables(0))) groups[_const.G_READONLY] = tuple(sorted(Entities.list_variables(1))) groups[_const.G_WRITE] = tuple(sorted(Entities.list_variables(2))) class PRUCParmsFAC_2S_ACDC: """FAC_2S_ACDC-specific PRUC parameters.""" FREQ_SCAN = 2.0 # [Hz] # PS model parms model = _PSModelFactory.create('FAC_2S_ACDC') CONST_PSBSMP = model.bsmp_constants Entities = model.entities groups = dict() # reserved variable groups (not to be used) groups[_const.G_ALL] = tuple(sorted(Entities.list_variables(0))) groups[_const.G_READONLY] = tuple(sorted(Entities.list_variables(1))) groups[_const.G_WRITE] = tuple(sorted(Entities.list_variables(2))) class PRUCParmsFAC_2P4S_ACDC: """FAC_2P4S_ACDC-specific PRUC parameters.""" FREQ_SCAN = 2.0 # [Hz] # PS model parms model = _PSModelFactory.create('FAC_2P4S_ACDC') CONST_PSBSMP = model.bsmp_constants Entities = model.entities groups = dict() # reserved variable groups (not to be used) groups[_const.G_ALL] = tuple(sorted(Entities.list_variables(0))) groups[_const.G_READONLY] = tuple(sorted(Entities.list_variables(1))) groups[_const.G_WRITE] = tuple(sorted(Entities.list_variables(2))) class PRUCParmsFAP: """FAC-specific PRUC parameters. Represent FAP """ FREQ_SCAN = 5.0 # [Hz] # PS model parms model = _PSModelFactory.create('FAP') CONST_PSBSMP = model.bsmp_constants Entities = model.entities groups = dict() # reserved variable groups (not to be used) groups[_const.G_ALL] = tuple(sorted(Entities.list_variables(0))) groups[_const.G_READONLY] = tuple(sorted(Entities.list_variables(1))) groups[_const.G_WRITE] = tuple(sorted(Entities.list_variables(2))) class PRUCParmsFAP_4P: """FAC-specific PRUC parameters. Represent FAP_4P """ FREQ_SCAN = 5.0 # [Hz] # PS model parms model = _PSModelFactory.create('FAP_4P') CONST_PSBSMP = model.bsmp_constants Entities = model.entities groups = dict() # reserved variable groups (not to be used) groups[_const.G_ALL] = tuple(sorted(Entities.list_variables(0))) groups[_const.G_READONLY] = tuple(sorted(Entities.list_variables(1))) groups[_const.G_WRITE] = tuple(sorted(Entities.list_variables(2))) class PRUCParmsFAP_2P2S: """FAC_2P2S-specific PRUC parameters. Represent FAP_2P2S """ FREQ_SCAN = 5.0 # [Hz] # PS model parms model = _PSModelFactory.create('FAP_2P2S') CONST_PSBSMP = model.bsmp_constants Entities = model.entities groups = dict() # reserved variable groups (not to be used) groups[_const.G_ALL] = tuple(sorted(Entities.list_variables(0))) groups[_const.G_READONLY] = tuple(sorted(Entities.list_variables(1))) groups[_const.G_WRITE] = tuple(sorted(Entities.list_variables(2)))
gpl-3.0
daeseokyoun/youtube-dl
youtube_dl/extractor/vodlocker.py
19
2762
# -*- coding: utf-8 -*- from __future__ import unicode_literals from .common import InfoExtractor from ..utils import ( ExtractorError, NO_DEFAULT, sanitized_Request, urlencode_postdata, ) class VodlockerIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?vodlocker\.(?:com|city)/(?:embed-)?(?P<id>[0-9a-zA-Z]+)(?:\..*?)?' _TESTS = [{ 'url': 'http://vodlocker.com/e8wvyzz4sl42', 'md5': 'ce0c2d18fa0735f1bd91b69b0e54aacf', 'info_dict': { 'id': 'e8wvyzz4sl42', 'ext': 'mp4', 'title': 'Germany vs Brazil', 'thumbnail': 're:http://.*\.jpg', }, }] def _real_extract(self, url): video_id = self._match_id(url) webpage = self._download_webpage(url, video_id) if any(p in webpage for p in ( '>THIS FILE WAS DELETED<', '>File Not Found<', 'The file you were looking for could not be found, sorry for any inconvenience.<')): raise ExtractorError('Video %s does not exist' % video_id, expected=True) fields = self._hidden_inputs(webpage) if fields['op'] == 'download1': self._sleep(3, video_id) # they do detect when requests happen too fast! post = urlencode_postdata(fields) req = sanitized_Request(url, post) req.add_header('Content-type', 'application/x-www-form-urlencoded') webpage = self._download_webpage( req, video_id, 'Downloading video page') def extract_file_url(html, default=NO_DEFAULT): return self._search_regex( r'file:\s*"(http[^\"]+)",', html, 'file url', default=default) video_url = extract_file_url(webpage, default=None) if not video_url: embed_url = self._search_regex( r'<iframe[^>]+src=(["\'])(?P<url>(?:https?://)?vodlocker\.(?:com|city)/embed-.+?)\1', webpage, 'embed url', group='url') embed_webpage = self._download_webpage( embed_url, video_id, 'Downloading embed webpage') video_url = extract_file_url(embed_webpage) thumbnail_webpage = embed_webpage else: thumbnail_webpage = webpage title = self._search_regex( r'id="file_title".*?>\s*(.*?)\s*<(?:br|span)', webpage, 'title') thumbnail = self._search_regex( r'image:\s*"(http[^\"]+)",', thumbnail_webpage, 'thumbnail', fatal=False) formats = [{ 'format_id': 'sd', 'url': video_url, }] return { 'id': video_id, 'title': title, 'thumbnail': thumbnail, 'formats': formats, }
unlicense
walimis/openembedded-gpib2410
contrib/source-checker/oe-checksums-sorter.py
5
1716
#!/usr/bin/env python # ex:ts=4:sw=4:sts=4:et # Copyright (C) 2007 OpenedHand # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # # OpenEmbedded source checksums sorter # # This script parse conf/checksums.ini and sorts it alphabetically by archive # name source archive. Duplicate entries are removed. # # Run it: # # oe-checksums-sorter.py path-to-conf/checksums.ini # # import sys if len(sys.argv) < 2: print """ OpenEmbedded source checksums script require argument: 1. location of conf/checksums.ini """ sys.exit(0) import ConfigParser, os checksums_parser = ConfigParser.ConfigParser() checksums_parser.read(sys.argv[1]) item = 1; files_total = len(checksums_parser.sections()) new_list = [] for source in checksums_parser.sections(): archive = source.split("/")[-1] md5 = checksums_parser.get(source, "md5") sha = checksums_parser.get(source, "sha256") if new_list.count([archive, source, md5, sha]) < 1: new_list += [[archive, source, md5, sha]] new_list.sort() for entry in new_list: print "[%s]\nmd5=%s\nsha256=%s\n" % (entry[1], entry[2], entry[3])
mit
dhiru1602/android_kernel_samsung_jf
tools/perf/scripts/python/net_dropmonitor.py
4235
1554
# Monitor the system for dropped packets and proudce a report of drop locations and counts import os import sys sys.path.append(os.environ['PERF_EXEC_PATH'] + \ '/scripts/python/Perf-Trace-Util/lib/Perf/Trace') from perf_trace_context import * from Core import * from Util import * drop_log = {} kallsyms = [] def get_kallsyms_table(): global kallsyms try: f = open("/proc/kallsyms", "r") linecount = 0 for line in f: linecount = linecount+1 f.seek(0) except: return j = 0 for line in f: loc = int(line.split()[0], 16) name = line.split()[2] j = j +1 if ((j % 100) == 0): print "\r" + str(j) + "/" + str(linecount), kallsyms.append({ 'loc': loc, 'name' : name}) print "\r" + str(j) + "/" + str(linecount) kallsyms.sort() return def get_sym(sloc): loc = int(sloc) for i in kallsyms: if (i['loc'] >= loc): return (i['name'], i['loc']-loc) return (None, 0) def print_drop_table(): print "%25s %25s %25s" % ("LOCATION", "OFFSET", "COUNT") for i in drop_log.keys(): (sym, off) = get_sym(i) if sym == None: sym = i print "%25s %25s %25s" % (sym, off, drop_log[i]) def trace_begin(): print "Starting trace (Ctrl-C to dump results)" def trace_end(): print "Gathering kallsyms data" get_kallsyms_table() print_drop_table() # called from perf, when it finds a correspoinding event def skb__kfree_skb(name, context, cpu, sec, nsec, pid, comm, skbaddr, protocol, location): slocation = str(location) try: drop_log[slocation] = drop_log[slocation] + 1 except: drop_log[slocation] = 1
gpl-2.0
santosh-surya/pcb-cnc-machine
desktop-application/node_modules/npm/node_modules/node-gyp/gyp/pylib/gyp/input.py
713
115880
# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from compiler.ast import Const from compiler.ast import Dict from compiler.ast import Discard from compiler.ast import List from compiler.ast import Module from compiler.ast import Node from compiler.ast import Stmt import compiler import gyp.common import gyp.simple_copy import multiprocessing import optparse import os.path import re import shlex import signal import subprocess import sys import threading import time import traceback from gyp.common import GypError from gyp.common import OrderedSet # A list of types that are treated as linkable. linkable_types = [ 'executable', 'shared_library', 'loadable_module', 'mac_kernel_extension', ] # A list of sections that contain links to other targets. dependency_sections = ['dependencies', 'export_dependent_settings'] # base_path_sections is a list of sections defined by GYP that contain # pathnames. The generators can provide more keys, the two lists are merged # into path_sections, but you should call IsPathSection instead of using either # list directly. base_path_sections = [ 'destination', 'files', 'include_dirs', 'inputs', 'libraries', 'outputs', 'sources', ] path_sections = set() # These per-process dictionaries are used to cache build file data when loading # in parallel mode. per_process_data = {} per_process_aux_data = {} def IsPathSection(section): # If section ends in one of the '=+?!' characters, it's applied to a section # without the trailing characters. '/' is notably absent from this list, # because there's no way for a regular expression to be treated as a path. while section and section[-1:] in '=+?!': section = section[:-1] if section in path_sections: return True # Sections mathing the regexp '_(dir|file|path)s?$' are also # considered PathSections. Using manual string matching since that # is much faster than the regexp and this can be called hundreds of # thousands of times so micro performance matters. if "_" in section: tail = section[-6:] if tail[-1] == 's': tail = tail[:-1] if tail[-5:] in ('_file', '_path'): return True return tail[-4:] == '_dir' return False # base_non_configuration_keys is a list of key names that belong in the target # itself and should not be propagated into its configurations. It is merged # with a list that can come from the generator to # create non_configuration_keys. base_non_configuration_keys = [ # Sections that must exist inside targets and not configurations. 'actions', 'configurations', 'copies', 'default_configuration', 'dependencies', 'dependencies_original', 'libraries', 'postbuilds', 'product_dir', 'product_extension', 'product_name', 'product_prefix', 'rules', 'run_as', 'sources', 'standalone_static_library', 'suppress_wildcard', 'target_name', 'toolset', 'toolsets', 'type', # Sections that can be found inside targets or configurations, but that # should not be propagated from targets into their configurations. 'variables', ] non_configuration_keys = [] # Keys that do not belong inside a configuration dictionary. invalid_configuration_keys = [ 'actions', 'all_dependent_settings', 'configurations', 'dependencies', 'direct_dependent_settings', 'libraries', 'link_settings', 'sources', 'standalone_static_library', 'target_name', 'type', ] # Controls whether or not the generator supports multiple toolsets. multiple_toolsets = False # Paths for converting filelist paths to output paths: { # toplevel, # qualified_output_dir, # } generator_filelist_paths = None def GetIncludedBuildFiles(build_file_path, aux_data, included=None): """Return a list of all build files included into build_file_path. The returned list will contain build_file_path as well as all other files that it included, either directly or indirectly. Note that the list may contain files that were included into a conditional section that evaluated to false and was not merged into build_file_path's dict. aux_data is a dict containing a key for each build file or included build file. Those keys provide access to dicts whose "included" keys contain lists of all other files included by the build file. included should be left at its default None value by external callers. It is used for recursion. The returned list will not contain any duplicate entries. Each build file in the list will be relative to the current directory. """ if included == None: included = [] if build_file_path in included: return included included.append(build_file_path) for included_build_file in aux_data[build_file_path].get('included', []): GetIncludedBuildFiles(included_build_file, aux_data, included) return included def CheckedEval(file_contents): """Return the eval of a gyp file. The gyp file is restricted to dictionaries and lists only, and repeated keys are not allowed. Note that this is slower than eval() is. """ ast = compiler.parse(file_contents) assert isinstance(ast, Module) c1 = ast.getChildren() assert c1[0] is None assert isinstance(c1[1], Stmt) c2 = c1[1].getChildren() assert isinstance(c2[0], Discard) c3 = c2[0].getChildren() assert len(c3) == 1 return CheckNode(c3[0], []) def CheckNode(node, keypath): if isinstance(node, Dict): c = node.getChildren() dict = {} for n in range(0, len(c), 2): assert isinstance(c[n], Const) key = c[n].getChildren()[0] if key in dict: raise GypError("Key '" + key + "' repeated at level " + repr(len(keypath) + 1) + " with key path '" + '.'.join(keypath) + "'") kp = list(keypath) # Make a copy of the list for descending this node. kp.append(key) dict[key] = CheckNode(c[n + 1], kp) return dict elif isinstance(node, List): c = node.getChildren() children = [] for index, child in enumerate(c): kp = list(keypath) # Copy list. kp.append(repr(index)) children.append(CheckNode(child, kp)) return children elif isinstance(node, Const): return node.getChildren()[0] else: raise TypeError("Unknown AST node at key path '" + '.'.join(keypath) + "': " + repr(node)) def LoadOneBuildFile(build_file_path, data, aux_data, includes, is_target, check): if build_file_path in data: return data[build_file_path] if os.path.exists(build_file_path): build_file_contents = open(build_file_path).read() else: raise GypError("%s not found (cwd: %s)" % (build_file_path, os.getcwd())) build_file_data = None try: if check: build_file_data = CheckedEval(build_file_contents) else: build_file_data = eval(build_file_contents, {'__builtins__': None}, None) except SyntaxError, e: e.filename = build_file_path raise except Exception, e: gyp.common.ExceptionAppend(e, 'while reading ' + build_file_path) raise if type(build_file_data) is not dict: raise GypError("%s does not evaluate to a dictionary." % build_file_path) data[build_file_path] = build_file_data aux_data[build_file_path] = {} # Scan for includes and merge them in. if ('skip_includes' not in build_file_data or not build_file_data['skip_includes']): try: if is_target: LoadBuildFileIncludesIntoDict(build_file_data, build_file_path, data, aux_data, includes, check) else: LoadBuildFileIncludesIntoDict(build_file_data, build_file_path, data, aux_data, None, check) except Exception, e: gyp.common.ExceptionAppend(e, 'while reading includes of ' + build_file_path) raise return build_file_data def LoadBuildFileIncludesIntoDict(subdict, subdict_path, data, aux_data, includes, check): includes_list = [] if includes != None: includes_list.extend(includes) if 'includes' in subdict: for include in subdict['includes']: # "include" is specified relative to subdict_path, so compute the real # path to include by appending the provided "include" to the directory # in which subdict_path resides. relative_include = \ os.path.normpath(os.path.join(os.path.dirname(subdict_path), include)) includes_list.append(relative_include) # Unhook the includes list, it's no longer needed. del subdict['includes'] # Merge in the included files. for include in includes_list: if not 'included' in aux_data[subdict_path]: aux_data[subdict_path]['included'] = [] aux_data[subdict_path]['included'].append(include) gyp.DebugOutput(gyp.DEBUG_INCLUDES, "Loading Included File: '%s'", include) MergeDicts(subdict, LoadOneBuildFile(include, data, aux_data, None, False, check), subdict_path, include) # Recurse into subdictionaries. for k, v in subdict.iteritems(): if type(v) is dict: LoadBuildFileIncludesIntoDict(v, subdict_path, data, aux_data, None, check) elif type(v) is list: LoadBuildFileIncludesIntoList(v, subdict_path, data, aux_data, check) # This recurses into lists so that it can look for dicts. def LoadBuildFileIncludesIntoList(sublist, sublist_path, data, aux_data, check): for item in sublist: if type(item) is dict: LoadBuildFileIncludesIntoDict(item, sublist_path, data, aux_data, None, check) elif type(item) is list: LoadBuildFileIncludesIntoList(item, sublist_path, data, aux_data, check) # Processes toolsets in all the targets. This recurses into condition entries # since they can contain toolsets as well. def ProcessToolsetsInDict(data): if 'targets' in data: target_list = data['targets'] new_target_list = [] for target in target_list: # If this target already has an explicit 'toolset', and no 'toolsets' # list, don't modify it further. if 'toolset' in target and 'toolsets' not in target: new_target_list.append(target) continue if multiple_toolsets: toolsets = target.get('toolsets', ['target']) else: toolsets = ['target'] # Make sure this 'toolsets' definition is only processed once. if 'toolsets' in target: del target['toolsets'] if len(toolsets) > 0: # Optimization: only do copies if more than one toolset is specified. for build in toolsets[1:]: new_target = gyp.simple_copy.deepcopy(target) new_target['toolset'] = build new_target_list.append(new_target) target['toolset'] = toolsets[0] new_target_list.append(target) data['targets'] = new_target_list if 'conditions' in data: for condition in data['conditions']: if type(condition) is list: for condition_dict in condition[1:]: if type(condition_dict) is dict: ProcessToolsetsInDict(condition_dict) # TODO(mark): I don't love this name. It just means that it's going to load # a build file that contains targets and is expected to provide a targets dict # that contains the targets... def LoadTargetBuildFile(build_file_path, data, aux_data, variables, includes, depth, check, load_dependencies): # If depth is set, predefine the DEPTH variable to be a relative path from # this build file's directory to the directory identified by depth. if depth: # TODO(dglazkov) The backslash/forward-slash replacement at the end is a # temporary measure. This should really be addressed by keeping all paths # in POSIX until actual project generation. d = gyp.common.RelativePath(depth, os.path.dirname(build_file_path)) if d == '': variables['DEPTH'] = '.' else: variables['DEPTH'] = d.replace('\\', '/') # The 'target_build_files' key is only set when loading target build files in # the non-parallel code path, where LoadTargetBuildFile is called # recursively. In the parallel code path, we don't need to check whether the # |build_file_path| has already been loaded, because the 'scheduled' set in # ParallelState guarantees that we never load the same |build_file_path| # twice. if 'target_build_files' in data: if build_file_path in data['target_build_files']: # Already loaded. return False data['target_build_files'].add(build_file_path) gyp.DebugOutput(gyp.DEBUG_INCLUDES, "Loading Target Build File '%s'", build_file_path) build_file_data = LoadOneBuildFile(build_file_path, data, aux_data, includes, True, check) # Store DEPTH for later use in generators. build_file_data['_DEPTH'] = depth # Set up the included_files key indicating which .gyp files contributed to # this target dict. if 'included_files' in build_file_data: raise GypError(build_file_path + ' must not contain included_files key') included = GetIncludedBuildFiles(build_file_path, aux_data) build_file_data['included_files'] = [] for included_file in included: # included_file is relative to the current directory, but it needs to # be made relative to build_file_path's directory. included_relative = \ gyp.common.RelativePath(included_file, os.path.dirname(build_file_path)) build_file_data['included_files'].append(included_relative) # Do a first round of toolsets expansion so that conditions can be defined # per toolset. ProcessToolsetsInDict(build_file_data) # Apply "pre"/"early" variable expansions and condition evaluations. ProcessVariablesAndConditionsInDict( build_file_data, PHASE_EARLY, variables, build_file_path) # Since some toolsets might have been defined conditionally, perform # a second round of toolsets expansion now. ProcessToolsetsInDict(build_file_data) # Look at each project's target_defaults dict, and merge settings into # targets. if 'target_defaults' in build_file_data: if 'targets' not in build_file_data: raise GypError("Unable to find targets in build file %s" % build_file_path) index = 0 while index < len(build_file_data['targets']): # This procedure needs to give the impression that target_defaults is # used as defaults, and the individual targets inherit from that. # The individual targets need to be merged into the defaults. Make # a deep copy of the defaults for each target, merge the target dict # as found in the input file into that copy, and then hook up the # copy with the target-specific data merged into it as the replacement # target dict. old_target_dict = build_file_data['targets'][index] new_target_dict = gyp.simple_copy.deepcopy( build_file_data['target_defaults']) MergeDicts(new_target_dict, old_target_dict, build_file_path, build_file_path) build_file_data['targets'][index] = new_target_dict index += 1 # No longer needed. del build_file_data['target_defaults'] # Look for dependencies. This means that dependency resolution occurs # after "pre" conditionals and variable expansion, but before "post" - # in other words, you can't put a "dependencies" section inside a "post" # conditional within a target. dependencies = [] if 'targets' in build_file_data: for target_dict in build_file_data['targets']: if 'dependencies' not in target_dict: continue for dependency in target_dict['dependencies']: dependencies.append( gyp.common.ResolveTarget(build_file_path, dependency, None)[0]) if load_dependencies: for dependency in dependencies: try: LoadTargetBuildFile(dependency, data, aux_data, variables, includes, depth, check, load_dependencies) except Exception, e: gyp.common.ExceptionAppend( e, 'while loading dependencies of %s' % build_file_path) raise else: return (build_file_path, dependencies) def CallLoadTargetBuildFile(global_flags, build_file_path, variables, includes, depth, check, generator_input_info): """Wrapper around LoadTargetBuildFile for parallel processing. This wrapper is used when LoadTargetBuildFile is executed in a worker process. """ try: signal.signal(signal.SIGINT, signal.SIG_IGN) # Apply globals so that the worker process behaves the same. for key, value in global_flags.iteritems(): globals()[key] = value SetGeneratorGlobals(generator_input_info) result = LoadTargetBuildFile(build_file_path, per_process_data, per_process_aux_data, variables, includes, depth, check, False) if not result: return result (build_file_path, dependencies) = result # We can safely pop the build_file_data from per_process_data because it # will never be referenced by this process again, so we don't need to keep # it in the cache. build_file_data = per_process_data.pop(build_file_path) # This gets serialized and sent back to the main process via a pipe. # It's handled in LoadTargetBuildFileCallback. return (build_file_path, build_file_data, dependencies) except GypError, e: sys.stderr.write("gyp: %s\n" % e) return None except Exception, e: print >>sys.stderr, 'Exception:', e print >>sys.stderr, traceback.format_exc() return None class ParallelProcessingError(Exception): pass class ParallelState(object): """Class to keep track of state when processing input files in parallel. If build files are loaded in parallel, use this to keep track of state during farming out and processing parallel jobs. It's stored in a global so that the callback function can have access to it. """ def __init__(self): # The multiprocessing pool. self.pool = None # The condition variable used to protect this object and notify # the main loop when there might be more data to process. self.condition = None # The "data" dict that was passed to LoadTargetBuildFileParallel self.data = None # The number of parallel calls outstanding; decremented when a response # was received. self.pending = 0 # The set of all build files that have been scheduled, so we don't # schedule the same one twice. self.scheduled = set() # A list of dependency build file paths that haven't been scheduled yet. self.dependencies = [] # Flag to indicate if there was an error in a child process. self.error = False def LoadTargetBuildFileCallback(self, result): """Handle the results of running LoadTargetBuildFile in another process. """ self.condition.acquire() if not result: self.error = True self.condition.notify() self.condition.release() return (build_file_path0, build_file_data0, dependencies0) = result self.data[build_file_path0] = build_file_data0 self.data['target_build_files'].add(build_file_path0) for new_dependency in dependencies0: if new_dependency not in self.scheduled: self.scheduled.add(new_dependency) self.dependencies.append(new_dependency) self.pending -= 1 self.condition.notify() self.condition.release() def LoadTargetBuildFilesParallel(build_files, data, variables, includes, depth, check, generator_input_info): parallel_state = ParallelState() parallel_state.condition = threading.Condition() # Make copies of the build_files argument that we can modify while working. parallel_state.dependencies = list(build_files) parallel_state.scheduled = set(build_files) parallel_state.pending = 0 parallel_state.data = data try: parallel_state.condition.acquire() while parallel_state.dependencies or parallel_state.pending: if parallel_state.error: break if not parallel_state.dependencies: parallel_state.condition.wait() continue dependency = parallel_state.dependencies.pop() parallel_state.pending += 1 global_flags = { 'path_sections': globals()['path_sections'], 'non_configuration_keys': globals()['non_configuration_keys'], 'multiple_toolsets': globals()['multiple_toolsets']} if not parallel_state.pool: parallel_state.pool = multiprocessing.Pool(multiprocessing.cpu_count()) parallel_state.pool.apply_async( CallLoadTargetBuildFile, args = (global_flags, dependency, variables, includes, depth, check, generator_input_info), callback = parallel_state.LoadTargetBuildFileCallback) except KeyboardInterrupt, e: parallel_state.pool.terminate() raise e parallel_state.condition.release() parallel_state.pool.close() parallel_state.pool.join() parallel_state.pool = None if parallel_state.error: sys.exit(1) # Look for the bracket that matches the first bracket seen in a # string, and return the start and end as a tuple. For example, if # the input is something like "<(foo <(bar)) blah", then it would # return (1, 13), indicating the entire string except for the leading # "<" and trailing " blah". LBRACKETS= set('{[(') BRACKETS = {'}': '{', ']': '[', ')': '('} def FindEnclosingBracketGroup(input_str): stack = [] start = -1 for index, char in enumerate(input_str): if char in LBRACKETS: stack.append(char) if start == -1: start = index elif char in BRACKETS: if not stack: return (-1, -1) if stack.pop() != BRACKETS[char]: return (-1, -1) if not stack: return (start, index + 1) return (-1, -1) def IsStrCanonicalInt(string): """Returns True if |string| is in its canonical integer form. The canonical form is such that str(int(string)) == string. """ if type(string) is str: # This function is called a lot so for maximum performance, avoid # involving regexps which would otherwise make the code much # shorter. Regexps would need twice the time of this function. if string: if string == "0": return True if string[0] == "-": string = string[1:] if not string: return False if '1' <= string[0] <= '9': return string.isdigit() return False # This matches things like "<(asdf)", "<!(cmd)", "<!@(cmd)", "<|(list)", # "<!interpreter(arguments)", "<([list])", and even "<([)" and "<(<())". # In the last case, the inner "<()" is captured in match['content']. early_variable_re = re.compile( r'(?P<replace>(?P<type><(?:(?:!?@?)|\|)?)' r'(?P<command_string>[-a-zA-Z0-9_.]+)?' r'\((?P<is_array>\s*\[?)' r'(?P<content>.*?)(\]?)\))') # This matches the same as early_variable_re, but with '>' instead of '<'. late_variable_re = re.compile( r'(?P<replace>(?P<type>>(?:(?:!?@?)|\|)?)' r'(?P<command_string>[-a-zA-Z0-9_.]+)?' r'\((?P<is_array>\s*\[?)' r'(?P<content>.*?)(\]?)\))') # This matches the same as early_variable_re, but with '^' instead of '<'. latelate_variable_re = re.compile( r'(?P<replace>(?P<type>[\^](?:(?:!?@?)|\|)?)' r'(?P<command_string>[-a-zA-Z0-9_.]+)?' r'\((?P<is_array>\s*\[?)' r'(?P<content>.*?)(\]?)\))') # Global cache of results from running commands so they don't have to be run # more then once. cached_command_results = {} def FixupPlatformCommand(cmd): if sys.platform == 'win32': if type(cmd) is list: cmd = [re.sub('^cat ', 'type ', cmd[0])] + cmd[1:] else: cmd = re.sub('^cat ', 'type ', cmd) return cmd PHASE_EARLY = 0 PHASE_LATE = 1 PHASE_LATELATE = 2 def ExpandVariables(input, phase, variables, build_file): # Look for the pattern that gets expanded into variables if phase == PHASE_EARLY: variable_re = early_variable_re expansion_symbol = '<' elif phase == PHASE_LATE: variable_re = late_variable_re expansion_symbol = '>' elif phase == PHASE_LATELATE: variable_re = latelate_variable_re expansion_symbol = '^' else: assert False input_str = str(input) if IsStrCanonicalInt(input_str): return int(input_str) # Do a quick scan to determine if an expensive regex search is warranted. if expansion_symbol not in input_str: return input_str # Get the entire list of matches as a list of MatchObject instances. # (using findall here would return strings instead of MatchObjects). matches = list(variable_re.finditer(input_str)) if not matches: return input_str output = input_str # Reverse the list of matches so that replacements are done right-to-left. # That ensures that earlier replacements won't mess up the string in a # way that causes later calls to find the earlier substituted text instead # of what's intended for replacement. matches.reverse() for match_group in matches: match = match_group.groupdict() gyp.DebugOutput(gyp.DEBUG_VARIABLES, "Matches: %r", match) # match['replace'] is the substring to look for, match['type'] # is the character code for the replacement type (< > <! >! <| >| <@ # >@ <!@ >!@), match['is_array'] contains a '[' for command # arrays, and match['content'] is the name of the variable (< >) # or command to run (<! >!). match['command_string'] is an optional # command string. Currently, only 'pymod_do_main' is supported. # run_command is true if a ! variant is used. run_command = '!' in match['type'] command_string = match['command_string'] # file_list is true if a | variant is used. file_list = '|' in match['type'] # Capture these now so we can adjust them later. replace_start = match_group.start('replace') replace_end = match_group.end('replace') # Find the ending paren, and re-evaluate the contained string. (c_start, c_end) = FindEnclosingBracketGroup(input_str[replace_start:]) # Adjust the replacement range to match the entire command # found by FindEnclosingBracketGroup (since the variable_re # probably doesn't match the entire command if it contained # nested variables). replace_end = replace_start + c_end # Find the "real" replacement, matching the appropriate closing # paren, and adjust the replacement start and end. replacement = input_str[replace_start:replace_end] # Figure out what the contents of the variable parens are. contents_start = replace_start + c_start + 1 contents_end = replace_end - 1 contents = input_str[contents_start:contents_end] # Do filter substitution now for <|(). # Admittedly, this is different than the evaluation order in other # contexts. However, since filtration has no chance to run on <|(), # this seems like the only obvious way to give them access to filters. if file_list: processed_variables = gyp.simple_copy.deepcopy(variables) ProcessListFiltersInDict(contents, processed_variables) # Recurse to expand variables in the contents contents = ExpandVariables(contents, phase, processed_variables, build_file) else: # Recurse to expand variables in the contents contents = ExpandVariables(contents, phase, variables, build_file) # Strip off leading/trailing whitespace so that variable matches are # simpler below (and because they are rarely needed). contents = contents.strip() # expand_to_list is true if an @ variant is used. In that case, # the expansion should result in a list. Note that the caller # is to be expecting a list in return, and not all callers do # because not all are working in list context. Also, for list # expansions, there can be no other text besides the variable # expansion in the input string. expand_to_list = '@' in match['type'] and input_str == replacement if run_command or file_list: # Find the build file's directory, so commands can be run or file lists # generated relative to it. build_file_dir = os.path.dirname(build_file) if build_file_dir == '' and not file_list: # If build_file is just a leaf filename indicating a file in the # current directory, build_file_dir might be an empty string. Set # it to None to signal to subprocess.Popen that it should run the # command in the current directory. build_file_dir = None # Support <|(listfile.txt ...) which generates a file # containing items from a gyp list, generated at gyp time. # This works around actions/rules which have more inputs than will # fit on the command line. if file_list: if type(contents) is list: contents_list = contents else: contents_list = contents.split(' ') replacement = contents_list[0] if os.path.isabs(replacement): raise GypError('| cannot handle absolute paths, got "%s"' % replacement) if not generator_filelist_paths: path = os.path.join(build_file_dir, replacement) else: if os.path.isabs(build_file_dir): toplevel = generator_filelist_paths['toplevel'] rel_build_file_dir = gyp.common.RelativePath(build_file_dir, toplevel) else: rel_build_file_dir = build_file_dir qualified_out_dir = generator_filelist_paths['qualified_out_dir'] path = os.path.join(qualified_out_dir, rel_build_file_dir, replacement) gyp.common.EnsureDirExists(path) replacement = gyp.common.RelativePath(path, build_file_dir) f = gyp.common.WriteOnDiff(path) for i in contents_list[1:]: f.write('%s\n' % i) f.close() elif run_command: use_shell = True if match['is_array']: contents = eval(contents) use_shell = False # Check for a cached value to avoid executing commands, or generating # file lists more than once. The cache key contains the command to be # run as well as the directory to run it from, to account for commands # that depend on their current directory. # TODO(http://code.google.com/p/gyp/issues/detail?id=111): In theory, # someone could author a set of GYP files where each time the command # is invoked it produces different output by design. When the need # arises, the syntax should be extended to support no caching off a # command's output so it is run every time. cache_key = (str(contents), build_file_dir) cached_value = cached_command_results.get(cache_key, None) if cached_value is None: gyp.DebugOutput(gyp.DEBUG_VARIABLES, "Executing command '%s' in directory '%s'", contents, build_file_dir) replacement = '' if command_string == 'pymod_do_main': # <!pymod_do_main(modulename param eters) loads |modulename| as a # python module and then calls that module's DoMain() function, # passing ["param", "eters"] as a single list argument. For modules # that don't load quickly, this can be faster than # <!(python modulename param eters). Do this in |build_file_dir|. oldwd = os.getcwd() # Python doesn't like os.open('.'): no fchdir. if build_file_dir: # build_file_dir may be None (see above). os.chdir(build_file_dir) try: parsed_contents = shlex.split(contents) try: py_module = __import__(parsed_contents[0]) except ImportError as e: raise GypError("Error importing pymod_do_main" "module (%s): %s" % (parsed_contents[0], e)) replacement = str(py_module.DoMain(parsed_contents[1:])).rstrip() finally: os.chdir(oldwd) assert replacement != None elif command_string: raise GypError("Unknown command string '%s' in '%s'." % (command_string, contents)) else: # Fix up command with platform specific workarounds. contents = FixupPlatformCommand(contents) try: p = subprocess.Popen(contents, shell=use_shell, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, cwd=build_file_dir) except Exception, e: raise GypError("%s while executing command '%s' in %s" % (e, contents, build_file)) p_stdout, p_stderr = p.communicate('') if p.wait() != 0 or p_stderr: sys.stderr.write(p_stderr) # Simulate check_call behavior, since check_call only exists # in python 2.5 and later. raise GypError("Call to '%s' returned exit status %d while in %s." % (contents, p.returncode, build_file)) replacement = p_stdout.rstrip() cached_command_results[cache_key] = replacement else: gyp.DebugOutput(gyp.DEBUG_VARIABLES, "Had cache value for command '%s' in directory '%s'", contents,build_file_dir) replacement = cached_value else: if not contents in variables: if contents[-1] in ['!', '/']: # In order to allow cross-compiles (nacl) to happen more naturally, # we will allow references to >(sources/) etc. to resolve to # and empty list if undefined. This allows actions to: # 'action!': [ # '>@(_sources!)', # ], # 'action/': [ # '>@(_sources/)', # ], replacement = [] else: raise GypError('Undefined variable ' + contents + ' in ' + build_file) else: replacement = variables[contents] if type(replacement) is list: for item in replacement: if not contents[-1] == '/' and type(item) not in (str, int): raise GypError('Variable ' + contents + ' must expand to a string or list of strings; ' + 'list contains a ' + item.__class__.__name__) # Run through the list and handle variable expansions in it. Since # the list is guaranteed not to contain dicts, this won't do anything # with conditions sections. ProcessVariablesAndConditionsInList(replacement, phase, variables, build_file) elif type(replacement) not in (str, int): raise GypError('Variable ' + contents + ' must expand to a string or list of strings; ' + 'found a ' + replacement.__class__.__name__) if expand_to_list: # Expanding in list context. It's guaranteed that there's only one # replacement to do in |input_str| and that it's this replacement. See # above. if type(replacement) is list: # If it's already a list, make a copy. output = replacement[:] else: # Split it the same way sh would split arguments. output = shlex.split(str(replacement)) else: # Expanding in string context. encoded_replacement = '' if type(replacement) is list: # When expanding a list into string context, turn the list items # into a string in a way that will work with a subprocess call. # # TODO(mark): This isn't completely correct. This should # call a generator-provided function that observes the # proper list-to-argument quoting rules on a specific # platform instead of just calling the POSIX encoding # routine. encoded_replacement = gyp.common.EncodePOSIXShellList(replacement) else: encoded_replacement = replacement output = output[:replace_start] + str(encoded_replacement) + \ output[replace_end:] # Prepare for the next match iteration. input_str = output if output == input: gyp.DebugOutput(gyp.DEBUG_VARIABLES, "Found only identity matches on %r, avoiding infinite " "recursion.", output) else: # Look for more matches now that we've replaced some, to deal with # expanding local variables (variables defined in the same # variables block as this one). gyp.DebugOutput(gyp.DEBUG_VARIABLES, "Found output %r, recursing.", output) if type(output) is list: if output and type(output[0]) is list: # Leave output alone if it's a list of lists. # We don't want such lists to be stringified. pass else: new_output = [] for item in output: new_output.append( ExpandVariables(item, phase, variables, build_file)) output = new_output else: output = ExpandVariables(output, phase, variables, build_file) # Convert all strings that are canonically-represented integers into integers. if type(output) is list: for index in xrange(0, len(output)): if IsStrCanonicalInt(output[index]): output[index] = int(output[index]) elif IsStrCanonicalInt(output): output = int(output) return output # The same condition is often evaluated over and over again so it # makes sense to cache as much as possible between evaluations. cached_conditions_asts = {} def EvalCondition(condition, conditions_key, phase, variables, build_file): """Returns the dict that should be used or None if the result was that nothing should be used.""" if type(condition) is not list: raise GypError(conditions_key + ' must be a list') if len(condition) < 2: # It's possible that condition[0] won't work in which case this # attempt will raise its own IndexError. That's probably fine. raise GypError(conditions_key + ' ' + condition[0] + ' must be at least length 2, not ' + str(len(condition))) i = 0 result = None while i < len(condition): cond_expr = condition[i] true_dict = condition[i + 1] if type(true_dict) is not dict: raise GypError('{} {} must be followed by a dictionary, not {}'.format( conditions_key, cond_expr, type(true_dict))) if len(condition) > i + 2 and type(condition[i + 2]) is dict: false_dict = condition[i + 2] i = i + 3 if i != len(condition): raise GypError('{} {} has {} unexpected trailing items'.format( conditions_key, cond_expr, len(condition) - i)) else: false_dict = None i = i + 2 if result == None: result = EvalSingleCondition( cond_expr, true_dict, false_dict, phase, variables, build_file) return result def EvalSingleCondition( cond_expr, true_dict, false_dict, phase, variables, build_file): """Returns true_dict if cond_expr evaluates to true, and false_dict otherwise.""" # Do expansions on the condition itself. Since the conditon can naturally # contain variable references without needing to resort to GYP expansion # syntax, this is of dubious value for variables, but someone might want to # use a command expansion directly inside a condition. cond_expr_expanded = ExpandVariables(cond_expr, phase, variables, build_file) if type(cond_expr_expanded) not in (str, int): raise ValueError( 'Variable expansion in this context permits str and int ' + \ 'only, found ' + cond_expr_expanded.__class__.__name__) try: if cond_expr_expanded in cached_conditions_asts: ast_code = cached_conditions_asts[cond_expr_expanded] else: ast_code = compile(cond_expr_expanded, '<string>', 'eval') cached_conditions_asts[cond_expr_expanded] = ast_code if eval(ast_code, {'__builtins__': None}, variables): return true_dict return false_dict except SyntaxError, e: syntax_error = SyntaxError('%s while evaluating condition \'%s\' in %s ' 'at character %d.' % (str(e.args[0]), e.text, build_file, e.offset), e.filename, e.lineno, e.offset, e.text) raise syntax_error except NameError, e: gyp.common.ExceptionAppend(e, 'while evaluating condition \'%s\' in %s' % (cond_expr_expanded, build_file)) raise GypError(e) def ProcessConditionsInDict(the_dict, phase, variables, build_file): # Process a 'conditions' or 'target_conditions' section in the_dict, # depending on phase. # early -> conditions # late -> target_conditions # latelate -> no conditions # # Each item in a conditions list consists of cond_expr, a string expression # evaluated as the condition, and true_dict, a dict that will be merged into # the_dict if cond_expr evaluates to true. Optionally, a third item, # false_dict, may be present. false_dict is merged into the_dict if # cond_expr evaluates to false. # # Any dict merged into the_dict will be recursively processed for nested # conditionals and other expansions, also according to phase, immediately # prior to being merged. if phase == PHASE_EARLY: conditions_key = 'conditions' elif phase == PHASE_LATE: conditions_key = 'target_conditions' elif phase == PHASE_LATELATE: return else: assert False if not conditions_key in the_dict: return conditions_list = the_dict[conditions_key] # Unhook the conditions list, it's no longer needed. del the_dict[conditions_key] for condition in conditions_list: merge_dict = EvalCondition(condition, conditions_key, phase, variables, build_file) if merge_dict != None: # Expand variables and nested conditinals in the merge_dict before # merging it. ProcessVariablesAndConditionsInDict(merge_dict, phase, variables, build_file) MergeDicts(the_dict, merge_dict, build_file, build_file) def LoadAutomaticVariablesFromDict(variables, the_dict): # Any keys with plain string values in the_dict become automatic variables. # The variable name is the key name with a "_" character prepended. for key, value in the_dict.iteritems(): if type(value) in (str, int, list): variables['_' + key] = value def LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key): # Any keys in the_dict's "variables" dict, if it has one, becomes a # variable. The variable name is the key name in the "variables" dict. # Variables that end with the % character are set only if they are unset in # the variables dict. the_dict_key is the name of the key that accesses # the_dict in the_dict's parent dict. If the_dict's parent is not a dict # (it could be a list or it could be parentless because it is a root dict), # the_dict_key will be None. for key, value in the_dict.get('variables', {}).iteritems(): if type(value) not in (str, int, list): continue if key.endswith('%'): variable_name = key[:-1] if variable_name in variables: # If the variable is already set, don't set it. continue if the_dict_key is 'variables' and variable_name in the_dict: # If the variable is set without a % in the_dict, and the_dict is a # variables dict (making |variables| a varaibles sub-dict of a # variables dict), use the_dict's definition. value = the_dict[variable_name] else: variable_name = key variables[variable_name] = value def ProcessVariablesAndConditionsInDict(the_dict, phase, variables_in, build_file, the_dict_key=None): """Handle all variable and command expansion and conditional evaluation. This function is the public entry point for all variable expansions and conditional evaluations. The variables_in dictionary will not be modified by this function. """ # Make a copy of the variables_in dict that can be modified during the # loading of automatics and the loading of the variables dict. variables = variables_in.copy() LoadAutomaticVariablesFromDict(variables, the_dict) if 'variables' in the_dict: # Make sure all the local variables are added to the variables # list before we process them so that you can reference one # variable from another. They will be fully expanded by recursion # in ExpandVariables. for key, value in the_dict['variables'].iteritems(): variables[key] = value # Handle the associated variables dict first, so that any variable # references within can be resolved prior to using them as variables. # Pass a copy of the variables dict to avoid having it be tainted. # Otherwise, it would have extra automatics added for everything that # should just be an ordinary variable in this scope. ProcessVariablesAndConditionsInDict(the_dict['variables'], phase, variables, build_file, 'variables') LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key) for key, value in the_dict.iteritems(): # Skip "variables", which was already processed if present. if key != 'variables' and type(value) is str: expanded = ExpandVariables(value, phase, variables, build_file) if type(expanded) not in (str, int): raise ValueError( 'Variable expansion in this context permits str and int ' + \ 'only, found ' + expanded.__class__.__name__ + ' for ' + key) the_dict[key] = expanded # Variable expansion may have resulted in changes to automatics. Reload. # TODO(mark): Optimization: only reload if no changes were made. variables = variables_in.copy() LoadAutomaticVariablesFromDict(variables, the_dict) LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key) # Process conditions in this dict. This is done after variable expansion # so that conditions may take advantage of expanded variables. For example, # if the_dict contains: # {'type': '<(library_type)', # 'conditions': [['_type=="static_library"', { ... }]]}, # _type, as used in the condition, will only be set to the value of # library_type if variable expansion is performed before condition # processing. However, condition processing should occur prior to recursion # so that variables (both automatic and "variables" dict type) may be # adjusted by conditions sections, merged into the_dict, and have the # intended impact on contained dicts. # # This arrangement means that a "conditions" section containing a "variables" # section will only have those variables effective in subdicts, not in # the_dict. The workaround is to put a "conditions" section within a # "variables" section. For example: # {'conditions': [['os=="mac"', {'variables': {'define': 'IS_MAC'}}]], # 'defines': ['<(define)'], # 'my_subdict': {'defines': ['<(define)']}}, # will not result in "IS_MAC" being appended to the "defines" list in the # current scope but would result in it being appended to the "defines" list # within "my_subdict". By comparison: # {'variables': {'conditions': [['os=="mac"', {'define': 'IS_MAC'}]]}, # 'defines': ['<(define)'], # 'my_subdict': {'defines': ['<(define)']}}, # will append "IS_MAC" to both "defines" lists. # Evaluate conditions sections, allowing variable expansions within them # as well as nested conditionals. This will process a 'conditions' or # 'target_conditions' section, perform appropriate merging and recursive # conditional and variable processing, and then remove the conditions section # from the_dict if it is present. ProcessConditionsInDict(the_dict, phase, variables, build_file) # Conditional processing may have resulted in changes to automatics or the # variables dict. Reload. variables = variables_in.copy() LoadAutomaticVariablesFromDict(variables, the_dict) LoadVariablesFromVariablesDict(variables, the_dict, the_dict_key) # Recurse into child dicts, or process child lists which may result in # further recursion into descendant dicts. for key, value in the_dict.iteritems(): # Skip "variables" and string values, which were already processed if # present. if key == 'variables' or type(value) is str: continue if type(value) is dict: # Pass a copy of the variables dict so that subdicts can't influence # parents. ProcessVariablesAndConditionsInDict(value, phase, variables, build_file, key) elif type(value) is list: # The list itself can't influence the variables dict, and # ProcessVariablesAndConditionsInList will make copies of the variables # dict if it needs to pass it to something that can influence it. No # copy is necessary here. ProcessVariablesAndConditionsInList(value, phase, variables, build_file) elif type(value) is not int: raise TypeError('Unknown type ' + value.__class__.__name__ + \ ' for ' + key) def ProcessVariablesAndConditionsInList(the_list, phase, variables, build_file): # Iterate using an index so that new values can be assigned into the_list. index = 0 while index < len(the_list): item = the_list[index] if type(item) is dict: # Make a copy of the variables dict so that it won't influence anything # outside of its own scope. ProcessVariablesAndConditionsInDict(item, phase, variables, build_file) elif type(item) is list: ProcessVariablesAndConditionsInList(item, phase, variables, build_file) elif type(item) is str: expanded = ExpandVariables(item, phase, variables, build_file) if type(expanded) in (str, int): the_list[index] = expanded elif type(expanded) is list: the_list[index:index+1] = expanded index += len(expanded) # index now identifies the next item to examine. Continue right now # without falling into the index increment below. continue else: raise ValueError( 'Variable expansion in this context permits strings and ' + \ 'lists only, found ' + expanded.__class__.__name__ + ' at ' + \ index) elif type(item) is not int: raise TypeError('Unknown type ' + item.__class__.__name__ + \ ' at index ' + index) index = index + 1 def BuildTargetsDict(data): """Builds a dict mapping fully-qualified target names to their target dicts. |data| is a dict mapping loaded build files by pathname relative to the current directory. Values in |data| are build file contents. For each |data| value with a "targets" key, the value of the "targets" key is taken as a list containing target dicts. Each target's fully-qualified name is constructed from the pathname of the build file (|data| key) and its "target_name" property. These fully-qualified names are used as the keys in the returned dict. These keys provide access to the target dicts, the dicts in the "targets" lists. """ targets = {} for build_file in data['target_build_files']: for target in data[build_file].get('targets', []): target_name = gyp.common.QualifiedTarget(build_file, target['target_name'], target['toolset']) if target_name in targets: raise GypError('Duplicate target definitions for ' + target_name) targets[target_name] = target return targets def QualifyDependencies(targets): """Make dependency links fully-qualified relative to the current directory. |targets| is a dict mapping fully-qualified target names to their target dicts. For each target in this dict, keys known to contain dependency links are examined, and any dependencies referenced will be rewritten so that they are fully-qualified and relative to the current directory. All rewritten dependencies are suitable for use as keys to |targets| or a similar dict. """ all_dependency_sections = [dep + op for dep in dependency_sections for op in ('', '!', '/')] for target, target_dict in targets.iteritems(): target_build_file = gyp.common.BuildFile(target) toolset = target_dict['toolset'] for dependency_key in all_dependency_sections: dependencies = target_dict.get(dependency_key, []) for index in xrange(0, len(dependencies)): dep_file, dep_target, dep_toolset = gyp.common.ResolveTarget( target_build_file, dependencies[index], toolset) if not multiple_toolsets: # Ignore toolset specification in the dependency if it is specified. dep_toolset = toolset dependency = gyp.common.QualifiedTarget(dep_file, dep_target, dep_toolset) dependencies[index] = dependency # Make sure anything appearing in a list other than "dependencies" also # appears in the "dependencies" list. if dependency_key != 'dependencies' and \ dependency not in target_dict['dependencies']: raise GypError('Found ' + dependency + ' in ' + dependency_key + ' of ' + target + ', but not in dependencies') def ExpandWildcardDependencies(targets, data): """Expands dependencies specified as build_file:*. For each target in |targets|, examines sections containing links to other targets. If any such section contains a link of the form build_file:*, it is taken as a wildcard link, and is expanded to list each target in build_file. The |data| dict provides access to build file dicts. Any target that does not wish to be included by wildcard can provide an optional "suppress_wildcard" key in its target dict. When present and true, a wildcard dependency link will not include such targets. All dependency names, including the keys to |targets| and the values in each dependency list, must be qualified when this function is called. """ for target, target_dict in targets.iteritems(): toolset = target_dict['toolset'] target_build_file = gyp.common.BuildFile(target) for dependency_key in dependency_sections: dependencies = target_dict.get(dependency_key, []) # Loop this way instead of "for dependency in" or "for index in xrange" # because the dependencies list will be modified within the loop body. index = 0 while index < len(dependencies): (dependency_build_file, dependency_target, dependency_toolset) = \ gyp.common.ParseQualifiedTarget(dependencies[index]) if dependency_target != '*' and dependency_toolset != '*': # Not a wildcard. Keep it moving. index = index + 1 continue if dependency_build_file == target_build_file: # It's an error for a target to depend on all other targets in # the same file, because a target cannot depend on itself. raise GypError('Found wildcard in ' + dependency_key + ' of ' + target + ' referring to same build file') # Take the wildcard out and adjust the index so that the next # dependency in the list will be processed the next time through the # loop. del dependencies[index] index = index - 1 # Loop through the targets in the other build file, adding them to # this target's list of dependencies in place of the removed # wildcard. dependency_target_dicts = data[dependency_build_file]['targets'] for dependency_target_dict in dependency_target_dicts: if int(dependency_target_dict.get('suppress_wildcard', False)): continue dependency_target_name = dependency_target_dict['target_name'] if (dependency_target != '*' and dependency_target != dependency_target_name): continue dependency_target_toolset = dependency_target_dict['toolset'] if (dependency_toolset != '*' and dependency_toolset != dependency_target_toolset): continue dependency = gyp.common.QualifiedTarget(dependency_build_file, dependency_target_name, dependency_target_toolset) index = index + 1 dependencies.insert(index, dependency) index = index + 1 def Unify(l): """Removes duplicate elements from l, keeping the first element.""" seen = {} return [seen.setdefault(e, e) for e in l if e not in seen] def RemoveDuplicateDependencies(targets): """Makes sure every dependency appears only once in all targets's dependency lists.""" for target_name, target_dict in targets.iteritems(): for dependency_key in dependency_sections: dependencies = target_dict.get(dependency_key, []) if dependencies: target_dict[dependency_key] = Unify(dependencies) def Filter(l, item): """Removes item from l.""" res = {} return [res.setdefault(e, e) for e in l if e != item] def RemoveSelfDependencies(targets): """Remove self dependencies from targets that have the prune_self_dependency variable set.""" for target_name, target_dict in targets.iteritems(): for dependency_key in dependency_sections: dependencies = target_dict.get(dependency_key, []) if dependencies: for t in dependencies: if t == target_name: if targets[t].get('variables', {}).get('prune_self_dependency', 0): target_dict[dependency_key] = Filter(dependencies, target_name) def RemoveLinkDependenciesFromNoneTargets(targets): """Remove dependencies having the 'link_dependency' attribute from the 'none' targets.""" for target_name, target_dict in targets.iteritems(): for dependency_key in dependency_sections: dependencies = target_dict.get(dependency_key, []) if dependencies: for t in dependencies: if target_dict.get('type', None) == 'none': if targets[t].get('variables', {}).get('link_dependency', 0): target_dict[dependency_key] = \ Filter(target_dict[dependency_key], t) class DependencyGraphNode(object): """ Attributes: ref: A reference to an object that this DependencyGraphNode represents. dependencies: List of DependencyGraphNodes on which this one depends. dependents: List of DependencyGraphNodes that depend on this one. """ class CircularException(GypError): pass def __init__(self, ref): self.ref = ref self.dependencies = [] self.dependents = [] def __repr__(self): return '<DependencyGraphNode: %r>' % self.ref def FlattenToList(self): # flat_list is the sorted list of dependencies - actually, the list items # are the "ref" attributes of DependencyGraphNodes. Every target will # appear in flat_list after all of its dependencies, and before all of its # dependents. flat_list = OrderedSet() # in_degree_zeros is the list of DependencyGraphNodes that have no # dependencies not in flat_list. Initially, it is a copy of the children # of this node, because when the graph was built, nodes with no # dependencies were made implicit dependents of the root node. in_degree_zeros = set(self.dependents[:]) while in_degree_zeros: # Nodes in in_degree_zeros have no dependencies not in flat_list, so they # can be appended to flat_list. Take these nodes out of in_degree_zeros # as work progresses, so that the next node to process from the list can # always be accessed at a consistent position. node = in_degree_zeros.pop() flat_list.add(node.ref) # Look at dependents of the node just added to flat_list. Some of them # may now belong in in_degree_zeros. for node_dependent in node.dependents: is_in_degree_zero = True # TODO: We want to check through the # node_dependent.dependencies list but if it's long and we # always start at the beginning, then we get O(n^2) behaviour. for node_dependent_dependency in node_dependent.dependencies: if not node_dependent_dependency.ref in flat_list: # The dependent one or more dependencies not in flat_list. There # will be more chances to add it to flat_list when examining # it again as a dependent of those other dependencies, provided # that there are no cycles. is_in_degree_zero = False break if is_in_degree_zero: # All of the dependent's dependencies are already in flat_list. Add # it to in_degree_zeros where it will be processed in a future # iteration of the outer loop. in_degree_zeros.add(node_dependent) return list(flat_list) def FindCycles(self): """ Returns a list of cycles in the graph, where each cycle is its own list. """ results = [] visited = set() def Visit(node, path): for child in node.dependents: if child in path: results.append([child] + path[:path.index(child) + 1]) elif not child in visited: visited.add(child) Visit(child, [child] + path) visited.add(self) Visit(self, [self]) return results def DirectDependencies(self, dependencies=None): """Returns a list of just direct dependencies.""" if dependencies == None: dependencies = [] for dependency in self.dependencies: # Check for None, corresponding to the root node. if dependency.ref != None and dependency.ref not in dependencies: dependencies.append(dependency.ref) return dependencies def _AddImportedDependencies(self, targets, dependencies=None): """Given a list of direct dependencies, adds indirect dependencies that other dependencies have declared to export their settings. This method does not operate on self. Rather, it operates on the list of dependencies in the |dependencies| argument. For each dependency in that list, if any declares that it exports the settings of one of its own dependencies, those dependencies whose settings are "passed through" are added to the list. As new items are added to the list, they too will be processed, so it is possible to import settings through multiple levels of dependencies. This method is not terribly useful on its own, it depends on being "primed" with a list of direct dependencies such as one provided by DirectDependencies. DirectAndImportedDependencies is intended to be the public entry point. """ if dependencies == None: dependencies = [] index = 0 while index < len(dependencies): dependency = dependencies[index] dependency_dict = targets[dependency] # Add any dependencies whose settings should be imported to the list # if not already present. Newly-added items will be checked for # their own imports when the list iteration reaches them. # Rather than simply appending new items, insert them after the # dependency that exported them. This is done to more closely match # the depth-first method used by DeepDependencies. add_index = 1 for imported_dependency in \ dependency_dict.get('export_dependent_settings', []): if imported_dependency not in dependencies: dependencies.insert(index + add_index, imported_dependency) add_index = add_index + 1 index = index + 1 return dependencies def DirectAndImportedDependencies(self, targets, dependencies=None): """Returns a list of a target's direct dependencies and all indirect dependencies that a dependency has advertised settings should be exported through the dependency for. """ dependencies = self.DirectDependencies(dependencies) return self._AddImportedDependencies(targets, dependencies) def DeepDependencies(self, dependencies=None): """Returns an OrderedSet of all of a target's dependencies, recursively.""" if dependencies is None: # Using a list to get ordered output and a set to do fast "is it # already added" checks. dependencies = OrderedSet() for dependency in self.dependencies: # Check for None, corresponding to the root node. if dependency.ref is None: continue if dependency.ref not in dependencies: dependency.DeepDependencies(dependencies) dependencies.add(dependency.ref) return dependencies def _LinkDependenciesInternal(self, targets, include_shared_libraries, dependencies=None, initial=True): """Returns an OrderedSet of dependency targets that are linked into this target. This function has a split personality, depending on the setting of |initial|. Outside callers should always leave |initial| at its default setting. When adding a target to the list of dependencies, this function will recurse into itself with |initial| set to False, to collect dependencies that are linked into the linkable target for which the list is being built. If |include_shared_libraries| is False, the resulting dependencies will not include shared_library targets that are linked into this target. """ if dependencies is None: # Using a list to get ordered output and a set to do fast "is it # already added" checks. dependencies = OrderedSet() # Check for None, corresponding to the root node. if self.ref is None: return dependencies # It's kind of sucky that |targets| has to be passed into this function, # but that's presently the easiest way to access the target dicts so that # this function can find target types. if 'target_name' not in targets[self.ref]: raise GypError("Missing 'target_name' field in target.") if 'type' not in targets[self.ref]: raise GypError("Missing 'type' field in target %s" % targets[self.ref]['target_name']) target_type = targets[self.ref]['type'] is_linkable = target_type in linkable_types if initial and not is_linkable: # If this is the first target being examined and it's not linkable, # return an empty list of link dependencies, because the link # dependencies are intended to apply to the target itself (initial is # True) and this target won't be linked. return dependencies # Don't traverse 'none' targets if explicitly excluded. if (target_type == 'none' and not targets[self.ref].get('dependencies_traverse', True)): dependencies.add(self.ref) return dependencies # Executables, mac kernel extensions and loadable modules are already fully # and finally linked. Nothing else can be a link dependency of them, there # can only be dependencies in the sense that a dependent target might run # an executable or load the loadable_module. if not initial and target_type in ('executable', 'loadable_module', 'mac_kernel_extension'): return dependencies # Shared libraries are already fully linked. They should only be included # in |dependencies| when adjusting static library dependencies (in order to # link against the shared_library's import lib), but should not be included # in |dependencies| when propagating link_settings. # The |include_shared_libraries| flag controls which of these two cases we # are handling. if (not initial and target_type == 'shared_library' and not include_shared_libraries): return dependencies # The target is linkable, add it to the list of link dependencies. if self.ref not in dependencies: dependencies.add(self.ref) if initial or not is_linkable: # If this is a subsequent target and it's linkable, don't look any # further for linkable dependencies, as they'll already be linked into # this target linkable. Always look at dependencies of the initial # target, and always look at dependencies of non-linkables. for dependency in self.dependencies: dependency._LinkDependenciesInternal(targets, include_shared_libraries, dependencies, False) return dependencies def DependenciesForLinkSettings(self, targets): """ Returns a list of dependency targets whose link_settings should be merged into this target. """ # TODO(sbaig) Currently, chrome depends on the bug that shared libraries' # link_settings are propagated. So for now, we will allow it, unless the # 'allow_sharedlib_linksettings_propagation' flag is explicitly set to # False. Once chrome is fixed, we can remove this flag. include_shared_libraries = \ targets[self.ref].get('allow_sharedlib_linksettings_propagation', True) return self._LinkDependenciesInternal(targets, include_shared_libraries) def DependenciesToLinkAgainst(self, targets): """ Returns a list of dependency targets that are linked into this target. """ return self._LinkDependenciesInternal(targets, True) def BuildDependencyList(targets): # Create a DependencyGraphNode for each target. Put it into a dict for easy # access. dependency_nodes = {} for target, spec in targets.iteritems(): if target not in dependency_nodes: dependency_nodes[target] = DependencyGraphNode(target) # Set up the dependency links. Targets that have no dependencies are treated # as dependent on root_node. root_node = DependencyGraphNode(None) for target, spec in targets.iteritems(): target_node = dependency_nodes[target] target_build_file = gyp.common.BuildFile(target) dependencies = spec.get('dependencies') if not dependencies: target_node.dependencies = [root_node] root_node.dependents.append(target_node) else: for dependency in dependencies: dependency_node = dependency_nodes.get(dependency) if not dependency_node: raise GypError("Dependency '%s' not found while " "trying to load target %s" % (dependency, target)) target_node.dependencies.append(dependency_node) dependency_node.dependents.append(target_node) flat_list = root_node.FlattenToList() # If there's anything left unvisited, there must be a circular dependency # (cycle). if len(flat_list) != len(targets): if not root_node.dependents: # If all targets have dependencies, add the first target as a dependent # of root_node so that the cycle can be discovered from root_node. target = targets.keys()[0] target_node = dependency_nodes[target] target_node.dependencies.append(root_node) root_node.dependents.append(target_node) cycles = [] for cycle in root_node.FindCycles(): paths = [node.ref for node in cycle] cycles.append('Cycle: %s' % ' -> '.join(paths)) raise DependencyGraphNode.CircularException( 'Cycles in dependency graph detected:\n' + '\n'.join(cycles)) return [dependency_nodes, flat_list] def VerifyNoGYPFileCircularDependencies(targets): # Create a DependencyGraphNode for each gyp file containing a target. Put # it into a dict for easy access. dependency_nodes = {} for target in targets.iterkeys(): build_file = gyp.common.BuildFile(target) if not build_file in dependency_nodes: dependency_nodes[build_file] = DependencyGraphNode(build_file) # Set up the dependency links. for target, spec in targets.iteritems(): build_file = gyp.common.BuildFile(target) build_file_node = dependency_nodes[build_file] target_dependencies = spec.get('dependencies', []) for dependency in target_dependencies: try: dependency_build_file = gyp.common.BuildFile(dependency) except GypError, e: gyp.common.ExceptionAppend( e, 'while computing dependencies of .gyp file %s' % build_file) raise if dependency_build_file == build_file: # A .gyp file is allowed to refer back to itself. continue dependency_node = dependency_nodes.get(dependency_build_file) if not dependency_node: raise GypError("Dependancy '%s' not found" % dependency_build_file) if dependency_node not in build_file_node.dependencies: build_file_node.dependencies.append(dependency_node) dependency_node.dependents.append(build_file_node) # Files that have no dependencies are treated as dependent on root_node. root_node = DependencyGraphNode(None) for build_file_node in dependency_nodes.itervalues(): if len(build_file_node.dependencies) == 0: build_file_node.dependencies.append(root_node) root_node.dependents.append(build_file_node) flat_list = root_node.FlattenToList() # If there's anything left unvisited, there must be a circular dependency # (cycle). if len(flat_list) != len(dependency_nodes): if not root_node.dependents: # If all files have dependencies, add the first file as a dependent # of root_node so that the cycle can be discovered from root_node. file_node = dependency_nodes.values()[0] file_node.dependencies.append(root_node) root_node.dependents.append(file_node) cycles = [] for cycle in root_node.FindCycles(): paths = [node.ref for node in cycle] cycles.append('Cycle: %s' % ' -> '.join(paths)) raise DependencyGraphNode.CircularException( 'Cycles in .gyp file dependency graph detected:\n' + '\n'.join(cycles)) def DoDependentSettings(key, flat_list, targets, dependency_nodes): # key should be one of all_dependent_settings, direct_dependent_settings, # or link_settings. for target in flat_list: target_dict = targets[target] build_file = gyp.common.BuildFile(target) if key == 'all_dependent_settings': dependencies = dependency_nodes[target].DeepDependencies() elif key == 'direct_dependent_settings': dependencies = \ dependency_nodes[target].DirectAndImportedDependencies(targets) elif key == 'link_settings': dependencies = \ dependency_nodes[target].DependenciesForLinkSettings(targets) else: raise GypError("DoDependentSettings doesn't know how to determine " 'dependencies for ' + key) for dependency in dependencies: dependency_dict = targets[dependency] if not key in dependency_dict: continue dependency_build_file = gyp.common.BuildFile(dependency) MergeDicts(target_dict, dependency_dict[key], build_file, dependency_build_file) def AdjustStaticLibraryDependencies(flat_list, targets, dependency_nodes, sort_dependencies): # Recompute target "dependencies" properties. For each static library # target, remove "dependencies" entries referring to other static libraries, # unless the dependency has the "hard_dependency" attribute set. For each # linkable target, add a "dependencies" entry referring to all of the # target's computed list of link dependencies (including static libraries # if no such entry is already present. for target in flat_list: target_dict = targets[target] target_type = target_dict['type'] if target_type == 'static_library': if not 'dependencies' in target_dict: continue target_dict['dependencies_original'] = target_dict.get( 'dependencies', [])[:] # A static library should not depend on another static library unless # the dependency relationship is "hard," which should only be done when # a dependent relies on some side effect other than just the build # product, like a rule or action output. Further, if a target has a # non-hard dependency, but that dependency exports a hard dependency, # the non-hard dependency can safely be removed, but the exported hard # dependency must be added to the target to keep the same dependency # ordering. dependencies = \ dependency_nodes[target].DirectAndImportedDependencies(targets) index = 0 while index < len(dependencies): dependency = dependencies[index] dependency_dict = targets[dependency] # Remove every non-hard static library dependency and remove every # non-static library dependency that isn't a direct dependency. if (dependency_dict['type'] == 'static_library' and \ not dependency_dict.get('hard_dependency', False)) or \ (dependency_dict['type'] != 'static_library' and \ not dependency in target_dict['dependencies']): # Take the dependency out of the list, and don't increment index # because the next dependency to analyze will shift into the index # formerly occupied by the one being removed. del dependencies[index] else: index = index + 1 # Update the dependencies. If the dependencies list is empty, it's not # needed, so unhook it. if len(dependencies) > 0: target_dict['dependencies'] = dependencies else: del target_dict['dependencies'] elif target_type in linkable_types: # Get a list of dependency targets that should be linked into this # target. Add them to the dependencies list if they're not already # present. link_dependencies = \ dependency_nodes[target].DependenciesToLinkAgainst(targets) for dependency in link_dependencies: if dependency == target: continue if not 'dependencies' in target_dict: target_dict['dependencies'] = [] if not dependency in target_dict['dependencies']: target_dict['dependencies'].append(dependency) # Sort the dependencies list in the order from dependents to dependencies. # e.g. If A and B depend on C and C depends on D, sort them in A, B, C, D. # Note: flat_list is already sorted in the order from dependencies to # dependents. if sort_dependencies and 'dependencies' in target_dict: target_dict['dependencies'] = [dep for dep in reversed(flat_list) if dep in target_dict['dependencies']] # Initialize this here to speed up MakePathRelative. exception_re = re.compile(r'''["']?[-/$<>^]''') def MakePathRelative(to_file, fro_file, item): # If item is a relative path, it's relative to the build file dict that it's # coming from. Fix it up to make it relative to the build file dict that # it's going into. # Exception: any |item| that begins with these special characters is # returned without modification. # / Used when a path is already absolute (shortcut optimization; # such paths would be returned as absolute anyway) # $ Used for build environment variables # - Used for some build environment flags (such as -lapr-1 in a # "libraries" section) # < Used for our own variable and command expansions (see ExpandVariables) # > Used for our own variable and command expansions (see ExpandVariables) # ^ Used for our own variable and command expansions (see ExpandVariables) # # "/' Used when a value is quoted. If these are present, then we # check the second character instead. # if to_file == fro_file or exception_re.match(item): return item else: # TODO(dglazkov) The backslash/forward-slash replacement at the end is a # temporary measure. This should really be addressed by keeping all paths # in POSIX until actual project generation. ret = os.path.normpath(os.path.join( gyp.common.RelativePath(os.path.dirname(fro_file), os.path.dirname(to_file)), item)).replace('\\', '/') if item[-1] == '/': ret += '/' return ret def MergeLists(to, fro, to_file, fro_file, is_paths=False, append=True): # Python documentation recommends objects which do not support hash # set this value to None. Python library objects follow this rule. is_hashable = lambda val: val.__hash__ # If x is hashable, returns whether x is in s. Else returns whether x is in l. def is_in_set_or_list(x, s, l): if is_hashable(x): return x in s return x in l prepend_index = 0 # Make membership testing of hashables in |to| (in particular, strings) # faster. hashable_to_set = set(x for x in to if is_hashable(x)) for item in fro: singleton = False if type(item) in (str, int): # The cheap and easy case. if is_paths: to_item = MakePathRelative(to_file, fro_file, item) else: to_item = item if not (type(item) is str and item.startswith('-')): # Any string that doesn't begin with a "-" is a singleton - it can # only appear once in a list, to be enforced by the list merge append # or prepend. singleton = True elif type(item) is dict: # Make a copy of the dictionary, continuing to look for paths to fix. # The other intelligent aspects of merge processing won't apply because # item is being merged into an empty dict. to_item = {} MergeDicts(to_item, item, to_file, fro_file) elif type(item) is list: # Recurse, making a copy of the list. If the list contains any # descendant dicts, path fixing will occur. Note that here, custom # values for is_paths and append are dropped; those are only to be # applied to |to| and |fro|, not sublists of |fro|. append shouldn't # matter anyway because the new |to_item| list is empty. to_item = [] MergeLists(to_item, item, to_file, fro_file) else: raise TypeError( 'Attempt to merge list item of unsupported type ' + \ item.__class__.__name__) if append: # If appending a singleton that's already in the list, don't append. # This ensures that the earliest occurrence of the item will stay put. if not singleton or not is_in_set_or_list(to_item, hashable_to_set, to): to.append(to_item) if is_hashable(to_item): hashable_to_set.add(to_item) else: # If prepending a singleton that's already in the list, remove the # existing instance and proceed with the prepend. This ensures that the # item appears at the earliest possible position in the list. while singleton and to_item in to: to.remove(to_item) # Don't just insert everything at index 0. That would prepend the new # items to the list in reverse order, which would be an unwelcome # surprise. to.insert(prepend_index, to_item) if is_hashable(to_item): hashable_to_set.add(to_item) prepend_index = prepend_index + 1 def MergeDicts(to, fro, to_file, fro_file): # I wanted to name the parameter "from" but it's a Python keyword... for k, v in fro.iteritems(): # It would be nice to do "if not k in to: to[k] = v" but that wouldn't give # copy semantics. Something else may want to merge from the |fro| dict # later, and having the same dict ref pointed to twice in the tree isn't # what anyone wants considering that the dicts may subsequently be # modified. if k in to: bad_merge = False if type(v) in (str, int): if type(to[k]) not in (str, int): bad_merge = True elif type(v) is not type(to[k]): bad_merge = True if bad_merge: raise TypeError( 'Attempt to merge dict value of type ' + v.__class__.__name__ + \ ' into incompatible type ' + to[k].__class__.__name__ + \ ' for key ' + k) if type(v) in (str, int): # Overwrite the existing value, if any. Cheap and easy. is_path = IsPathSection(k) if is_path: to[k] = MakePathRelative(to_file, fro_file, v) else: to[k] = v elif type(v) is dict: # Recurse, guaranteeing copies will be made of objects that require it. if not k in to: to[k] = {} MergeDicts(to[k], v, to_file, fro_file) elif type(v) is list: # Lists in dicts can be merged with different policies, depending on # how the key in the "from" dict (k, the from-key) is written. # # If the from-key has ...the to-list will have this action # this character appended:... applied when receiving the from-list: # = replace # + prepend # ? set, only if to-list does not yet exist # (none) append # # This logic is list-specific, but since it relies on the associated # dict key, it's checked in this dict-oriented function. ext = k[-1] append = True if ext == '=': list_base = k[:-1] lists_incompatible = [list_base, list_base + '?'] to[list_base] = [] elif ext == '+': list_base = k[:-1] lists_incompatible = [list_base + '=', list_base + '?'] append = False elif ext == '?': list_base = k[:-1] lists_incompatible = [list_base, list_base + '=', list_base + '+'] else: list_base = k lists_incompatible = [list_base + '=', list_base + '?'] # Some combinations of merge policies appearing together are meaningless. # It's stupid to replace and append simultaneously, for example. Append # and prepend are the only policies that can coexist. for list_incompatible in lists_incompatible: if list_incompatible in fro: raise GypError('Incompatible list policies ' + k + ' and ' + list_incompatible) if list_base in to: if ext == '?': # If the key ends in "?", the list will only be merged if it doesn't # already exist. continue elif type(to[list_base]) is not list: # This may not have been checked above if merging in a list with an # extension character. raise TypeError( 'Attempt to merge dict value of type ' + v.__class__.__name__ + \ ' into incompatible type ' + to[list_base].__class__.__name__ + \ ' for key ' + list_base + '(' + k + ')') else: to[list_base] = [] # Call MergeLists, which will make copies of objects that require it. # MergeLists can recurse back into MergeDicts, although this will be # to make copies of dicts (with paths fixed), there will be no # subsequent dict "merging" once entering a list because lists are # always replaced, appended to, or prepended to. is_paths = IsPathSection(list_base) MergeLists(to[list_base], v, to_file, fro_file, is_paths, append) else: raise TypeError( 'Attempt to merge dict value of unsupported type ' + \ v.__class__.__name__ + ' for key ' + k) def MergeConfigWithInheritance(new_configuration_dict, build_file, target_dict, configuration, visited): # Skip if previously visted. if configuration in visited: return # Look at this configuration. configuration_dict = target_dict['configurations'][configuration] # Merge in parents. for parent in configuration_dict.get('inherit_from', []): MergeConfigWithInheritance(new_configuration_dict, build_file, target_dict, parent, visited + [configuration]) # Merge it into the new config. MergeDicts(new_configuration_dict, configuration_dict, build_file, build_file) # Drop abstract. if 'abstract' in new_configuration_dict: del new_configuration_dict['abstract'] def SetUpConfigurations(target, target_dict): # key_suffixes is a list of key suffixes that might appear on key names. # These suffixes are handled in conditional evaluations (for =, +, and ?) # and rules/exclude processing (for ! and /). Keys with these suffixes # should be treated the same as keys without. key_suffixes = ['=', '+', '?', '!', '/'] build_file = gyp.common.BuildFile(target) # Provide a single configuration by default if none exists. # TODO(mark): Signal an error if default_configurations exists but # configurations does not. if not 'configurations' in target_dict: target_dict['configurations'] = {'Default': {}} if not 'default_configuration' in target_dict: concrete = [i for (i, config) in target_dict['configurations'].iteritems() if not config.get('abstract')] target_dict['default_configuration'] = sorted(concrete)[0] merged_configurations = {} configs = target_dict['configurations'] for (configuration, old_configuration_dict) in configs.iteritems(): # Skip abstract configurations (saves work only). if old_configuration_dict.get('abstract'): continue # Configurations inherit (most) settings from the enclosing target scope. # Get the inheritance relationship right by making a copy of the target # dict. new_configuration_dict = {} for (key, target_val) in target_dict.iteritems(): key_ext = key[-1:] if key_ext in key_suffixes: key_base = key[:-1] else: key_base = key if not key_base in non_configuration_keys: new_configuration_dict[key] = gyp.simple_copy.deepcopy(target_val) # Merge in configuration (with all its parents first). MergeConfigWithInheritance(new_configuration_dict, build_file, target_dict, configuration, []) merged_configurations[configuration] = new_configuration_dict # Put the new configurations back into the target dict as a configuration. for configuration in merged_configurations.keys(): target_dict['configurations'][configuration] = ( merged_configurations[configuration]) # Now drop all the abstract ones. for configuration in target_dict['configurations'].keys(): old_configuration_dict = target_dict['configurations'][configuration] if old_configuration_dict.get('abstract'): del target_dict['configurations'][configuration] # Now that all of the target's configurations have been built, go through # the target dict's keys and remove everything that's been moved into a # "configurations" section. delete_keys = [] for key in target_dict: key_ext = key[-1:] if key_ext in key_suffixes: key_base = key[:-1] else: key_base = key if not key_base in non_configuration_keys: delete_keys.append(key) for key in delete_keys: del target_dict[key] # Check the configurations to see if they contain invalid keys. for configuration in target_dict['configurations'].keys(): configuration_dict = target_dict['configurations'][configuration] for key in configuration_dict.keys(): if key in invalid_configuration_keys: raise GypError('%s not allowed in the %s configuration, found in ' 'target %s' % (key, configuration, target)) def ProcessListFiltersInDict(name, the_dict): """Process regular expression and exclusion-based filters on lists. An exclusion list is in a dict key named with a trailing "!", like "sources!". Every item in such a list is removed from the associated main list, which in this example, would be "sources". Removed items are placed into a "sources_excluded" list in the dict. Regular expression (regex) filters are contained in dict keys named with a trailing "/", such as "sources/" to operate on the "sources" list. Regex filters in a dict take the form: 'sources/': [ ['exclude', '_(linux|mac|win)\\.cc$'], ['include', '_mac\\.cc$'] ], The first filter says to exclude all files ending in _linux.cc, _mac.cc, and _win.cc. The second filter then includes all files ending in _mac.cc that are now or were once in the "sources" list. Items matching an "exclude" filter are subject to the same processing as would occur if they were listed by name in an exclusion list (ending in "!"). Items matching an "include" filter are brought back into the main list if previously excluded by an exclusion list or exclusion regex filter. Subsequent matching "exclude" patterns can still cause items to be excluded after matching an "include". """ # Look through the dictionary for any lists whose keys end in "!" or "/". # These are lists that will be treated as exclude lists and regular # expression-based exclude/include lists. Collect the lists that are # needed first, looking for the lists that they operate on, and assemble # then into |lists|. This is done in a separate loop up front, because # the _included and _excluded keys need to be added to the_dict, and that # can't be done while iterating through it. lists = [] del_lists = [] for key, value in the_dict.iteritems(): operation = key[-1] if operation != '!' and operation != '/': continue if type(value) is not list: raise ValueError(name + ' key ' + key + ' must be list, not ' + \ value.__class__.__name__) list_key = key[:-1] if list_key not in the_dict: # This happens when there's a list like "sources!" but no corresponding # "sources" list. Since there's nothing for it to operate on, queue up # the "sources!" list for deletion now. del_lists.append(key) continue if type(the_dict[list_key]) is not list: value = the_dict[list_key] raise ValueError(name + ' key ' + list_key + \ ' must be list, not ' + \ value.__class__.__name__ + ' when applying ' + \ {'!': 'exclusion', '/': 'regex'}[operation]) if not list_key in lists: lists.append(list_key) # Delete the lists that are known to be unneeded at this point. for del_list in del_lists: del the_dict[del_list] for list_key in lists: the_list = the_dict[list_key] # Initialize the list_actions list, which is parallel to the_list. Each # item in list_actions identifies whether the corresponding item in # the_list should be excluded, unconditionally preserved (included), or # whether no exclusion or inclusion has been applied. Items for which # no exclusion or inclusion has been applied (yet) have value -1, items # excluded have value 0, and items included have value 1. Includes and # excludes override previous actions. All items in list_actions are # initialized to -1 because no excludes or includes have been processed # yet. list_actions = list((-1,) * len(the_list)) exclude_key = list_key + '!' if exclude_key in the_dict: for exclude_item in the_dict[exclude_key]: for index in xrange(0, len(the_list)): if exclude_item == the_list[index]: # This item matches the exclude_item, so set its action to 0 # (exclude). list_actions[index] = 0 # The "whatever!" list is no longer needed, dump it. del the_dict[exclude_key] regex_key = list_key + '/' if regex_key in the_dict: for regex_item in the_dict[regex_key]: [action, pattern] = regex_item pattern_re = re.compile(pattern) if action == 'exclude': # This item matches an exclude regex, so set its value to 0 (exclude). action_value = 0 elif action == 'include': # This item matches an include regex, so set its value to 1 (include). action_value = 1 else: # This is an action that doesn't make any sense. raise ValueError('Unrecognized action ' + action + ' in ' + name + \ ' key ' + regex_key) for index in xrange(0, len(the_list)): list_item = the_list[index] if list_actions[index] == action_value: # Even if the regex matches, nothing will change so continue (regex # searches are expensive). continue if pattern_re.search(list_item): # Regular expression match. list_actions[index] = action_value # The "whatever/" list is no longer needed, dump it. del the_dict[regex_key] # Add excluded items to the excluded list. # # Note that exclude_key ("sources!") is different from excluded_key # ("sources_excluded"). The exclude_key list is input and it was already # processed and deleted; the excluded_key list is output and it's about # to be created. excluded_key = list_key + '_excluded' if excluded_key in the_dict: raise GypError(name + ' key ' + excluded_key + ' must not be present prior ' ' to applying exclusion/regex filters for ' + list_key) excluded_list = [] # Go backwards through the list_actions list so that as items are deleted, # the indices of items that haven't been seen yet don't shift. That means # that things need to be prepended to excluded_list to maintain them in the # same order that they existed in the_list. for index in xrange(len(list_actions) - 1, -1, -1): if list_actions[index] == 0: # Dump anything with action 0 (exclude). Keep anything with action 1 # (include) or -1 (no include or exclude seen for the item). excluded_list.insert(0, the_list[index]) del the_list[index] # If anything was excluded, put the excluded list into the_dict at # excluded_key. if len(excluded_list) > 0: the_dict[excluded_key] = excluded_list # Now recurse into subdicts and lists that may contain dicts. for key, value in the_dict.iteritems(): if type(value) is dict: ProcessListFiltersInDict(key, value) elif type(value) is list: ProcessListFiltersInList(key, value) def ProcessListFiltersInList(name, the_list): for item in the_list: if type(item) is dict: ProcessListFiltersInDict(name, item) elif type(item) is list: ProcessListFiltersInList(name, item) def ValidateTargetType(target, target_dict): """Ensures the 'type' field on the target is one of the known types. Arguments: target: string, name of target. target_dict: dict, target spec. Raises an exception on error. """ VALID_TARGET_TYPES = ('executable', 'loadable_module', 'static_library', 'shared_library', 'mac_kernel_extension', 'none') target_type = target_dict.get('type', None) if target_type not in VALID_TARGET_TYPES: raise GypError("Target %s has an invalid target type '%s'. " "Must be one of %s." % (target, target_type, '/'.join(VALID_TARGET_TYPES))) if (target_dict.get('standalone_static_library', 0) and not target_type == 'static_library'): raise GypError('Target %s has type %s but standalone_static_library flag is' ' only valid for static_library type.' % (target, target_type)) def ValidateSourcesInTarget(target, target_dict, build_file, duplicate_basename_check): if not duplicate_basename_check: return if target_dict.get('type', None) != 'static_library': return sources = target_dict.get('sources', []) basenames = {} for source in sources: name, ext = os.path.splitext(source) is_compiled_file = ext in [ '.c', '.cc', '.cpp', '.cxx', '.m', '.mm', '.s', '.S'] if not is_compiled_file: continue basename = os.path.basename(name) # Don't include extension. basenames.setdefault(basename, []).append(source) error = '' for basename, files in basenames.iteritems(): if len(files) > 1: error += ' %s: %s\n' % (basename, ' '.join(files)) if error: print('static library %s has several files with the same basename:\n' % target + error + 'libtool on Mac cannot handle that. Use ' '--no-duplicate-basename-check to disable this validation.') raise GypError('Duplicate basenames in sources section, see list above') def ValidateRulesInTarget(target, target_dict, extra_sources_for_rules): """Ensures that the rules sections in target_dict are valid and consistent, and determines which sources they apply to. Arguments: target: string, name of target. target_dict: dict, target spec containing "rules" and "sources" lists. extra_sources_for_rules: a list of keys to scan for rule matches in addition to 'sources'. """ # Dicts to map between values found in rules' 'rule_name' and 'extension' # keys and the rule dicts themselves. rule_names = {} rule_extensions = {} rules = target_dict.get('rules', []) for rule in rules: # Make sure that there's no conflict among rule names and extensions. rule_name = rule['rule_name'] if rule_name in rule_names: raise GypError('rule %s exists in duplicate, target %s' % (rule_name, target)) rule_names[rule_name] = rule rule_extension = rule['extension'] if rule_extension.startswith('.'): rule_extension = rule_extension[1:] if rule_extension in rule_extensions: raise GypError(('extension %s associated with multiple rules, ' + 'target %s rules %s and %s') % (rule_extension, target, rule_extensions[rule_extension]['rule_name'], rule_name)) rule_extensions[rule_extension] = rule # Make sure rule_sources isn't already there. It's going to be # created below if needed. if 'rule_sources' in rule: raise GypError( 'rule_sources must not exist in input, target %s rule %s' % (target, rule_name)) rule_sources = [] source_keys = ['sources'] source_keys.extend(extra_sources_for_rules) for source_key in source_keys: for source in target_dict.get(source_key, []): (source_root, source_extension) = os.path.splitext(source) if source_extension.startswith('.'): source_extension = source_extension[1:] if source_extension == rule_extension: rule_sources.append(source) if len(rule_sources) > 0: rule['rule_sources'] = rule_sources def ValidateRunAsInTarget(target, target_dict, build_file): target_name = target_dict.get('target_name') run_as = target_dict.get('run_as') if not run_as: return if type(run_as) is not dict: raise GypError("The 'run_as' in target %s from file %s should be a " "dictionary." % (target_name, build_file)) action = run_as.get('action') if not action: raise GypError("The 'run_as' in target %s from file %s must have an " "'action' section." % (target_name, build_file)) if type(action) is not list: raise GypError("The 'action' for 'run_as' in target %s from file %s " "must be a list." % (target_name, build_file)) working_directory = run_as.get('working_directory') if working_directory and type(working_directory) is not str: raise GypError("The 'working_directory' for 'run_as' in target %s " "in file %s should be a string." % (target_name, build_file)) environment = run_as.get('environment') if environment and type(environment) is not dict: raise GypError("The 'environment' for 'run_as' in target %s " "in file %s should be a dictionary." % (target_name, build_file)) def ValidateActionsInTarget(target, target_dict, build_file): '''Validates the inputs to the actions in a target.''' target_name = target_dict.get('target_name') actions = target_dict.get('actions', []) for action in actions: action_name = action.get('action_name') if not action_name: raise GypError("Anonymous action in target %s. " "An action must have an 'action_name' field." % target_name) inputs = action.get('inputs', None) if inputs is None: raise GypError('Action in target %s has no inputs.' % target_name) action_command = action.get('action') if action_command and not action_command[0]: raise GypError("Empty action as command in target %s." % target_name) def TurnIntIntoStrInDict(the_dict): """Given dict the_dict, recursively converts all integers into strings. """ # Use items instead of iteritems because there's no need to try to look at # reinserted keys and their associated values. for k, v in the_dict.items(): if type(v) is int: v = str(v) the_dict[k] = v elif type(v) is dict: TurnIntIntoStrInDict(v) elif type(v) is list: TurnIntIntoStrInList(v) if type(k) is int: del the_dict[k] the_dict[str(k)] = v def TurnIntIntoStrInList(the_list): """Given list the_list, recursively converts all integers into strings. """ for index in xrange(0, len(the_list)): item = the_list[index] if type(item) is int: the_list[index] = str(item) elif type(item) is dict: TurnIntIntoStrInDict(item) elif type(item) is list: TurnIntIntoStrInList(item) def PruneUnwantedTargets(targets, flat_list, dependency_nodes, root_targets, data): """Return only the targets that are deep dependencies of |root_targets|.""" qualified_root_targets = [] for target in root_targets: target = target.strip() qualified_targets = gyp.common.FindQualifiedTargets(target, flat_list) if not qualified_targets: raise GypError("Could not find target %s" % target) qualified_root_targets.extend(qualified_targets) wanted_targets = {} for target in qualified_root_targets: wanted_targets[target] = targets[target] for dependency in dependency_nodes[target].DeepDependencies(): wanted_targets[dependency] = targets[dependency] wanted_flat_list = [t for t in flat_list if t in wanted_targets] # Prune unwanted targets from each build_file's data dict. for build_file in data['target_build_files']: if not 'targets' in data[build_file]: continue new_targets = [] for target in data[build_file]['targets']: qualified_name = gyp.common.QualifiedTarget(build_file, target['target_name'], target['toolset']) if qualified_name in wanted_targets: new_targets.append(target) data[build_file]['targets'] = new_targets return wanted_targets, wanted_flat_list def VerifyNoCollidingTargets(targets): """Verify that no two targets in the same directory share the same name. Arguments: targets: A list of targets in the form 'path/to/file.gyp:target_name'. """ # Keep a dict going from 'subdirectory:target_name' to 'foo.gyp'. used = {} for target in targets: # Separate out 'path/to/file.gyp, 'target_name' from # 'path/to/file.gyp:target_name'. path, name = target.rsplit(':', 1) # Separate out 'path/to', 'file.gyp' from 'path/to/file.gyp'. subdir, gyp = os.path.split(path) # Use '.' for the current directory '', so that the error messages make # more sense. if not subdir: subdir = '.' # Prepare a key like 'path/to:target_name'. key = subdir + ':' + name if key in used: # Complain if this target is already used. raise GypError('Duplicate target name "%s" in directory "%s" used both ' 'in "%s" and "%s".' % (name, subdir, gyp, used[key])) used[key] = gyp def SetGeneratorGlobals(generator_input_info): # Set up path_sections and non_configuration_keys with the default data plus # the generator-specific data. global path_sections path_sections = set(base_path_sections) path_sections.update(generator_input_info['path_sections']) global non_configuration_keys non_configuration_keys = base_non_configuration_keys[:] non_configuration_keys.extend(generator_input_info['non_configuration_keys']) global multiple_toolsets multiple_toolsets = generator_input_info[ 'generator_supports_multiple_toolsets'] global generator_filelist_paths generator_filelist_paths = generator_input_info['generator_filelist_paths'] def Load(build_files, variables, includes, depth, generator_input_info, check, circular_check, duplicate_basename_check, parallel, root_targets): SetGeneratorGlobals(generator_input_info) # A generator can have other lists (in addition to sources) be processed # for rules. extra_sources_for_rules = generator_input_info['extra_sources_for_rules'] # Load build files. This loads every target-containing build file into # the |data| dictionary such that the keys to |data| are build file names, # and the values are the entire build file contents after "early" or "pre" # processing has been done and includes have been resolved. # NOTE: data contains both "target" files (.gyp) and "includes" (.gypi), as # well as meta-data (e.g. 'included_files' key). 'target_build_files' keeps # track of the keys corresponding to "target" files. data = {'target_build_files': set()} # Normalize paths everywhere. This is important because paths will be # used as keys to the data dict and for references between input files. build_files = set(map(os.path.normpath, build_files)) if parallel: LoadTargetBuildFilesParallel(build_files, data, variables, includes, depth, check, generator_input_info) else: aux_data = {} for build_file in build_files: try: LoadTargetBuildFile(build_file, data, aux_data, variables, includes, depth, check, True) except Exception, e: gyp.common.ExceptionAppend(e, 'while trying to load %s' % build_file) raise # Build a dict to access each target's subdict by qualified name. targets = BuildTargetsDict(data) # Fully qualify all dependency links. QualifyDependencies(targets) # Remove self-dependencies from targets that have 'prune_self_dependencies' # set to 1. RemoveSelfDependencies(targets) # Expand dependencies specified as build_file:*. ExpandWildcardDependencies(targets, data) # Remove all dependencies marked as 'link_dependency' from the targets of # type 'none'. RemoveLinkDependenciesFromNoneTargets(targets) # Apply exclude (!) and regex (/) list filters only for dependency_sections. for target_name, target_dict in targets.iteritems(): tmp_dict = {} for key_base in dependency_sections: for op in ('', '!', '/'): key = key_base + op if key in target_dict: tmp_dict[key] = target_dict[key] del target_dict[key] ProcessListFiltersInDict(target_name, tmp_dict) # Write the results back to |target_dict|. for key in tmp_dict: target_dict[key] = tmp_dict[key] # Make sure every dependency appears at most once. RemoveDuplicateDependencies(targets) if circular_check: # Make sure that any targets in a.gyp don't contain dependencies in other # .gyp files that further depend on a.gyp. VerifyNoGYPFileCircularDependencies(targets) [dependency_nodes, flat_list] = BuildDependencyList(targets) if root_targets: # Remove, from |targets| and |flat_list|, the targets that are not deep # dependencies of the targets specified in |root_targets|. targets, flat_list = PruneUnwantedTargets( targets, flat_list, dependency_nodes, root_targets, data) # Check that no two targets in the same directory have the same name. VerifyNoCollidingTargets(flat_list) # Handle dependent settings of various types. for settings_type in ['all_dependent_settings', 'direct_dependent_settings', 'link_settings']: DoDependentSettings(settings_type, flat_list, targets, dependency_nodes) # Take out the dependent settings now that they've been published to all # of the targets that require them. for target in flat_list: if settings_type in targets[target]: del targets[target][settings_type] # Make sure static libraries don't declare dependencies on other static # libraries, but that linkables depend on all unlinked static libraries # that they need so that their link steps will be correct. gii = generator_input_info if gii['generator_wants_static_library_dependencies_adjusted']: AdjustStaticLibraryDependencies(flat_list, targets, dependency_nodes, gii['generator_wants_sorted_dependencies']) # Apply "post"/"late"/"target" variable expansions and condition evaluations. for target in flat_list: target_dict = targets[target] build_file = gyp.common.BuildFile(target) ProcessVariablesAndConditionsInDict( target_dict, PHASE_LATE, variables, build_file) # Move everything that can go into a "configurations" section into one. for target in flat_list: target_dict = targets[target] SetUpConfigurations(target, target_dict) # Apply exclude (!) and regex (/) list filters. for target in flat_list: target_dict = targets[target] ProcessListFiltersInDict(target, target_dict) # Apply "latelate" variable expansions and condition evaluations. for target in flat_list: target_dict = targets[target] build_file = gyp.common.BuildFile(target) ProcessVariablesAndConditionsInDict( target_dict, PHASE_LATELATE, variables, build_file) # Make sure that the rules make sense, and build up rule_sources lists as # needed. Not all generators will need to use the rule_sources lists, but # some may, and it seems best to build the list in a common spot. # Also validate actions and run_as elements in targets. for target in flat_list: target_dict = targets[target] build_file = gyp.common.BuildFile(target) ValidateTargetType(target, target_dict) ValidateSourcesInTarget(target, target_dict, build_file, duplicate_basename_check) ValidateRulesInTarget(target, target_dict, extra_sources_for_rules) ValidateRunAsInTarget(target, target_dict, build_file) ValidateActionsInTarget(target, target_dict, build_file) # Generators might not expect ints. Turn them into strs. TurnIntIntoStrInDict(data) # TODO(mark): Return |data| for now because the generator needs a list of # build files that came in. In the future, maybe it should just accept # a list, and not the whole data dict. return [flat_list, targets, data]
gpl-3.0
dawnpower/nova
nova/tests/unit/objects/test_virt_cpu_topology.py
94
1397
# 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. from nova import objects from nova.tests.unit.objects import test_objects _top_dict = { 'sockets': 2, 'cores': 4, 'threads': 8 } class _TestVirtCPUTopologyObject(object): def test_object_from_dict(self): top_obj = objects.VirtCPUTopology.from_dict(_top_dict) self.compare_obj(top_obj, _top_dict) def test_object_to_dict(self): top_obj = objects.VirtCPUTopology() top_obj.sockets = 2 top_obj.cores = 4 top_obj.threads = 8 spec = top_obj.to_dict() self.assertEqual(_top_dict, spec) class TestVirtCPUTopologyObject(test_objects._LocalTest, _TestVirtCPUTopologyObject): pass class TestRemoteVirtCPUTopologyObject(test_objects._RemoteTest, _TestVirtCPUTopologyObject): pass
apache-2.0
FurCode/RoboCop
core/reload.py
8
5196
import collections import glob import os import re import sys import traceback if 'mtimes' not in globals(): mtimes = {} if 'lastfiles' not in globals(): lastfiles = set() def make_signature(f): return f.func_code.co_filename, f.func_name, f.func_code.co_firstlineno def format_plug(plug, kind='', lpad=0): out = ' ' * lpad + '{}:{}:{}'.format(*make_signature(plug[0])) if kind == 'command': out += ' ' * (50 - len(out)) + plug[1]['name'] if kind == 'event': out += ' ' * (50 - len(out)) + ', '.join(plug[1]['events']) if kind == 'regex': out += ' ' * (50 - len(out)) + plug[1]['regex'] return out def reload(init=False): changed = False if init: bot.plugs = collections.defaultdict(list) bot.threads = {} core_fileset = set(glob.glob(os.path.join("core", "*.py"))) for filename in core_fileset: mtime = os.stat(filename).st_mtime if mtime != mtimes.get(filename): mtimes[filename] = mtime changed = True try: eval(compile(open(filename, 'U').read(), filename, 'exec'), globals()) except Exception: traceback.print_exc() if init: # stop if there's an error (syntax?) in a core sys.exit() # script on startup continue if filename == os.path.join('core', 'reload.py'): reload(init=init) return fileset = set(glob.glob(os.path.join('plugins', '*.py'))) # remove deleted/moved plugins for name, data in bot.plugs.iteritems(): bot.plugs[name] = [x for x in data if x[0]._filename in fileset] for filename in list(mtimes): if filename not in fileset and filename not in core_fileset: mtimes.pop(filename) for func, handler in list(bot.threads.iteritems()): if func._filename not in fileset: handler.stop() del bot.threads[func] # compile new plugins for filename in fileset: mtime = os.stat(filename).st_mtime if mtime != mtimes.get(filename): mtimes[filename] = mtime changed = True try: code = compile(open(filename, 'U').read(), filename, 'exec') namespace = {} eval(code, namespace) except Exception: traceback.print_exc() continue # remove plugins already loaded from this filename for name, data in bot.plugs.iteritems(): bot.plugs[name] = [x for x in data if x[0]._filename != filename] for func, handler in list(bot.threads.iteritems()): if func._filename == filename: handler.stop() del bot.threads[func] for obj in namespace.itervalues(): if hasattr(obj, '_hook'): # check for magic if obj._thread: bot.threads[obj] = Handler(obj) for type, data in obj._hook: bot.plugs[type] += [data] if not init: print '### new plugin (type: %s) loaded:' % \ type, format_plug(data) if changed: bot.commands = {} for plug in bot.plugs['command']: name = plug[1]['name'].lower() if not re.match(r'^\w+$', name): print '### ERROR: invalid command name "{}" ({})'.format(name, format_plug(plug)) continue if name in bot.commands: print "### ERROR: command '{}' already registered ({}, {})".format(name, format_plug(bot.commands[name]), format_plug(plug)) continue bot.commands[name] = plug bot.events = collections.defaultdict(list) for func, args in bot.plugs['event']: for event in args['events']: bot.events[event].append((func, args)) if init: print ' plugin listing:' if bot.commands: # hack to make commands with multiple aliases # print nicely print ' command:' commands = collections.defaultdict(list) for name, (func, args) in bot.commands.iteritems(): commands[make_signature(func)].append(name) for sig, names in sorted(commands.iteritems()): names.sort(key=lambda x: (-len(x), x)) # long names first out = ' ' * 6 + '%s:%s:%s' % sig out += ' ' * (50 - len(out)) + ', '.join(names) print out for kind, plugs in sorted(bot.plugs.iteritems()): if kind == 'command': continue print ' {}:'.format(kind) for plug in plugs: print format_plug(plug, kind=kind, lpad=6) print
gpl-3.0
qzane/you-get
src/you_get/extractors/mgtv.py
2
5914
#!/usr/bin/env python # -*- coding: utf-8 -*- from ..common import * from ..extractor import VideoExtractor from json import loads from urllib.parse import urlsplit from os.path import dirname import re class MGTV(VideoExtractor): name = "芒果 (MGTV)" # Last updated: 2016-11-13 stream_types = [ {'id': 'hd', 'container': 'ts', 'video_profile': '超清'}, {'id': 'sd', 'container': 'ts', 'video_profile': '高清'}, {'id': 'ld', 'container': 'ts', 'video_profile': '标清'}, ] id_dic = {i['video_profile']:(i['id']) for i in stream_types} api_endpoint = 'http://pcweb.api.mgtv.com/player/video?video_id={video_id}' @staticmethod def get_vid_from_url(url): """Extracts video ID from URL. """ vid = match1(url, 'http://www.mgtv.com/b/\d+/(\d+).html') if not vid: vid = match1(url, 'http://www.mgtv.com/hz/bdpz/\d+/(\d+).html') return vid #---------------------------------------------------------------------- @staticmethod def get_mgtv_real_url(url): """str->list of str Give you the real URLs.""" content = loads(get_content(url)) m3u_url = content['info'] split = urlsplit(m3u_url) base_url = "{scheme}://{netloc}{path}/".format(scheme = split[0], netloc = split[1], path = dirname(split[2])) content = get_content(content['info']) #get the REAL M3U url, maybe to be changed later? segment_list = [] segments_size = 0 for i in content.split(): if not i.startswith('#'): #not the best way, better we use the m3u8 package segment_list.append(base_url + i) # use ext-info for fast size calculate elif i.startswith('#EXT-MGTV-File-SIZE:'): segments_size += int(i[i.rfind(':')+1:]) return m3u_url, segments_size, segment_list def download_playlist_by_url(self, url, **kwargs): pass def prepare(self, **kwargs): if self.url: self.vid = self.get_vid_from_url(self.url) content = get_content(self.api_endpoint.format(video_id = self.vid)) content = loads(content) self.title = content['data']['info']['title'] domain = content['data']['stream_domain'][0] #stream_avalable = [i['name'] for i in content['data']['stream']] stream_available = {} for i in content['data']['stream']: stream_available[i['name']] = i['url'] for s in self.stream_types: if s['video_profile'] in stream_available.keys(): quality_id = self.id_dic[s['video_profile']] url = stream_available[s['video_profile']] url = domain + re.sub( r'(\&arange\=\d+)', '', url) #Un-Hum m3u8_url, m3u8_size, segment_list_this = self.get_mgtv_real_url(url) stream_fileid_list = [] for i in segment_list_this: stream_fileid_list.append(os.path.basename(i).split('.')[0]) #make pieces pieces = [] for i in zip(stream_fileid_list, segment_list_this): pieces.append({'fileid': i[0], 'segs': i[1],}) self.streams[quality_id] = { 'container': s['container'], 'video_profile': s['video_profile'], 'size': m3u8_size, 'pieces': pieces, 'm3u8_url': m3u8_url } if not kwargs['info_only']: self.streams[quality_id]['src'] = segment_list_this def extract(self, **kwargs): if 'stream_id' in kwargs and kwargs['stream_id']: # Extract the stream stream_id = kwargs['stream_id'] if stream_id not in self.streams: log.e('[Error] Invalid video format.') log.e('Run \'-i\' command with no specific video format to view all available formats.') exit(2) else: # Extract stream with the best quality stream_id = self.streams_sorted[0]['id'] def download(self, **kwargs): if 'stream_id' in kwargs and kwargs['stream_id']: stream_id = kwargs['stream_id'] else: stream_id = 'null' # print video info only if 'info_only' in kwargs and kwargs['info_only']: if stream_id != 'null': if 'index' not in kwargs: self.p(stream_id) else: self.p_i(stream_id) else: # Display all available streams if 'index' not in kwargs: self.p([]) else: stream_id = self.streams_sorted[0]['id'] if 'id' in self.streams_sorted[0] else self.streams_sorted[0]['itag'] self.p_i(stream_id) # default to use the best quality if stream_id == 'null': stream_id = self.streams_sorted[0]['id'] stream_info = self.streams[stream_id] if not kwargs['info_only']: if player: # with m3u8 format because some video player can process urls automatically (e.g. mpv) launch_player(player, [stream_info['m3u8_url']]) else: download_urls(stream_info['src'], self.title, stream_info['container'], stream_info['size'], output_dir=kwargs['output_dir'], merge=kwargs.get('merge', True)) # av=stream_id in self.dash_streams) site = MGTV() download = site.download_by_url download_playlist = site.download_playlist_by_url
mit
meredith-digops/ansible
test/units/modules/cloud/amazon/test_cloudformation.py
89
3685
# (c) 2017 Red Hat Inc. # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. import pytest from mock import patch from . placebo_fixtures import placeboify, maybe_sleep from ansible.modules.cloud.amazon import cloudformation as cfn_module basic_yaml_tpl = """ --- AWSTemplateFormatVersion: '2010-09-09' Description: 'Basic template that creates an S3 bucket' Resources: MyBucket: Type: "AWS::S3::Bucket" Outputs: TheName: Value: !Ref MyBucket """ bad_json_tpl = """{ "AWSTemplateFormatVersion": "2010-09-09", "Description": "Broken template, no comma here ->" "Resources": { "MyBucket": { "Type": "AWS::S3::Bucket" } } }""" class FakeModule(object): def __init__(self, **kwargs): self.params = kwargs def fail_json(self, *args, **kwargs): self.exit_args = args self.exit_kwargs = kwargs raise Exception('FAIL') def exit_json(self, *args, **kwargs): self.exit_args = args self.exit_kwargs = kwargs raise Exception('EXIT') def test_invalid_template_json(placeboify): connection = placeboify.client('cloudformation') params = { 'StackName': 'ansible-test-wrong-json', 'TemplateBody': bad_json_tpl, } m = FakeModule(disable_rollback=False) with pytest.raises(Exception, message='Malformed JSON should cause the test to fail') as exc_info: cfn_module.create_stack(m, params, connection) assert exc_info.match('FAIL') assert "ValidationError" in m.exit_kwargs['msg'] def test_basic_s3_stack(maybe_sleep, placeboify): connection = placeboify.client('cloudformation') params = { 'StackName': 'ansible-test-basic-yaml', 'TemplateBody': basic_yaml_tpl, } m = FakeModule(disable_rollback=False) result = cfn_module.create_stack(m, params, connection) assert result['changed'] assert len(result['events']) > 1 # require that the final recorded stack state was CREATE_COMPLETE # events are retrieved newest-first, so 0 is the latest assert 'CREATE_COMPLETE' in result['events'][0] connection.delete_stack(StackName='ansible-test-basic-yaml') def test_delete_nonexistent_stack(maybe_sleep, placeboify): connection = placeboify.client('cloudformation') result = cfn_module.stack_operation(connection, 'ansible-test-nonexist', 'DELETE') assert result['changed'] assert 'Stack does not exist.' in result['log'] def test_get_nonexistent_stack(placeboify): connection = placeboify.client('cloudformation') assert cfn_module.get_stack_facts(connection, 'ansible-test-nonexist') is None def test_missing_template_body(placeboify): m = FakeModule() with pytest.raises(Exception, message='Expected module to fail with no template') as exc_info: cfn_module.create_stack( module=m, stack_params={}, cfn=None ) assert exc_info.match('FAIL') assert not m.exit_args assert "Either 'template' or 'template_url' is required when the stack does not exist." == m.exit_kwargs['msg']
gpl-3.0
Lujeni/ansible
lib/ansible/modules/cloud/google/gcp_mlengine_version_info.py
13
10048
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (C) 2017 Google # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # ---------------------------------------------------------------------------- # # *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** # # ---------------------------------------------------------------------------- # # This file is automatically generated by Magic Modules and manual # changes will be clobbered when the file is regenerated. # # Please read more about how to change this file at # https://www.github.com/GoogleCloudPlatform/magic-modules # # ---------------------------------------------------------------------------- from __future__ import absolute_import, division, print_function __metaclass__ = type ################################################################################ # Documentation ################################################################################ ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ["preview"], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: gcp_mlengine_version_info description: - Gather info for GCP Version short_description: Gather info for GCP Version version_added: '2.9' author: Google Inc. (@googlecloudplatform) requirements: - python >= 2.6 - requests >= 2.18.4 - google-auth >= 1.3.0 options: model: description: - The model that this version belongs to. - 'This field represents a link to a Model resource in GCP. It can be specified in two ways. First, you can place a dictionary with key ''name'' and value of your resource''s name Alternatively, you can add `register: name-of-resource` to a gcp_mlengine_model task and then set this model field to "{{ name-of-resource }}"' required: true type: dict project: description: - The Google Cloud Platform project to use. type: str auth_kind: description: - The type of credential used. type: str required: true choices: - application - machineaccount - serviceaccount service_account_contents: description: - The contents of a Service Account JSON file, either in a dictionary or as a JSON string that represents it. type: jsonarg service_account_file: description: - The path of a Service Account JSON file if serviceaccount is selected as type. type: path service_account_email: description: - An optional service account email address if machineaccount is selected and the user does not wish to use the default email. type: str scopes: description: - Array of scopes to be used type: list env_type: description: - Specifies which Ansible environment you're running this module within. - This should not be set unless you know what you're doing. - This only alters the User Agent string for any API requests. type: str notes: - for authentication, you can set service_account_file using the C(gcp_service_account_file) env variable. - for authentication, you can set service_account_contents using the C(GCP_SERVICE_ACCOUNT_CONTENTS) env variable. - For authentication, you can set service_account_email using the C(GCP_SERVICE_ACCOUNT_EMAIL) env variable. - For authentication, you can set auth_kind using the C(GCP_AUTH_KIND) env variable. - For authentication, you can set scopes using the C(GCP_SCOPES) env variable. - Environment variables values will only be used if the playbook values are not set. - The I(service_account_email) and I(service_account_file) options are mutually exclusive. ''' EXAMPLES = ''' - name: get info on a version gcp_mlengine_version_info: model: "{{ model }}" project: test_project auth_kind: serviceaccount service_account_file: "/tmp/auth.pem" ''' RETURN = ''' resources: description: List of resources returned: always type: complex contains: name: description: - The name specified for the version when it was created. - The version name must be unique within the model it is created in. returned: success type: str description: description: - The description specified for the version when it was created. returned: success type: str deploymentUri: description: - The Cloud Storage location of the trained model used to create the version. returned: success type: str createTime: description: - The time the version was created. returned: success type: str lastUseTime: description: - The time the version was last used for prediction. returned: success type: str runtimeVersion: description: - The AI Platform runtime version to use for this deployment. returned: success type: str machineType: description: - The type of machine on which to serve the model. Currently only applies to online prediction service. returned: success type: str state: description: - The state of a version. returned: success type: str errorMessage: description: - The details of a failure or cancellation. returned: success type: str packageUris: description: - Cloud Storage paths (gs://…) of packages for custom prediction routines or scikit-learn pipelines with custom code. returned: success type: list labels: description: - One or more labels that you can add, to organize your model versions. returned: success type: dict framework: description: - The machine learning framework AI Platform uses to train this version of the model. returned: success type: str pythonVersion: description: - The version of Python used in prediction. If not set, the default version is '2.7'. Python '3.5' is available when runtimeVersion is set to '1.4' and above. Python '2.7' works with all supported runtime versions. returned: success type: str serviceAccount: description: - Specifies the service account for resource access control. returned: success type: str autoScaling: description: - Automatically scale the number of nodes used to serve the model in response to increases and decreases in traffic. Care should be taken to ramp up traffic according to the model's ability to scale or you will start seeing increases in latency and 429 response codes. returned: success type: complex contains: minNodes: description: - The minimum number of nodes to allocate for this mode. returned: success type: int manualScaling: description: - Manually select the number of nodes to use for serving the model. You should generally use autoScaling with an appropriate minNodes instead, but this option is available if you want more predictable billing. Beware that latency and error rates will increase if the traffic exceeds that capability of the system to serve it based on the selected number of nodes. returned: success type: complex contains: nodes: description: - The number of nodes to allocate for this model. These nodes are always up, starting from the time the model is deployed. returned: success type: int predictionClass: description: - The fully qualified name (module_name.class_name) of a class that implements the Predictor interface described in this reference field. The module containing this class should be included in a package provided to the packageUris field. returned: success type: str model: description: - The model that this version belongs to. returned: success type: dict isDefault: description: - If true, this version will be used to handle prediction requests that do not specify a version. returned: success type: bool ''' ################################################################################ # Imports ################################################################################ from ansible.module_utils.gcp_utils import navigate_hash, GcpSession, GcpModule, GcpRequest, replace_resource_dict import json ################################################################################ # Main ################################################################################ def main(): module = GcpModule(argument_spec=dict(model=dict(required=True, type='dict'))) if not module.params['scopes']: module.params['scopes'] = ['https://www.googleapis.com/auth/cloud-platform'] return_value = {'resources': fetch_list(module, collection(module))} module.exit_json(**return_value) def collection(module): res = {'project': module.params['project'], 'model': replace_resource_dict(module.params['model'], 'name')} return "https://ml.googleapis.com/v1/projects/{project}/models/{model}/versions".format(**res) def fetch_list(module, link): auth = GcpSession(module, 'mlengine') return auth.list(link, return_if_object, array_name='versions') def return_if_object(module, response): # If not found, return nothing. if response.status_code == 404: return None # If no content, return nothing. if response.status_code == 204: return None try: module.raise_for_status(response) result = response.json() except getattr(json.decoder, 'JSONDecodeError', ValueError) as inst: module.fail_json(msg="Invalid JSON response with error: %s" % inst) if navigate_hash(result, ['error', 'errors']): module.fail_json(msg=navigate_hash(result, ['error', 'errors'])) return result if __name__ == "__main__": main()
gpl-3.0
nharraud/b2share
invenio/modules/workflows/upgrades/workflows_2014_08_12_task_results_to_dict.py
15
3644
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2014 CERN. # # Invenio is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any later version. # # Invenio is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Invenio; if not, write to the Free Software Foundation, Inc., # 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. """Upgrade script for removing WorkflowsTaskResult class to use a dict.""" import os import cPickle import base64 from invenio.legacy.dbquery import run_sql depends_on = ["workflows_2014_08_12_initial"] def info(): """Display info.""" return "Will convert all task results to dict instead of object" def do_upgrade(): """Perform the upgrade from WorkflowsTaskResult to a simple dict.""" class WorkflowsTaskResult(object): """The class to contain the current task results.""" __module__ = os.path.splitext(os.path.basename(__file__))[0] def __init__(self, task_name, name, result): """Create a task result passing task_name, name and result.""" self.task_name = task_name self.name = name self.result = result def to_dict(self): """Return a dictionary representing a full task result.""" return { 'name': self.name, 'task_name': self.task_name, 'result': self.result } from invenio.modules.workflows import utils utils.WorkflowsTaskResult = WorkflowsTaskResult all_data_objects = run_sql("SELECT id, _extra_data FROM bwlOBJECT") for object_id, _extra_data in all_data_objects: extra_data = cPickle.loads(base64.b64decode(_extra_data)) if "_tasks_results" in extra_data: extra_data["_tasks_results"] = convert_to_dict( extra_data["_tasks_results"] ) _extra_data = base64.b64encode(cPickle.dumps(extra_data)) run_sql("UPDATE bwlOBJECT set _extra_data=%s WHERE id=%s", (_extra_data, str(object_id))) def estimate(): """Estimate running time of upgrade in seconds (optional).""" return 1 def convert_to_dict(results): """Convert WorkflowTask object to dict.""" results_new = {} if isinstance(results, list): if len(results) == 0: return results_new else: raise RuntimeError("Cannot convert task result.") for task, res in results.iteritems(): result_list = [] for result in res: if isinstance(result, dict): result_list.append(result) elif hasattr(result, "to_dict"): new_result = result.to_dict() # Set default template new_result["template"] = map_existing_templates(task) result_list.append(new_result) results_new[task] = result_list return results_new def map_existing_templates(name): """Return a template given a task name, else return default.""" mapping = { "fulltext_download": "workflows/results/files.html", "refextract": "workflows/results/refextract.html", } return mapping.get(name, "workflows/results/default.html")
gpl-2.0
SKIRT/PTS
do/modeling/sfr_to_lum.py
1
12053
#!/usr/bin/env python # -*- coding: utf8 -*- # ***************************************************************** # ** PTS -- Python Toolkit for working with SKIRT ** # ** © Astronomical Observatory, Ghent University ** # ***************************************************************** ## \package pts.do.modeling.sfr_to_lum Convert a SFR to a luminosity in a certain band. # ----------------------------------------------------------------- # Ensure Python 3 compatibility from __future__ import absolute_import, division, print_function # Import standard modules import inspect import numpy as np # Import the relevant PTS classes and modules from pts.core.units.parsing import parse_unit as u from pts.modeling.core.mappings import Mappings from pts.core.basics.log import log from pts.core.tools.stringify import tostr from pts.modeling.misc.playground import MappingsPlayground from pts.core.plot.sed import SEDPlotter from pts.core.basics.configuration import ConfigurationDefinition, parse_arguments from pts.core.data.sun import Sun from pts.core.tools import filesystem as fs from pts.core.data.sed import SED from pts.core.simulation.wavelengthgrid import WavelengthGrid # ----------------------------------------------------------------- # Create definition definition = ConfigurationDefinition() # Filter definition.add_required("filter", "filter", "filter in which to calculate the luminosity") # SFR definition.add_positional_optional("sfr", "quantity", "star formation rate", "1. Msun/yr", convert_default=True) # MAPPINGS parameters definition.add_optional("metallicity", "positive_real", "metallicity", 0.02) definition.add_optional("compactness", "positive_real", "compactness", 6) definition.add_optional("pressure", "quantity", "pressure", 1e12 * u("K/m3")) definition.add_optional("covering_factor", "positive_real", "covering factor", 0.2) # fPDR # Flags definition.add_flag("plot", "plot the SEDs", False) definition.add_flag("skirt", "use SKIRT", True) definition.add_flag("pts", "use PTS", True) definition.add_flag("sampled", "use SKIRT luminosities already sampled on a wavelength grid", True) definition.add_flag("only_skirt", "only SKIRT", False) definition.add_flag("only_pts", "only PTS", False) definition.add_flag("only_sampled", "only sampled", False) # Output path definition.add_optional("output", "directory_path", "output path") # Get the configuration config = parse_arguments("sfr_to_lum", definition, "Convert a SFR to a luminosity in a certain band") # ----------------------------------------------------------------- # Check if config.only_skirt: config.pts = config.sampled = False config.skirt = True elif config.only_pts: config.skirt = config.sampled = False config.pts = True elif config.only_sampled: config.skirt = config.pts = False config.sampled = True # ----------------------------------------------------------------- fltr = config.filter fltr_wavelength = fltr.wavelength sun = Sun() print("") solar_neutral_density = sun.luminosity_for_wavelength(fltr_wavelength, unit="W", density=True) solar_wavelength_density = sun.luminosity_for_wavelength(fltr_wavelength, unit="W/micron") log.info("solar in neutral density: " + tostr(solar_neutral_density)) log.info("solar in wavelength density: " + tostr(solar_wavelength_density)) log.info("bolometric solar luminosity: " + tostr(sun.total_luminosity())) print("") # ----------------------------------------------------------------- sfr_scalar = config.sfr.to("Msun/yr").value # ----------------------------------------------------------------- def show_luminosities(sed): """ This function ... :param sed: :return: """ # Get spectral luminosity density lum = sed.photometry_at(fltr_wavelength, unit="W/micron") lum2 = sed.photometry_at(fltr_wavelength, unit="W/micron", interpolate=False) # log.info("Luminosity: " + tostr(lum)) log.info("No interpolation: " + tostr(lum2)) # Convert to solar SPECTRAL luminosity DENSITY at wavelength lum_spectral_solar = lum.to("W/micron").value / solar_wavelength_density.to("W/micron").value # Convert to neutral lum_neutral = lum.to("W", density=True, wavelength=fltr_wavelength) lum_solar = lum.to("Lsun", density=True, wavelength=fltr_wavelength) # Neutral and solar log.info("Luminosity in spectral solar units: " + tostr(lum_spectral_solar) + " Lsun_" + fltr.band) log.info("Luminosity in neutral units: " + tostr(lum_neutral)) log.info("Luminosity in solar units: " + tostr(lum_solar)) # ----------------------------------------------------------------- # Calculate from file with sampled luminosituies if config.sampled: # Determine the path to this directory this_filepath = fs.absolute_or_in_cwd(inspect.getfile(inspect.currentframe())) directory_path = fs.directory_of(this_filepath) # Determine the filepath filepath = fs.join(directory_path, "MappingsTemplate.dat") # Get wavelength grid, calculate luminosities in W wg = WavelengthGrid.from_text_file(filepath, "m") deltas = wg.deltas(asarray=True, unit="m") lums = np.loadtxt(filepath, skiprows=0, unpack=True, usecols=(1)) lums *= sfr_scalar # CORRECT FOR SFR # Construct the SED spectrallums = lums / deltas sampled_sed = SED.from_arrays(wg.wavelengths(asarray=True, unit="m"), spectrallums, "m", "W/m") print("FROM SAMPLED LUMINOSITIES:") print("") # Show show_luminosities(sampled_sed) print("") # Don't calculate else: sampled_sed = None # ----------------------------------------------------------------- # Calculate with PTS if config.pts: # Mappings SED mappings = Mappings(config.metallicity, config.compactness, config.pressure, config.covering_factor, sfr_scalar) sed = mappings.sed print("USING PTS:") print("") # Show show_luminosities(sed) print("") # Don't calculate with PTS else: sed = None # ----------------------------------------------------------------- # Calculate with SKIRT if config.skirt: logp = np.log10(config.pressure.to("K/cm3").value) # Get the SED playground = MappingsPlayground() sed_skirt = playground.simulate_sed(logp, sfr_scalar, config.metallicity, config.compactness, config.covering_factor, output_path=config.output) lum_skirt = sed_skirt.photometry_at(fltr_wavelength, unit="W/micron") lum_skirt2 = sed_skirt.photometry_at(fltr_wavelength, unit="W/micron", interpolate=False) print("USING SKIRT:") print("") # Show show_luminosities(sed_skirt) print("") # EXTRA CHECK: if config.output is not None: # Determine path to SKIRT output file luminosities_path = fs.join(config.output, "oneparticle_hii_luminosities.dat") # Load the SED sed_luminosities_skirt = SED.from_skirt(luminosities_path) # Get the deltas deltas = sed_luminosities_skirt.wavelength_deltas(unit="micron", asarray=True) # Get the spectral luminosities luminosities = sed_luminosities_skirt.photometry(unit="W", asarray=True) spectral_luminosities = luminosities / deltas # Create SED with wavelength luminosity densities wavelengths = sed_luminosities_skirt.wavelengths(unit="micron", asarray=True) extra_sed = SED.from_arrays(wavelengths, spectral_luminosities, wavelength_unit="micron", photometry_unit="W/micron") print("EXTRA:") print("") # Show show_luminosities(extra_sed) print("") # Don't calculate with SKIRT else: sed_skirt = None # ----------------------------------------------------------------- # Plot? if config.plot: plotter = SEDPlotter() plotter.config.unit = u("W/micron", density=True) if sed is not None: plotter.add_sed(sed, "PTS") if sed_skirt is not None: plotter.add_sed(sed_skirt, "SKIRT") if sampled_sed is not None: plotter.add_sed(sampled_sed, "Sampled") plotter.run() # ----------------------------------------------------------------- #metallicity = 0.03 #compactness = 6 # logC #pressure = 1e12 * u("K/m3") #covering_factor = 0.2 # fPDR #logp = np.log10(pressure.to("K/cm3").value) #print(logp) #minlogp_value = 4. #maxlogp_value = 8. # Q_CLASSINFO("MinValue", "1e10 K/m3") # Q_CLASSINFO("MaxValue", "1e14 K/m3") # Q_CLASSINFO("Default", "1e11 K/m3") #min_pressure = 1e10 * u("K/m3") #max_pressure = 1e14 * u("K/m3") #minlogp = np.log10(min_pressure.to("K/cm3").value) #maxlogp = np.log10(max_pressure.to("K/cm3").value) #print(minlogp_value, minlogp) #print(maxlogp_value, maxlogp) #logp: 4 -> 8 # LIMITS: # Zrel = max(Zrel,0.05); #Zrel = min(Zrel,2.0-1e-8); #logC = max(logC,4.0); #logC = min(logC,6.5-1e-8); #logp = max(logp,4.0); #logp = min(logp,8.0-1e-8); #sfr_scalar = sfr.value # ----------------------------------------------------------------- # Mappings SED #mappings = Mappings(metallicity, compactness, pressure, covering_factor, sfr_scalar) # ----------------------------------------------------------------- # Luminosity for FUV (wavelength) #lum = mappings.luminosity_at(fuv_wavelength) #lum2 = mappings.luminosity_at(fuv_wavelength, interpolate=False) #lum3 = mappings.luminosity_for_filter(fuv) #log.info("For SFR of " + tostr(sfr) + ", the luminosity at FUV wavelength is " + str(lum)) #log.info("Without interpolation: " + str(lum2)) #log.info("When convolved over the FUV filter, the luminosity is " + str(lum3)) # ----------------------------------------------------------------- #mappings_normalized = Mappings(metallicity, compactness, pressure, covering_factor, 1.0) # Luminosity for FUV (wavelength) #lum_one = mappings_normalized.luminosity_at(fuv_wavelength) #lum_one2 = mappings_normalized.luminosity_at(fuv_wavelength, interpolate=False) #lum_one3 = mappings_normalized.luminosity_for_filter(fuv) #log.info("For SFR of 1.0, the luminosity at FUV wavelength is " + str(lum_one)) #log.info("Without interpolation: " + str(lum_one2)) #log.info("When convolved over the FUV filter, the luminosity is " + str(lum_one3)) # ----------------------------------------------------------------- #sim_wavelengths_range = QuantityRange(0.1, 1000., "micron") #sim_wavelengths = sim_wavelengths_range.log(150, as_list=True) # Add FUV wavelength #sim_wavelengths.append(fuv_wavelength) #sim_wavelengths = sorted(sim_wavelengths) #wavelengths_array = np.array([wav.to("micron").value for wav in sim_wavelengths]) #sim_wavelengths = RealRange(0.05, 10, "micron").log(150, as_list=True) #sim_wavelengths.append(fuv_wavelength.to("micron").value) #wavelength_grid = WavelengthGrid.from_wavelengths(wavelengths_array, "micron", sort=True) # ----------------------------------------------------------------- #ski = get_oligochromatic_template() # Remove all stellar components except the ionizing stars #ski.remove_stellar_components_except("Ionizing stars") # Remove the dust system #ski.remove_dust_system() # Set number of packages per wavelength #ski.setpackages(1e5) # Perform the SKIRT simulation #simulation = SkirtExec().execute(ski_path, inpath=in_path, outpath=out_path)[0] # ----------------------------------------------------------------- # # 1 SFR: # sed_one = playground.simulate_sed(logp, 1., metallicity, compactness, covering_factor) # # lum_skirt = sed_one.photometry_at(fuv_wavelength, unit="W/micron") # lum_skirt2 = sed_one.photometry_at(fuv_wavelength, unit="W/micron", interpolate=False) # # log.info("Luminosity [SFR = 1]: " + tostr(lum_skirt)) # log.info("No interpolation [SFR = 1]: " + tostr(lum_skirt2)) # # # Convert to neutral # lum_skirt_neutral = lum_skirt.to("W", density=True, wavelength=fuv_wavelength) # lum_skirt_solar = lum_skirt.to("Lsun", density=True, wavelength=fuv_wavelength) # # log.info("Luminosity in neutral units [SFR = 1]: " + tostr(lum_skirt_neutral)) # log.info("Luminosity in solar units [SFR = 1]: " + tostr(lum_skirt_solar)) # -----------------------------------------------------------------
agpl-3.0
tsdmgz/ansible
lib/ansible/modules/messaging/rabbitmq_parameter.py
49
4553
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2013, Chatham Financial <oss@chathamfinancial.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: rabbitmq_parameter short_description: Adds or removes parameters to RabbitMQ description: - Manage dynamic, cluster-wide parameters for RabbitMQ version_added: "1.1" author: '"Chris Hoffman (@chrishoffman)"' options: component: description: - Name of the component of which the parameter is being set required: true default: null name: description: - Name of the parameter being set required: true default: null value: description: - Value of the parameter, as a JSON term required: false default: null vhost: description: - vhost to apply access privileges. required: false default: / node: description: - erlang node name of the rabbit we wish to configure required: false default: rabbit version_added: "1.2" state: description: - Specify if user is to be added or removed required: false default: present choices: [ 'present', 'absent'] ''' EXAMPLES = """ # Set the federation parameter 'local_username' to a value of 'guest' (in quotes) - rabbitmq_parameter: component: federation name: local-username value: '"guest"' state: present """ import json from ansible.module_utils.basic import AnsibleModule class RabbitMqParameter(object): def __init__(self, module, component, name, value, vhost, node): self.module = module self.component = component self.name = name self.value = value self.vhost = vhost self.node = node self._value = None self._rabbitmqctl = module.get_bin_path('rabbitmqctl', True) def _exec(self, args, run_in_check_mode=False): if not self.module.check_mode or (self.module.check_mode and run_in_check_mode): cmd = [self._rabbitmqctl, '-q', '-n', self.node] rc, out, err = self.module.run_command(cmd + args, check_rc=True) return out.splitlines() return list() def get(self): parameters = self._exec(['list_parameters', '-p', self.vhost], True) for param_item in parameters: component, name, value = param_item.split('\t') if component == self.component and name == self.name: self._value = json.loads(value) return True return False def set(self): self._exec(['set_parameter', '-p', self.vhost, self.component, self.name, json.dumps(self.value)]) def delete(self): self._exec(['clear_parameter', '-p', self.vhost, self.component, self.name]) def has_modifications(self): return self.value != self._value def main(): arg_spec = dict( component=dict(required=True), name=dict(required=True), value=dict(default=None), vhost=dict(default='/'), state=dict(default='present', choices=['present', 'absent']), node=dict(default='rabbit') ) module = AnsibleModule( argument_spec=arg_spec, supports_check_mode=True ) component = module.params['component'] name = module.params['name'] value = module.params['value'] if isinstance(value, str): value = json.loads(value) vhost = module.params['vhost'] state = module.params['state'] node = module.params['node'] result = dict(changed=False) rabbitmq_parameter = RabbitMqParameter(module, component, name, value, vhost, node) if rabbitmq_parameter.get(): if state == 'absent': rabbitmq_parameter.delete() result['changed'] = True else: if rabbitmq_parameter.has_modifications(): rabbitmq_parameter.set() result['changed'] = True elif state == 'present': rabbitmq_parameter.set() result['changed'] = True result['component'] = component result['name'] = name result['vhost'] = vhost result['state'] = state module.exit_json(**result) if __name__ == '__main__': main()
gpl-3.0
pusnik/pyexchange
tests/exchange2010/test_create_event.py
1
10568
""" (c) 2013 LinkedIn Corp. All rights reserved. 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. """ import pickle import unittest from httpretty import HTTPretty, httprettified from pytest import raises from pyexchange import Exchange2010Service from pyexchange.connection import ExchangeNTLMAuthConnection from pyexchange.base.calendar import ExchangeEventAttendee from pyexchange.exceptions import * # noqa from .fixtures import * # noqa class Test_PopulatingANewEvent(unittest.TestCase): """ Tests all the attribute setting works when creating a new event """ calendar = None @classmethod def setUpClass(cls): cls.calendar = Exchange2010Service( connection=ExchangeNTLMAuthConnection( url=FAKE_EXCHANGE_URL, username=FAKE_EXCHANGE_USERNAME, password=FAKE_EXCHANGE_PASSWORD, ) ).calendar() def test_canary(self): event = self.calendar.event() assert event is not None def test_events_created_dont_have_an_id(self): event = self.calendar.event() assert event.id is None def test_can_add_a_subject(self): event = self.calendar.event(subject=TEST_EVENT.subject) assert event.subject == TEST_EVENT.subject def test_can_add_a_location(self): event = self.calendar.event(location=TEST_EVENT.location) assert event.location == TEST_EVENT.location def test_can_add_an_html_body(self): event = self.calendar.event(html_body=TEST_EVENT.body) assert event.html_body == TEST_EVENT.body assert event.text_body is None assert event.body == TEST_EVENT.body def test_can_add_a_text_body(self): event = self.calendar.event(text_body=TEST_EVENT.body) assert event.text_body == TEST_EVENT.body assert event.html_body is None assert event.body == TEST_EVENT.body def test_can_add_a_start_time(self): event = self.calendar.event(start=TEST_EVENT.start) assert event.start == TEST_EVENT.start def test_can_add_an_end_time(self): event = self.calendar.event(end=TEST_EVENT.end) assert event.end == TEST_EVENT.end def test_can_add_attendees_via_email(self): event = self.calendar.event(attendees=PERSON_REQUIRED_ACCEPTED.email) assert len(event.attendees) == 1 assert len(event.required_attendees) == 1 assert len(event.optional_attendees) == 0 assert event.attendees[0].email == PERSON_REQUIRED_ACCEPTED.email def test_can_add_multiple_attendees_via_email(self): event = self.calendar.event(attendees=[PERSON_REQUIRED_ACCEPTED.email, PERSON_REQUIRED_TENTATIVE.email]) assert len(event.attendees) == 2 assert len(event.required_attendees) == 2 assert len(event.optional_attendees) == 0 def test_can_add_attendees_via_named_tuple(self): person = ExchangeEventAttendee(name=PERSON_OPTIONAL_ACCEPTED.name, email=PERSON_OPTIONAL_ACCEPTED.email, required=PERSON_OPTIONAL_ACCEPTED.required) event = self.calendar.event(attendees=person) assert len(event.attendees) == 1 assert len(event.required_attendees) == 0 assert len(event.optional_attendees) == 1 assert event.attendees[0].email == PERSON_OPTIONAL_ACCEPTED.email def test_can_assign_to_required_attendees(self): event = self.calendar.event(attendees=PERSON_REQUIRED_ACCEPTED.email) event.required_attendees = [PERSON_REQUIRED_ACCEPTED.email, PERSON_OPTIONAL_ACCEPTED.email] assert len(event.attendees) == 2 assert len(event.required_attendees) == 2 assert len(event.optional_attendees) == 0 def test_can_assign_to_optional_attendees(self): event = self.calendar.event(attendees=PERSON_REQUIRED_ACCEPTED.email) event.optional_attendees = PERSON_OPTIONAL_ACCEPTED.email assert len(event.attendees) == 2 assert len(event.required_attendees) == 1 assert len(event.optional_attendees) == 1 assert event.required_attendees[0].email == PERSON_REQUIRED_ACCEPTED.email assert event.optional_attendees[0].email == PERSON_OPTIONAL_ACCEPTED.email def test_can_add_resources(self): event = self.calendar.event(resources=[RESOURCE.email]) assert len(event.resources) == 1 assert event.resources[0].email == RESOURCE.email assert event.conference_room.email == RESOURCE.email def test_can_add_delegate(self): event = self.calendar.event(delegate_for=TEST_EVENT.delegate_for) assert event.delegate_for == TEST_EVENT.delegate_for class Test_CreatingANewEvent(unittest.TestCase): service = None event = None @classmethod def setUpClass(cls): cls.service = Exchange2010Service(connection=ExchangeNTLMAuthConnection(url=FAKE_EXCHANGE_URL, username=FAKE_EXCHANGE_USERNAME, password=FAKE_EXCHANGE_PASSWORD)) def setUp(self): self.event = self.service.calendar().event(start=TEST_EVENT.start, end=TEST_EVENT.end) def test_events_must_have_a_start_date(self): self.event.start = None with raises(ValueError): self.event.create() def test_events_must_have_an_end_date(self): self.event.end = None with raises(ValueError): self.event.create() def test_event_end_date_must_come_after_start_date(self): self.event.start, self.event.end = self.event.end, self.event.start with raises(ValueError): self.event.create() def test_attendees_must_have_an_email_address_take1(self): with raises(ValueError): self.event.add_attendees(ExchangeEventAttendee(name="Bomb", email=None, required=True)) self.event.create() def test_attendees_must_have_an_email_address_take2(self): with raises(ValueError): self.event.add_attendees([None]) self.event.create() def test_event_reminder_must_be_int(self): self.event.reminder_minutes_before_start = "not an integer" with raises(TypeError): self.event.create() def test_event_all_day_must_be_bool(self): self.event.is_all_day = "not a bool" with raises(TypeError): self.event.create() def cant_delete_a_newly_created_event(self): with raises(ValueError): self.event.delete() def cant_update_a_newly_created_event(self): with raises(ValueError): self.event.update() def cant_resend_invites_for_a_newly_created_event(self): with raises(ValueError): self.event.resend_invitations() @httprettified def test_can_set_subject(self): HTTPretty.register_uri( HTTPretty.POST, FAKE_EXCHANGE_URL, body=CREATE_ITEM_RESPONSE.encode('utf-8'), content_type='text/xml; charset=utf-8', ) self.event.subject = TEST_EVENT.subject self.event.create() assert TEST_EVENT.subject in HTTPretty.last_request.body.decode('utf-8') @httprettified def test_can_set_location(self): HTTPretty.register_uri( HTTPretty.POST, FAKE_EXCHANGE_URL, body=CREATE_ITEM_RESPONSE.encode('utf-8'), content_type='text/xml; charset=utf-8', ) self.event.location = TEST_EVENT.location self.event.create() assert TEST_EVENT.location in HTTPretty.last_request.body.decode('utf-8') @httprettified def test_can_set_html_body(self): HTTPretty.register_uri( HTTPretty.POST, FAKE_EXCHANGE_URL, body=CREATE_ITEM_RESPONSE.encode('utf-8'), content_type='text/xml; charset=utf-8' ) self.event.html_body = TEST_EVENT.body self.event.create() assert TEST_EVENT.body in HTTPretty.last_request.body.decode('utf-8') @httprettified def test_can_set_text_body(self): HTTPretty.register_uri( HTTPretty.POST, FAKE_EXCHANGE_URL, body=CREATE_ITEM_RESPONSE.encode('utf-8'), content_type='text/xml; charset=utf-8', ) self.event.text_body = TEST_EVENT.body self.event.create() assert TEST_EVENT.body in HTTPretty.last_request.body.decode('utf-8') @httprettified def test_start_time(self): HTTPretty.register_uri( HTTPretty.POST, FAKE_EXCHANGE_URL, body=CREATE_ITEM_RESPONSE.encode('utf-8'), content_type='text/xml; charset=utf-8', ) self.event.create() assert TEST_EVENT.start.strftime(EXCHANGE_DATE_FORMAT) in HTTPretty.last_request.body.decode('utf-8') @httprettified def test_end_time(self): HTTPretty.register_uri( HTTPretty.POST, FAKE_EXCHANGE_URL, body=CREATE_ITEM_RESPONSE.encode('utf-8'), content_type='text/xml; charset=utf-8', ) self.event.create() assert TEST_EVENT.end.strftime(EXCHANGE_DATE_FORMAT) in HTTPretty.last_request.body.decode('utf-8') @httprettified def test_attendees(self): HTTPretty.register_uri( HTTPretty.POST, FAKE_EXCHANGE_URL, body=CREATE_ITEM_RESPONSE.encode('utf-8'), content_type='text/xml; charset=utf-8', ) attendees = [PERSON_REQUIRED_ACCEPTED.email, PERSON_REQUIRED_TENTATIVE.email] self.event.attendees = attendees self.event.create() for email in attendees: assert email in HTTPretty.last_request.body.decode('utf-8') def test_resources_must_have_an_email_address(self): HTTPretty.register_uri( HTTPretty.POST, FAKE_EXCHANGE_URL, body=CREATE_ITEM_RESPONSE.encode('utf-8'), content_type='text/xml; charset=utf-8', ) attendees = [PERSON_WITH_NO_EMAIL_ADDRESS] with raises(ValueError): self.event.attendees = attendees self.event.create() @httprettified def test_resources(self): HTTPretty.register_uri( HTTPretty.POST, FAKE_EXCHANGE_URL, body=CREATE_ITEM_RESPONSE.encode('utf-8'), content_type='text/xml; charset=utf-8', ) self.event.resources = [RESOURCE.email] self.event.create() assert RESOURCE.email in HTTPretty.last_request.body.decode('utf-8') def test_events_can_be_pickled(self): self.event.subject = "events can be pickled" pickled_event = pickle.dumps(self.event) new_event = pickle.loads(pickled_event) assert new_event.subject == "events can be pickled" @httprettified def test_delegate_for(self): HTTPretty.register_uri( HTTPretty.POST, FAKE_EXCHANGE_URL, body=CREATE_ITEM_RESPONSE.encode('utf-8'), content_type='text/xml; charset=utf-8', ) self.event.delegate_for = RESOURCE.email self.event.create() assert RESOURCE.email in HTTPretty.last_request.body.decode('utf-8')
apache-2.0
syphar/django
django/contrib/flatpages/models.py
115
1583
from __future__ import unicode_literals from django.contrib.sites.models import Site from django.db import models from django.urls import get_script_prefix from django.utils.encoding import iri_to_uri, python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ @python_2_unicode_compatible class FlatPage(models.Model): url = models.CharField(_('URL'), max_length=100, db_index=True) title = models.CharField(_('title'), max_length=200) content = models.TextField(_('content'), blank=True) enable_comments = models.BooleanField(_('enable comments'), default=False) template_name = models.CharField( _('template name'), max_length=70, blank=True, help_text=_( "Example: 'flatpages/contact_page.html'. If this isn't provided, " "the system will use 'flatpages/default.html'." ), ) registration_required = models.BooleanField( _('registration required'), help_text=_("If this is checked, only logged-in users will be able to view the page."), default=False, ) sites = models.ManyToManyField(Site, verbose_name=_('sites')) class Meta: db_table = 'django_flatpage' verbose_name = _('flat page') verbose_name_plural = _('flat pages') ordering = ('url',) def __str__(self): return "%s -- %s" % (self.url, self.title) def get_absolute_url(self): # Handle script prefix manually because we bypass reverse() return iri_to_uri(get_script_prefix().rstrip('/') + self.url)
bsd-3-clause
wevote/WebAppPublic
apis_v1/documentation_source/facebook_sign_in_doc.py
1
2777
# apis_v1/documentation_source/facebook_sign_in_doc.py # Brought to you by We Vote. Be good. # -*- coding: UTF-8 -*- def facebook_sign_in_doc_template_values(url_root): """ Show documentation about facebookSignIn """ required_query_parameter_list = [ { 'name': 'voter_device_id', 'value': 'string', # boolean, integer, long, string 'description': 'An 88 character unique identifier linked to a voter record on the server', }, { 'name': 'api_key', 'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, string 'description': 'The unique key provided to any organization using the WeVoteServer APIs', }, ] optional_query_parameter_list = [ { 'name': 'facebook_id', 'value': 'integer', # boolean, integer, long, string 'description': 'The Facebook big integer id', }, { 'name': 'facebook_email', 'value': 'string', # boolean, integer, long, string 'description': 'Email address from Facebook', }, ] potential_status_codes_list = [ { 'code': 'VALID_VOTER_DEVICE_ID_MISSING', 'description': 'Cannot proceed. A valid voter_device_id parameter was not included.', }, { 'code': 'VALID_VOTER_ID_MISSING', 'description': 'Cannot proceed. A valid voter_id was not found.', }, # { # 'code': '', # 'description': '', # }, ] try_now_link_variables_dict = { # 'organization_we_vote_id': 'wv85org1', } api_response = '{\n' \ ' "status": string,\n' \ ' "success": boolean,\n' \ ' "voter_device_id": string (88 characters long),\n' \ ' "facebook_id": integer,\n' \ ' "facebook_email": string,\n' \ '}' template_values = { 'api_name': 'facebookSignIn', 'api_slug': 'facebookSignIn', 'api_introduction': "", 'try_now_link': 'apis_v1:facebookSignInView', 'try_now_link_variables_dict': try_now_link_variables_dict, 'url_root': url_root, 'get_or_post': 'GET', 'required_query_parameter_list': required_query_parameter_list, 'optional_query_parameter_list': optional_query_parameter_list, 'api_response': api_response, 'api_response_notes': "", 'potential_status_codes_list': potential_status_codes_list, } return template_values
bsd-3-clause
nzlosh/st2
st2common/st2common/util/http.py
3
1728
# Copyright 2020 The StackStorm Authors. # Copyright 2019 Extreme Networks, Inc. # # 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. from __future__ import absolute_import import six http_client = six.moves.http_client __all__ = ["HTTP_SUCCESS", "parse_content_type_header"] HTTP_SUCCESS = [ http_client.OK, http_client.CREATED, http_client.ACCEPTED, http_client.NON_AUTHORITATIVE_INFORMATION, http_client.NO_CONTENT, http_client.RESET_CONTENT, http_client.PARTIAL_CONTENT, http_client.MULTI_STATUS, http_client.IM_USED, ] def parse_content_type_header(content_type): """ Parse and normalize request content type and return a tuple with the content type and the options. :rype: ``tuple`` """ if ";" in content_type: split = content_type.split(";") media = split[0] options = {} for pair in split[1:]: split_pair = pair.split("=", 1) if len(split_pair) != 2: continue key = split_pair[0].strip() value = split_pair[1].strip() options[key] = value else: media = content_type options = {} result = (media, options) return result
apache-2.0
WhireCrow/openwrt-mt7620
staging_dir/target-mipsel_r2_uClibc-0.9.33.2/usr/lib/python2.7/multiprocessing/queues.py
103
12318
# # Module implementing queues # # multiprocessing/queues.py # # Copyright (c) 2006-2008, R Oudkerk # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # 3. Neither the name of author nor the names of any contributors may be # used to endorse or promote products derived from this software # without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF # SUCH DAMAGE. # __all__ = ['Queue', 'SimpleQueue', 'JoinableQueue'] import sys import os import threading import collections import time import atexit import weakref from Queue import Empty, Full import _multiprocessing from multiprocessing import Pipe from multiprocessing.synchronize import Lock, BoundedSemaphore, Semaphore, Condition from multiprocessing.util import debug, info, Finalize, register_after_fork from multiprocessing.forking import assert_spawning # # Queue type using a pipe, buffer and thread # class Queue(object): def __init__(self, maxsize=0): if maxsize <= 0: maxsize = _multiprocessing.SemLock.SEM_VALUE_MAX self._maxsize = maxsize self._reader, self._writer = Pipe(duplex=False) self._rlock = Lock() self._opid = os.getpid() if sys.platform == 'win32': self._wlock = None else: self._wlock = Lock() self._sem = BoundedSemaphore(maxsize) self._after_fork() if sys.platform != 'win32': register_after_fork(self, Queue._after_fork) def __getstate__(self): assert_spawning(self) return (self._maxsize, self._reader, self._writer, self._rlock, self._wlock, self._sem, self._opid) def __setstate__(self, state): (self._maxsize, self._reader, self._writer, self._rlock, self._wlock, self._sem, self._opid) = state self._after_fork() def _after_fork(self): debug('Queue._after_fork()') self._notempty = threading.Condition(threading.Lock()) self._buffer = collections.deque() self._thread = None self._jointhread = None self._joincancelled = False self._closed = False self._close = None self._send = self._writer.send self._recv = self._reader.recv self._poll = self._reader.poll def put(self, obj, block=True, timeout=None): assert not self._closed if not self._sem.acquire(block, timeout): raise Full self._notempty.acquire() try: if self._thread is None: self._start_thread() self._buffer.append(obj) self._notempty.notify() finally: self._notempty.release() def get(self, block=True, timeout=None): if block and timeout is None: self._rlock.acquire() try: res = self._recv() self._sem.release() return res finally: self._rlock.release() else: if block: deadline = time.time() + timeout if not self._rlock.acquire(block, timeout): raise Empty try: if block: timeout = deadline - time.time() if timeout < 0 or not self._poll(timeout): raise Empty elif not self._poll(): raise Empty res = self._recv() self._sem.release() return res finally: self._rlock.release() def qsize(self): # Raises NotImplementedError on Mac OSX because of broken sem_getvalue() return self._maxsize - self._sem._semlock._get_value() def empty(self): return not self._poll() def full(self): return self._sem._semlock._is_zero() def get_nowait(self): return self.get(False) def put_nowait(self, obj): return self.put(obj, False) def close(self): self._closed = True self._reader.close() if self._close: self._close() def join_thread(self): debug('Queue.join_thread()') assert self._closed if self._jointhread: self._jointhread() def cancel_join_thread(self): debug('Queue.cancel_join_thread()') self._joincancelled = True try: self._jointhread.cancel() except AttributeError: pass def _start_thread(self): debug('Queue._start_thread()') # Start thread which transfers data from buffer to pipe self._buffer.clear() self._thread = threading.Thread( target=Queue._feed, args=(self._buffer, self._notempty, self._send, self._wlock, self._writer.close), name='QueueFeederThread' ) self._thread.daemon = True debug('doing self._thread.start()') self._thread.start() debug('... done self._thread.start()') # On process exit we will wait for data to be flushed to pipe. if not self._joincancelled: self._jointhread = Finalize( self._thread, Queue._finalize_join, [weakref.ref(self._thread)], exitpriority=-5 ) # Send sentinel to the thread queue object when garbage collected self._close = Finalize( self, Queue._finalize_close, [self._buffer, self._notempty], exitpriority=10 ) @staticmethod def _finalize_join(twr): debug('joining queue thread') thread = twr() if thread is not None: thread.join() debug('... queue thread joined') else: debug('... queue thread already dead') @staticmethod def _finalize_close(buffer, notempty): debug('telling queue thread to quit') notempty.acquire() try: buffer.append(_sentinel) notempty.notify() finally: notempty.release() @staticmethod def _feed(buffer, notempty, send, writelock, close): debug('starting thread to feed data to pipe') from .util import is_exiting nacquire = notempty.acquire nrelease = notempty.release nwait = notempty.wait bpopleft = buffer.popleft sentinel = _sentinel if sys.platform != 'win32': wacquire = writelock.acquire wrelease = writelock.release else: wacquire = None try: while 1: nacquire() try: if not buffer: nwait() finally: nrelease() try: while 1: obj = bpopleft() if obj is sentinel: debug('feeder thread got sentinel -- exiting') close() return if wacquire is None: send(obj) else: wacquire() try: send(obj) finally: wrelease() except IndexError: pass except Exception, e: # Since this runs in a daemon thread the resources it uses # may be become unusable while the process is cleaning up. # We ignore errors which happen after the process has # started to cleanup. try: if is_exiting(): info('error in queue thread: %s', e) else: import traceback traceback.print_exc() except Exception: pass _sentinel = object() # # A queue type which also supports join() and task_done() methods # # Note that if you do not call task_done() for each finished task then # eventually the counter's semaphore may overflow causing Bad Things # to happen. # class JoinableQueue(Queue): def __init__(self, maxsize=0): Queue.__init__(self, maxsize) self._unfinished_tasks = Semaphore(0) self._cond = Condition() def __getstate__(self): return Queue.__getstate__(self) + (self._cond, self._unfinished_tasks) def __setstate__(self, state): Queue.__setstate__(self, state[:-2]) self._cond, self._unfinished_tasks = state[-2:] def put(self, obj, block=True, timeout=None): assert not self._closed if not self._sem.acquire(block, timeout): raise Full self._notempty.acquire() self._cond.acquire() try: if self._thread is None: self._start_thread() self._buffer.append(obj) self._unfinished_tasks.release() self._notempty.notify() finally: self._cond.release() self._notempty.release() def task_done(self): self._cond.acquire() try: if not self._unfinished_tasks.acquire(False): raise ValueError('task_done() called too many times') if self._unfinished_tasks._semlock._is_zero(): self._cond.notify_all() finally: self._cond.release() def join(self): self._cond.acquire() try: if not self._unfinished_tasks._semlock._is_zero(): self._cond.wait() finally: self._cond.release() # # Simplified Queue type -- really just a locked pipe # class SimpleQueue(object): def __init__(self): self._reader, self._writer = Pipe(duplex=False) self._rlock = Lock() if sys.platform == 'win32': self._wlock = None else: self._wlock = Lock() self._make_methods() def empty(self): return not self._reader.poll() def __getstate__(self): assert_spawning(self) return (self._reader, self._writer, self._rlock, self._wlock) def __setstate__(self, state): (self._reader, self._writer, self._rlock, self._wlock) = state self._make_methods() def _make_methods(self): recv = self._reader.recv racquire, rrelease = self._rlock.acquire, self._rlock.release def get(): racquire() try: return recv() finally: rrelease() self.get = get if self._wlock is None: # writes to a message oriented win32 pipe are atomic self.put = self._writer.send else: send = self._writer.send wacquire, wrelease = self._wlock.acquire, self._wlock.release def put(obj): wacquire() try: return send(obj) finally: wrelease() self.put = put
gpl-2.0
sonnyhu/scikit-learn
examples/cluster/plot_birch_vs_minibatchkmeans.py
333
3694
""" ================================= Compare BIRCH and MiniBatchKMeans ================================= This example compares the timing of Birch (with and without the global clustering step) and MiniBatchKMeans on a synthetic dataset having 100,000 samples and 2 features generated using make_blobs. If ``n_clusters`` is set to None, the data is reduced from 100,000 samples to a set of 158 clusters. This can be viewed as a preprocessing step before the final (global) clustering step that further reduces these 158 clusters to 100 clusters. """ # Authors: Manoj Kumar <manojkumarsivaraj334@gmail.com # Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # License: BSD 3 clause print(__doc__) from itertools import cycle from time import time import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as colors from sklearn.preprocessing import StandardScaler from sklearn.cluster import Birch, MiniBatchKMeans from sklearn.datasets.samples_generator import make_blobs # Generate centers for the blobs so that it forms a 10 X 10 grid. xx = np.linspace(-22, 22, 10) yy = np.linspace(-22, 22, 10) xx, yy = np.meshgrid(xx, yy) n_centres = np.hstack((np.ravel(xx)[:, np.newaxis], np.ravel(yy)[:, np.newaxis])) # Generate blobs to do a comparison between MiniBatchKMeans and Birch. X, y = make_blobs(n_samples=100000, centers=n_centres, random_state=0) # Use all colors that matplotlib provides by default. colors_ = cycle(colors.cnames.keys()) fig = plt.figure(figsize=(12, 4)) fig.subplots_adjust(left=0.04, right=0.98, bottom=0.1, top=0.9) # Compute clustering with Birch with and without the final clustering step # and plot. birch_models = [Birch(threshold=1.7, n_clusters=None), Birch(threshold=1.7, n_clusters=100)] final_step = ['without global clustering', 'with global clustering'] for ind, (birch_model, info) in enumerate(zip(birch_models, final_step)): t = time() birch_model.fit(X) time_ = time() - t print("Birch %s as the final step took %0.2f seconds" % ( info, (time() - t))) # Plot result labels = birch_model.labels_ centroids = birch_model.subcluster_centers_ n_clusters = np.unique(labels).size print("n_clusters : %d" % n_clusters) ax = fig.add_subplot(1, 3, ind + 1) for this_centroid, k, col in zip(centroids, range(n_clusters), colors_): mask = labels == k ax.plot(X[mask, 0], X[mask, 1], 'w', markerfacecolor=col, marker='.') if birch_model.n_clusters is None: ax.plot(this_centroid[0], this_centroid[1], '+', markerfacecolor=col, markeredgecolor='k', markersize=5) ax.set_ylim([-25, 25]) ax.set_xlim([-25, 25]) ax.set_autoscaley_on(False) ax.set_title('Birch %s' % info) # Compute clustering with MiniBatchKMeans. mbk = MiniBatchKMeans(init='k-means++', n_clusters=100, batch_size=100, n_init=10, max_no_improvement=10, verbose=0, random_state=0) t0 = time() mbk.fit(X) t_mini_batch = time() - t0 print("Time taken to run MiniBatchKMeans %0.2f seconds" % t_mini_batch) mbk_means_labels_unique = np.unique(mbk.labels_) ax = fig.add_subplot(1, 3, 3) for this_centroid, k, col in zip(mbk.cluster_centers_, range(n_clusters), colors_): mask = mbk.labels_ == k ax.plot(X[mask, 0], X[mask, 1], 'w', markerfacecolor=col, marker='.') ax.plot(this_centroid[0], this_centroid[1], '+', markeredgecolor='k', markersize=5) ax.set_xlim([-25, 25]) ax.set_ylim([-25, 25]) ax.set_title("MiniBatchKMeans") ax.set_autoscaley_on(False) plt.show()
bsd-3-clause
ojengwa/oh-mainline
vendor/packages/twisted/twisted/protocols/ftp.py
18
93459
# -*- test-case-name: twisted.test.test_ftp -*- # Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """ An FTP protocol implementation @author: Itamar Shtull-Trauring @author: Jp Calderone @author: Andrew Bennetts """ # System Imports import os import time import re import operator import stat import errno import fnmatch import warnings try: import pwd, grp except ImportError: pwd = grp = None from zope.interface import Interface, implements # Twisted Imports from twisted import copyright from twisted.internet import reactor, interfaces, protocol, error, defer from twisted.protocols import basic, policies from twisted.python import log, failure, filepath from twisted.python.compat import reduce from twisted.cred import error as cred_error, portal, credentials, checkers # constants # response codes RESTART_MARKER_REPLY = "100" SERVICE_READY_IN_N_MINUTES = "120" DATA_CNX_ALREADY_OPEN_START_XFR = "125" FILE_STATUS_OK_OPEN_DATA_CNX = "150" CMD_OK = "200.1" TYPE_SET_OK = "200.2" ENTERING_PORT_MODE = "200.3" CMD_NOT_IMPLMNTD_SUPERFLUOUS = "202" SYS_STATUS_OR_HELP_REPLY = "211" DIR_STATUS = "212" FILE_STATUS = "213" HELP_MSG = "214" NAME_SYS_TYPE = "215" SVC_READY_FOR_NEW_USER = "220.1" WELCOME_MSG = "220.2" SVC_CLOSING_CTRL_CNX = "221" GOODBYE_MSG = "221" DATA_CNX_OPEN_NO_XFR_IN_PROGRESS = "225" CLOSING_DATA_CNX = "226" TXFR_COMPLETE_OK = "226" ENTERING_PASV_MODE = "227" ENTERING_EPSV_MODE = "229" USR_LOGGED_IN_PROCEED = "230.1" # v1 of code 230 GUEST_LOGGED_IN_PROCEED = "230.2" # v2 of code 230 REQ_FILE_ACTN_COMPLETED_OK = "250" PWD_REPLY = "257.1" MKD_REPLY = "257.2" USR_NAME_OK_NEED_PASS = "331.1" # v1 of Code 331 GUEST_NAME_OK_NEED_EMAIL = "331.2" # v2 of code 331 NEED_ACCT_FOR_LOGIN = "332" REQ_FILE_ACTN_PENDING_FURTHER_INFO = "350" SVC_NOT_AVAIL_CLOSING_CTRL_CNX = "421.1" TOO_MANY_CONNECTIONS = "421.2" CANT_OPEN_DATA_CNX = "425" CNX_CLOSED_TXFR_ABORTED = "426" REQ_ACTN_ABRTD_FILE_UNAVAIL = "450" REQ_ACTN_ABRTD_LOCAL_ERR = "451" REQ_ACTN_ABRTD_INSUFF_STORAGE = "452" SYNTAX_ERR = "500" SYNTAX_ERR_IN_ARGS = "501" CMD_NOT_IMPLMNTD = "502" BAD_CMD_SEQ = "503" CMD_NOT_IMPLMNTD_FOR_PARAM = "504" NOT_LOGGED_IN = "530.1" # v1 of code 530 - please log in AUTH_FAILURE = "530.2" # v2 of code 530 - authorization failure NEED_ACCT_FOR_STOR = "532" FILE_NOT_FOUND = "550.1" # no such file or directory PERMISSION_DENIED = "550.2" # permission denied ANON_USER_DENIED = "550.3" # anonymous users can't alter filesystem IS_NOT_A_DIR = "550.4" # rmd called on a path that is not a directory REQ_ACTN_NOT_TAKEN = "550.5" FILE_EXISTS = "550.6" IS_A_DIR = "550.7" PAGE_TYPE_UNK = "551" EXCEEDED_STORAGE_ALLOC = "552" FILENAME_NOT_ALLOWED = "553" RESPONSE = { # -- 100's -- RESTART_MARKER_REPLY: '110 MARK yyyy-mmmm', # TODO: this must be fixed SERVICE_READY_IN_N_MINUTES: '120 service ready in %s minutes', DATA_CNX_ALREADY_OPEN_START_XFR: '125 Data connection already open, starting transfer', FILE_STATUS_OK_OPEN_DATA_CNX: '150 File status okay; about to open data connection.', # -- 200's -- CMD_OK: '200 Command OK', TYPE_SET_OK: '200 Type set to %s.', ENTERING_PORT_MODE: '200 PORT OK', CMD_NOT_IMPLMNTD_SUPERFLUOUS: '202 Command not implemented, superfluous at this site', SYS_STATUS_OR_HELP_REPLY: '211 System status reply', DIR_STATUS: '212 %s', FILE_STATUS: '213 %s', HELP_MSG: '214 help: %s', NAME_SYS_TYPE: '215 UNIX Type: L8', WELCOME_MSG: "220 %s", SVC_READY_FOR_NEW_USER: '220 Service ready', GOODBYE_MSG: '221 Goodbye.', DATA_CNX_OPEN_NO_XFR_IN_PROGRESS: '225 data connection open, no transfer in progress', CLOSING_DATA_CNX: '226 Abort successful', TXFR_COMPLETE_OK: '226 Transfer Complete.', ENTERING_PASV_MODE: '227 Entering Passive Mode (%s).', ENTERING_EPSV_MODE: '229 Entering Extended Passive Mode (|||%s|).', # where is epsv defined in the rfc's? USR_LOGGED_IN_PROCEED: '230 User logged in, proceed', GUEST_LOGGED_IN_PROCEED: '230 Anonymous login ok, access restrictions apply.', REQ_FILE_ACTN_COMPLETED_OK: '250 Requested File Action Completed OK', #i.e. CWD completed ok PWD_REPLY: '257 "%s"', MKD_REPLY: '257 "%s" created', # -- 300's -- 'userotp': '331 Response to %s.', # ??? USR_NAME_OK_NEED_PASS: '331 Password required for %s.', GUEST_NAME_OK_NEED_EMAIL: '331 Guest login ok, type your email address as password.', REQ_FILE_ACTN_PENDING_FURTHER_INFO: '350 Requested file action pending further information.', # -- 400's -- SVC_NOT_AVAIL_CLOSING_CTRL_CNX: '421 Service not available, closing control connection.', TOO_MANY_CONNECTIONS: '421 Too many users right now, try again in a few minutes.', CANT_OPEN_DATA_CNX: "425 Can't open data connection.", CNX_CLOSED_TXFR_ABORTED: '426 Transfer aborted. Data connection closed.', REQ_ACTN_ABRTD_LOCAL_ERR: '451 Requested action aborted. Local error in processing.', # -- 500's -- SYNTAX_ERR: "500 Syntax error: %s", SYNTAX_ERR_IN_ARGS: '501 syntax error in argument(s) %s.', CMD_NOT_IMPLMNTD: "502 Command '%s' not implemented", BAD_CMD_SEQ: '503 Incorrect sequence of commands: %s', CMD_NOT_IMPLMNTD_FOR_PARAM: "504 Not implemented for parameter '%s'.", NOT_LOGGED_IN: '530 Please login with USER and PASS.', AUTH_FAILURE: '530 Sorry, Authentication failed.', NEED_ACCT_FOR_STOR: '532 Need an account for storing files', FILE_NOT_FOUND: '550 %s: No such file or directory.', PERMISSION_DENIED: '550 %s: Permission denied.', ANON_USER_DENIED: '550 Anonymous users are forbidden to change the filesystem', IS_NOT_A_DIR: '550 Cannot rmd, %s is not a directory', FILE_EXISTS: '550 %s: File exists', IS_A_DIR: '550 %s: is a directory', REQ_ACTN_NOT_TAKEN: '550 Requested action not taken: %s', EXCEEDED_STORAGE_ALLOC: '552 Requested file action aborted, exceeded file storage allocation', FILENAME_NOT_ALLOWED: '553 Requested action not taken, file name not allowed' } class InvalidPath(Exception): """ Internal exception used to signify an error during parsing a path. """ def toSegments(cwd, path): """ Normalize a path, as represented by a list of strings each representing one segment of the path. """ if path.startswith('/'): segs = [] else: segs = cwd[:] for s in path.split('/'): if s == '.' or s == '': continue elif s == '..': if segs: segs.pop() else: raise InvalidPath(cwd, path) elif '\0' in s or '/' in s: raise InvalidPath(cwd, path) else: segs.append(s) return segs def errnoToFailure(e, path): """ Map C{OSError} and C{IOError} to standard FTP errors. """ if e == errno.ENOENT: return defer.fail(FileNotFoundError(path)) elif e == errno.EACCES or e == errno.EPERM: return defer.fail(PermissionDeniedError(path)) elif e == errno.ENOTDIR: return defer.fail(IsNotADirectoryError(path)) elif e == errno.EEXIST: return defer.fail(FileExistsError(path)) elif e == errno.EISDIR: return defer.fail(IsADirectoryError(path)) else: return defer.fail() class FTPCmdError(Exception): """ Generic exception for FTP commands. """ def __init__(self, *msg): Exception.__init__(self, *msg) self.errorMessage = msg def response(self): """ Generate a FTP response message for this error. """ return RESPONSE[self.errorCode] % self.errorMessage class FileNotFoundError(FTPCmdError): """ Raised when trying to access a non existent file or directory. """ errorCode = FILE_NOT_FOUND class AnonUserDeniedError(FTPCmdError): """ Raised when an anonymous user issues a command that will alter the filesystem """ errorCode = ANON_USER_DENIED class PermissionDeniedError(FTPCmdError): """ Raised when access is attempted to a resource to which access is not allowed. """ errorCode = PERMISSION_DENIED class IsNotADirectoryError(FTPCmdError): """ Raised when RMD is called on a path that isn't a directory. """ errorCode = IS_NOT_A_DIR class FileExistsError(FTPCmdError): """ Raised when attempted to override an existing resource. """ errorCode = FILE_EXISTS class IsADirectoryError(FTPCmdError): """ Raised when DELE is called on a path that is a directory. """ errorCode = IS_A_DIR class CmdSyntaxError(FTPCmdError): """ Raised when a command syntax is wrong. """ errorCode = SYNTAX_ERR class CmdArgSyntaxError(FTPCmdError): """ Raised when a command is called with wrong value or a wrong number of arguments. """ errorCode = SYNTAX_ERR_IN_ARGS class CmdNotImplementedError(FTPCmdError): """ Raised when an unimplemented command is given to the server. """ errorCode = CMD_NOT_IMPLMNTD class CmdNotImplementedForArgError(FTPCmdError): """ Raised when the handling of a parameter for a command is not implemented by the server. """ errorCode = CMD_NOT_IMPLMNTD_FOR_PARAM class FTPError(Exception): pass class PortConnectionError(Exception): pass class BadCmdSequenceError(FTPCmdError): """ Raised when a client sends a series of commands in an illogical sequence. """ errorCode = BAD_CMD_SEQ class AuthorizationError(FTPCmdError): """ Raised when client authentication fails. """ errorCode = AUTH_FAILURE def debugDeferred(self, *_): log.msg('debugDeferred(): %s' % str(_), debug=True) # -- DTP Protocol -- _months = [ None, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] class DTP(object, protocol.Protocol): implements(interfaces.IConsumer) isConnected = False _cons = None _onConnLost = None _buffer = None def connectionMade(self): self.isConnected = True self.factory.deferred.callback(None) self._buffer = [] def connectionLost(self, reason): self.isConnected = False if self._onConnLost is not None: self._onConnLost.callback(None) def sendLine(self, line): self.transport.write(line + '\r\n') def _formatOneListResponse(self, name, size, directory, permissions, hardlinks, modified, owner, group): def formatMode(mode): return ''.join([mode & (256 >> n) and 'rwx'[n % 3] or '-' for n in range(9)]) def formatDate(mtime): now = time.gmtime() info = { 'month': _months[mtime.tm_mon], 'day': mtime.tm_mday, 'year': mtime.tm_year, 'hour': mtime.tm_hour, 'minute': mtime.tm_min } if now.tm_year != mtime.tm_year: return '%(month)s %(day)02d %(year)5d' % info else: return '%(month)s %(day)02d %(hour)02d:%(minute)02d' % info format = ('%(directory)s%(permissions)s%(hardlinks)4d ' '%(owner)-9s %(group)-9s %(size)15d %(date)12s ' '%(name)s') return format % { 'directory': directory and 'd' or '-', 'permissions': formatMode(permissions), 'hardlinks': hardlinks, 'owner': owner[:8], 'group': group[:8], 'size': size, 'date': formatDate(time.gmtime(modified)), 'name': name} def sendListResponse(self, name, response): self.sendLine(self._formatOneListResponse(name, *response)) # Proxy IConsumer to our transport def registerProducer(self, producer, streaming): return self.transport.registerProducer(producer, streaming) def unregisterProducer(self): self.transport.unregisterProducer() self.transport.loseConnection() def write(self, data): if self.isConnected: return self.transport.write(data) raise Exception("Crap damn crap damn crap damn") # Pretend to be a producer, too. def _conswrite(self, bytes): try: self._cons.write(bytes) except: self._onConnLost.errback() def dataReceived(self, bytes): if self._cons is not None: self._conswrite(bytes) else: self._buffer.append(bytes) def _unregConsumer(self, ignored): self._cons.unregisterProducer() self._cons = None del self._onConnLost return ignored def registerConsumer(self, cons): assert self._cons is None self._cons = cons self._cons.registerProducer(self, True) for chunk in self._buffer: self._conswrite(chunk) self._buffer = None if self.isConnected: self._onConnLost = d = defer.Deferred() d.addBoth(self._unregConsumer) return d else: self._cons.unregisterProducer() self._cons = None return defer.succeed(None) def resumeProducing(self): self.transport.resumeProducing() def pauseProducing(self): self.transport.pauseProducing() def stopProducing(self): self.transport.stopProducing() class DTPFactory(protocol.ClientFactory): """ Client factory for I{data transfer process} protocols. @ivar peerCheck: perform checks to make sure the ftp-pi's peer is the same as the dtp's @ivar pi: a reference to this factory's protocol interpreter @ivar _state: Indicates the current state of the DTPFactory. Initially, this is L{_IN_PROGRESS}. If the connection fails or times out, it is L{_FAILED}. If the connection succeeds before the timeout, it is L{_FINISHED}. """ _IN_PROGRESS = object() _FAILED = object() _FINISHED = object() _state = _IN_PROGRESS # -- configuration variables -- peerCheck = False # -- class variables -- def __init__(self, pi, peerHost=None, reactor=None): """Constructor @param pi: this factory's protocol interpreter @param peerHost: if peerCheck is True, this is the tuple that the generated instance will use to perform security checks """ self.pi = pi # the protocol interpreter that is using this factory self.peerHost = peerHost # the from FTP.transport.peerHost() self.deferred = defer.Deferred() # deferred will fire when instance is connected self.delayedCall = None if reactor is None: from twisted.internet import reactor self._reactor = reactor def buildProtocol(self, addr): log.msg('DTPFactory.buildProtocol', debug=True) if self._state is not self._IN_PROGRESS: return None self._state = self._FINISHED self.cancelTimeout() p = DTP() p.factory = self p.pi = self.pi self.pi.dtpInstance = p return p def stopFactory(self): log.msg('dtpFactory.stopFactory', debug=True) self.cancelTimeout() def timeoutFactory(self): log.msg('timed out waiting for DTP connection') if self._state is not self._IN_PROGRESS: return self._state = self._FAILED d = self.deferred self.deferred = None d.errback( PortConnectionError(defer.TimeoutError("DTPFactory timeout"))) def cancelTimeout(self): if self.delayedCall is not None and self.delayedCall.active(): log.msg('cancelling DTP timeout', debug=True) self.delayedCall.cancel() def setTimeout(self, seconds): log.msg('DTPFactory.setTimeout set to %s seconds' % seconds) self.delayedCall = self._reactor.callLater(seconds, self.timeoutFactory) def clientConnectionFailed(self, connector, reason): if self._state is not self._IN_PROGRESS: return self._state = self._FAILED d = self.deferred self.deferred = None d.errback(PortConnectionError(reason)) # -- FTP-PI (Protocol Interpreter) -- class ASCIIConsumerWrapper(object): def __init__(self, cons): self.cons = cons self.registerProducer = cons.registerProducer self.unregisterProducer = cons.unregisterProducer assert os.linesep == "\r\n" or len(os.linesep) == 1, "Unsupported platform (yea right like this even exists)" if os.linesep == "\r\n": self.write = cons.write def write(self, bytes): return self.cons.write(bytes.replace(os.linesep, "\r\n")) class FileConsumer(object): """ A consumer for FTP input that writes data to a file. @ivar fObj: a file object opened for writing, used to write data received. @type fObj: C{file} """ implements(interfaces.IConsumer) def __init__(self, fObj): self.fObj = fObj def registerProducer(self, producer, streaming): self.producer = producer assert streaming def unregisterProducer(self): self.producer = None self.fObj.close() def write(self, bytes): self.fObj.write(bytes) class FTPOverflowProtocol(basic.LineReceiver): """FTP mini-protocol for when there are too many connections.""" def connectionMade(self): self.sendLine(RESPONSE[TOO_MANY_CONNECTIONS]) self.transport.loseConnection() class FTP(object, basic.LineReceiver, policies.TimeoutMixin): """ Protocol Interpreter for the File Transfer Protocol @ivar state: The current server state. One of L{UNAUTH}, L{INAUTH}, L{AUTHED}, L{RENAMING}. @ivar shell: The connected avatar @ivar binary: The transfer mode. If false, ASCII. @ivar dtpFactory: Generates a single DTP for this session @ivar dtpPort: Port returned from listenTCP @ivar listenFactory: A callable with the signature of L{twisted.internet.interfaces.IReactorTCP.listenTCP} which will be used to create Ports for passive connections (mainly for testing). @ivar passivePortRange: iterator used as source of passive port numbers. @type passivePortRange: C{iterator} """ disconnected = False # States an FTP can be in UNAUTH, INAUTH, AUTHED, RENAMING = range(4) # how long the DTP waits for a connection dtpTimeout = 10 portal = None shell = None dtpFactory = None dtpPort = None dtpInstance = None binary = True passivePortRange = xrange(0, 1) listenFactory = reactor.listenTCP def reply(self, key, *args): msg = RESPONSE[key] % args self.sendLine(msg) def connectionMade(self): self.state = self.UNAUTH self.setTimeout(self.timeOut) self.reply(WELCOME_MSG, self.factory.welcomeMessage) def connectionLost(self, reason): # if we have a DTP protocol instance running and # we lose connection to the client's PI, kill the # DTP connection and close the port if self.dtpFactory: self.cleanupDTP() self.setTimeout(None) if hasattr(self.shell, 'logout') and self.shell.logout is not None: self.shell.logout() self.shell = None self.transport = None def timeoutConnection(self): self.transport.loseConnection() def lineReceived(self, line): self.resetTimeout() self.pauseProducing() def processFailed(err): if err.check(FTPCmdError): self.sendLine(err.value.response()) elif (err.check(TypeError) and err.value.args[0].find('takes exactly') != -1): self.reply(SYNTAX_ERR, "%s requires an argument." % (cmd,)) else: log.msg("Unexpected FTP error") log.err(err) self.reply(REQ_ACTN_NOT_TAKEN, "internal server error") def processSucceeded(result): if isinstance(result, tuple): self.reply(*result) elif result is not None: self.reply(result) def allDone(ignored): if not self.disconnected: self.resumeProducing() spaceIndex = line.find(' ') if spaceIndex != -1: cmd = line[:spaceIndex] args = (line[spaceIndex + 1:],) else: cmd = line args = () d = defer.maybeDeferred(self.processCommand, cmd, *args) d.addCallbacks(processSucceeded, processFailed) d.addErrback(log.err) # XXX It burnsss # LineReceiver doesn't let you resumeProducing inside # lineReceived atm from twisted.internet import reactor reactor.callLater(0, d.addBoth, allDone) def processCommand(self, cmd, *params): cmd = cmd.upper() if self.state == self.UNAUTH: if cmd == 'USER': return self.ftp_USER(*params) elif cmd == 'PASS': return BAD_CMD_SEQ, "USER required before PASS" else: return NOT_LOGGED_IN elif self.state == self.INAUTH: if cmd == 'PASS': return self.ftp_PASS(*params) else: return BAD_CMD_SEQ, "PASS required after USER" elif self.state == self.AUTHED: method = getattr(self, "ftp_" + cmd, None) if method is not None: return method(*params) return defer.fail(CmdNotImplementedError(cmd)) elif self.state == self.RENAMING: if cmd == 'RNTO': return self.ftp_RNTO(*params) else: return BAD_CMD_SEQ, "RNTO required after RNFR" def getDTPPort(self, factory): """ Return a port for passive access, using C{self.passivePortRange} attribute. """ for portn in self.passivePortRange: try: dtpPort = self.listenFactory(portn, factory) except error.CannotListenError: continue else: return dtpPort raise error.CannotListenError('', portn, "No port available in range %s" % (self.passivePortRange,)) def ftp_USER(self, username): """ First part of login. Get the username the peer wants to authenticate as. """ if not username: return defer.fail(CmdSyntaxError('USER requires an argument')) self._user = username self.state = self.INAUTH if self.factory.allowAnonymous and self._user == self.factory.userAnonymous: return GUEST_NAME_OK_NEED_EMAIL else: return (USR_NAME_OK_NEED_PASS, username) # TODO: add max auth try before timeout from ip... # TODO: need to implement minimal ABOR command def ftp_PASS(self, password): """ Second part of login. Get the password the peer wants to authenticate with. """ if self.factory.allowAnonymous and self._user == self.factory.userAnonymous: # anonymous login creds = credentials.Anonymous() reply = GUEST_LOGGED_IN_PROCEED else: # user login creds = credentials.UsernamePassword(self._user, password) reply = USR_LOGGED_IN_PROCEED del self._user def _cbLogin((interface, avatar, logout)): assert interface is IFTPShell, "The realm is busted, jerk." self.shell = avatar self.logout = logout self.workingDirectory = [] self.state = self.AUTHED return reply def _ebLogin(failure): failure.trap(cred_error.UnauthorizedLogin, cred_error.UnhandledCredentials) self.state = self.UNAUTH raise AuthorizationError d = self.portal.login(creds, None, IFTPShell) d.addCallbacks(_cbLogin, _ebLogin) return d def ftp_PASV(self): """Request for a passive connection from the rfc:: This command requests the server-DTP to \"listen\" on a data port (which is not its default data port) and to wait for a connection rather than initiate one upon receipt of a transfer command. The response to this command includes the host and port address this server is listening on. """ # if we have a DTP port set up, lose it. if self.dtpFactory is not None: # cleanupDTP sets dtpFactory to none. Later we'll do # cleanup here or something. self.cleanupDTP() self.dtpFactory = DTPFactory(pi=self) self.dtpFactory.setTimeout(self.dtpTimeout) self.dtpPort = self.getDTPPort(self.dtpFactory) host = self.transport.getHost().host port = self.dtpPort.getHost().port self.reply(ENTERING_PASV_MODE, encodeHostPort(host, port)) return self.dtpFactory.deferred.addCallback(lambda ign: None) def ftp_PORT(self, address): addr = map(int, address.split(',')) ip = '%d.%d.%d.%d' % tuple(addr[:4]) port = addr[4] << 8 | addr[5] # if we have a DTP port set up, lose it. if self.dtpFactory is not None: self.cleanupDTP() self.dtpFactory = DTPFactory(pi=self, peerHost=self.transport.getPeer().host) self.dtpFactory.setTimeout(self.dtpTimeout) self.dtpPort = reactor.connectTCP(ip, port, self.dtpFactory) def connected(ignored): return ENTERING_PORT_MODE def connFailed(err): err.trap(PortConnectionError) return CANT_OPEN_DATA_CNX return self.dtpFactory.deferred.addCallbacks(connected, connFailed) def ftp_LIST(self, path=''): """ This command causes a list to be sent from the server to the passive DTP. If the pathname specifies a directory or other group of files, the server should transfer a list of files in the specified directory. If the pathname specifies a file then the server should send current information on the file. A null argument implies the user's current working or default directory. """ # Uh, for now, do this retarded thing. if self.dtpInstance is None or not self.dtpInstance.isConnected: return defer.fail(BadCmdSequenceError('must send PORT or PASV before RETR')) # bug in konqueror if path == "-a": path = '' # bug in gFTP 2.0.15 if path == "-aL": path = '' # bug in Nautilus 2.10.0 if path == "-L": path = '' # bug in ange-ftp if path == "-la": path = '' def gotListing(results): self.reply(DATA_CNX_ALREADY_OPEN_START_XFR) for (name, attrs) in results: self.dtpInstance.sendListResponse(name, attrs) self.dtpInstance.transport.loseConnection() return (TXFR_COMPLETE_OK,) try: segments = toSegments(self.workingDirectory, path) except InvalidPath: return defer.fail(FileNotFoundError(path)) d = self.shell.list( segments, ('size', 'directory', 'permissions', 'hardlinks', 'modified', 'owner', 'group')) d.addCallback(gotListing) return d def ftp_NLST(self, path): """ This command causes a directory listing to be sent from the server to the client. The pathname should specify a directory or other system-specific file group descriptor. An empty path implies the current working directory. If the path is non-existent, send nothing. If the path is to a file, send only the file name. @type path: C{str} @param path: The path for which a directory listing should be returned. @rtype: L{Deferred} @return: a L{Deferred} which will be fired when the listing request is finished. """ # XXX: why is this check different from ftp_RETR/ftp_STOR? See #4180 if self.dtpInstance is None or not self.dtpInstance.isConnected: return defer.fail( BadCmdSequenceError('must send PORT or PASV before RETR')) try: segments = toSegments(self.workingDirectory, path) except InvalidPath: return defer.fail(FileNotFoundError(path)) def cbList(results): """ Send, line by line, each file in the directory listing, and then close the connection. @type results: A C{list} of C{tuple}. The first element of each C{tuple} is a C{str} and the second element is a C{list}. @param results: The names of the files in the directory. @rtype: C{tuple} @return: A C{tuple} containing the status code for a successful transfer. """ self.reply(DATA_CNX_ALREADY_OPEN_START_XFR) for (name, ignored) in results: self.dtpInstance.sendLine(name) self.dtpInstance.transport.loseConnection() return (TXFR_COMPLETE_OK,) def cbGlob(results): self.reply(DATA_CNX_ALREADY_OPEN_START_XFR) for (name, ignored) in results: if fnmatch.fnmatch(name, segments[-1]): self.dtpInstance.sendLine(name) self.dtpInstance.transport.loseConnection() return (TXFR_COMPLETE_OK,) def listErr(results): """ RFC 959 specifies that an NLST request may only return directory listings. Thus, send nothing and just close the connection. @type results: L{Failure} @param results: The L{Failure} wrapping a L{FileNotFoundError} that occurred while trying to list the contents of a nonexistent directory. @rtype: C{tuple} @returns: A C{tuple} containing the status code for a successful transfer. """ self.dtpInstance.transport.loseConnection() return (TXFR_COMPLETE_OK,) # XXX This globbing may be incomplete: see #4181 if segments and ( '*' in segments[-1] or '?' in segments[-1] or ('[' in segments[-1] and ']' in segments[-1])): d = self.shell.list(segments[:-1]) d.addCallback(cbGlob) else: d = self.shell.list(segments) d.addCallback(cbList) # self.shell.list will generate an error if the path is invalid d.addErrback(listErr) return d def ftp_CWD(self, path): try: segments = toSegments(self.workingDirectory, path) except InvalidPath: # XXX Eh, what to fail with here? return defer.fail(FileNotFoundError(path)) def accessGranted(result): self.workingDirectory = segments return (REQ_FILE_ACTN_COMPLETED_OK,) return self.shell.access(segments).addCallback(accessGranted) def ftp_CDUP(self): return self.ftp_CWD('..') def ftp_PWD(self): return (PWD_REPLY, '/' + '/'.join(self.workingDirectory)) def ftp_RETR(self, path): if self.dtpInstance is None: raise BadCmdSequenceError('PORT or PASV required before RETR') try: newsegs = toSegments(self.workingDirectory, path) except InvalidPath: return defer.fail(FileNotFoundError(path)) # XXX For now, just disable the timeout. Later we'll want to # leave it active and have the DTP connection reset it # periodically. self.setTimeout(None) # Put it back later def enableTimeout(result): self.setTimeout(self.factory.timeOut) return result # And away she goes if not self.binary: cons = ASCIIConsumerWrapper(self.dtpInstance) else: cons = self.dtpInstance def cbSent(result): return (TXFR_COMPLETE_OK,) def ebSent(err): log.msg("Unexpected error attempting to transmit file to client:") log.err(err) return (CNX_CLOSED_TXFR_ABORTED,) def cbOpened(file): # Tell them what to doooo if self.dtpInstance.isConnected: self.reply(DATA_CNX_ALREADY_OPEN_START_XFR) else: self.reply(FILE_STATUS_OK_OPEN_DATA_CNX) d = file.send(cons) d.addCallbacks(cbSent, ebSent) return d def ebOpened(err): if not err.check(PermissionDeniedError, FileNotFoundError, IsNotADirectoryError): log.msg("Unexpected error attempting to open file for transmission:") log.err(err) if err.check(FTPCmdError): return (err.value.errorCode, '/'.join(newsegs)) return (FILE_NOT_FOUND, '/'.join(newsegs)) d = self.shell.openForReading(newsegs) d.addCallbacks(cbOpened, ebOpened) d.addBoth(enableTimeout) # Pass back Deferred that fires when the transfer is done return d def ftp_STOR(self, path): if self.dtpInstance is None: raise BadCmdSequenceError('PORT or PASV required before STOR') try: newsegs = toSegments(self.workingDirectory, path) except InvalidPath: return defer.fail(FileNotFoundError(path)) # XXX For now, just disable the timeout. Later we'll want to # leave it active and have the DTP connection reset it # periodically. self.setTimeout(None) # Put it back later def enableTimeout(result): self.setTimeout(self.factory.timeOut) return result def cbSent(result): return (TXFR_COMPLETE_OK,) def ebSent(err): log.msg("Unexpected error receiving file from client:") log.err(err) if err.check(FTPCmdError): return err return (CNX_CLOSED_TXFR_ABORTED,) def cbConsumer(cons): if not self.binary: cons = ASCIIConsumerWrapper(cons) d = self.dtpInstance.registerConsumer(cons) # Tell them what to doooo if self.dtpInstance.isConnected: self.reply(DATA_CNX_ALREADY_OPEN_START_XFR) else: self.reply(FILE_STATUS_OK_OPEN_DATA_CNX) return d def cbOpened(file): d = file.receive() d.addCallback(cbConsumer) d.addCallback(lambda ignored: file.close()) d.addCallbacks(cbSent, ebSent) return d def ebOpened(err): if not err.check(PermissionDeniedError, FileNotFoundError, IsNotADirectoryError): log.msg("Unexpected error attempting to open file for upload:") log.err(err) if isinstance(err.value, FTPCmdError): return (err.value.errorCode, '/'.join(newsegs)) return (FILE_NOT_FOUND, '/'.join(newsegs)) d = self.shell.openForWriting(newsegs) d.addCallbacks(cbOpened, ebOpened) d.addBoth(enableTimeout) # Pass back Deferred that fires when the transfer is done return d def ftp_SIZE(self, path): try: newsegs = toSegments(self.workingDirectory, path) except InvalidPath: return defer.fail(FileNotFoundError(path)) def cbStat((size,)): return (FILE_STATUS, str(size)) return self.shell.stat(newsegs, ('size',)).addCallback(cbStat) def ftp_MDTM(self, path): try: newsegs = toSegments(self.workingDirectory, path) except InvalidPath: return defer.fail(FileNotFoundError(path)) def cbStat((modified,)): return (FILE_STATUS, time.strftime('%Y%m%d%H%M%S', time.gmtime(modified))) return self.shell.stat(newsegs, ('modified',)).addCallback(cbStat) def ftp_TYPE(self, type): p = type.upper() if p: f = getattr(self, 'type_' + p[0], None) if f is not None: return f(p[1:]) return self.type_UNKNOWN(p) return (SYNTAX_ERR,) def type_A(self, code): if code == '' or code == 'N': self.binary = False return (TYPE_SET_OK, 'A' + code) else: return defer.fail(CmdArgSyntaxError(code)) def type_I(self, code): if code == '': self.binary = True return (TYPE_SET_OK, 'I') else: return defer.fail(CmdArgSyntaxError(code)) def type_UNKNOWN(self, code): return defer.fail(CmdNotImplementedForArgError(code)) def ftp_SYST(self): return NAME_SYS_TYPE def ftp_STRU(self, structure): p = structure.upper() if p == 'F': return (CMD_OK,) return defer.fail(CmdNotImplementedForArgError(structure)) def ftp_MODE(self, mode): p = mode.upper() if p == 'S': return (CMD_OK,) return defer.fail(CmdNotImplementedForArgError(mode)) def ftp_MKD(self, path): try: newsegs = toSegments(self.workingDirectory, path) except InvalidPath: return defer.fail(FileNotFoundError(path)) return self.shell.makeDirectory(newsegs).addCallback(lambda ign: (MKD_REPLY, path)) def ftp_RMD(self, path): try: newsegs = toSegments(self.workingDirectory, path) except InvalidPath: return defer.fail(FileNotFoundError(path)) return self.shell.removeDirectory(newsegs).addCallback(lambda ign: (REQ_FILE_ACTN_COMPLETED_OK,)) def ftp_DELE(self, path): try: newsegs = toSegments(self.workingDirectory, path) except InvalidPath: return defer.fail(FileNotFoundError(path)) return self.shell.removeFile(newsegs).addCallback(lambda ign: (REQ_FILE_ACTN_COMPLETED_OK,)) def ftp_NOOP(self): return (CMD_OK,) def ftp_RNFR(self, fromName): self._fromName = fromName self.state = self.RENAMING return (REQ_FILE_ACTN_PENDING_FURTHER_INFO,) def ftp_RNTO(self, toName): fromName = self._fromName del self._fromName self.state = self.AUTHED try: fromsegs = toSegments(self.workingDirectory, fromName) tosegs = toSegments(self.workingDirectory, toName) except InvalidPath: return defer.fail(FileNotFoundError(fromName)) return self.shell.rename(fromsegs, tosegs).addCallback(lambda ign: (REQ_FILE_ACTN_COMPLETED_OK,)) def ftp_QUIT(self): self.reply(GOODBYE_MSG) self.transport.loseConnection() self.disconnected = True def cleanupDTP(self): """call when DTP connection exits """ log.msg('cleanupDTP', debug=True) log.msg(self.dtpPort) dtpPort, self.dtpPort = self.dtpPort, None if interfaces.IListeningPort.providedBy(dtpPort): dtpPort.stopListening() elif interfaces.IConnector.providedBy(dtpPort): dtpPort.disconnect() else: assert False, "dtpPort should be an IListeningPort or IConnector, instead is %r" % (dtpPort,) self.dtpFactory.stopFactory() self.dtpFactory = None if self.dtpInstance is not None: self.dtpInstance = None class FTPFactory(policies.LimitTotalConnectionsFactory): """ A factory for producing ftp protocol instances @ivar timeOut: the protocol interpreter's idle timeout time in seconds, default is 600 seconds. @ivar passivePortRange: value forwarded to C{protocol.passivePortRange}. @type passivePortRange: C{iterator} """ protocol = FTP overflowProtocol = FTPOverflowProtocol allowAnonymous = True userAnonymous = 'anonymous' timeOut = 600 welcomeMessage = "Twisted %s FTP Server" % (copyright.version,) passivePortRange = xrange(0, 1) def __init__(self, portal=None, userAnonymous='anonymous'): self.portal = portal self.userAnonymous = userAnonymous self.instances = [] def buildProtocol(self, addr): p = policies.LimitTotalConnectionsFactory.buildProtocol(self, addr) if p is not None: p.wrappedProtocol.portal = self.portal p.wrappedProtocol.timeOut = self.timeOut p.wrappedProtocol.passivePortRange = self.passivePortRange return p def stopFactory(self): # make sure ftp instance's timeouts are set to None # to avoid reactor complaints [p.setTimeout(None) for p in self.instances if p.timeOut is not None] policies.LimitTotalConnectionsFactory.stopFactory(self) # -- Cred Objects -- class IFTPShell(Interface): """ An abstraction of the shell commands used by the FTP protocol for a given user account. All path names must be absolute. """ def makeDirectory(path): """ Create a directory. @param path: The path, as a list of segments, to create @type path: C{list} of C{unicode} @return: A Deferred which fires when the directory has been created, or which fails if the directory cannot be created. """ def removeDirectory(path): """ Remove a directory. @param path: The path, as a list of segments, to remove @type path: C{list} of C{unicode} @return: A Deferred which fires when the directory has been removed, or which fails if the directory cannot be removed. """ def removeFile(path): """ Remove a file. @param path: The path, as a list of segments, to remove @type path: C{list} of C{unicode} @return: A Deferred which fires when the file has been removed, or which fails if the file cannot be removed. """ def rename(fromPath, toPath): """ Rename a file or directory. @param fromPath: The current name of the path. @type fromPath: C{list} of C{unicode} @param toPath: The desired new name of the path. @type toPath: C{list} of C{unicode} @return: A Deferred which fires when the path has been renamed, or which fails if the path cannot be renamed. """ def access(path): """ Determine whether access to the given path is allowed. @param path: The path, as a list of segments @return: A Deferred which fires with None if access is allowed or which fails with a specific exception type if access is denied. """ def stat(path, keys=()): """ Retrieve information about the given path. This is like list, except it will never return results about child paths. """ def list(path, keys=()): """ Retrieve information about the given path. If the path represents a non-directory, the result list should have only one entry with information about that non-directory. Otherwise, the result list should have an element for each child of the directory. @param path: The path, as a list of segments, to list @type path: C{list} of C{unicode} @param keys: A tuple of keys desired in the resulting dictionaries. @return: A Deferred which fires with a list of (name, list), where the name is the name of the entry as a unicode string and each list contains values corresponding to the requested keys. The following are possible elements of keys, and the values which should be returned for them: - C{'size'}: size in bytes, as an integer (this is kinda required) - C{'directory'}: boolean indicating the type of this entry - C{'permissions'}: a bitvector (see os.stat(foo).st_mode) - C{'hardlinks'}: Number of hard links to this entry - C{'modified'}: number of seconds since the epoch since entry was modified - C{'owner'}: string indicating the user owner of this entry - C{'group'}: string indicating the group owner of this entry """ def openForReading(path): """ @param path: The path, as a list of segments, to open @type path: C{list} of C{unicode} @rtype: C{Deferred} which will fire with L{IReadFile} """ def openForWriting(path): """ @param path: The path, as a list of segments, to open @type path: C{list} of C{unicode} @rtype: C{Deferred} which will fire with L{IWriteFile} """ class IReadFile(Interface): """ A file out of which bytes may be read. """ def send(consumer): """ Produce the contents of the given path to the given consumer. This method may only be invoked once on each provider. @type consumer: C{IConsumer} @return: A Deferred which fires when the file has been consumed completely. """ class IWriteFile(Interface): """ A file into which bytes may be written. """ def receive(): """ Create a consumer which will write to this file. This method may only be invoked once on each provider. @rtype: C{Deferred} of C{IConsumer} """ def close(): """ Perform any post-write work that needs to be done. This method may only be invoked once on each provider, and will always be invoked after receive(). @rtype: C{Deferred} of anything: the value is ignored. The FTP client will not see their upload request complete until this Deferred has been fired. """ def _getgroups(uid): """Return the primary and supplementary groups for the given UID. @type uid: C{int} """ result = [] pwent = pwd.getpwuid(uid) result.append(pwent.pw_gid) for grent in grp.getgrall(): if pwent.pw_name in grent.gr_mem: result.append(grent.gr_gid) return result def _testPermissions(uid, gid, spath, mode='r'): """ checks to see if uid has proper permissions to access path with mode @type uid: C{int} @param uid: numeric user id @type gid: C{int} @param gid: numeric group id @type spath: C{str} @param spath: the path on the server to test @type mode: C{str} @param mode: 'r' or 'w' (read or write) @rtype: C{bool} @return: True if the given credentials have the specified form of access to the given path """ if mode == 'r': usr = stat.S_IRUSR grp = stat.S_IRGRP oth = stat.S_IROTH amode = os.R_OK elif mode == 'w': usr = stat.S_IWUSR grp = stat.S_IWGRP oth = stat.S_IWOTH amode = os.W_OK else: raise ValueError("Invalid mode %r: must specify 'r' or 'w'" % (mode,)) access = False if os.path.exists(spath): if uid == 0: access = True else: s = os.stat(spath) if usr & s.st_mode and uid == s.st_uid: access = True elif grp & s.st_mode and gid in _getgroups(uid): access = True elif oth & s.st_mode: access = True if access: if not os.access(spath, amode): access = False log.msg("Filesystem grants permission to UID %d but it is inaccessible to me running as UID %d" % ( uid, os.getuid())) return access class FTPAnonymousShell(object): """ An anonymous implementation of IFTPShell @type filesystemRoot: L{twisted.python.filepath.FilePath} @ivar filesystemRoot: The path which is considered the root of this shell. """ implements(IFTPShell) def __init__(self, filesystemRoot): self.filesystemRoot = filesystemRoot def _path(self, path): return reduce(filepath.FilePath.child, path, self.filesystemRoot) def makeDirectory(self, path): return defer.fail(AnonUserDeniedError()) def removeDirectory(self, path): return defer.fail(AnonUserDeniedError()) def removeFile(self, path): return defer.fail(AnonUserDeniedError()) def rename(self, fromPath, toPath): return defer.fail(AnonUserDeniedError()) def receive(self, path): path = self._path(path) return defer.fail(AnonUserDeniedError()) def openForReading(self, path): """ Open C{path} for reading. @param path: The path, as a list of segments, to open. @type path: C{list} of C{unicode} @return: A L{Deferred} is returned that will fire with an object implementing L{IReadFile} if the file is successfully opened. If C{path} is a directory, or if an exception is raised while trying to open the file, the L{Deferred} will fire with an error. """ p = self._path(path) if p.isdir(): # Normally, we would only check for EISDIR in open, but win32 # returns EACCES in this case, so we check before return defer.fail(IsADirectoryError(path)) try: f = p.open('r') except (IOError, OSError), e: return errnoToFailure(e.errno, path) except: return defer.fail() else: return defer.succeed(_FileReader(f)) def openForWriting(self, path): """ Reject write attempts by anonymous users with L{PermissionDeniedError}. """ return defer.fail(PermissionDeniedError("STOR not allowed")) def access(self, path): p = self._path(path) if not p.exists(): # Again, win32 doesn't report a sane error after, so let's fail # early if we can return defer.fail(FileNotFoundError(path)) # For now, just see if we can os.listdir() it try: p.listdir() except (IOError, OSError), e: return errnoToFailure(e.errno, path) except: return defer.fail() else: return defer.succeed(None) def stat(self, path, keys=()): p = self._path(path) if p.isdir(): try: statResult = self._statNode(p, keys) except (IOError, OSError), e: return errnoToFailure(e.errno, path) except: return defer.fail() else: return defer.succeed(statResult) else: return self.list(path, keys).addCallback(lambda res: res[0][1]) def list(self, path, keys=()): """ Return the list of files at given C{path}, adding C{keys} stat informations if specified. @param path: the directory or file to check. @type path: C{str} @param keys: the list of desired metadata @type keys: C{list} of C{str} """ filePath = self._path(path) if filePath.isdir(): entries = filePath.listdir() fileEntries = [filePath.child(p) for p in entries] elif filePath.isfile(): entries = [os.path.join(*filePath.segmentsFrom(self.filesystemRoot))] fileEntries = [filePath] else: return defer.fail(FileNotFoundError(path)) results = [] for fileName, filePath in zip(entries, fileEntries): ent = [] results.append((fileName, ent)) if keys: try: ent.extend(self._statNode(filePath, keys)) except (IOError, OSError), e: return errnoToFailure(e.errno, fileName) except: return defer.fail() return defer.succeed(results) def _statNode(self, filePath, keys): """ Shortcut method to get stat info on a node. @param filePath: the node to stat. @type filePath: C{filepath.FilePath} @param keys: the stat keys to get. @type keys: C{iterable} """ filePath.restat() return [getattr(self, '_stat_' + k)(filePath.statinfo) for k in keys] _stat_size = operator.attrgetter('st_size') _stat_permissions = operator.attrgetter('st_mode') _stat_hardlinks = operator.attrgetter('st_nlink') _stat_modified = operator.attrgetter('st_mtime') def _stat_owner(self, st): if pwd is not None: try: return pwd.getpwuid(st.st_uid)[0] except KeyError: pass return str(st.st_uid) def _stat_group(self, st): if grp is not None: try: return grp.getgrgid(st.st_gid)[0] except KeyError: pass return str(st.st_gid) def _stat_directory(self, st): return bool(st.st_mode & stat.S_IFDIR) class _FileReader(object): implements(IReadFile) def __init__(self, fObj): self.fObj = fObj self._send = False def _close(self, passthrough): self._send = True self.fObj.close() return passthrough def send(self, consumer): assert not self._send, "Can only call IReadFile.send *once* per instance" self._send = True d = basic.FileSender().beginFileTransfer(self.fObj, consumer) d.addBoth(self._close) return d class FTPShell(FTPAnonymousShell): """ An authenticated implementation of L{IFTPShell}. """ def makeDirectory(self, path): p = self._path(path) try: p.makedirs() except (IOError, OSError), e: return errnoToFailure(e.errno, path) except: return defer.fail() else: return defer.succeed(None) def removeDirectory(self, path): p = self._path(path) if p.isfile(): # Win32 returns the wrong errno when rmdir is called on a file # instead of a directory, so as we have the info here, let's fail # early with a pertinent error return defer.fail(IsNotADirectoryError(path)) try: os.rmdir(p.path) except (IOError, OSError), e: return errnoToFailure(e.errno, path) except: return defer.fail() else: return defer.succeed(None) def removeFile(self, path): p = self._path(path) if p.isdir(): # Win32 returns the wrong errno when remove is called on a # directory instead of a file, so as we have the info here, # let's fail early with a pertinent error return defer.fail(IsADirectoryError(path)) try: p.remove() except (IOError, OSError), e: return errnoToFailure(e.errno, path) except: return defer.fail() else: return defer.succeed(None) def rename(self, fromPath, toPath): fp = self._path(fromPath) tp = self._path(toPath) try: os.rename(fp.path, tp.path) except (IOError, OSError), e: return errnoToFailure(e.errno, fromPath) except: return defer.fail() else: return defer.succeed(None) def openForWriting(self, path): """ Open C{path} for writing. @param path: The path, as a list of segments, to open. @type path: C{list} of C{unicode} @return: A L{Deferred} is returned that will fire with an object implementing L{IWriteFile} if the file is successfully opened. If C{path} is a directory, or if an exception is raised while trying to open the file, the L{Deferred} will fire with an error. """ p = self._path(path) if p.isdir(): # Normally, we would only check for EISDIR in open, but win32 # returns EACCES in this case, so we check before return defer.fail(IsADirectoryError(path)) try: fObj = p.open('w') except (IOError, OSError), e: return errnoToFailure(e.errno, path) except: return defer.fail() return defer.succeed(_FileWriter(fObj)) class _FileWriter(object): implements(IWriteFile) def __init__(self, fObj): self.fObj = fObj self._receive = False def receive(self): assert not self._receive, "Can only call IWriteFile.receive *once* per instance" self._receive = True # FileConsumer will close the file object return defer.succeed(FileConsumer(self.fObj)) def close(self): return defer.succeed(None) class BaseFTPRealm: """ Base class for simple FTP realms which provides an easy hook for specifying the home directory for each user. """ implements(portal.IRealm) def __init__(self, anonymousRoot): self.anonymousRoot = filepath.FilePath(anonymousRoot) def getHomeDirectory(self, avatarId): """ Return a L{FilePath} representing the home directory of the given avatar. Override this in a subclass. @param avatarId: A user identifier returned from a credentials checker. @type avatarId: C{str} @rtype: L{FilePath} """ raise NotImplementedError( "%r did not override getHomeDirectory" % (self.__class__,)) def requestAvatar(self, avatarId, mind, *interfaces): for iface in interfaces: if iface is IFTPShell: if avatarId is checkers.ANONYMOUS: avatar = FTPAnonymousShell(self.anonymousRoot) else: avatar = FTPShell(self.getHomeDirectory(avatarId)) return (IFTPShell, avatar, getattr(avatar, 'logout', lambda: None)) raise NotImplementedError( "Only IFTPShell interface is supported by this realm") class FTPRealm(BaseFTPRealm): """ @type anonymousRoot: L{twisted.python.filepath.FilePath} @ivar anonymousRoot: Root of the filesystem to which anonymous users will be granted access. @type userHome: L{filepath.FilePath} @ivar userHome: Root of the filesystem containing user home directories. """ def __init__(self, anonymousRoot, userHome='/home'): BaseFTPRealm.__init__(self, anonymousRoot) self.userHome = filepath.FilePath(userHome) def getHomeDirectory(self, avatarId): """ Use C{avatarId} as a single path segment to construct a child of C{self.userHome} and return that child. """ return self.userHome.child(avatarId) class SystemFTPRealm(BaseFTPRealm): """ L{SystemFTPRealm} uses system user account information to decide what the home directory for a particular avatarId is. This works on POSIX but probably is not reliable on Windows. """ def getHomeDirectory(self, avatarId): """ Return the system-defined home directory of the system user account with the name C{avatarId}. """ path = os.path.expanduser('~' + avatarId) if path.startswith('~'): raise cred_error.UnauthorizedLogin() return filepath.FilePath(path) # --- FTP CLIENT ------------------------------------------------------------- #### # And now for the client... # Notes: # * Reference: http://cr.yp.to/ftp.html # * FIXME: Does not support pipelining (which is not supported by all # servers anyway). This isn't a functionality limitation, just a # small performance issue. # * Only has a rudimentary understanding of FTP response codes (although # the full response is passed to the caller if they so choose). # * Assumes that USER and PASS should always be sent # * Always sets TYPE I (binary mode) # * Doesn't understand any of the weird, obscure TELNET stuff (\377...) # * FIXME: Doesn't share any code with the FTPServer class ConnectionLost(FTPError): pass class CommandFailed(FTPError): pass class BadResponse(FTPError): pass class UnexpectedResponse(FTPError): pass class UnexpectedData(FTPError): pass class FTPCommand: def __init__(self, text=None, public=0): self.text = text self.deferred = defer.Deferred() self.ready = 1 self.public = public self.transferDeferred = None def fail(self, failure): if self.public: self.deferred.errback(failure) class ProtocolWrapper(protocol.Protocol): def __init__(self, original, deferred): self.original = original self.deferred = deferred def makeConnection(self, transport): self.original.makeConnection(transport) def dataReceived(self, data): self.original.dataReceived(data) def connectionLost(self, reason): self.original.connectionLost(reason) # Signal that transfer has completed self.deferred.callback(None) class IFinishableConsumer(interfaces.IConsumer): """ A Consumer for producers that finish. @since: 11.0 """ def finish(): """ The producer has finished producing. """ class SenderProtocol(protocol.Protocol): implements(IFinishableConsumer) def __init__(self): # Fired upon connection self.connectedDeferred = defer.Deferred() # Fired upon disconnection self.deferred = defer.Deferred() #Protocol stuff def dataReceived(self, data): raise UnexpectedData( "Received data from the server on a " "send-only data-connection" ) def makeConnection(self, transport): protocol.Protocol.makeConnection(self, transport) self.connectedDeferred.callback(self) def connectionLost(self, reason): if reason.check(error.ConnectionDone): self.deferred.callback('connection done') else: self.deferred.errback(reason) #IFinishableConsumer stuff def write(self, data): self.transport.write(data) def registerProducer(self, producer, streaming): """ Register the given producer with our transport. """ self.transport.registerProducer(producer, streaming) def unregisterProducer(self): """ Unregister the previously registered producer. """ self.transport.unregisterProducer() def finish(self): self.transport.loseConnection() def decodeHostPort(line): """Decode an FTP response specifying a host and port. @return: a 2-tuple of (host, port). """ abcdef = re.sub('[^0-9, ]', '', line) parsed = [int(p.strip()) for p in abcdef.split(',')] for x in parsed: if x < 0 or x > 255: raise ValueError("Out of range", line, x) a, b, c, d, e, f = parsed host = "%s.%s.%s.%s" % (a, b, c, d) port = (int(e) << 8) + int(f) return host, port def encodeHostPort(host, port): numbers = host.split('.') + [str(port >> 8), str(port % 256)] return ','.join(numbers) def _unwrapFirstError(failure): failure.trap(defer.FirstError) return failure.value.subFailure class FTPDataPortFactory(protocol.ServerFactory): """Factory for data connections that use the PORT command (i.e. "active" transfers) """ noisy = 0 def buildProtocol(self, addr): # This is a bit hackish -- we already have a Protocol instance, # so just return it instead of making a new one # FIXME: Reject connections from the wrong address/port # (potential security problem) self.protocol.factory = self self.port.loseConnection() return self.protocol class FTPClientBasic(basic.LineReceiver): """ Foundations of an FTP client. """ debug = False def __init__(self): self.actionQueue = [] self.greeting = None self.nextDeferred = defer.Deferred().addCallback(self._cb_greeting) self.nextDeferred.addErrback(self.fail) self.response = [] self._failed = 0 def fail(self, error): """ Give an error to any queued deferreds. """ self._fail(error) def _fail(self, error): """ Errback all queued deferreds. """ if self._failed: # We're recursing; bail out here for simplicity return error self._failed = 1 if self.nextDeferred: try: self.nextDeferred.errback(failure.Failure(ConnectionLost('FTP connection lost', error))) except defer.AlreadyCalledError: pass for ftpCommand in self.actionQueue: ftpCommand.fail(failure.Failure(ConnectionLost('FTP connection lost', error))) return error def _cb_greeting(self, greeting): self.greeting = greeting def sendLine(self, line): """ (Private) Sends a line, unless line is None. """ if line is None: return basic.LineReceiver.sendLine(self, line) def sendNextCommand(self): """ (Private) Processes the next command in the queue. """ ftpCommand = self.popCommandQueue() if ftpCommand is None: self.nextDeferred = None return if not ftpCommand.ready: self.actionQueue.insert(0, ftpCommand) reactor.callLater(1.0, self.sendNextCommand) self.nextDeferred = None return # FIXME: this if block doesn't belong in FTPClientBasic, it belongs in # FTPClient. if ftpCommand.text == 'PORT': self.generatePortCommand(ftpCommand) if self.debug: log.msg('<-- %s' % ftpCommand.text) self.nextDeferred = ftpCommand.deferred self.sendLine(ftpCommand.text) def queueCommand(self, ftpCommand): """ Add an FTPCommand object to the queue. If it's the only thing in the queue, and we are connected and we aren't waiting for a response of an earlier command, the command will be sent immediately. @param ftpCommand: an L{FTPCommand} """ self.actionQueue.append(ftpCommand) if (len(self.actionQueue) == 1 and self.transport is not None and self.nextDeferred is None): self.sendNextCommand() def queueStringCommand(self, command, public=1): """ Queues a string to be issued as an FTP command @param command: string of an FTP command to queue @param public: a flag intended for internal use by FTPClient. Don't change it unless you know what you're doing. @return: a L{Deferred} that will be called when the response to the command has been received. """ ftpCommand = FTPCommand(command, public) self.queueCommand(ftpCommand) return ftpCommand.deferred def popCommandQueue(self): """ Return the front element of the command queue, or None if empty. """ if self.actionQueue: return self.actionQueue.pop(0) else: return None def queueLogin(self, username, password): """ Login: send the username, send the password. If the password is C{None}, the PASS command won't be sent. Also, if the response to the USER command has a response code of 230 (User logged in), then PASS won't be sent either. """ # Prepare the USER command deferreds = [] userDeferred = self.queueStringCommand('USER ' + username, public=0) deferreds.append(userDeferred) # Prepare the PASS command (if a password is given) if password is not None: passwordCmd = FTPCommand('PASS ' + password, public=0) self.queueCommand(passwordCmd) deferreds.append(passwordCmd.deferred) # Avoid sending PASS if the response to USER is 230. # (ref: http://cr.yp.to/ftp/user.html#user) def cancelPasswordIfNotNeeded(response): if response[0].startswith('230'): # No password needed! self.actionQueue.remove(passwordCmd) return response userDeferred.addCallback(cancelPasswordIfNotNeeded) # Error handling. for deferred in deferreds: # If something goes wrong, call fail deferred.addErrback(self.fail) # But also swallow the error, so we don't cause spurious errors deferred.addErrback(lambda x: None) def lineReceived(self, line): """ (Private) Parses the response messages from the FTP server. """ # Add this line to the current response if self.debug: log.msg('--> %s' % line) self.response.append(line) # Bail out if this isn't the last line of a response # The last line of response starts with 3 digits followed by a space codeIsValid = re.match(r'\d{3} ', line) if not codeIsValid: return code = line[0:3] # Ignore marks if code[0] == '1': return # Check that we were expecting a response if self.nextDeferred is None: self.fail(UnexpectedResponse(self.response)) return # Reset the response response = self.response self.response = [] # Look for a success or error code, and call the appropriate callback if code[0] in ('2', '3'): # Success self.nextDeferred.callback(response) elif code[0] in ('4', '5'): # Failure self.nextDeferred.errback(failure.Failure(CommandFailed(response))) else: # This shouldn't happen unless something screwed up. log.msg('Server sent invalid response code %s' % (code,)) self.nextDeferred.errback(failure.Failure(BadResponse(response))) # Run the next command self.sendNextCommand() def connectionLost(self, reason): self._fail(reason) class _PassiveConnectionFactory(protocol.ClientFactory): noisy = False def __init__(self, protoInstance): self.protoInstance = protoInstance def buildProtocol(self, ignored): self.protoInstance.factory = self return self.protoInstance def clientConnectionFailed(self, connector, reason): e = FTPError('Connection Failed', reason) self.protoInstance.deferred.errback(e) class FTPClient(FTPClientBasic): """ L{FTPClient} is a client implementation of the FTP protocol which exposes FTP commands as methods which return L{Deferred}s. Each command method returns a L{Deferred} which is called back when a successful response code (2xx or 3xx) is received from the server or which is error backed if an error response code (4xx or 5xx) is received from the server or if a protocol violation occurs. If an error response code is received, the L{Deferred} fires with a L{Failure} wrapping a L{CommandFailed} instance. The L{CommandFailed} instance is created with a list of the response lines received from the server. See U{RFC 959<http://www.ietf.org/rfc/rfc959.txt>} for error code definitions. Both active and passive transfers are supported. @ivar passive: See description in __init__. """ connectFactory = reactor.connectTCP def __init__(self, username='anonymous', password='twisted@twistedmatrix.com', passive=1): """ Constructor. I will login as soon as I receive the welcome message from the server. @param username: FTP username @param password: FTP password @param passive: flag that controls if I use active or passive data connections. You can also change this after construction by assigning to C{self.passive}. """ FTPClientBasic.__init__(self) self.queueLogin(username, password) self.passive = passive def fail(self, error): """ Disconnect, and also give an error to any queued deferreds. """ self.transport.loseConnection() self._fail(error) def receiveFromConnection(self, commands, protocol): """ Retrieves a file or listing generated by the given command, feeding it to the given protocol. @param commands: list of strings of FTP commands to execute then receive the results of (e.g. C{LIST}, C{RETR}) @param protocol: A L{Protocol} B{instance} e.g. an L{FTPFileListProtocol}, or something that can be adapted to one. Typically this will be an L{IConsumer} implementation. @return: L{Deferred}. """ protocol = interfaces.IProtocol(protocol) wrapper = ProtocolWrapper(protocol, defer.Deferred()) return self._openDataConnection(commands, wrapper) def queueLogin(self, username, password): """ Login: send the username, send the password, and set retrieval mode to binary """ FTPClientBasic.queueLogin(self, username, password) d = self.queueStringCommand('TYPE I', public=0) # If something goes wrong, call fail d.addErrback(self.fail) # But also swallow the error, so we don't cause spurious errors d.addErrback(lambda x: None) def sendToConnection(self, commands): """ XXX @return: A tuple of two L{Deferred}s: - L{Deferred} L{IFinishableConsumer}. You must call the C{finish} method on the IFinishableConsumer when the file is completely transferred. - L{Deferred} list of control-connection responses. """ s = SenderProtocol() r = self._openDataConnection(commands, s) return (s.connectedDeferred, r) def _openDataConnection(self, commands, protocol): """ This method returns a DeferredList. """ cmds = [FTPCommand(command, public=1) for command in commands] cmdsDeferred = defer.DeferredList([cmd.deferred for cmd in cmds], fireOnOneErrback=True, consumeErrors=True) cmdsDeferred.addErrback(_unwrapFirstError) if self.passive: # Hack: use a mutable object to sneak a variable out of the # scope of doPassive _mutable = [None] def doPassive(response): """Connect to the port specified in the response to PASV""" host, port = decodeHostPort(response[-1][4:]) f = _PassiveConnectionFactory(protocol) _mutable[0] = self.connectFactory(host, port, f) pasvCmd = FTPCommand('PASV') self.queueCommand(pasvCmd) pasvCmd.deferred.addCallback(doPassive).addErrback(self.fail) results = [cmdsDeferred, pasvCmd.deferred, protocol.deferred] d = defer.DeferredList(results, fireOnOneErrback=True, consumeErrors=True) d.addErrback(_unwrapFirstError) # Ensure the connection is always closed def close(x, m=_mutable): m[0] and m[0].disconnect() return x d.addBoth(close) else: # We just place a marker command in the queue, and will fill in # the host and port numbers later (see generatePortCommand) portCmd = FTPCommand('PORT') # Ok, now we jump through a few hoops here. # This is the problem: a transfer is not to be trusted as complete # until we get both the "226 Transfer complete" message on the # control connection, and the data socket is closed. Thus, we use # a DeferredList to make sure we only fire the callback at the # right time. portCmd.transferDeferred = protocol.deferred portCmd.protocol = protocol portCmd.deferred.addErrback(portCmd.transferDeferred.errback) self.queueCommand(portCmd) # Create dummy functions for the next callback to call. # These will also be replaced with real functions in # generatePortCommand. portCmd.loseConnection = lambda result: result portCmd.fail = lambda error: error # Ensure that the connection always gets closed cmdsDeferred.addErrback(lambda e, pc=portCmd: pc.fail(e) or e) results = [cmdsDeferred, portCmd.deferred, portCmd.transferDeferred] d = defer.DeferredList(results, fireOnOneErrback=True, consumeErrors=True) d.addErrback(_unwrapFirstError) for cmd in cmds: self.queueCommand(cmd) return d def generatePortCommand(self, portCmd): """ (Private) Generates the text of a given PORT command. """ # The problem is that we don't create the listening port until we need # it for various reasons, and so we have to muck about to figure out # what interface and port it's listening on, and then finally we can # create the text of the PORT command to send to the FTP server. # FIXME: This method is far too ugly. # FIXME: The best solution is probably to only create the data port # once per FTPClient, and just recycle it for each new download. # This should be ok, because we don't pipeline commands. # Start listening on a port factory = FTPDataPortFactory() factory.protocol = portCmd.protocol listener = reactor.listenTCP(0, factory) factory.port = listener # Ensure we close the listening port if something goes wrong def listenerFail(error, listener=listener): if listener.connected: listener.loseConnection() return error portCmd.fail = listenerFail # Construct crufty FTP magic numbers that represent host & port host = self.transport.getHost().host port = listener.getHost().port portCmd.text = 'PORT ' + encodeHostPort(host, port) def escapePath(self, path): """ Returns a FTP escaped path (replace newlines with nulls). """ # Escape newline characters return path.replace('\n', '\0') def retrieveFile(self, path, protocol, offset=0): """ Retrieve a file from the given path This method issues the 'RETR' FTP command. The file is fed into the given Protocol instance. The data connection will be passive if self.passive is set. @param path: path to file that you wish to receive. @param protocol: a L{Protocol} instance. @param offset: offset to start downloading from @return: L{Deferred} """ cmds = ['RETR ' + self.escapePath(path)] if offset: cmds.insert(0, ('REST ' + str(offset))) return self.receiveFromConnection(cmds, protocol) retr = retrieveFile def storeFile(self, path, offset=0): """ Store a file at the given path. This method issues the 'STOR' FTP command. @return: A tuple of two L{Deferred}s: - L{Deferred} L{IFinishableConsumer}. You must call the C{finish} method on the IFinishableConsumer when the file is completely transferred. - L{Deferred} list of control-connection responses. """ cmds = ['STOR ' + self.escapePath(path)] if offset: cmds.insert(0, ('REST ' + str(offset))) return self.sendToConnection(cmds) stor = storeFile def rename(self, pathFrom, pathTo): """ Rename a file. This method issues the I{RNFR}/I{RNTO} command sequence to rename C{pathFrom} to C{pathTo}. @param: pathFrom: the absolute path to the file to be renamed @type pathFrom: C{str} @param: pathTo: the absolute path to rename the file to. @type pathTo: C{str} @return: A L{Deferred} which fires when the rename operation has succeeded or failed. If it succeeds, the L{Deferred} is called back with a two-tuple of lists. The first list contains the responses to the I{RNFR} command. The second list contains the responses to the I{RNTO} command. If either I{RNFR} or I{RNTO} fails, the L{Deferred} is errbacked with L{CommandFailed} or L{BadResponse}. @rtype: L{Deferred} @since: 8.2 """ renameFrom = self.queueStringCommand('RNFR ' + self.escapePath(pathFrom)) renameTo = self.queueStringCommand('RNTO ' + self.escapePath(pathTo)) fromResponse = [] # Use a separate Deferred for the ultimate result so that Deferred # chaining can't interfere with its result. result = defer.Deferred() # Bundle up all the responses result.addCallback(lambda toResponse: (fromResponse, toResponse)) def ebFrom(failure): # Make sure the RNTO doesn't run if the RNFR failed. self.popCommandQueue() result.errback(failure) # Save the RNFR response to pass to the result Deferred later renameFrom.addCallbacks(fromResponse.extend, ebFrom) # Hook up the RNTO to the result Deferred as well renameTo.chainDeferred(result) return result def list(self, path, protocol): """ Retrieve a file listing into the given protocol instance. This method issues the 'LIST' FTP command. @param path: path to get a file listing for. @param protocol: a L{Protocol} instance, probably a L{FTPFileListProtocol} instance. It can cope with most common file listing formats. @return: L{Deferred} """ if path is None: path = '' return self.receiveFromConnection(['LIST ' + self.escapePath(path)], protocol) def nlst(self, path, protocol): """ Retrieve a short file listing into the given protocol instance. This method issues the 'NLST' FTP command. NLST (should) return a list of filenames, one per line. @param path: path to get short file listing for. @param protocol: a L{Protocol} instance. """ if path is None: path = '' return self.receiveFromConnection(['NLST ' + self.escapePath(path)], protocol) def cwd(self, path): """ Issues the CWD (Change Working Directory) command. It's also available as changeDirectory, which parses the result. @return: a L{Deferred} that will be called when done. """ return self.queueStringCommand('CWD ' + self.escapePath(path)) def changeDirectory(self, path): """ Change the directory on the server and parse the result to determine if it was successful or not. @type path: C{str} @param path: The path to which to change. @return: a L{Deferred} which will be called back when the directory change has succeeded or errbacked if an error occurrs. """ warnings.warn( "FTPClient.changeDirectory is deprecated in Twisted 8.2 and " "newer. Use FTPClient.cwd instead.", category=DeprecationWarning, stacklevel=2) def cbResult(result): if result[-1][:3] != '250': return failure.Failure(CommandFailed(result)) return True return self.cwd(path).addCallback(cbResult) def makeDirectory(self, path): """ Make a directory This method issues the MKD command. @param path: The path to the directory to create. @type path: C{str} @return: A L{Deferred} which fires when the server responds. If the directory is created, the L{Deferred} is called back with the server response. If the server response indicates the directory was not created, the L{Deferred} is errbacked with a L{Failure} wrapping L{CommandFailed} or L{BadResponse}. @rtype: L{Deferred} @since: 8.2 """ return self.queueStringCommand('MKD ' + self.escapePath(path)) def removeFile(self, path): """ Delete a file on the server. L{removeFile} issues a I{DELE} command to the server to remove the indicated file. Note that this command cannot remove a directory. @param path: The path to the file to delete. May be relative to the current dir. @type path: C{str} @return: A L{Deferred} which fires when the server responds. On error, it is errbacked with either L{CommandFailed} or L{BadResponse}. On success, it is called back with a list of response lines. @rtype: L{Deferred} @since: 8.2 """ return self.queueStringCommand('DELE ' + self.escapePath(path)) def cdup(self): """ Issues the CDUP (Change Directory UP) command. @return: a L{Deferred} that will be called when done. """ return self.queueStringCommand('CDUP') def pwd(self): """ Issues the PWD (Print Working Directory) command. The L{getDirectory} does the same job but automatically parses the result. @return: a L{Deferred} that will be called when done. It is up to the caller to interpret the response, but the L{parsePWDResponse} method in this module should work. """ return self.queueStringCommand('PWD') def getDirectory(self): """ Returns the current remote directory. @return: a L{Deferred} that will be called back with a C{str} giving the remote directory or which will errback with L{CommandFailed} if an error response is returned. """ def cbParse(result): try: # The only valid code is 257 if int(result[0].split(' ', 1)[0]) != 257: raise ValueError except (IndexError, ValueError): return failure.Failure(CommandFailed(result)) path = parsePWDResponse(result[0]) if path is None: return failure.Failure(CommandFailed(result)) return path return self.pwd().addCallback(cbParse) def quit(self): """ Issues the I{QUIT} command. @return: A L{Deferred} that fires when the server acknowledges the I{QUIT} command. The transport should not be disconnected until this L{Deferred} fires. """ return self.queueStringCommand('QUIT') class FTPFileListProtocol(basic.LineReceiver): """Parser for standard FTP file listings This is the evil required to match:: -rw-r--r-- 1 root other 531 Jan 29 03:26 README If you need different evil for a wacky FTP server, you can override either C{fileLinePattern} or C{parseDirectoryLine()}. It populates the instance attribute self.files, which is a list containing dicts with the following keys (examples from the above line): - filetype: e.g. 'd' for directories, or '-' for an ordinary file - perms: e.g. 'rw-r--r--' - nlinks: e.g. 1 - owner: e.g. 'root' - group: e.g. 'other' - size: e.g. 531 - date: e.g. 'Jan 29 03:26' - filename: e.g. 'README' - linktarget: e.g. 'some/file' Note that the 'date' value will be formatted differently depending on the date. Check U{http://cr.yp.to/ftp.html} if you really want to try to parse it. @ivar files: list of dicts describing the files in this listing """ fileLinePattern = re.compile( r'^(?P<filetype>.)(?P<perms>.{9})\s+(?P<nlinks>\d*)\s*' r'(?P<owner>\S+)\s+(?P<group>\S+)\s+(?P<size>\d+)\s+' r'(?P<date>...\s+\d+\s+[\d:]+)\s+(?P<filename>([^ ]|\\ )*?)' r'( -> (?P<linktarget>[^\r]*))?\r?$' ) delimiter = '\n' def __init__(self): self.files = [] def lineReceived(self, line): d = self.parseDirectoryLine(line) if d is None: self.unknownLine(line) else: self.addFile(d) def parseDirectoryLine(self, line): """Return a dictionary of fields, or None if line cannot be parsed. @param line: line of text expected to contain a directory entry @type line: str @return: dict """ match = self.fileLinePattern.match(line) if match is None: return None else: d = match.groupdict() d['filename'] = d['filename'].replace(r'\ ', ' ') d['nlinks'] = int(d['nlinks']) d['size'] = int(d['size']) if d['linktarget']: d['linktarget'] = d['linktarget'].replace(r'\ ', ' ') return d def addFile(self, info): """Append file information dictionary to the list of known files. Subclasses can override or extend this method to handle file information differently without affecting the parsing of data from the server. @param info: dictionary containing the parsed representation of the file information @type info: dict """ self.files.append(info) def unknownLine(self, line): """Deal with received lines which could not be parsed as file information. Subclasses can override this to perform any special processing needed. @param line: unparsable line as received @type line: str """ pass def parsePWDResponse(response): """Returns the path from a response to a PWD command. Responses typically look like:: 257 "/home/andrew" is current directory. For this example, I will return C{'/home/andrew'}. If I can't find the path, I return C{None}. """ match = re.search('"(.*)"', response) if match: return match.groups()[0] else: return None
agpl-3.0
martynovp/edx-platform
common/djangoapps/student/migrations/0038_auto__add_usersignupsource.py
114
13943
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'UserSignupSource' db.create_table('student_usersignupsource', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('user_id', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['auth.User'])), ('site', self.gf('django.db.models.fields.CharField')(max_length=255, db_index=True)), )) db.send_create_signal('student', ['UserSignupSource']) def backwards(self, orm): # Deleting model 'UserSignupSource' db.delete_table('student_usersignupsource') models = { 'auth.group': { 'Meta': {'object_name': 'Group'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}), 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}) }, 'auth.permission': { 'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'}, 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'}) }, 'auth.user': { 'Meta': {'object_name': 'User'}, 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}), 'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}) }, 'contenttypes.contenttype': { 'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"}, 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'}) }, 'student.anonymoususerid': { 'Meta': {'object_name': 'AnonymousUserId'}, 'anonymous_user_id': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '32'}), 'course_id': ('xmodule_django.models.CourseKeyField', [], {'db_index': 'True', 'max_length': '255', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'student.courseaccessrole': { 'Meta': {'unique_together': "(('user', 'org', 'course_id', 'role'),)", 'object_name': 'CourseAccessRole'}, 'course_id': ('xmodule_django.models.CourseKeyField', [], {'db_index': 'True', 'max_length': '255', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'org': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '64', 'blank': 'True'}), 'role': ('django.db.models.fields.CharField', [], {'max_length': '64', 'db_index': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'student.courseenrollment': { 'Meta': {'ordering': "('user', 'course_id')", 'unique_together': "(('user', 'course_id'),)", 'object_name': 'CourseEnrollment'}, 'course_id': ('xmodule_django.models.CourseKeyField', [], {'max_length': '255', 'db_index': 'True'}), 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'db_index': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'mode': ('django.db.models.fields.CharField', [], {'default': "'honor'", 'max_length': '100'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'student.courseenrollmentallowed': { 'Meta': {'unique_together': "(('email', 'course_id'),)", 'object_name': 'CourseEnrollmentAllowed'}, 'auto_enroll': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'course_id': ('xmodule_django.models.CourseKeyField', [], {'max_length': '255', 'db_index': 'True'}), 'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'db_index': 'True', 'blank': 'True'}), 'email': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}) }, 'student.courseregistrationcode': { 'Meta': {'object_name': 'CourseRegistrationCode'}, 'code': ('django.db.models.fields.CharField', [], {'max_length': '32', 'db_index': 'True'}), 'course_id': ('xmodule_django.models.CourseKeyField', [], {'max_length': '255', 'db_index': 'True'}), 'created_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2014, 6, 25, 0, 0)'}), 'created_by': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'created_by_user'", 'to': "orm['auth.User']"}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'redeemed_at': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2014, 6, 25, 0, 0)', 'null': 'True'}), 'redeemed_by': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'redeemed_by_user'", 'null': 'True', 'to': "orm['auth.User']"}), 'transaction_group_name': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '255', 'null': 'True', 'blank': 'True'}) }, 'student.loginfailures': { 'Meta': {'object_name': 'LoginFailures'}, 'failure_count': ('django.db.models.fields.IntegerField', [], {'default': '0'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'lockout_until': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'student.passwordhistory': { 'Meta': {'object_name': 'PasswordHistory'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'time_set': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'student.pendingemailchange': { 'Meta': {'object_name': 'PendingEmailChange'}, 'activation_key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '32', 'db_index': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'new_email': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '255', 'blank': 'True'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True'}) }, 'student.pendingnamechange': { 'Meta': {'object_name': 'PendingNameChange'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'new_name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}), 'rationale': ('django.db.models.fields.CharField', [], {'max_length': '1024', 'blank': 'True'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True'}) }, 'student.registration': { 'Meta': {'object_name': 'Registration', 'db_table': "'auth_registration'"}, 'activation_key': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '32', 'db_index': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'unique': 'True'}) }, 'student.userprofile': { 'Meta': {'object_name': 'UserProfile', 'db_table': "'auth_userprofile'"}, 'allow_certificate': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'city': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'country': ('django_countries.fields.CountryField', [], {'max_length': '2', 'null': 'True', 'blank': 'True'}), 'courseware': ('django.db.models.fields.CharField', [], {'default': "'course.xml'", 'max_length': '255', 'blank': 'True'}), 'gender': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '6', 'null': 'True', 'blank': 'True'}), 'goals': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'language': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '255', 'blank': 'True'}), 'level_of_education': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '6', 'null': 'True', 'blank': 'True'}), 'location': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '255', 'blank': 'True'}), 'mailing_address': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}), 'meta': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'db_index': 'True', 'max_length': '255', 'blank': 'True'}), 'user': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'profile'", 'unique': 'True', 'to': "orm['auth.User']"}), 'year_of_birth': ('django.db.models.fields.IntegerField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}) }, 'student.usersignupsource': { 'Meta': {'object_name': 'UserSignupSource'}, 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'site': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}), 'user_id': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"}) }, 'student.userstanding': { 'Meta': {'object_name': 'UserStanding'}, 'account_status': ('django.db.models.fields.CharField', [], {'max_length': '31', 'blank': 'True'}), 'changed_by': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']", 'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'standing_last_changed_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}), 'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'standing'", 'unique': 'True', 'to': "orm['auth.User']"}) }, 'student.usertestgroup': { 'Meta': {'object_name': 'UserTestGroup'}, 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'name': ('django.db.models.fields.CharField', [], {'max_length': '32', 'db_index': 'True'}), 'users': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.User']", 'db_index': 'True', 'symmetrical': 'False'}) } } complete_apps = ['student']
agpl-3.0
cindyyu/kuma
vendor/packages/pygments/lexers/_vim_builtins.py
75
57090
# -*- coding: utf-8 -*- """ pygments.lexers._vim_builtins ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This file is autogenerated by scripts/get_vimkw.py :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ # Split up in multiple functions so it's importable by jython, which has a # per-method size limit. def _getauto(): var = ( ('BufAdd','BufAdd'), ('BufCreate','BufCreate'), ('BufDelete','BufDelete'), ('BufEnter','BufEnter'), ('BufFilePost','BufFilePost'), ('BufFilePre','BufFilePre'), ('BufHidden','BufHidden'), ('BufLeave','BufLeave'), ('BufNew','BufNew'), ('BufNewFile','BufNewFile'), ('BufRead','BufRead'), ('BufReadCmd','BufReadCmd'), ('BufReadPost','BufReadPost'), ('BufReadPre','BufReadPre'), ('BufUnload','BufUnload'), ('BufWinEnter','BufWinEnter'), ('BufWinLeave','BufWinLeave'), ('BufWipeout','BufWipeout'), ('BufWrite','BufWrite'), ('BufWriteCmd','BufWriteCmd'), ('BufWritePost','BufWritePost'), ('BufWritePre','BufWritePre'), ('Cmd','Cmd'), ('CmdwinEnter','CmdwinEnter'), ('CmdwinLeave','CmdwinLeave'), ('ColorScheme','ColorScheme'), ('CompleteDone','CompleteDone'), ('CursorHold','CursorHold'), ('CursorHoldI','CursorHoldI'), ('CursorMoved','CursorMoved'), ('CursorMovedI','CursorMovedI'), ('EncodingChanged','EncodingChanged'), ('FileAppendCmd','FileAppendCmd'), ('FileAppendPost','FileAppendPost'), ('FileAppendPre','FileAppendPre'), ('FileChangedRO','FileChangedRO'), ('FileChangedShell','FileChangedShell'), ('FileChangedShellPost','FileChangedShellPost'), ('FileEncoding','FileEncoding'), ('FileReadCmd','FileReadCmd'), ('FileReadPost','FileReadPost'), ('FileReadPre','FileReadPre'), ('FileType','FileType'), ('FileWriteCmd','FileWriteCmd'), ('FileWritePost','FileWritePost'), ('FileWritePre','FileWritePre'), ('FilterReadPost','FilterReadPost'), ('FilterReadPre','FilterReadPre'), ('FilterWritePost','FilterWritePost'), ('FilterWritePre','FilterWritePre'), ('FocusGained','FocusGained'), ('FocusLost','FocusLost'), ('FuncUndefined','FuncUndefined'), ('GUIEnter','GUIEnter'), ('GUIFailed','GUIFailed'), ('InsertChange','InsertChange'), ('InsertCharPre','InsertCharPre'), ('InsertEnter','InsertEnter'), ('InsertLeave','InsertLeave'), ('MenuPopup','MenuPopup'), ('QuickFixCmdPost','QuickFixCmdPost'), ('QuickFixCmdPre','QuickFixCmdPre'), ('QuitPre','QuitPre'), ('RemoteReply','RemoteReply'), ('SessionLoadPost','SessionLoadPost'), ('ShellCmdPost','ShellCmdPost'), ('ShellFilterPost','ShellFilterPost'), ('SourceCmd','SourceCmd'), ('SourcePre','SourcePre'), ('SpellFileMissing','SpellFileMissing'), ('StdinReadPost','StdinReadPost'), ('StdinReadPre','StdinReadPre'), ('SwapExists','SwapExists'), ('Syntax','Syntax'), ('TabEnter','TabEnter'), ('TabLeave','TabLeave'), ('TermChanged','TermChanged'), ('TermResponse','TermResponse'), ('TextChanged','TextChanged'), ('TextChangedI','TextChangedI'), ('User','User'), ('UserGettingBored','UserGettingBored'), ('VimEnter','VimEnter'), ('VimLeave','VimLeave'), ('VimLeavePre','VimLeavePre'), ('VimResized','VimResized'), ('WinEnter','WinEnter'), ('WinLeave','WinLeave'), ('event','event'), ) return var auto = _getauto() def _getcommand(): var = ( ('a','a'), ('ab','ab'), ('abc','abclear'), ('abo','aboveleft'), ('al','all'), ('ar','ar'), ('ar','args'), ('arga','argadd'), ('argd','argdelete'), ('argdo','argdo'), ('arge','argedit'), ('argg','argglobal'), ('argl','arglocal'), ('argu','argument'), ('as','ascii'), ('au','au'), ('b','buffer'), ('bN','bNext'), ('ba','ball'), ('bad','badd'), ('bd','bdelete'), ('bel','belowright'), ('bf','bfirst'), ('bl','blast'), ('bm','bmodified'), ('bn','bnext'), ('bo','botright'), ('bp','bprevious'), ('br','br'), ('br','brewind'), ('brea','break'), ('breaka','breakadd'), ('breakd','breakdel'), ('breakl','breaklist'), ('bro','browse'), ('bu','bu'), ('buf','buf'), ('bufdo','bufdo'), ('buffers','buffers'), ('bun','bunload'), ('bw','bwipeout'), ('c','c'), ('c','change'), ('cN','cN'), ('cN','cNext'), ('cNf','cNf'), ('cNf','cNfile'), ('cabc','cabclear'), ('cad','cad'), ('cad','caddexpr'), ('caddb','caddbuffer'), ('caddf','caddfile'), ('cal','call'), ('cat','catch'), ('cb','cbuffer'), ('cc','cc'), ('ccl','cclose'), ('cd','cd'), ('ce','center'), ('cex','cexpr'), ('cf','cfile'), ('cfir','cfirst'), ('cg','cgetfile'), ('cgetb','cgetbuffer'), ('cgete','cgetexpr'), ('changes','changes'), ('chd','chdir'), ('che','checkpath'), ('checkt','checktime'), ('cl','cl'), ('cl','clist'), ('cla','clast'), ('clo','close'), ('cmapc','cmapclear'), ('cn','cn'), ('cn','cnext'), ('cnew','cnewer'), ('cnf','cnf'), ('cnf','cnfile'), ('co','copy'), ('col','colder'), ('colo','colorscheme'), ('com','com'), ('comc','comclear'), ('comp','compiler'), ('con','con'), ('con','continue'), ('conf','confirm'), ('cope','copen'), ('cp','cprevious'), ('cpf','cpfile'), ('cq','cquit'), ('cr','crewind'), ('cs','cs'), ('cscope','cscope'), ('cstag','cstag'), ('cuna','cunabbrev'), ('cw','cwindow'), ('d','d'), ('d','delete'), ('de','de'), ('debug','debug'), ('debugg','debuggreedy'), ('del','del'), ('delc','delcommand'), ('delel','delel'), ('delep','delep'), ('deletel','deletel'), ('deletep','deletep'), ('deletl','deletl'), ('deletp','deletp'), ('delf','delf'), ('delf','delfunction'), ('dell','dell'), ('delm','delmarks'), ('delp','delp'), ('dep','dep'), ('di','di'), ('di','display'), ('diffg','diffget'), ('diffo','diffoff'), ('diffp','diffpatch'), ('diffpu','diffput'), ('diffs','diffsplit'), ('difft','diffthis'), ('diffu','diffupdate'), ('dig','dig'), ('dig','digraphs'), ('dir','dir'), ('dj','djump'), ('dl','dl'), ('dli','dlist'), ('do','do'), ('doau','doau'), ('dp','dp'), ('dr','drop'), ('ds','dsearch'), ('dsp','dsplit'), ('e','e'), ('e','edit'), ('ea','ea'), ('earlier','earlier'), ('ec','ec'), ('echoe','echoerr'), ('echom','echomsg'), ('echon','echon'), ('el','else'), ('elsei','elseif'), ('em','emenu'), ('en','en'), ('en','endif'), ('endf','endf'), ('endf','endfunction'), ('endfo','endfor'), ('endfun','endfun'), ('endt','endtry'), ('endw','endwhile'), ('ene','enew'), ('ex','ex'), ('exi','exit'), ('exu','exusage'), ('f','f'), ('f','file'), ('files','files'), ('filet','filet'), ('filetype','filetype'), ('fin','fin'), ('fin','find'), ('fina','finally'), ('fini','finish'), ('fir','first'), ('fix','fixdel'), ('fo','fold'), ('foldc','foldclose'), ('foldd','folddoopen'), ('folddoc','folddoclosed'), ('foldo','foldopen'), ('for','for'), ('fu','fu'), ('fu','function'), ('fun','fun'), ('g','g'), ('go','goto'), ('gr','grep'), ('grepa','grepadd'), ('gui','gui'), ('gvim','gvim'), ('h','h'), ('h','help'), ('ha','hardcopy'), ('helpf','helpfind'), ('helpg','helpgrep'), ('helpt','helptags'), ('hi','hi'), ('hid','hide'), ('his','history'), ('i','i'), ('ia','ia'), ('iabc','iabclear'), ('if','if'), ('ij','ijump'), ('il','ilist'), ('imapc','imapclear'), ('in','in'), ('intro','intro'), ('is','isearch'), ('isp','isplit'), ('iuna','iunabbrev'), ('j','join'), ('ju','jumps'), ('k','k'), ('kee','keepmarks'), ('keepa','keepa'), ('keepalt','keepalt'), ('keepj','keepjumps'), ('keepp','keeppatterns'), ('l','l'), ('l','list'), ('lN','lN'), ('lN','lNext'), ('lNf','lNf'), ('lNf','lNfile'), ('la','la'), ('la','last'), ('lad','lad'), ('lad','laddexpr'), ('laddb','laddbuffer'), ('laddf','laddfile'), ('lan','lan'), ('lan','language'), ('lat','lat'), ('later','later'), ('lb','lbuffer'), ('lc','lcd'), ('lch','lchdir'), ('lcl','lclose'), ('lcs','lcs'), ('lcscope','lcscope'), ('le','left'), ('lefta','leftabove'), ('lex','lexpr'), ('lf','lfile'), ('lfir','lfirst'), ('lg','lgetfile'), ('lgetb','lgetbuffer'), ('lgete','lgetexpr'), ('lgr','lgrep'), ('lgrepa','lgrepadd'), ('lh','lhelpgrep'), ('ll','ll'), ('lla','llast'), ('lli','llist'), ('lmak','lmake'), ('lmapc','lmapclear'), ('lne','lne'), ('lne','lnext'), ('lnew','lnewer'), ('lnf','lnf'), ('lnf','lnfile'), ('lo','lo'), ('lo','loadview'), ('loadk','loadk'), ('loadkeymap','loadkeymap'), ('loc','lockmarks'), ('lockv','lockvar'), ('lol','lolder'), ('lop','lopen'), ('lp','lprevious'), ('lpf','lpfile'), ('lr','lrewind'), ('ls','ls'), ('lt','ltag'), ('lua','lua'), ('luado','luado'), ('luafile','luafile'), ('lv','lvimgrep'), ('lvimgrepa','lvimgrepadd'), ('lw','lwindow'), ('m','move'), ('ma','ma'), ('ma','mark'), ('mak','make'), ('marks','marks'), ('mat','match'), ('menut','menut'), ('menut','menutranslate'), ('mes','mes'), ('messages','messages'), ('mk','mk'), ('mk','mkexrc'), ('mks','mksession'), ('mksp','mkspell'), ('mkv','mkv'), ('mkv','mkvimrc'), ('mkvie','mkview'), ('mo','mo'), ('mod','mode'), ('mz','mz'), ('mz','mzscheme'), ('mzf','mzfile'), ('n','n'), ('n','next'), ('nb','nbkey'), ('nbc','nbclose'), ('nbs','nbstart'), ('ne','ne'), ('new','new'), ('nmapc','nmapclear'), ('noa','noa'), ('noautocmd','noautocmd'), ('noh','nohlsearch'), ('nu','number'), ('o','o'), ('o','open'), ('ol','oldfiles'), ('omapc','omapclear'), ('on','only'), ('opt','options'), ('ownsyntax','ownsyntax'), ('p','p'), ('p','print'), ('pc','pclose'), ('pe','pe'), ('pe','perl'), ('ped','pedit'), ('perld','perldo'), ('po','pop'), ('popu','popu'), ('popu','popup'), ('pp','ppop'), ('pr','pr'), ('pre','preserve'), ('prev','previous'), ('pro','pro'), ('prof','profile'), ('profd','profdel'), ('promptf','promptfind'), ('promptr','promptrepl'), ('ps','psearch'), ('ptN','ptN'), ('ptN','ptNext'), ('pta','ptag'), ('ptf','ptfirst'), ('ptj','ptjump'), ('ptl','ptlast'), ('ptn','ptn'), ('ptn','ptnext'), ('ptp','ptprevious'), ('ptr','ptrewind'), ('pts','ptselect'), ('pu','put'), ('pw','pwd'), ('py','py'), ('py','python'), ('py3','py3'), ('py3','py3'), ('py3do','py3do'), ('pydo','pydo'), ('pyf','pyfile'), ('python3','python3'), ('q','q'), ('q','quit'), ('qa','qall'), ('quita','quitall'), ('r','r'), ('r','read'), ('re','re'), ('rec','recover'), ('red','red'), ('red','redo'), ('redi','redir'), ('redr','redraw'), ('redraws','redrawstatus'), ('reg','registers'), ('res','resize'), ('ret','retab'), ('retu','return'), ('rew','rewind'), ('ri','right'), ('rightb','rightbelow'), ('ru','ru'), ('ru','runtime'), ('rub','ruby'), ('rubyd','rubydo'), ('rubyf','rubyfile'), ('rundo','rundo'), ('rv','rviminfo'), ('sN','sNext'), ('sa','sargument'), ('sal','sall'), ('san','sandbox'), ('sav','saveas'), ('sb','sbuffer'), ('sbN','sbNext'), ('sba','sball'), ('sbf','sbfirst'), ('sbl','sblast'), ('sbm','sbmodified'), ('sbn','sbnext'), ('sbp','sbprevious'), ('sbr','sbrewind'), ('scrip','scrip'), ('scrip','scriptnames'), ('scripte','scriptencoding'), ('scs','scs'), ('scscope','scscope'), ('se','set'), ('setf','setfiletype'), ('setg','setglobal'), ('setl','setlocal'), ('sf','sfind'), ('sfir','sfirst'), ('sh','shell'), ('si','si'), ('sig','sig'), ('sign','sign'), ('sil','silent'), ('sim','simalt'), ('sl','sl'), ('sl','sleep'), ('sla','slast'), ('sm','smagic'), ('sm','smap'), ('sme','sme'), ('smenu','smenu'), ('sn','snext'), ('sni','sniff'), ('sno','snomagic'), ('snoreme','snoreme'), ('snoremenu','snoremenu'), ('so','so'), ('so','source'), ('sor','sort'), ('sp','split'), ('spe','spe'), ('spe','spellgood'), ('spelld','spelldump'), ('spelli','spellinfo'), ('spellr','spellrepall'), ('spellu','spellundo'), ('spellw','spellwrong'), ('spr','sprevious'), ('sre','srewind'), ('st','st'), ('st','stop'), ('sta','stag'), ('star','star'), ('star','startinsert'), ('start','start'), ('startg','startgreplace'), ('startr','startreplace'), ('stj','stjump'), ('stopi','stopinsert'), ('sts','stselect'), ('sun','sunhide'), ('sunme','sunme'), ('sunmenu','sunmenu'), ('sus','suspend'), ('sv','sview'), ('sw','swapname'), ('sy','sy'), ('syn','syn'), ('sync','sync'), ('syncbind','syncbind'), ('syntime','syntime'), ('t','t'), ('tN','tN'), ('tN','tNext'), ('ta','ta'), ('ta','tag'), ('tab','tab'), ('tabN','tabN'), ('tabN','tabNext'), ('tabc','tabclose'), ('tabd','tabdo'), ('tabe','tabedit'), ('tabf','tabfind'), ('tabfir','tabfirst'), ('tabl','tablast'), ('tabm','tabmove'), ('tabn','tabnext'), ('tabnew','tabnew'), ('tabo','tabonly'), ('tabp','tabprevious'), ('tabr','tabrewind'), ('tabs','tabs'), ('tags','tags'), ('tc','tcl'), ('tcld','tcldo'), ('tclf','tclfile'), ('te','tearoff'), ('tf','tfirst'), ('th','throw'), ('tj','tjump'), ('tl','tlast'), ('tm','tm'), ('tm','tmenu'), ('tn','tn'), ('tn','tnext'), ('to','topleft'), ('tp','tprevious'), ('tr','tr'), ('tr','trewind'), ('try','try'), ('ts','tselect'), ('tu','tu'), ('tu','tunmenu'), ('u','u'), ('u','undo'), ('un','un'), ('una','unabbreviate'), ('undoj','undojoin'), ('undol','undolist'), ('unh','unhide'), ('unl','unl'), ('unlo','unlockvar'), ('uns','unsilent'), ('up','update'), ('v','v'), ('ve','ve'), ('ve','version'), ('verb','verbose'), ('vert','vertical'), ('vi','vi'), ('vi','visual'), ('vie','view'), ('vim','vimgrep'), ('vimgrepa','vimgrepadd'), ('viu','viusage'), ('vmapc','vmapclear'), ('vne','vnew'), ('vs','vsplit'), ('w','w'), ('w','write'), ('wN','wNext'), ('wa','wall'), ('wh','while'), ('win','win'), ('win','winsize'), ('winc','wincmd'), ('windo','windo'), ('winp','winpos'), ('wn','wnext'), ('wp','wprevious'), ('wq','wq'), ('wqa','wqall'), ('ws','wsverb'), ('wundo','wundo'), ('wv','wviminfo'), ('x','x'), ('x','xit'), ('xa','xall'), ('xmapc','xmapclear'), ('xme','xme'), ('xmenu','xmenu'), ('xnoreme','xnoreme'), ('xnoremenu','xnoremenu'), ('xunme','xunme'), ('xunmenu','xunmenu'), ('xwininfo','xwininfo'), ('y','yank'), ) return var command = _getcommand() def _getoption(): var = ( ('acd','acd'), ('ai','ai'), ('akm','akm'), ('al','al'), ('aleph','aleph'), ('allowrevins','allowrevins'), ('altkeymap','altkeymap'), ('ambiwidth','ambiwidth'), ('ambw','ambw'), ('anti','anti'), ('antialias','antialias'), ('ar','ar'), ('arab','arab'), ('arabic','arabic'), ('arabicshape','arabicshape'), ('ari','ari'), ('arshape','arshape'), ('autochdir','autochdir'), ('autoindent','autoindent'), ('autoread','autoread'), ('autowrite','autowrite'), ('autowriteall','autowriteall'), ('aw','aw'), ('awa','awa'), ('background','background'), ('backspace','backspace'), ('backup','backup'), ('backupcopy','backupcopy'), ('backupdir','backupdir'), ('backupext','backupext'), ('backupskip','backupskip'), ('balloondelay','balloondelay'), ('ballooneval','ballooneval'), ('balloonexpr','balloonexpr'), ('bdir','bdir'), ('bdlay','bdlay'), ('beval','beval'), ('bex','bex'), ('bexpr','bexpr'), ('bg','bg'), ('bh','bh'), ('bin','bin'), ('binary','binary'), ('biosk','biosk'), ('bioskey','bioskey'), ('bk','bk'), ('bkc','bkc'), ('bl','bl'), ('bomb','bomb'), ('breakat','breakat'), ('brk','brk'), ('browsedir','browsedir'), ('bs','bs'), ('bsdir','bsdir'), ('bsk','bsk'), ('bt','bt'), ('bufhidden','bufhidden'), ('buflisted','buflisted'), ('buftype','buftype'), ('casemap','casemap'), ('cb','cb'), ('cc','cc'), ('ccv','ccv'), ('cd','cd'), ('cdpath','cdpath'), ('cedit','cedit'), ('cf','cf'), ('cfu','cfu'), ('ch','ch'), ('charconvert','charconvert'), ('ci','ci'), ('cin','cin'), ('cindent','cindent'), ('cink','cink'), ('cinkeys','cinkeys'), ('cino','cino'), ('cinoptions','cinoptions'), ('cinw','cinw'), ('cinwords','cinwords'), ('clipboard','clipboard'), ('cmdheight','cmdheight'), ('cmdwinheight','cmdwinheight'), ('cmp','cmp'), ('cms','cms'), ('co','co'), ('cocu','cocu'), ('cole','cole'), ('colorcolumn','colorcolumn'), ('columns','columns'), ('com','com'), ('comments','comments'), ('commentstring','commentstring'), ('compatible','compatible'), ('complete','complete'), ('completefunc','completefunc'), ('completeopt','completeopt'), ('concealcursor','concealcursor'), ('conceallevel','conceallevel'), ('confirm','confirm'), ('consk','consk'), ('conskey','conskey'), ('copyindent','copyindent'), ('cot','cot'), ('cp','cp'), ('cpo','cpo'), ('cpoptions','cpoptions'), ('cpt','cpt'), ('crb','crb'), ('cryptmethod','cryptmethod'), ('cscopepathcomp','cscopepathcomp'), ('cscopeprg','cscopeprg'), ('cscopequickfix','cscopequickfix'), ('cscoperelative','cscoperelative'), ('cscopetag','cscopetag'), ('cscopetagorder','cscopetagorder'), ('cscopeverbose','cscopeverbose'), ('cspc','cspc'), ('csprg','csprg'), ('csqf','csqf'), ('csre','csre'), ('cst','cst'), ('csto','csto'), ('csverb','csverb'), ('cuc','cuc'), ('cul','cul'), ('cursorbind','cursorbind'), ('cursorcolumn','cursorcolumn'), ('cursorline','cursorline'), ('cwh','cwh'), ('debug','debug'), ('deco','deco'), ('def','def'), ('define','define'), ('delcombine','delcombine'), ('dex','dex'), ('dg','dg'), ('dict','dict'), ('dictionary','dictionary'), ('diff','diff'), ('diffexpr','diffexpr'), ('diffopt','diffopt'), ('digraph','digraph'), ('dip','dip'), ('dir','dir'), ('directory','directory'), ('display','display'), ('dy','dy'), ('ea','ea'), ('ead','ead'), ('eadirection','eadirection'), ('eb','eb'), ('ed','ed'), ('edcompatible','edcompatible'), ('ef','ef'), ('efm','efm'), ('ei','ei'), ('ek','ek'), ('enc','enc'), ('encoding','encoding'), ('endofline','endofline'), ('eol','eol'), ('ep','ep'), ('equalalways','equalalways'), ('equalprg','equalprg'), ('errorbells','errorbells'), ('errorfile','errorfile'), ('errorformat','errorformat'), ('esckeys','esckeys'), ('et','et'), ('eventignore','eventignore'), ('ex','ex'), ('expandtab','expandtab'), ('exrc','exrc'), ('fcl','fcl'), ('fcs','fcs'), ('fdc','fdc'), ('fde','fde'), ('fdi','fdi'), ('fdl','fdl'), ('fdls','fdls'), ('fdm','fdm'), ('fdn','fdn'), ('fdo','fdo'), ('fdt','fdt'), ('fen','fen'), ('fenc','fenc'), ('fencs','fencs'), ('fex','fex'), ('ff','ff'), ('ffs','ffs'), ('fic','fic'), ('fileencoding','fileencoding'), ('fileencodings','fileencodings'), ('fileformat','fileformat'), ('fileformats','fileformats'), ('fileignorecase','fileignorecase'), ('filetype','filetype'), ('fillchars','fillchars'), ('fk','fk'), ('fkmap','fkmap'), ('flp','flp'), ('fml','fml'), ('fmr','fmr'), ('fo','fo'), ('foldclose','foldclose'), ('foldcolumn','foldcolumn'), ('foldenable','foldenable'), ('foldexpr','foldexpr'), ('foldignore','foldignore'), ('foldlevel','foldlevel'), ('foldlevelstart','foldlevelstart'), ('foldmarker','foldmarker'), ('foldmethod','foldmethod'), ('foldminlines','foldminlines'), ('foldnestmax','foldnestmax'), ('foldopen','foldopen'), ('foldtext','foldtext'), ('formatexpr','formatexpr'), ('formatlistpat','formatlistpat'), ('formatoptions','formatoptions'), ('formatprg','formatprg'), ('fp','fp'), ('fs','fs'), ('fsync','fsync'), ('ft','ft'), ('gcr','gcr'), ('gd','gd'), ('gdefault','gdefault'), ('gfm','gfm'), ('gfn','gfn'), ('gfs','gfs'), ('gfw','gfw'), ('ghr','ghr'), ('go','go'), ('gp','gp'), ('grepformat','grepformat'), ('grepprg','grepprg'), ('gtl','gtl'), ('gtt','gtt'), ('guicursor','guicursor'), ('guifont','guifont'), ('guifontset','guifontset'), ('guifontwide','guifontwide'), ('guiheadroom','guiheadroom'), ('guioptions','guioptions'), ('guipty','guipty'), ('guitablabel','guitablabel'), ('guitabtooltip','guitabtooltip'), ('helpfile','helpfile'), ('helpheight','helpheight'), ('helplang','helplang'), ('hf','hf'), ('hh','hh'), ('hi','hi'), ('hid','hid'), ('hidden','hidden'), ('highlight','highlight'), ('history','history'), ('hk','hk'), ('hkmap','hkmap'), ('hkmapp','hkmapp'), ('hkp','hkp'), ('hl','hl'), ('hlg','hlg'), ('hls','hls'), ('hlsearch','hlsearch'), ('ic','ic'), ('icon','icon'), ('iconstring','iconstring'), ('ignorecase','ignorecase'), ('im','im'), ('imactivatefunc','imactivatefunc'), ('imactivatekey','imactivatekey'), ('imaf','imaf'), ('imak','imak'), ('imc','imc'), ('imcmdline','imcmdline'), ('imd','imd'), ('imdisable','imdisable'), ('imi','imi'), ('iminsert','iminsert'), ('ims','ims'), ('imsearch','imsearch'), ('imsf','imsf'), ('imstatusfunc','imstatusfunc'), ('inc','inc'), ('include','include'), ('includeexpr','includeexpr'), ('incsearch','incsearch'), ('inde','inde'), ('indentexpr','indentexpr'), ('indentkeys','indentkeys'), ('indk','indk'), ('inex','inex'), ('inf','inf'), ('infercase','infercase'), ('inoremap','inoremap'), ('insertmode','insertmode'), ('invacd','invacd'), ('invai','invai'), ('invakm','invakm'), ('invallowrevins','invallowrevins'), ('invaltkeymap','invaltkeymap'), ('invanti','invanti'), ('invantialias','invantialias'), ('invar','invar'), ('invarab','invarab'), ('invarabic','invarabic'), ('invarabicshape','invarabicshape'), ('invari','invari'), ('invarshape','invarshape'), ('invautochdir','invautochdir'), ('invautoindent','invautoindent'), ('invautoread','invautoread'), ('invautowrite','invautowrite'), ('invautowriteall','invautowriteall'), ('invaw','invaw'), ('invawa','invawa'), ('invbackup','invbackup'), ('invballooneval','invballooneval'), ('invbeval','invbeval'), ('invbin','invbin'), ('invbinary','invbinary'), ('invbiosk','invbiosk'), ('invbioskey','invbioskey'), ('invbk','invbk'), ('invbl','invbl'), ('invbomb','invbomb'), ('invbuflisted','invbuflisted'), ('invcf','invcf'), ('invci','invci'), ('invcin','invcin'), ('invcindent','invcindent'), ('invcompatible','invcompatible'), ('invconfirm','invconfirm'), ('invconsk','invconsk'), ('invconskey','invconskey'), ('invcopyindent','invcopyindent'), ('invcp','invcp'), ('invcrb','invcrb'), ('invcscoperelative','invcscoperelative'), ('invcscopetag','invcscopetag'), ('invcscopeverbose','invcscopeverbose'), ('invcsre','invcsre'), ('invcst','invcst'), ('invcsverb','invcsverb'), ('invcuc','invcuc'), ('invcul','invcul'), ('invcursorbind','invcursorbind'), ('invcursorcolumn','invcursorcolumn'), ('invcursorline','invcursorline'), ('invdeco','invdeco'), ('invdelcombine','invdelcombine'), ('invdg','invdg'), ('invdiff','invdiff'), ('invdigraph','invdigraph'), ('invea','invea'), ('inveb','inveb'), ('inved','inved'), ('invedcompatible','invedcompatible'), ('invek','invek'), ('invendofline','invendofline'), ('inveol','inveol'), ('invequalalways','invequalalways'), ('inverrorbells','inverrorbells'), ('invesckeys','invesckeys'), ('invet','invet'), ('invex','invex'), ('invexpandtab','invexpandtab'), ('invexrc','invexrc'), ('invfen','invfen'), ('invfic','invfic'), ('invfileignorecase','invfileignorecase'), ('invfk','invfk'), ('invfkmap','invfkmap'), ('invfoldenable','invfoldenable'), ('invgd','invgd'), ('invgdefault','invgdefault'), ('invguipty','invguipty'), ('invhid','invhid'), ('invhidden','invhidden'), ('invhk','invhk'), ('invhkmap','invhkmap'), ('invhkmapp','invhkmapp'), ('invhkp','invhkp'), ('invhls','invhls'), ('invhlsearch','invhlsearch'), ('invic','invic'), ('invicon','invicon'), ('invignorecase','invignorecase'), ('invim','invim'), ('invimc','invimc'), ('invimcmdline','invimcmdline'), ('invimd','invimd'), ('invimdisable','invimdisable'), ('invincsearch','invincsearch'), ('invinf','invinf'), ('invinfercase','invinfercase'), ('invinsertmode','invinsertmode'), ('invis','invis'), ('invjoinspaces','invjoinspaces'), ('invjs','invjs'), ('invlazyredraw','invlazyredraw'), ('invlbr','invlbr'), ('invlinebreak','invlinebreak'), ('invlisp','invlisp'), ('invlist','invlist'), ('invloadplugins','invloadplugins'), ('invlpl','invlpl'), ('invlz','invlz'), ('invma','invma'), ('invmacatsui','invmacatsui'), ('invmagic','invmagic'), ('invmh','invmh'), ('invml','invml'), ('invmod','invmod'), ('invmodeline','invmodeline'), ('invmodifiable','invmodifiable'), ('invmodified','invmodified'), ('invmore','invmore'), ('invmousef','invmousef'), ('invmousefocus','invmousefocus'), ('invmousehide','invmousehide'), ('invnu','invnu'), ('invnumber','invnumber'), ('invodev','invodev'), ('invopendevice','invopendevice'), ('invpaste','invpaste'), ('invpi','invpi'), ('invpreserveindent','invpreserveindent'), ('invpreviewwindow','invpreviewwindow'), ('invprompt','invprompt'), ('invpvw','invpvw'), ('invreadonly','invreadonly'), ('invrelativenumber','invrelativenumber'), ('invremap','invremap'), ('invrestorescreen','invrestorescreen'), ('invrevins','invrevins'), ('invri','invri'), ('invrightleft','invrightleft'), ('invrl','invrl'), ('invrnu','invrnu'), ('invro','invro'), ('invrs','invrs'), ('invru','invru'), ('invruler','invruler'), ('invsb','invsb'), ('invsc','invsc'), ('invscb','invscb'), ('invscrollbind','invscrollbind'), ('invscs','invscs'), ('invsecure','invsecure'), ('invsft','invsft'), ('invshellslash','invshellslash'), ('invshelltemp','invshelltemp'), ('invshiftround','invshiftround'), ('invshortname','invshortname'), ('invshowcmd','invshowcmd'), ('invshowfulltag','invshowfulltag'), ('invshowmatch','invshowmatch'), ('invshowmode','invshowmode'), ('invsi','invsi'), ('invsm','invsm'), ('invsmartcase','invsmartcase'), ('invsmartindent','invsmartindent'), ('invsmarttab','invsmarttab'), ('invsmd','invsmd'), ('invsn','invsn'), ('invsol','invsol'), ('invspell','invspell'), ('invsplitbelow','invsplitbelow'), ('invsplitright','invsplitright'), ('invspr','invspr'), ('invsr','invsr'), ('invssl','invssl'), ('invsta','invsta'), ('invstartofline','invstartofline'), ('invstmp','invstmp'), ('invswapfile','invswapfile'), ('invswf','invswf'), ('invta','invta'), ('invtagbsearch','invtagbsearch'), ('invtagrelative','invtagrelative'), ('invtagstack','invtagstack'), ('invtbi','invtbi'), ('invtbidi','invtbidi'), ('invtbs','invtbs'), ('invtermbidi','invtermbidi'), ('invterse','invterse'), ('invtextauto','invtextauto'), ('invtextmode','invtextmode'), ('invtf','invtf'), ('invtgst','invtgst'), ('invtildeop','invtildeop'), ('invtimeout','invtimeout'), ('invtitle','invtitle'), ('invto','invto'), ('invtop','invtop'), ('invtr','invtr'), ('invttimeout','invttimeout'), ('invttybuiltin','invttybuiltin'), ('invttyfast','invttyfast'), ('invtx','invtx'), ('invudf','invudf'), ('invundofile','invundofile'), ('invvb','invvb'), ('invvisualbell','invvisualbell'), ('invwa','invwa'), ('invwarn','invwarn'), ('invwb','invwb'), ('invweirdinvert','invweirdinvert'), ('invwfh','invwfh'), ('invwfw','invwfw'), ('invwic','invwic'), ('invwildignorecase','invwildignorecase'), ('invwildmenu','invwildmenu'), ('invwinfixheight','invwinfixheight'), ('invwinfixwidth','invwinfixwidth'), ('invwiv','invwiv'), ('invwmnu','invwmnu'), ('invwrap','invwrap'), ('invwrapscan','invwrapscan'), ('invwrite','invwrite'), ('invwriteany','invwriteany'), ('invwritebackup','invwritebackup'), ('invws','invws'), ('is','is'), ('isf','isf'), ('isfname','isfname'), ('isi','isi'), ('isident','isident'), ('isk','isk'), ('iskeyword','iskeyword'), ('isp','isp'), ('isprint','isprint'), ('joinspaces','joinspaces'), ('js','js'), ('key','key'), ('keymap','keymap'), ('keymodel','keymodel'), ('keywordprg','keywordprg'), ('km','km'), ('kmp','kmp'), ('kp','kp'), ('langmap','langmap'), ('langmenu','langmenu'), ('laststatus','laststatus'), ('lazyredraw','lazyredraw'), ('lbr','lbr'), ('lcs','lcs'), ('linebreak','linebreak'), ('lines','lines'), ('linespace','linespace'), ('lisp','lisp'), ('lispwords','lispwords'), ('list','list'), ('listchars','listchars'), ('lm','lm'), ('lmap','lmap'), ('loadplugins','loadplugins'), ('lpl','lpl'), ('ls','ls'), ('lsp','lsp'), ('lw','lw'), ('lz','lz'), ('ma','ma'), ('macatsui','macatsui'), ('magic','magic'), ('makeef','makeef'), ('makeprg','makeprg'), ('mat','mat'), ('matchpairs','matchpairs'), ('matchtime','matchtime'), ('maxcombine','maxcombine'), ('maxfuncdepth','maxfuncdepth'), ('maxmapdepth','maxmapdepth'), ('maxmem','maxmem'), ('maxmempattern','maxmempattern'), ('maxmemtot','maxmemtot'), ('mco','mco'), ('mef','mef'), ('menuitems','menuitems'), ('mfd','mfd'), ('mh','mh'), ('mis','mis'), ('mkspellmem','mkspellmem'), ('ml','ml'), ('mls','mls'), ('mm','mm'), ('mmd','mmd'), ('mmp','mmp'), ('mmt','mmt'), ('mod','mod'), ('modeline','modeline'), ('modelines','modelines'), ('modifiable','modifiable'), ('modified','modified'), ('more','more'), ('mouse','mouse'), ('mousef','mousef'), ('mousefocus','mousefocus'), ('mousehide','mousehide'), ('mousem','mousem'), ('mousemodel','mousemodel'), ('mouses','mouses'), ('mouseshape','mouseshape'), ('mouset','mouset'), ('mousetime','mousetime'), ('mp','mp'), ('mps','mps'), ('msm','msm'), ('mzq','mzq'), ('mzquantum','mzquantum'), ('nf','nf'), ('nnoremap','nnoremap'), ('noacd','noacd'), ('noai','noai'), ('noakm','noakm'), ('noallowrevins','noallowrevins'), ('noaltkeymap','noaltkeymap'), ('noanti','noanti'), ('noantialias','noantialias'), ('noar','noar'), ('noarab','noarab'), ('noarabic','noarabic'), ('noarabicshape','noarabicshape'), ('noari','noari'), ('noarshape','noarshape'), ('noautochdir','noautochdir'), ('noautoindent','noautoindent'), ('noautoread','noautoread'), ('noautowrite','noautowrite'), ('noautowriteall','noautowriteall'), ('noaw','noaw'), ('noawa','noawa'), ('nobackup','nobackup'), ('noballooneval','noballooneval'), ('nobeval','nobeval'), ('nobin','nobin'), ('nobinary','nobinary'), ('nobiosk','nobiosk'), ('nobioskey','nobioskey'), ('nobk','nobk'), ('nobl','nobl'), ('nobomb','nobomb'), ('nobuflisted','nobuflisted'), ('nocf','nocf'), ('noci','noci'), ('nocin','nocin'), ('nocindent','nocindent'), ('nocompatible','nocompatible'), ('noconfirm','noconfirm'), ('noconsk','noconsk'), ('noconskey','noconskey'), ('nocopyindent','nocopyindent'), ('nocp','nocp'), ('nocrb','nocrb'), ('nocscoperelative','nocscoperelative'), ('nocscopetag','nocscopetag'), ('nocscopeverbose','nocscopeverbose'), ('nocsre','nocsre'), ('nocst','nocst'), ('nocsverb','nocsverb'), ('nocuc','nocuc'), ('nocul','nocul'), ('nocursorbind','nocursorbind'), ('nocursorcolumn','nocursorcolumn'), ('nocursorline','nocursorline'), ('nodeco','nodeco'), ('nodelcombine','nodelcombine'), ('nodg','nodg'), ('nodiff','nodiff'), ('nodigraph','nodigraph'), ('noea','noea'), ('noeb','noeb'), ('noed','noed'), ('noedcompatible','noedcompatible'), ('noek','noek'), ('noendofline','noendofline'), ('noeol','noeol'), ('noequalalways','noequalalways'), ('noerrorbells','noerrorbells'), ('noesckeys','noesckeys'), ('noet','noet'), ('noex','noex'), ('noexpandtab','noexpandtab'), ('noexrc','noexrc'), ('nofen','nofen'), ('nofic','nofic'), ('nofileignorecase','nofileignorecase'), ('nofk','nofk'), ('nofkmap','nofkmap'), ('nofoldenable','nofoldenable'), ('nogd','nogd'), ('nogdefault','nogdefault'), ('noguipty','noguipty'), ('nohid','nohid'), ('nohidden','nohidden'), ('nohk','nohk'), ('nohkmap','nohkmap'), ('nohkmapp','nohkmapp'), ('nohkp','nohkp'), ('nohls','nohls'), ('nohlsearch','nohlsearch'), ('noic','noic'), ('noicon','noicon'), ('noignorecase','noignorecase'), ('noim','noim'), ('noimc','noimc'), ('noimcmdline','noimcmdline'), ('noimd','noimd'), ('noimdisable','noimdisable'), ('noincsearch','noincsearch'), ('noinf','noinf'), ('noinfercase','noinfercase'), ('noinsertmode','noinsertmode'), ('nois','nois'), ('nojoinspaces','nojoinspaces'), ('nojs','nojs'), ('nolazyredraw','nolazyredraw'), ('nolbr','nolbr'), ('nolinebreak','nolinebreak'), ('nolisp','nolisp'), ('nolist','nolist'), ('noloadplugins','noloadplugins'), ('nolpl','nolpl'), ('nolz','nolz'), ('noma','noma'), ('nomacatsui','nomacatsui'), ('nomagic','nomagic'), ('nomh','nomh'), ('noml','noml'), ('nomod','nomod'), ('nomodeline','nomodeline'), ('nomodifiable','nomodifiable'), ('nomodified','nomodified'), ('nomore','nomore'), ('nomousef','nomousef'), ('nomousefocus','nomousefocus'), ('nomousehide','nomousehide'), ('nonu','nonu'), ('nonumber','nonumber'), ('noodev','noodev'), ('noopendevice','noopendevice'), ('nopaste','nopaste'), ('nopi','nopi'), ('nopreserveindent','nopreserveindent'), ('nopreviewwindow','nopreviewwindow'), ('noprompt','noprompt'), ('nopvw','nopvw'), ('noreadonly','noreadonly'), ('norelativenumber','norelativenumber'), ('noremap','noremap'), ('norestorescreen','norestorescreen'), ('norevins','norevins'), ('nori','nori'), ('norightleft','norightleft'), ('norl','norl'), ('nornu','nornu'), ('noro','noro'), ('nors','nors'), ('noru','noru'), ('noruler','noruler'), ('nosb','nosb'), ('nosc','nosc'), ('noscb','noscb'), ('noscrollbind','noscrollbind'), ('noscs','noscs'), ('nosecure','nosecure'), ('nosft','nosft'), ('noshellslash','noshellslash'), ('noshelltemp','noshelltemp'), ('noshiftround','noshiftround'), ('noshortname','noshortname'), ('noshowcmd','noshowcmd'), ('noshowfulltag','noshowfulltag'), ('noshowmatch','noshowmatch'), ('noshowmode','noshowmode'), ('nosi','nosi'), ('nosm','nosm'), ('nosmartcase','nosmartcase'), ('nosmartindent','nosmartindent'), ('nosmarttab','nosmarttab'), ('nosmd','nosmd'), ('nosn','nosn'), ('nosol','nosol'), ('nospell','nospell'), ('nosplitbelow','nosplitbelow'), ('nosplitright','nosplitright'), ('nospr','nospr'), ('nosr','nosr'), ('nossl','nossl'), ('nosta','nosta'), ('nostartofline','nostartofline'), ('nostmp','nostmp'), ('noswapfile','noswapfile'), ('noswf','noswf'), ('nota','nota'), ('notagbsearch','notagbsearch'), ('notagrelative','notagrelative'), ('notagstack','notagstack'), ('notbi','notbi'), ('notbidi','notbidi'), ('notbs','notbs'), ('notermbidi','notermbidi'), ('noterse','noterse'), ('notextauto','notextauto'), ('notextmode','notextmode'), ('notf','notf'), ('notgst','notgst'), ('notildeop','notildeop'), ('notimeout','notimeout'), ('notitle','notitle'), ('noto','noto'), ('notop','notop'), ('notr','notr'), ('nottimeout','nottimeout'), ('nottybuiltin','nottybuiltin'), ('nottyfast','nottyfast'), ('notx','notx'), ('noudf','noudf'), ('noundofile','noundofile'), ('novb','novb'), ('novisualbell','novisualbell'), ('nowa','nowa'), ('nowarn','nowarn'), ('nowb','nowb'), ('noweirdinvert','noweirdinvert'), ('nowfh','nowfh'), ('nowfw','nowfw'), ('nowic','nowic'), ('nowildignorecase','nowildignorecase'), ('nowildmenu','nowildmenu'), ('nowinfixheight','nowinfixheight'), ('nowinfixwidth','nowinfixwidth'), ('nowiv','nowiv'), ('nowmnu','nowmnu'), ('nowrap','nowrap'), ('nowrapscan','nowrapscan'), ('nowrite','nowrite'), ('nowriteany','nowriteany'), ('nowritebackup','nowritebackup'), ('nows','nows'), ('nrformats','nrformats'), ('nu','nu'), ('number','number'), ('numberwidth','numberwidth'), ('nuw','nuw'), ('odev','odev'), ('oft','oft'), ('ofu','ofu'), ('omnifunc','omnifunc'), ('opendevice','opendevice'), ('operatorfunc','operatorfunc'), ('opfunc','opfunc'), ('osfiletype','osfiletype'), ('pa','pa'), ('para','para'), ('paragraphs','paragraphs'), ('paste','paste'), ('pastetoggle','pastetoggle'), ('patchexpr','patchexpr'), ('patchmode','patchmode'), ('path','path'), ('pdev','pdev'), ('penc','penc'), ('pex','pex'), ('pexpr','pexpr'), ('pfn','pfn'), ('ph','ph'), ('pheader','pheader'), ('pi','pi'), ('pm','pm'), ('pmbcs','pmbcs'), ('pmbfn','pmbfn'), ('popt','popt'), ('preserveindent','preserveindent'), ('previewheight','previewheight'), ('previewwindow','previewwindow'), ('printdevice','printdevice'), ('printencoding','printencoding'), ('printexpr','printexpr'), ('printfont','printfont'), ('printheader','printheader'), ('printmbcharset','printmbcharset'), ('printmbfont','printmbfont'), ('printoptions','printoptions'), ('prompt','prompt'), ('pt','pt'), ('pumheight','pumheight'), ('pvh','pvh'), ('pvw','pvw'), ('qe','qe'), ('quoteescape','quoteescape'), ('rdt','rdt'), ('re','re'), ('readonly','readonly'), ('redrawtime','redrawtime'), ('regexpengine','regexpengine'), ('relativenumber','relativenumber'), ('remap','remap'), ('report','report'), ('restorescreen','restorescreen'), ('revins','revins'), ('ri','ri'), ('rightleft','rightleft'), ('rightleftcmd','rightleftcmd'), ('rl','rl'), ('rlc','rlc'), ('rnu','rnu'), ('ro','ro'), ('rs','rs'), ('rtp','rtp'), ('ru','ru'), ('ruf','ruf'), ('ruler','ruler'), ('rulerformat','rulerformat'), ('runtimepath','runtimepath'), ('sb','sb'), ('sbo','sbo'), ('sbr','sbr'), ('sc','sc'), ('scb','scb'), ('scr','scr'), ('scroll','scroll'), ('scrollbind','scrollbind'), ('scrolljump','scrolljump'), ('scrolloff','scrolloff'), ('scrollopt','scrollopt'), ('scs','scs'), ('sect','sect'), ('sections','sections'), ('secure','secure'), ('sel','sel'), ('selection','selection'), ('selectmode','selectmode'), ('sessionoptions','sessionoptions'), ('sft','sft'), ('sh','sh'), ('shcf','shcf'), ('shell','shell'), ('shellcmdflag','shellcmdflag'), ('shellpipe','shellpipe'), ('shellquote','shellquote'), ('shellredir','shellredir'), ('shellslash','shellslash'), ('shelltemp','shelltemp'), ('shelltype','shelltype'), ('shellxescape','shellxescape'), ('shellxquote','shellxquote'), ('shiftround','shiftround'), ('shiftwidth','shiftwidth'), ('shm','shm'), ('shortmess','shortmess'), ('shortname','shortname'), ('showbreak','showbreak'), ('showcmd','showcmd'), ('showfulltag','showfulltag'), ('showmatch','showmatch'), ('showmode','showmode'), ('showtabline','showtabline'), ('shq','shq'), ('si','si'), ('sidescroll','sidescroll'), ('sidescrolloff','sidescrolloff'), ('siso','siso'), ('sj','sj'), ('slm','slm'), ('sm','sm'), ('smartcase','smartcase'), ('smartindent','smartindent'), ('smarttab','smarttab'), ('smc','smc'), ('smd','smd'), ('sn','sn'), ('so','so'), ('softtabstop','softtabstop'), ('sol','sol'), ('sp','sp'), ('spc','spc'), ('spell','spell'), ('spellcapcheck','spellcapcheck'), ('spellfile','spellfile'), ('spelllang','spelllang'), ('spellsuggest','spellsuggest'), ('spf','spf'), ('spl','spl'), ('splitbelow','splitbelow'), ('splitright','splitright'), ('spr','spr'), ('sps','sps'), ('sr','sr'), ('srr','srr'), ('ss','ss'), ('ssl','ssl'), ('ssop','ssop'), ('st','st'), ('sta','sta'), ('stal','stal'), ('startofline','startofline'), ('statusline','statusline'), ('stl','stl'), ('stmp','stmp'), ('sts','sts'), ('su','su'), ('sua','sua'), ('suffixes','suffixes'), ('suffixesadd','suffixesadd'), ('sw','sw'), ('swapfile','swapfile'), ('swapsync','swapsync'), ('swb','swb'), ('swf','swf'), ('switchbuf','switchbuf'), ('sws','sws'), ('sxe','sxe'), ('sxq','sxq'), ('syn','syn'), ('synmaxcol','synmaxcol'), ('syntax','syntax'), ('t_AB','t_AB'), ('t_AF','t_AF'), ('t_AL','t_AL'), ('t_CS','t_CS'), ('t_CV','t_CV'), ('t_Ce','t_Ce'), ('t_Co','t_Co'), ('t_Cs','t_Cs'), ('t_DL','t_DL'), ('t_EI','t_EI'), ('t_F1','t_F1'), ('t_F2','t_F2'), ('t_F3','t_F3'), ('t_F4','t_F4'), ('t_F5','t_F5'), ('t_F6','t_F6'), ('t_F7','t_F7'), ('t_F8','t_F8'), ('t_F9','t_F9'), ('t_IE','t_IE'), ('t_IS','t_IS'), ('t_K1','t_K1'), ('t_K3','t_K3'), ('t_K4','t_K4'), ('t_K5','t_K5'), ('t_K6','t_K6'), ('t_K7','t_K7'), ('t_K8','t_K8'), ('t_K9','t_K9'), ('t_KA','t_KA'), ('t_KB','t_KB'), ('t_KC','t_KC'), ('t_KD','t_KD'), ('t_KE','t_KE'), ('t_KF','t_KF'), ('t_KG','t_KG'), ('t_KH','t_KH'), ('t_KI','t_KI'), ('t_KJ','t_KJ'), ('t_KK','t_KK'), ('t_KL','t_KL'), ('t_RI','t_RI'), ('t_RV','t_RV'), ('t_SI','t_SI'), ('t_Sb','t_Sb'), ('t_Sf','t_Sf'), ('t_WP','t_WP'), ('t_WS','t_WS'), ('t_ZH','t_ZH'), ('t_ZR','t_ZR'), ('t_al','t_al'), ('t_bc','t_bc'), ('t_cd','t_cd'), ('t_ce','t_ce'), ('t_cl','t_cl'), ('t_cm','t_cm'), ('t_cs','t_cs'), ('t_da','t_da'), ('t_db','t_db'), ('t_dl','t_dl'), ('t_fs','t_fs'), ('t_k1','t_k1'), ('t_k2','t_k2'), ('t_k3','t_k3'), ('t_k4','t_k4'), ('t_k5','t_k5'), ('t_k6','t_k6'), ('t_k7','t_k7'), ('t_k8','t_k8'), ('t_k9','t_k9'), ('t_kB','t_kB'), ('t_kD','t_kD'), ('t_kI','t_kI'), ('t_kN','t_kN'), ('t_kP','t_kP'), ('t_kb','t_kb'), ('t_kd','t_kd'), ('t_ke','t_ke'), ('t_kh','t_kh'), ('t_kl','t_kl'), ('t_kr','t_kr'), ('t_ks','t_ks'), ('t_ku','t_ku'), ('t_le','t_le'), ('t_mb','t_mb'), ('t_md','t_md'), ('t_me','t_me'), ('t_mr','t_mr'), ('t_ms','t_ms'), ('t_nd','t_nd'), ('t_op','t_op'), ('t_se','t_se'), ('t_so','t_so'), ('t_sr','t_sr'), ('t_te','t_te'), ('t_ti','t_ti'), ('t_ts','t_ts'), ('t_u7','t_u7'), ('t_ue','t_ue'), ('t_us','t_us'), ('t_ut','t_ut'), ('t_vb','t_vb'), ('t_ve','t_ve'), ('t_vi','t_vi'), ('t_vs','t_vs'), ('t_xs','t_xs'), ('ta','ta'), ('tabline','tabline'), ('tabpagemax','tabpagemax'), ('tabstop','tabstop'), ('tag','tag'), ('tagbsearch','tagbsearch'), ('taglength','taglength'), ('tagrelative','tagrelative'), ('tags','tags'), ('tagstack','tagstack'), ('tal','tal'), ('tb','tb'), ('tbi','tbi'), ('tbidi','tbidi'), ('tbis','tbis'), ('tbs','tbs'), ('tenc','tenc'), ('term','term'), ('termbidi','termbidi'), ('termencoding','termencoding'), ('terse','terse'), ('textauto','textauto'), ('textmode','textmode'), ('textwidth','textwidth'), ('tf','tf'), ('tgst','tgst'), ('thesaurus','thesaurus'), ('tildeop','tildeop'), ('timeout','timeout'), ('timeoutlen','timeoutlen'), ('title','title'), ('titlelen','titlelen'), ('titleold','titleold'), ('titlestring','titlestring'), ('tl','tl'), ('tm','tm'), ('to','to'), ('toolbar','toolbar'), ('toolbariconsize','toolbariconsize'), ('top','top'), ('tpm','tpm'), ('tr','tr'), ('ts','ts'), ('tsl','tsl'), ('tsr','tsr'), ('ttimeout','ttimeout'), ('ttimeoutlen','ttimeoutlen'), ('ttm','ttm'), ('tty','tty'), ('ttybuiltin','ttybuiltin'), ('ttyfast','ttyfast'), ('ttym','ttym'), ('ttymouse','ttymouse'), ('ttyscroll','ttyscroll'), ('ttytype','ttytype'), ('tw','tw'), ('tx','tx'), ('uc','uc'), ('udf','udf'), ('udir','udir'), ('ul','ul'), ('undodir','undodir'), ('undofile','undofile'), ('undolevels','undolevels'), ('undoreload','undoreload'), ('updatecount','updatecount'), ('updatetime','updatetime'), ('ur','ur'), ('ut','ut'), ('vb','vb'), ('vbs','vbs'), ('vdir','vdir'), ('ve','ve'), ('verbose','verbose'), ('verbosefile','verbosefile'), ('vfile','vfile'), ('vi','vi'), ('viewdir','viewdir'), ('viewoptions','viewoptions'), ('viminfo','viminfo'), ('virtualedit','virtualedit'), ('visualbell','visualbell'), ('vnoremap','vnoremap'), ('vop','vop'), ('wa','wa'), ('wak','wak'), ('warn','warn'), ('wb','wb'), ('wc','wc'), ('wcm','wcm'), ('wd','wd'), ('weirdinvert','weirdinvert'), ('wfh','wfh'), ('wfw','wfw'), ('wh','wh'), ('whichwrap','whichwrap'), ('wi','wi'), ('wic','wic'), ('wig','wig'), ('wildchar','wildchar'), ('wildcharm','wildcharm'), ('wildignore','wildignore'), ('wildignorecase','wildignorecase'), ('wildmenu','wildmenu'), ('wildmode','wildmode'), ('wildoptions','wildoptions'), ('wim','wim'), ('winaltkeys','winaltkeys'), ('window','window'), ('winfixheight','winfixheight'), ('winfixwidth','winfixwidth'), ('winheight','winheight'), ('winminheight','winminheight'), ('winminwidth','winminwidth'), ('winwidth','winwidth'), ('wiv','wiv'), ('wiw','wiw'), ('wm','wm'), ('wmh','wmh'), ('wmnu','wmnu'), ('wmw','wmw'), ('wop','wop'), ('wrap','wrap'), ('wrapmargin','wrapmargin'), ('wrapscan','wrapscan'), ('write','write'), ('writeany','writeany'), ('writebackup','writebackup'), ('writedelay','writedelay'), ('ws','ws'), ('ww','ww'), ) return var option = _getoption()
mpl-2.0
perkinslr/pypyjs
website/js/pypy.js-0.2.0/lib/modules/test/test_buffer.py
34
1455
"""Unit tests for buffer objects. For now, tests just new or changed functionality. """ import sys import unittest from test import test_support class BufferTests(unittest.TestCase): def test_extended_getslice(self): # Test extended slicing by comparing with list slicing. s = "".join(chr(c) for c in list(range(255, -1, -1))) b = buffer(s) indices = (0, None, 1, 3, 19, 300, -1, -2, -31, -300) for start in indices: for stop in indices: # Skip step 0 (invalid) for step in indices[1:]: self.assertEqual(b[start:stop:step], s[start:stop:step]) def test_newbuffer_interface(self): # Test that the buffer object has the new buffer interface # as used by the memoryview object s = "".join(chr(c) for c in list(range(255, -1, -1))) b = buffer(s) m = memoryview(b) # Should not raise an exception self.assertEqual(m.tobytes(), s) def test_large_buffer_size_and_offset(self): data = bytearray('hola mundo') buf = buffer(data, sys.maxsize, sys.maxsize) self.assertEqual(buf[:4096], "") def test_main(): with test_support.check_py3k_warnings(("buffer.. not supported", DeprecationWarning)): test_support.run_unittest(BufferTests) if __name__ == "__main__": test_main()
mit
michalliu/OpenWrt-Firefly-Libraries
staging_dir/target-mipsel_1004kc+dsp_uClibc-0.9.33.2/usr/lib/python2.7/distutils/version.py
259
11433
# # distutils/version.py # # Implements multiple version numbering conventions for the # Python Module Distribution Utilities. # # $Id$ # """Provides classes to represent module version numbers (one class for each style of version numbering). There are currently two such classes implemented: StrictVersion and LooseVersion. Every version number class implements the following interface: * the 'parse' method takes a string and parses it to some internal representation; if the string is an invalid version number, 'parse' raises a ValueError exception * the class constructor takes an optional string argument which, if supplied, is passed to 'parse' * __str__ reconstructs the string that was passed to 'parse' (or an equivalent string -- ie. one that will generate an equivalent version number instance) * __repr__ generates Python code to recreate the version number instance * __cmp__ compares the current instance with either another instance of the same class or a string (which will be parsed to an instance of the same class, thus must follow the same rules) """ import string, re from types import StringType class Version: """Abstract base class for version numbering classes. Just provides constructor (__init__) and reproducer (__repr__), because those seem to be the same for all version numbering classes. """ def __init__ (self, vstring=None): if vstring: self.parse(vstring) def __repr__ (self): return "%s ('%s')" % (self.__class__.__name__, str(self)) # Interface for version-number classes -- must be implemented # by the following classes (the concrete ones -- Version should # be treated as an abstract class). # __init__ (string) - create and take same action as 'parse' # (string parameter is optional) # parse (string) - convert a string representation to whatever # internal representation is appropriate for # this style of version numbering # __str__ (self) - convert back to a string; should be very similar # (if not identical to) the string supplied to parse # __repr__ (self) - generate Python code to recreate # the instance # __cmp__ (self, other) - compare two version numbers ('other' may # be an unparsed version string, or another # instance of your version class) class StrictVersion (Version): """Version numbering for anal retentives and software idealists. Implements the standard interface for version number classes as described above. A version number consists of two or three dot-separated numeric components, with an optional "pre-release" tag on the end. The pre-release tag consists of the letter 'a' or 'b' followed by a number. If the numeric components of two version numbers are equal, then one with a pre-release tag will always be deemed earlier (lesser) than one without. The following are valid version numbers (shown in the order that would be obtained by sorting according to the supplied cmp function): 0.4 0.4.0 (these two are equivalent) 0.4.1 0.5a1 0.5b3 0.5 0.9.6 1.0 1.0.4a3 1.0.4b1 1.0.4 The following are examples of invalid version numbers: 1 2.7.2.2 1.3.a4 1.3pl1 1.3c4 The rationale for this version numbering system will be explained in the distutils documentation. """ version_re = re.compile(r'^(\d+) \. (\d+) (\. (\d+))? ([ab](\d+))?$', re.VERBOSE) def parse (self, vstring): match = self.version_re.match(vstring) if not match: raise ValueError, "invalid version number '%s'" % vstring (major, minor, patch, prerelease, prerelease_num) = \ match.group(1, 2, 4, 5, 6) if patch: self.version = tuple(map(string.atoi, [major, minor, patch])) else: self.version = tuple(map(string.atoi, [major, minor]) + [0]) if prerelease: self.prerelease = (prerelease[0], string.atoi(prerelease_num)) else: self.prerelease = None def __str__ (self): if self.version[2] == 0: vstring = string.join(map(str, self.version[0:2]), '.') else: vstring = string.join(map(str, self.version), '.') if self.prerelease: vstring = vstring + self.prerelease[0] + str(self.prerelease[1]) return vstring def __cmp__ (self, other): if isinstance(other, StringType): other = StrictVersion(other) compare = cmp(self.version, other.version) if (compare == 0): # have to compare prerelease # case 1: neither has prerelease; they're equal # case 2: self has prerelease, other doesn't; other is greater # case 3: self doesn't have prerelease, other does: self is greater # case 4: both have prerelease: must compare them! if (not self.prerelease and not other.prerelease): return 0 elif (self.prerelease and not other.prerelease): return -1 elif (not self.prerelease and other.prerelease): return 1 elif (self.prerelease and other.prerelease): return cmp(self.prerelease, other.prerelease) else: # numeric versions don't match -- return compare # prerelease stuff doesn't matter # end class StrictVersion # The rules according to Greg Stein: # 1) a version number has 1 or more numbers separated by a period or by # sequences of letters. If only periods, then these are compared # left-to-right to determine an ordering. # 2) sequences of letters are part of the tuple for comparison and are # compared lexicographically # 3) recognize the numeric components may have leading zeroes # # The LooseVersion class below implements these rules: a version number # string is split up into a tuple of integer and string components, and # comparison is a simple tuple comparison. This means that version # numbers behave in a predictable and obvious way, but a way that might # not necessarily be how people *want* version numbers to behave. There # wouldn't be a problem if people could stick to purely numeric version # numbers: just split on period and compare the numbers as tuples. # However, people insist on putting letters into their version numbers; # the most common purpose seems to be: # - indicating a "pre-release" version # ('alpha', 'beta', 'a', 'b', 'pre', 'p') # - indicating a post-release patch ('p', 'pl', 'patch') # but of course this can't cover all version number schemes, and there's # no way to know what a programmer means without asking him. # # The problem is what to do with letters (and other non-numeric # characters) in a version number. The current implementation does the # obvious and predictable thing: keep them as strings and compare # lexically within a tuple comparison. This has the desired effect if # an appended letter sequence implies something "post-release": # eg. "0.99" < "0.99pl14" < "1.0", and "5.001" < "5.001m" < "5.002". # # However, if letters in a version number imply a pre-release version, # the "obvious" thing isn't correct. Eg. you would expect that # "1.5.1" < "1.5.2a2" < "1.5.2", but under the tuple/lexical comparison # implemented here, this just isn't so. # # Two possible solutions come to mind. The first is to tie the # comparison algorithm to a particular set of semantic rules, as has # been done in the StrictVersion class above. This works great as long # as everyone can go along with bondage and discipline. Hopefully a # (large) subset of Python module programmers will agree that the # particular flavour of bondage and discipline provided by StrictVersion # provides enough benefit to be worth using, and will submit their # version numbering scheme to its domination. The free-thinking # anarchists in the lot will never give in, though, and something needs # to be done to accommodate them. # # Perhaps a "moderately strict" version class could be implemented that # lets almost anything slide (syntactically), and makes some heuristic # assumptions about non-digits in version number strings. This could # sink into special-case-hell, though; if I was as talented and # idiosyncratic as Larry Wall, I'd go ahead and implement a class that # somehow knows that "1.2.1" < "1.2.2a2" < "1.2.2" < "1.2.2pl3", and is # just as happy dealing with things like "2g6" and "1.13++". I don't # think I'm smart enough to do it right though. # # In any case, I've coded the test suite for this module (see # ../test/test_version.py) specifically to fail on things like comparing # "1.2a2" and "1.2". That's not because the *code* is doing anything # wrong, it's because the simple, obvious design doesn't match my # complicated, hairy expectations for real-world version numbers. It # would be a snap to fix the test suite to say, "Yep, LooseVersion does # the Right Thing" (ie. the code matches the conception). But I'd rather # have a conception that matches common notions about version numbers. class LooseVersion (Version): """Version numbering for anarchists and software realists. Implements the standard interface for version number classes as described above. A version number consists of a series of numbers, separated by either periods or strings of letters. When comparing version numbers, the numeric components will be compared numerically, and the alphabetic components lexically. The following are all valid version numbers, in no particular order: 1.5.1 1.5.2b2 161 3.10a 8.02 3.4j 1996.07.12 3.2.pl0 3.1.1.6 2g6 11g 0.960923 2.2beta29 1.13++ 5.5.kw 2.0b1pl0 In fact, there is no such thing as an invalid version number under this scheme; the rules for comparison are simple and predictable, but may not always give the results you want (for some definition of "want"). """ component_re = re.compile(r'(\d+ | [a-z]+ | \.)', re.VERBOSE) def __init__ (self, vstring=None): if vstring: self.parse(vstring) def parse (self, vstring): # I've given up on thinking I can reconstruct the version string # from the parsed tuple -- so I just store the string here for # use by __str__ self.vstring = vstring components = filter(lambda x: x and x != '.', self.component_re.split(vstring)) for i in range(len(components)): try: components[i] = int(components[i]) except ValueError: pass self.version = components def __str__ (self): return self.vstring def __repr__ (self): return "LooseVersion ('%s')" % str(self) def __cmp__ (self, other): if isinstance(other, StringType): other = LooseVersion(other) return cmp(self.version, other.version) # end class LooseVersion
gpl-2.0
54Pany/pupy
pupy/packages/windows/all/pupwinutils/shellcode.py
28
1191
import ctypes import threading def allocate_exe(shellcode): ptr = ctypes.windll.kernel32.VirtualAlloc(ctypes.c_int(0), ctypes.c_int(len(shellcode)), ctypes.c_int(0x3000), ctypes.c_int(0x40)) buf = (ctypes.c_char * len(shellcode)).from_buffer(shellcode) ctypes.windll.kernel32.RtlMoveMemory(ctypes.c_int(ptr), buf, ctypes.c_int(len(shellcode))) ht = ctypes.windll.kernel32.CreateThread(ctypes.c_int(0), ctypes.c_int(0), ctypes.c_int(ptr), ctypes.c_int(0), ctypes.c_int(0), ctypes.pointer(ctypes.c_int(0))) ctypes.windll.kernel32.WaitForSingleObject(ctypes.c_int(ht),ctypes.c_int(-1)) def exec_shellcode(shellcode): shellcode = bytearray(shellcode) t = threading.Thread(target=allocate_exe, args=(shellcode,)) t.daemon = True t.start()
bsd-3-clause
0x46616c6b/ansible
lib/ansible/modules/cloud/openstack/os_networks_facts.py
15
4624
#!/usr/bin/python # Copyright (c) 2015 Hewlett-Packard Development Company, L.P. # # This module is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This software is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this software. If not, see <http://www.gnu.org/licenses/>. ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'version': '1.0'} DOCUMENTATION = ''' --- module: os_networks_facts short_description: Retrieve facts about one or more OpenStack networks. version_added: "2.0" author: "Davide Agnello (@dagnello)" description: - Retrieve facts about one or more networks from OpenStack. requirements: - "python >= 2.6" - "shade" options: name: description: - Name or ID of the Network required: false filters: description: - A dictionary of meta data to use for further filtering. Elements of this dictionary may be additional dictionaries. required: false availability_zone: description: - Ignored. Present for backwards compatability required: false extends_documentation_fragment: openstack ''' EXAMPLES = ''' - name: Gather facts about previously created networks os_networks_facts: auth: auth_url: https://your_api_url.com:9000/v2.0 username: user password: password project_name: someproject - name: Show openstack networks debug: var: openstack_networks - name: Gather facts about a previously created network by name os_networks_facts: auth: auth_url: https://your_api_url.com:9000/v2.0 username: user password: password project_name: someproject name: network1 - name: Show openstack networks debug: var: openstack_networks - name: Gather facts about a previously created network with filter # Note: name and filters parameters are Not mutually exclusive os_networks_facts: auth: auth_url: https://your_api_url.com:9000/v2.0 username: user password: password project_name: someproject filters: tenant_id: 55e2ce24b2a245b09f181bf025724cbe subnets: - 057d4bdf-6d4d-4728-bb0f-5ac45a6f7400 - 443d4dc0-91d4-4998-b21c-357d10433483 - name: Show openstack networks debug: var: openstack_networks ''' RETURN = ''' openstack_networks: description: has all the openstack facts about the networks returned: always, but can be null type: complex contains: id: description: Unique UUID. returned: success type: string name: description: Name given to the network. returned: success type: string status: description: Network status. returned: success type: string subnets: description: Subnet(s) included in this network. returned: success type: list of strings tenant_id: description: Tenant id associated with this network. returned: success type: string shared: description: Network shared flag. returned: success type: boolean ''' try: import shade HAS_SHADE = True except ImportError: HAS_SHADE = False def main(): argument_spec = openstack_full_argument_spec( name=dict(required=False, default=None), filters=dict(required=False, type='dict', default=None) ) module = AnsibleModule(argument_spec) if not HAS_SHADE: module.fail_json(msg='shade is required for this module') try: cloud = shade.openstack_cloud(**module.params) networks = cloud.search_networks(module.params['name'], module.params['filters']) module.exit_json(changed=False, ansible_facts=dict( openstack_networks=networks)) except shade.OpenStackCloudException as e: module.fail_json(msg=str(e)) # this is magic, see lib/ansible/module_common.py from ansible.module_utils.basic import * from ansible.module_utils.openstack import * if __name__ == '__main__': main()
gpl-3.0