<commit_before>#import pygame, random
#from pygame.locals import *

import random
from ggame import App, Color, LineStyle, Sprite, LineAsset, RectangleAsset, CircleAsset, PolygonAsset, ImageAsset, Frame

red = Color(0xff0000, 1.0)
green = Color(0x00ff00, 1.0)
black = Color(0x000000, 1.0)
white=Color(0xffffff,1.0)
yellow=Color(0xffff00,1.0)

thinline = LineStyle(1, black)
noline=LineStyle(0,white)

cLevel=0.0
cLeveli=int(cLevel)

cWidth=int(round(12*(1+cLevel*0.4),0))
cHeight=int(round(9*(1+cLevel*0.4),0))
cCellSize=16

aCellWallH=LineAsset(cCellSize,0,thinline)
aCellWallV=LineAsset(0,cCellSize,thinline)

def incGlobals():
    global cLevel
    global cLeveli

    global cWidth
    global cHeight
    global cCellSize

    cLevel+=1
    cLeveli=int(cLevel)

    cWidth=int(round(12*(1+cLevel*0.4),0))
    cHeight=int(round(9*(1+cLevel*0.4),0))

class Layout(object):
    def __init__(self, pScreen):
        self.dimX=cWidth #20 #40
        self.dimY=cHeight #10 #30
        self.cellSize=cCellSize
        self.compass = [(-1,0),(0,1),(1,0),(0,-1)]
        self.totalCells = self.dimX*self.dimY # 40 * 30
        #self.mLayer = pygame.Surface(pScreen.get_size())
        #self.mLayer = self.mLayer.convert_alpha()
        #self.mLayer.fill((0, 0, 0, 0))

        #self.sLayer = pygame.Surface(pScreen.get_size())
        #self.sLayer = self.sLayer.convert_alpha()
        #self.sLayer.fill((0, 0, 0, 0))

        self.currentCell = random.randint(0, self.totalCells-1)

    def myLocation(self):
        return self.currentCell

class Maze(Layout):

    def __init__(self, pScreen):
        super(Maze,self).__init__(pScreen)
        self.mazeArray = []
        self.ghostArray=[]
        self.ghostLocations=[]
        self.bubbleArray=[]
        self.cellStack = []
        self.visitedCells = 1
        self.score=0
        self.mScreen=pScreen

        self.bubbleArray=random.sample(range(1, self.totalCells-1), 1)

        for y in range(self.dimY): # 80 wide + 60 tall
            print('Maze init')
            Sprite(aCellWallH,(0, y*self.cellSize))
            #pygame.draw.line(self.mLayer, (0,0,0,255), (0, y*self.cellSize), (self.dimX*self.cellSize, y*self.cellSize))
            for x in range(self.dimX):
                self.mazeArray.append(0)
                if ( y == 0 ):
                    pass
                    #pygame.draw.line(self.mLayer, (0,0,0,255), (x*self.cellSize,0), (x*self.cellSize,self.dimY*self.cellSize))
        while(self.visitedCells < self.totalCells):
            x = int(self.currentCell % self.dimX)
            y = int(self.currentCell / self.dimX)
            neighbors = []
            for i in range(4):
                nx = x + self.compass[i][0]
                ny = y + self.compass[i][1]
                if ((nx >= 0) and (ny >= 0) and (nx < self.dimX) and (ny < self.dimY)):
                    if (self.mazeArray[(ny*self.dimX+nx)] & 0x000F) == 0:
                        nidx = ny*self.dimX+nx
                        neighbors.append((nidx,1<<i))
            if len(neighbors) > 0:
                idx = random.randint(0,len(neighbors)-1)
                nidx,direction = neighbors[idx]
                dx = x*self.cellSize
                dy = y*self.cellSize
                if direction & 1:
                    self.mazeArray[nidx] |= (4)
                    #pygame.draw.line(self.mLayer, (0,0,0,0), (dx,dy+1),(dx,dy+self.cellSize-1))
                elif direction & 2:
                    self.mazeArray[nidx] |= (8)
                    #pygame.draw.line(self.mLayer, (0,0,0,0), (dx+1,dy+self.cellSize),(dx+self.cellSize-1,dy+self.cellSize))
                elif direction & 4:
                    self.mazeArray[nidx] |= (1)
                    #pygame.draw.line(self.mLayer, (0,0,0,0), (dx+self.cellSize,dy+1),(dx+self.cellSize,dy+self.cellSize-1))
                elif direction & 8:
                    self.mazeArray[nidx] |= (2)
                    #pygame.draw.line(self.mLayer, (0,0,0,0), (dx+1,dy),(dx+self.cellSize-1,dy))
                self.mazeArray[self.currentCell] |= direction
                self.cellStack.append(self.currentCell)
                self.currentCell = nidx
                self.visitedCells = self.visitedCells + 1
            else:
                self.currentCell = self.cellStack.pop()

        for i in range(cLeveli):
            ghost1=Ghost(self.mScreen,self.getMazeArray(), self.getCellStack())
            self.addGhost(ghost1)

    def drawBubbles(self):
        for bubbleCell in self.bubbleArray:
            dx = (bubbleCell % self.dimX)*self.cellSize
            dy = (bubbleCell / self.dimX)*self.cellSize
            #pygame.draw.circle(self.sLayer, (0,0,255,200), (dx+self.cellSize/2,dy+self.cellSize/2),self.cellSize/4)

    def drawGhosts(self):
        for g in self.ghostArray:
            gCell=g.myLocation()
            dx = (gCell % self.dimX)*self.cellSize
            dy = (gCell / self.dimX)*self.cellSize
            #pygame.draw.rect(self.sLayer, (0,255,0,255), Rect(dx+self.cellSize/4,dy+self.cellSize/4,self.cellSize/2,self.cellSize/2))

    def drawPacman(self):
        pCell=self.Pacman.myLocation()
        dx = (pCell % self.dimX)*self.cellSize
        dy = (pCell / self.dimX)*self.cellSize
        if self.Pacman.getState()=='Playing':
            pass
            #pygame.draw.circle(self.sLayer, (250,240,0,250), (dx+self.cellSize/2,dy+self.cellSize/2),self.cellSize/2-1)
        elif self.Pacman.getState()=='Lost':
            pass
            #pygame.draw.circle(self.sLayer, (211,211,211,250), (dx+self.cellSize/2,dy+self.cellSize/2),self.cellSize/2-1)
        elif self.Pacman.getState()=='Won':
            pass
            #pygame.draw.circle(self.sLayer, (0,255,255,250), (dx+self.cellSize/2,dy+self.cellSize/2),self.cellSize/2-1)

    def getMazeArray(self):
        return self.mazeArray[:]

    def getCellStack(self):
        return self.cellStack[:]

    def addGhost(self, pGhost):
        self.ghostArray.append(pGhost)

    def addPacman(self, pPacman):
        self.Pacman=pPacman

    def draw(self,screen):
        #self.sLayer.fill((0, 0, 0, 0))

        self.drawBubbles()
        self.drawGhosts()
        self.drawPacman()

        #screen.blit(self.sLayer, (0,0))
        #screen.blit(self.mLayer, (0,0))

    def checkCollisions(self):
        self.ghostLocations=[]
        ghostLocation=0
        pCell=self.Pacman.myLocation()

        for g in self.ghostArray:
            g.update()
            ghostLocation=g.myLocation()
            if ghostLocation==self.totalCells-1:
                self.ghostArray.remove(g)
                ghost1=Ghost(self.mScreen,self.getMazeArray(), self.getCellStack())
                self.addGhost(ghost1)
            else:
                self.ghostLocations.append(ghostLocation)

        if pCell in self.ghostLocations:
            self.Pacman.setState('Lost')
            return

        if pCell in self.bubbleArray:
            self.score +=1
            self.bubbleArray.remove(pCell)
            if len(self.bubbleArray)==0:
                self.Pacman.setState('Won')

class Ghost(Layout):

    def __init__(self, pScreen, mArray, cStack):
        super(Ghost,self).__init__(pScreen)
        self.mazeArray = mArray
        self.cellStack=cStack

    def update(self):
        if self.currentCell == (self.totalCells-1): # have we reached the exit?
            return
        moved = False
        while(moved == False):
            x = self.currentCell % self.dimX
            y = self.currentCell / self.dimX
            neighbors = []
            directions = self.mazeArray[self.currentCell] & 0xF
            for i in range(4):
                if (directions & (1<<i)) > 0:
                    nx = x + self.compass[i][0]
                    ny = y + self.compass[i][1]
                    if ((nx >= 0) and (ny >= 0) and (nx < self.dimX) and (ny < self.dimY)):
                        nidx = ny*self.dimX+nx
                        if ((self.mazeArray[nidx] & 0xFF00) == 0): # make sure there's no backtrack
                            neighbors.append((nidx,1<<i))
            if len(neighbors) > 0:
                idx = random.randint(0,len(neighbors)-1)
                nidx,direction = neighbors[idx]
                if direction & 1:
                    self.mazeArray[nidx] |= (4 << 12)
                elif direction & 2:
                    self.mazeArray[nidx] |= (8 << 12)
                elif direction & 4:
                    self.mazeArray[nidx] |= (1 << 12)
                elif direction & 8:
                    self.mazeArray[nidx] |= (2 << 12)
                self.mazeArray[self.currentCell] |= direction << 8
                self.cellStack.append(self.currentCell)
                self.currentCell = nidx
                moved = True
            else:
                self.mazeArray[self.currentCell] &= 0xF0FF # not a solution
                self.currentCell = self.cellStack.pop()

class Pacman(Layout):

    def __init__(self, pScreen, mArray, cStack):
        super(Pacman,self).__init__(pScreen)
        self.mazeArray = mArray
        self.cellStack=cStack
        self.state='Playing'

    def update(self, uDirection):

        if self.state=='Lost':
            return

        x = self.currentCell % self.dimX
        y = self.currentCell / self.dimX
        dx = x*self.cellSize
        dy = y*self.cellSize

        neighbors = []
        directions = self.mazeArray[self.currentCell] & 0xF
        for i in xrange(4):
            if (directions & (1<<i)) > 0:
                nx = x + self.compass[i][0]
                ny = y + self.compass[i][1]

                if ((nx >= 0) and (ny >= 0) and (nx < self.dimX) and (ny < self.dimY)):
                    nidx = ny*self.dimX+nx
                    nX=(nidx % self.dimX)*self.cellSize
                    nY=(nidx / self.dimX)*self.cellSize

                    if (uDirection==K_UP) and (nY<dy):
                        neighbors.append((nidx,1<<i))

                    elif (uDirection==K_DOWN) and (nY>dy):
                        neighbors.append((nidx,1<<i))

                    elif (uDirection==K_RIGHT) and (nX>dx):
                        neighbors.append((nidx,1<<i))

                    elif (uDirection==K_LEFT) and (nX<dx):
                        neighbors.append((nidx,1<<i))

        if len(neighbors) > 0:
            nidx,direction = neighbors[0]
            if direction & 1:
                self.mazeArray[nidx] |= (4 << 12)
            elif direction & 2:
                self.mazeArray[nidx] |= (8 << 12)
            elif direction & 4:
                self.mazeArray[nidx] |= (1 << 12)
            elif direction & 8:
                self.mazeArray[nidx] |= (2 << 12)

            self.mazeArray[self.currentCell] |= direction << 8
            self.cellStack.append(self.currentCell)
            self.currentCell = nidx

    def getState(self):
        return self.state

    def setState(self,pState):
        self.state=pState

class MazeGame(App):

    def __init__(self, width, height):
        super().__init__(width, height)
        bg_asset = RectangleAsset(width-1, height-1, thinline, white)
        bg = Sprite(bg_asset, (0,0))

    def step(self):
        gState='Play'
        print ('init')
        while gState=='Play':
            incGlobals()
            #pygame.init()
            screen = 1 #pygame.display.set_mode((cWidth*cCellSize, cHeight*cCellSize))
            #pygame.display.set_caption('Labyrinth: level '+str(cLeveli))
            #pygame.mouse.set_visible(0)
            #background = pygame.Surface(screen.get_size())
            #background = background.convert()
            #background.fill((255, 255, 255))

            newMaze = Maze(screen)
            myPacman=Pacman(screen,newMaze.getMazeArray(), newMaze.getCellStack())
            newMaze.addPacman(myPacman)

            #screen.blit(background, (0, 0))
            #pygame.display.flip()
            #clock = pygame.time.Clock()
            while 1:
                #clock.tick(2)
                #screen.blit(background, (0, 0))
                #for event in pygame.event.get():
                #    if event.type == QUIT:
                #        return
                #    elif event.type == KEYDOWN and event.key in (K_UP,K_DOWN,K_RIGHT,K_LEFT):
                #        myPacman.update(event.key)
                #    elif event.type == KEYDOWN and event.key == K_ESCAPE:
                #        return
                if myPacman.getState() =='Playing':
                    newMaze.checkCollisions()

                newMaze.draw(screen)
                #pygame.display.flip()
                if myPacman.getState()=='Won':
                    #pygame.display.quit()
                    #pygame.quit()
                    break
                else:
                    break

            break

myapp = MazeGame(600,600)
myapp.run()<commit_msg>Updated from Brython Server: 1/10/2017 8:44:25 PM<commit_after>#import pygame, random
#from pygame.locals import *

import random
from ggame import App, Color, LineStyle, Sprite, LineAsset, RectangleAsset, CircleAsset, PolygonAsset, ImageAsset, Frame

red = Color(0xff0000, 1.0)
green = Color(0x00ff00, 1.0)
black = Color(0x000000, 1.0)
white=Color(0xffffff,1.0)
yellow=Color(0xffff00,1.0)

thinline = LineStyle(1, black)
noline=LineStyle(0,white)

cLevel=0.0
cLeveli=int(cLevel)

cWidth=int(round(12*(1+cLevel*0.4),0))
cHeight=int(round(9*(1+cLevel*0.4),0))
cCellSize=16

aCellWallH=LineAsset(cCellSize,0,thinline)
aCellWallV=LineAsset(0,cCellSize,thinline)

def incGlobals():
    global cLevel
    global cLeveli

    global cWidth
    global cHeight
    global cCellSize

    cLevel+=1
    cLeveli=int(cLevel)

    cWidth=int(round(12*(1+cLevel*0.4),0))
    cHeight=int(round(9*(1+cLevel*0.4),0))

class Layout(object):
    def __init__(self, pScreen):
        self.dimX=cWidth #20 #40
        self.dimY=cHeight #10 #30
        self.cellSize=cCellSize
        self.compass = [(-1,0),(0,1),(1,0),(0,-1)]
        self.totalCells = self.dimX*self.dimY # 40 * 30
        #self.mLayer = pygame.Surface(pScreen.get_size())
        #self.mLayer = self.mLayer.convert_alpha()
        #self.mLayer.fill((0, 0, 0, 0))

        #self.sLayer = pygame.Surface(pScreen.get_size())
        #self.sLayer = self.sLayer.convert_alpha()
        #self.sLayer.fill((0, 0, 0, 0))

        self.currentCell = random.randint(0, self.totalCells-1)

    def myLocation(self):
        return self.currentCell

class Maze(Layout):

    def __init__(self, pScreen):
        super(Maze,self).__init__(pScreen)
        self.mazeArray = []
        self.ghostArray=[]
        self.ghostLocations=[]
        self.bubbleArray=[]
        self.cellStack = []
        self.visitedCells = 1
        self.score=0
        self.mScreen=pScreen

        self.bubbleArray=random.sample(range(1, self.totalCells-1), 1)

        for y in range(self.dimY): # 80 wide + 60 tall
            for x in range(self.dimX):
                Sprite(aCellWallH,(x*self.cellSize, y*self.cellSize))
            #pygame.draw.line(self.mLayer, (0,0,0,255), (0, y*self.cellSize), (self.dimX*self.cellSize, y*self.cellSize))
            for x in range(self.dimX):
                self.mazeArray.append(0)
                if ( y == 0 ):
                    pass
                    #pygame.draw.line(self.mLayer, (0,0,0,255), (x*self.cellSize,0), (x*self.cellSize,self.dimY*self.cellSize))
        while(self.visitedCells < self.totalCells):
            x = int(self.currentCell % self.dimX)
            y = int(self.currentCell / self.dimX)
            neighbors = []
            for i in range(4):
                nx = x + self.compass[i][0]
                ny = y + self.compass[i][1]
                if ((nx >= 0) and (ny >= 0) and (nx < self.dimX) and (ny < self.dimY)):
                    if (self.mazeArray[(ny*self.dimX+nx)] & 0x000F) == 0:
                        nidx = ny*self.dimX+nx
                        neighbors.append((nidx,1<<i))
            if len(neighbors) > 0:
                idx = random.randint(0,len(neighbors)-1)
                nidx,direction = neighbors[idx]
                dx = x*self.cellSize
                dy = y*self.cellSize
                if direction & 1:
                    self.mazeArray[nidx] |= (4)
                    #pygame.draw.line(self.mLayer, (0,0,0,0), (dx,dy+1),(dx,dy+self.cellSize-1))
                elif direction & 2:
                    self.mazeArray[nidx] |= (8)
                    #pygame.draw.line(self.mLayer, (0,0,0,0), (dx+1,dy+self.cellSize),(dx+self.cellSize-1,dy+self.cellSize))
                elif direction & 4:
                    self.mazeArray[nidx] |= (1)
                    #pygame.draw.line(self.mLayer, (0,0,0,0), (dx+self.cellSize,dy+1),(dx+self.cellSize,dy+self.cellSize-1))
                elif direction & 8:
                    self.mazeArray[nidx] |= (2)
                    #pygame.draw.line(self.mLayer, (0,0,0,0), (dx+1,dy),(dx+self.cellSize-1,dy))
                self.mazeArray[self.currentCell] |= direction
                self.cellStack.append(self.currentCell)
                self.currentCell = nidx
                self.visitedCells = self.visitedCells + 1
            else:
                self.currentCell = self.cellStack.pop()

        for i in range(cLeveli):
            ghost1=Ghost(self.mScreen,self.getMazeArray(), self.getCellStack())
            self.addGhost(ghost1)

    def drawBubbles(self):
        for bubbleCell in self.bubbleArray:
            dx = (bubbleCell % self.dimX)*self.cellSize
            dy = (bubbleCell / self.dimX)*self.cellSize
            #pygame.draw.circle(self.sLayer, (0,0,255,200), (dx+self.cellSize/2,dy+self.cellSize/2),self.cellSize/4)

    def drawGhosts(self):
        for g in self.ghostArray:
            gCell=g.myLocation()
            dx = (gCell % self.dimX)*self.cellSize
            dy = (gCell / self.dimX)*self.cellSize
            #pygame.draw.rect(self.sLayer, (0,255,0,255), Rect(dx+self.cellSize/4,dy+self.cellSize/4,self.cellSize/2,self.cellSize/2))

    def drawPacman(self):
        pCell=self.Pacman.myLocation()
        dx = (pCell % self.dimX)*self.cellSize
        dy = (pCell / self.dimX)*self.cellSize
        if self.Pacman.getState()=='Playing':
            pass
            #pygame.draw.circle(self.sLayer, (250,240,0,250), (dx+self.cellSize/2,dy+self.cellSize/2),self.cellSize/2-1)
        elif self.Pacman.getState()=='Lost':
            pass
            #pygame.draw.circle(self.sLayer, (211,211,211,250), (dx+self.cellSize/2,dy+self.cellSize/2),self.cellSize/2-1)
        elif self.Pacman.getState()=='Won':
            pass
            #pygame.draw.circle(self.sLayer, (0,255,255,250), (dx+self.cellSize/2,dy+self.cellSize/2),self.cellSize/2-1)

    def getMazeArray(self):
        return self.mazeArray[:]

    def getCellStack(self):
        return self.cellStack[:]

    def addGhost(self, pGhost):
        self.ghostArray.append(pGhost)

    def addPacman(self, pPacman):
        self.Pacman=pPacman

    def draw(self,screen):
        #self.sLayer.fill((0, 0, 0, 0))

        self.drawBubbles()
        self.drawGhosts()
        self.drawPacman()

        #screen.blit(self.sLayer, (0,0))
        #screen.blit(self.mLayer, (0,0))

    def checkCollisions(self):
        self.ghostLocations=[]
        ghostLocation=0
        pCell=self.Pacman.myLocation()

        for g in self.ghostArray:
            g.update()
            ghostLocation=g.myLocation()
            if ghostLocation==self.totalCells-1:
                self.ghostArray.remove(g)
                ghost1=Ghost(self.mScreen,self.getMazeArray(), self.getCellStack())
                self.addGhost(ghost1)
            else:
                self.ghostLocations.append(ghostLocation)

        if pCell in self.ghostLocations:
            self.Pacman.setState('Lost')
            return

        if pCell in self.bubbleArray:
            self.score +=1
            self.bubbleArray.remove(pCell)
            if len(self.bubbleArray)==0:
                self.Pacman.setState('Won')

class Ghost(Layout):

    def __init__(self, pScreen, mArray, cStack):
        super(Ghost,self).__init__(pScreen)
        self.mazeArray = mArray
        self.cellStack=cStack

    def update(self):
        if self.currentCell == (self.totalCells-1): # have we reached the exit?
            return
        moved = False
        while(moved == False):
            x = self.currentCell % self.dimX
            y = self.currentCell / self.dimX
            neighbors = []
            directions = self.mazeArray[self.currentCell] & 0xF
            for i in range(4):
                if (directions & (1<<i)) > 0:
                    nx = x + self.compass[i][0]
                    ny = y + self.compass[i][1]
                    if ((nx >= 0) and (ny >= 0) and (nx < self.dimX) and (ny < self.dimY)):
                        nidx = ny*self.dimX+nx
                        if ((self.mazeArray[nidx] & 0xFF00) == 0): # make sure there's no backtrack
                            neighbors.append((nidx,1<<i))
            if len(neighbors) > 0:
                idx = random.randint(0,len(neighbors)-1)
                nidx,direction = neighbors[idx]
                if direction & 1:
                    self.mazeArray[nidx] |= (4 << 12)
                elif direction & 2:
                    self.mazeArray[nidx] |= (8 << 12)
                elif direction & 4:
                    self.mazeArray[nidx] |= (1 << 12)
                elif direction & 8:
                    self.mazeArray[nidx] |= (2 << 12)
                self.mazeArray[self.currentCell] |= direction << 8
                self.cellStack.append(self.currentCell)
                self.currentCell = nidx
                moved = True
            else:
                self.mazeArray[self.currentCell] &= 0xF0FF # not a solution
                self.currentCell = self.cellStack.pop()

class Pacman(Layout):

    def __init__(self, pScreen, mArray, cStack):
        super(Pacman,self).__init__(pScreen)
        self.mazeArray = mArray
        self.cellStack=cStack
        self.state='Playing'

    def update(self, uDirection):

        if self.state=='Lost':
            return

        x = self.currentCell % self.dimX
        y = self.currentCell / self.dimX
        dx = x*self.cellSize
        dy = y*self.cellSize

        neighbors = []
        directions = self.mazeArray[self.currentCell] & 0xF
        for i in xrange(4):
            if (directions & (1<<i)) > 0:
                nx = x + self.compass[i][0]
                ny = y + self.compass[i][1]

                if ((nx >= 0) and (ny >= 0) and (nx < self.dimX) and (ny < self.dimY)):
                    nidx = ny*self.dimX+nx
                    nX=(nidx % self.dimX)*self.cellSize
                    nY=(nidx / self.dimX)*self.cellSize

                    if (uDirection==K_UP) and (nY<dy):
                        neighbors.append((nidx,1<<i))

                    elif (uDirection==K_DOWN) and (nY>dy):
                        neighbors.append((nidx,1<<i))

                    elif (uDirection==K_RIGHT) and (nX>dx):
                        neighbors.append((nidx,1<<i))

                    elif (uDirection==K_LEFT) and (nX<dx):
                        neighbors.append((nidx,1<<i))

        if len(neighbors) > 0:
            nidx,direction = neighbors[0]
            if direction & 1:
                self.mazeArray[nidx] |= (4 << 12)
            elif direction & 2:
                self.mazeArray[nidx] |= (8 << 12)
            elif direction & 4:
                self.mazeArray[nidx] |= (1 << 12)
            elif direction & 8:
                self.mazeArray[nidx] |= (2 << 12)

            self.mazeArray[self.currentCell] |= direction << 8
            self.cellStack.append(self.currentCell)
            self.currentCell = nidx

    def getState(self):
        return self.state

    def setState(self,pState):
        self.state=pState

class MazeGame(App):

    def __init__(self, width, height):
        super().__init__(width, height)
        bg_asset = RectangleAsset(width-1, height-1, thinline, white)
        bg = Sprite(bg_asset, (0,0))

    def step(self):
        gState='Play'
        print ('init')
        while gState=='Play':
            incGlobals()
            #pygame.init()
            screen = 1 #pygame.display.set_mode((cWidth*cCellSize, cHeight*cCellSize))
            #pygame.display.set_caption('Labyrinth: level '+str(cLeveli))
            #pygame.mouse.set_visible(0)
            #background = pygame.Surface(screen.get_size())
            #background = background.convert()
            #background.fill((255, 255, 255))

            newMaze = Maze(screen)
            myPacman=Pacman(screen,newMaze.getMazeArray(), newMaze.getCellStack())
            newMaze.addPacman(myPacman)

            #screen.blit(background, (0, 0))
            #pygame.display.flip()
            #clock = pygame.time.Clock()
            while 1:
                #clock.tick(2)
                #screen.blit(background, (0, 0))
                #for event in pygame.event.get():
                #    if event.type == QUIT:
                #        return
                #    elif event.type == KEYDOWN and event.key in (K_UP,K_DOWN,K_RIGHT,K_LEFT):
                #        myPacman.update(event.key)
                #    elif event.type == KEYDOWN and event.key == K_ESCAPE:
                #        return
                if myPacman.getState() =='Playing':
                    newMaze.checkCollisions()

                newMaze.draw(screen)
                #pygame.display.flip()
                if myPacman.getState()=='Won':
                    #pygame.display.quit()
                    #pygame.quit()
                    break
                else:
                    break

            break

myapp = MazeGame(600,600)
myapp.run()<|endoftext|>


<commit_before>from KnowledgeBase import KnowledgeBase
from ML_Controller import ML_Controller
import sys

def main():
	kb = KnowledgeBase("config/login_file.txt")
	kb.importData("data/SPECT.data", "data/SPECT.schema")
	#importData("config/login_file.txt", "data/SPECTF.data", "data/SPECTF.schema")
	ml = ML_Controller(kb)
	ml.runAlgorithm()

	try:
		while True:
			ml.optimizeAlgorithm()
	except KeyboardInterrupt:
			print "NEMO ending. . ."
			sys.exit()

if __name__ == "__main__":
	main()
<commit_msg>Bug fixes<commit_after>from KnowledgeBase import KnowledgeBase
from ML_Controller import ML_Controller
import sys

def main():
	kb = KnowledgeBase("config/login_file.txt")
	kb.importData("data/SPECT.data", "data/SPECT.schema")
	#importData("config/login_file.txt", "data/SPECTF.data", "data/SPECTF.schema")
	ml = ML_Controller(kb)
	ml.runAlgorithm()

	try:
		while True:
			ml.optimizeAlgorithm()
	except:
			print "NEMO ending. . ."
			sys.exit()

if __name__ == "__main__":
	main()
<|endoftext|>


<commit_before>import KnowledgeBase
import ML-Controller

def main():
	kb = KnowledgeBase("config/login_file.txt")
	kb.importData("data/SPECT.data", "data/SPECT.schema")
	#importData("config/login_file.txt", "data/SPECTF.data", "data/SPECTF.schema")
	ml = ML_Controller(kb)

if __name__ == "__main__":
	main()
<commit_msg>Confirming all files are up to date<commit_after>import KnowledgeBase
import ML_Controller

def main():
	kb = KnowledgeBase("config/login_file.txt")
	kb.importData("data/SPECT.data", "data/SPECT.schema")
	#importData("config/login_file.txt", "data/SPECTF.data", "data/SPECTF.schema")
	ml = ML_Controller(kb)

if __name__ == "__main__":
	main()
<|endoftext|>


<commit_before>#!/usr/bin/env python

import json,fire,re
from pathlib import Path

def is_export(cell):
    if cell['cell_type'] != 'code': return False
    src = cell['source']
    if len(src) == 0 or len(src[0]) < 7: return False
    #import pdb; pdb.set_trace()
    return re.match(r'^\s*#\s*export\s*$', src[0], re.IGNORECASE) is not None

def getSortedFiles(allFiles, upTo=None):
    '''Returns all the notebok files sorted by name.
       allFiles = True : returns all files
                = '*_*.ipynb' : returns this pattern
       upTo = None : no upper limit
            = filter : returns all files up to 'filter' included
       The sorting optioj is important to ensure that the notebok are executed in correct order.
    '''
    import glob
    ret = []
    if (allFiles==True): ret = glob.glob('*.ipynb') # Checks both that is bool type and that is True
    if (isinstance(allFiles,str)): ret = glob.glob(allFiles)
    if 0==len(ret):
        print('WARNING: No files found')
        return ret
    if upTo is not None: ret = [f for f in ret if str(f)<=str(upTo)]
    return sorted(ret)

def notebook2script(fname=None, allFiles=None, upTo=None):
    '''Finds cells starting with `#export` and puts them into a new module
       + allFiles: convert all files in the folder
       + upTo: convert files up to specified one included

       ES:
       notebook2script --allFiles=True   # Parse all files
       notebook2script --allFiles=nb*   # Parse all files starting with nb*
       notebook2script --upTo=10   # Parse all files with (name<='10')
       notebook2script --allFiles=*_*.ipynb --upTo=10   # Parse all files with an '_' and (name<='10')
    '''
    # initial checks
    if (allFiles is None) and (upTo is not None): allFiles=True # Enable allFiles if upTo is present
    if (fname is None) and (not allFiles): print('Should provide a file name')
    if not allFiles: notebook2scriptSingle(fname)
    else:
        print('Begin...')
        [notebook2scriptSingle(f) for f in getSortedFiles(allFiles,upTo)]
        print('...End')

def notebook2scriptSingle(fname):
    "Finds cells starting with `#export` and puts them into a new module"
    fname = Path(fname)
    fname_out = f'nb_{fname.stem.split("_")[0]}.py'
    main_dic = json.load(open(fname,'r',encoding="utf-8"))
    code_cells = [c for c in main_dic['cells'] if is_export(c)]
    module = f'''
#################################################
### THIS FILE WAS AUTOGENERATED! DO NOT EDIT! ###
#################################################
# file to edit: dev_nb/{fname.name}

'''
    for cell in code_cells: module += ''.join(cell['source'][1:]) + '\n\n'
    # remove trailing spaces
    module = re.sub(r' +$', '', module, flags=re.MULTILINE)
    if not (fname.parent/'exp').exists(): (fname.parent/'exp').mkdir()
    output_path = fname.parent/'exp'/fname_out
    open(output_path,'w').write(module[:-2])
    print(f"Converted {fname} to {output_path}")

if __name__ == '__main__': fire.Fire(notebook2script)

<commit_msg>Fixes export with unicode characters (#413)<commit_after>#!/usr/bin/env python

import json,fire,re
from pathlib import Path
import io

def is_export(cell):
    if cell['cell_type'] != 'code': return False
    src = cell['source']
    if len(src) == 0 or len(src[0]) < 7: return False
    #import pdb; pdb.set_trace()
    return re.match(r'^\s*#\s*export\s*$', src[0], re.IGNORECASE) is not None

def getSortedFiles(allFiles, upTo=None):
    '''Returns all the notebok files sorted by name.
       allFiles = True : returns all files
                = '*_*.ipynb' : returns this pattern
       upTo = None : no upper limit
            = filter : returns all files up to 'filter' included
       The sorting optioj is important to ensure that the notebok are executed in correct order.
    '''
    import glob
    ret = []
    if (allFiles==True): ret = glob.glob('*.ipynb') # Checks both that is bool type and that is True
    if (isinstance(allFiles,str)): ret = glob.glob(allFiles)
    if 0==len(ret):
        print('WARNING: No files found')
        return ret
    if upTo is not None: ret = [f for f in ret if str(f)<=str(upTo)]
    return sorted(ret)

def notebook2script(fname=None, allFiles=None, upTo=None):
    '''Finds cells starting with `#export` and puts them into a new module
       + allFiles: convert all files in the folder
       + upTo: convert files up to specified one included

       ES:
       notebook2script --allFiles=True   # Parse all files
       notebook2script --allFiles=nb*   # Parse all files starting with nb*
       notebook2script --upTo=10   # Parse all files with (name<='10')
       notebook2script --allFiles=*_*.ipynb --upTo=10   # Parse all files with an '_' and (name<='10')
    '''
    # initial checks
    if (allFiles is None) and (upTo is not None): allFiles=True # Enable allFiles if upTo is present
    if (fname is None) and (not allFiles): print('Should provide a file name')
    if not allFiles: notebook2scriptSingle(fname)
    else:
        print('Begin...')
        [notebook2scriptSingle(f) for f in getSortedFiles(allFiles,upTo)]
        print('...End')

def notebook2scriptSingle(fname):
    "Finds cells starting with `#export` and puts them into a new module"
    fname = Path(fname)
    fname_out = f'nb_{fname.stem.split("_")[0]}.py'
    main_dic = json.load(open(fname,'r',encoding="utf-8"))
    code_cells = [c for c in main_dic['cells'] if is_export(c)]
    module = f'''
#################################################
### THIS FILE WAS AUTOGENERATED! DO NOT EDIT! ###
#################################################
# file to edit: dev_nb/{fname.name}

'''
    for cell in code_cells: module += ''.join(cell['source'][1:]) + '\n\n'
    # remove trailing spaces
    module = re.sub(r' +$', '', module, flags=re.MULTILINE)
    if not (fname.parent/'exp').exists(): (fname.parent/'exp').mkdir()
    output_path = fname.parent/'exp'/fname_out
    with io.open(output_path, "w", encoding="utf-8") as f:
        f.write(module[:-2])
    print(f"Converted {fname} to {output_path}")

if __name__ == '__main__': fire.Fire(notebook2script)

<|endoftext|>


<commit_before>"browser for lefigaro website"
# -*- coding: utf-8 -*-

# Copyright(C) 2011  Julien Hebert
#
# 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, version 3 of the License.
#
# 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.

from .pages.article import ArticlePage
from .pages.flashactu import FlashActuPage
from weboob.tools.browser import BaseBrowser

class NewspaperFigaroBrowser(BaseBrowser):
    "NewspaperFigaroBrowser class"
    PAGES = {
             "http://www.lefigaro.fr/flash-actu/(\d{4})/(\d{2})/(\d{2})/(.*$)": FlashActuPage,
             "http://www.lefigaro.fr/flash-sport/(\d{4})/(\d{2})/(\d{2})/(.*$)": FlashActuPage,
             "http://www.lefigaro.fr/politique/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/sciences/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/sport/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/sport-business/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/football-ligue-1-et-2/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/international/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/livres/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/immobilier/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/actualite-france/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/mon-figaro/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/cinema/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/conjoncture/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/football/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/automobile/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/marches/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/actualites/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/matieres-premieres/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/programmes-tele/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/le-talk/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/sortir-paris/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/vie-entreprise/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/autres-sports/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/environnement/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/rugby/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/societes/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/medias/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/hightech/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/conso/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/theatre/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/football-coupes-d-europe/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/sante/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/assurance/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/retraite/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/tennis/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/emploi/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/impots/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/placement/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/culture/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/musique/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/photos/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/formation/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/lefigaromagazine/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/creation-gestion-entreprise/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/flash-eco/(\d{4})/(\d{2})/(\d{2})/(.*$)": FlashActuPage,
             "http://www.lefigaro.fr/bd/(\d{4})/(\d{2})/(\d{2})/(.*$)": FlashActuPage,
            }

    def is_logged(self):
        return False

    def login(self):
        pass

    def fillobj(self, obj, fields):
        pass

    def get_content(self, _id):
        "return page article content"
        self.location(_id)
        return self.page.get_article(_id)
<commit_msg>add a category<commit_after>"browser for lefigaro website"
# -*- coding: utf-8 -*-

# Copyright(C) 2011  Julien Hebert
#
# 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, version 3 of the License.
#
# 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.

from .pages.article import ArticlePage
from .pages.flashactu import FlashActuPage
from weboob.tools.browser import BaseBrowser

class NewspaperFigaroBrowser(BaseBrowser):
    "NewspaperFigaroBrowser class"
    PAGES = {
             "http://www.lefigaro.fr/flash-actu/(\d{4})/(\d{2})/(\d{2})/(.*$)": FlashActuPage,
             "http://www.lefigaro.fr/flash-sport/(\d{4})/(\d{2})/(\d{2})/(.*$)": FlashActuPage,
             "http://www.lefigaro.fr/politique/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/sciences/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/sport/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/sport-business/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/football-ligue-1-et-2/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/international/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/livres/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/immobilier/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/actualite-france/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/mon-figaro/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/cinema/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/conjoncture/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/football/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/automobile/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/marches/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/actualites/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/matieres-premieres/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/programmes-tele/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/le-talk/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/sortir-paris/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/vie-entreprise/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/autres-sports/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/environnement/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/rugby/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/societes/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/medias/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/hightech/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/conso/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/theatre/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/football-coupes-d-europe/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/sante/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/voyages/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/assurance/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/retraite/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/tennis/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/emploi/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/impots/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/placement/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/culture/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/musique/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/photos/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/formation/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/lefigaromagazine/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/creation-gestion-entreprise/(\d{4})/(\d{2})/(\d{2})/(.*$)": ArticlePage,
             "http://www.lefigaro.fr/flash-eco/(\d{4})/(\d{2})/(\d{2})/(.*$)": FlashActuPage,
             "http://www.lefigaro.fr/bd/(\d{4})/(\d{2})/(\d{2})/(.*$)": FlashActuPage,
            }

    def is_logged(self):
        return False

    def login(self):
        pass

    def fillobj(self, obj, fields):
        pass

    def get_content(self, _id):
        "return page article content"
        self.location(_id)
        return self.page.get_article(_id)
<|endoftext|>


<commit_before># -*- coding: utf-8 -*-

# Copyright(C) 2010  Romain Bignon, Julien Hébert, Christophe Benz
#
# 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, version 3 of the License.
#
# 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.

from functools import partial
import getpass
from inspect import getargspec
import logging
from optparse import OptionGroup, OptionParser
import re
import sys

from weboob.core import CallErrors
from weboob.core.backends import BackendsConfig

from .base import BackendNotFound, BaseApplication
from .formatters.load import formatters, load_formatter
from .results import ResultsCondition, ResultsConditionException

__all__ = ['ConsoleApplication']

class ConsoleApplication(BaseApplication):
    """
    Base application class for CLI applications.
    """

    SYNOPSIS = 'Usage: %prog [options (-h for help)] command [parameters...]'

    def __init__(self):
        option_parser = OptionParser(self.SYNOPSIS, version=self._get_optparse_version())
        app_options = OptionGroup(option_parser, '%s Options' % self.APPNAME.capitalize())
        self.add_application_options(app_options)
        option_parser.add_option_group(app_options)

        try:
            BaseApplication.__init__(self, option_parser=option_parser)
        except BackendsConfig.WrongPermissions, e:
            logging.error(u'Error: %s' % e)
            sys.exit(1)

        self._parser.format_description = lambda x: self._parser.description

        if self._parser.description is None:
            self._parser.description = ''
        self._parser.description += 'Available commands:\n'
        for name, arguments, doc_string in self._commands:
            command = '%s %s' % (name, arguments)
            self._parser.description += '   %-30s %s\n' % (command, doc_string)

        results_options = OptionGroup(self._parser, 'Results Options')
        results_options.add_option('-c', '--condition', help='filter result items to display given a boolean condition')
        results_options.add_option('-n', '--count', type='int', help='get a maximum number of results (all backends merged)')
        results_options.add_option('-f', '--formatter', choices=formatters, help='select output formatter (%s)' % u','.join(formatters))
        results_options.add_option('-s', '--select', help='select result item keys to display (comma separated)')
        self._parser.add_option_group(results_options)

        formatting_options = OptionGroup(self._parser, 'Formatting Options')
        formatting_options.add_option('--no-header', dest='no_header', action='store_true', help='do not display header')
        formatting_options.add_option('--no-keys', dest='no_keys', action='store_true', help='do not display item keys')
        self._parser.add_option_group(formatting_options)

    def add_application_options(self, group):
        # XXX why is it in ConsoleApplication and not BaseApplication? -romain
        pass

    def _handle_app_options(self):
        if self.options.formatter:
            formatter_name = self.options.formatter
        else:
            formatter_name = 'multiline'
        self.formatter = load_formatter(formatter_name)

        if self.options.no_header:
            self.formatter.display_header = False

        if self.options.no_keys:
            self.formatter.display_keys = False

        if self.options.select:
            self.selected_fields = self.options.select.split(',')
        else:
            self.selected_fields = None

        if self.options.condition:
            self.condition = ResultsCondition(self.options.condition)
        else:
            self.condition = None

    def _get_completions(self):
        return set(name for name, arguments, doc_string in self._commands)

    def ask(self, question, default=None, masked=False, regexp=None):
        """
        Ask a question to user.

        @param question  text displayed (str)
        @param default  optional default value (str)
        @param masked  if True, do not show typed text (bool)
        @param regexp  text must match this regexp (str)
        @return  entered text by user (str)
        """

        if default is not None:
            question = u'%s [%s]' % (question, default)
        hidden_msg = u'(input chars are hidden) ' if masked else ''
        question = u'%s%s: ' % (hidden_msg, question)

        correct = False
        while not correct:
            line = getpass.getpass(question) if masked else raw_input(question)
            if not line and default is not None:
                line = default
            correct = not regexp or re.match(regexp, unicode(line))

        return line

    def process_command(self, command=None, *args):
        if command is None:
            self._parser.print_help()
            return 0

        def f(x):
            return x.startswith('command_' + command)

        matching_commands = filter(f, dir(self))

        if len(matching_commands) == 0:
            sys.stderr.write("No such command: %s.\n" % command)
            return 1
        if len(matching_commands) != 1:
            sys.stderr.write("Ambiguious command %s: %s.\n" % (command, ', '.join(
                [s.replace('command_', '', 1) for s in matching_commands])))
            return 1

        func = getattr(self, matching_commands[0])

        _args, varargs, varkw, defaults = getargspec(func)
        nb_max_args = nb_min_args = len(_args) - 1
        if defaults:
            nb_min_args -= len(defaults)

        if len(args) > nb_max_args and not varargs:
            sys.stderr.write("Command '%s' takes at most %d arguments.\n" % (command, nb_max_args))
            return 1
        if len(args) < nb_min_args:
            if varargs or defaults:
                sys.stderr.write("Command '%s' takes at least %d arguments.\n" % (command, nb_min_args))
            else:
                sys.stderr.write("Command '%s' takes %d arguments.\n" % (command, nb_min_args))
            return 1

        try:
            command_result = func(*args)
        except CallErrors, errors:
            logging.error(errors)
            return 1

        self.formatter.flush()

        # Process result if value is returned by command
        if isinstance(command_result, str):
            print command_result
        elif isinstance(command_result, unicode):
            print command_result.encode('utf-8')
        elif isinstance(command_result, int):
            return command_result
        elif command_result is None:
            return 0
        else:
            try:
                print unicode(command_result).encode('utf-8')
            except ValueError:
                raise Exception(u'Command result type not expected: %s' % type(command_result))

        return 0

    _commands = []
    def register_command(f, doc_string, register_to=_commands):
        def get_arguments(func, skip=0):
            """
            Get arguments of a function as a string.
            skip is the number of skipped arguments.
            """
            skip += 1
            args, varargs, varkw, defaults = getargspec(func)
            cut = len(args)
            if defaults:
                cut -= len(defaults)
            args = ["<%s>" % a for a in args[skip:cut]] + \
                   ["[%s]" % a for a in args[cut:]]
            if varargs:
                args.append("[%s..]" % varargs)
            if varkw:
                raise TypeError('Command %s requests illegal keyword args (**%s)' % varkw)
            return " ".join(args)

        command_name = f.func_name.replace('command_', '')
        register_to.append((command_name, get_arguments(f), doc_string))
        return f

    def command(doc_string, f=register_command):
        return partial(f, doc_string=doc_string)

    def set_default_formatter(self, name):
        if not self.options.formatter:
            try:
                self.formatter = load_formatter(name)
            except ImportError:
                default_name = 'multiline'
                logging.error('Could not load default formatter "%s" for this command. Falling back to "%s".' % (
                    name, default_name))
                self.formatter = load_formatter(default_name)

    def set_formatter_header(self, string):
        self.formatter.set_header(string)

    def format(self, result, backend_name=None):
        try:
            self.formatter.format(obj=result, backend_name=backend_name,
                                  selected_fields=self.selected_fields, condition=self.condition)
        except ResultsConditionException, e:
            logging.error(e)

    # XXX why do not use staticmethod as a decorator? -romain
    register_command = staticmethod(register_command)
    command = staticmethod(command)

    def load_configured_backends(self, caps=None, names=None, *args, **kwargs):
        loaded_backends = BaseApplication.load_configured_backends(self, caps, names, *args, **kwargs)
        if not loaded_backends:
            logging.error(u'Cannot start application: no configured backend was found.\nHere is a list of all available backends:')
            from weboob.applications.weboobcfg import WeboobCfg
            weboobcfg = WeboobCfg()
            weboobcfg.options, args = weboobcfg._parser.parse_args([])
            weboobcfg._handle_app_options()
            if caps is not None:
                if not isinstance(caps, (list, tuple, set)):
                    caps = (caps,)
                caps = iter(cap.__name__ for cap in caps)
            weboobcfg.command_backends(*caps)
            logging.error(u'You can configure a backends using the "weboobcfg add" command:\nweboobcfg add <name> [options..]')
            sys.exit(0)

    def parse_id(self, _id):
        try:
            _id, backend_name = _id.rsplit('@', 1)
        except ValueError:
            backend_name = None
        return _id, backend_name

    @classmethod
    def run(klass, args=None):
        try:
            super(ConsoleApplication, klass).run(args)
        except BackendNotFound, e:
            logging.error(e)

    def do(self, function, *args, **kwargs):
        """
        Call Weboob.do(), after having filled the yielded object, if selected fields are given by user.
        """
        for i, (backend, result) in enumerate(self.weboob.do(function, *args, **kwargs)):
            if self.options.count and i == self.options.count:
                break
            fields = set(self.selected_fields) - set('*')
            if fields:
                try:
                    backend.browser.fillobj(result, fields)
                except Exception, e:
                    logging.warning(u'Could not retrieve required fields (%s): %s' % (','.join(fields), e))
            yield backend, result

    def do_caps(self, caps, function, *args, **kwargs):
        """
        Call Weboob.do_caps(), after having filled the yielded object, if selected fields are given by user.
        """
        for backend, result in self.weboob.do_caps(caps, function, *args, **kwargs):
            if self.options.count and i == self.options.count:
                break
            fields = set(self.selected_fields) - set('*')
            if fields:
                try:
                    backend.browser.fillobj(result, fields)
                except Exception, e:
                    logging.warning(u'Could not retrieve required fields (%s): %s' % (','.join(fields), e))
            yield backend, result

    def do_backends(self, backends, function, *args, **kwargs):
        """
        Call Weboob.do_backends(), after having filled the yielded object, if selected fields are given by user.
        """
        for backend, result in self.weboob.do_backends(backends, function, *args, **kwargs):
            if self.options.count and i == self.options.count:
                break
            fields = set(self.selected_fields) - set('*')
            if fields:
                try:
                    backend.browser.fillobj(result, fields)
                except Exception, e:
                    logging.warning(u'Could not retrieve required fields (%s): %s' % (','.join(fields), e))
            yield backend, result
<commit_msg>missing enumeration<commit_after># -*- coding: utf-8 -*-

# Copyright(C) 2010  Romain Bignon, Julien Hébert, Christophe Benz
#
# 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, version 3 of the License.
#
# 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.

from functools import partial
import getpass
from inspect import getargspec
import logging
from optparse import OptionGroup, OptionParser
import re
import sys

from weboob.core import CallErrors
from weboob.core.backends import BackendsConfig

from .base import BackendNotFound, BaseApplication
from .formatters.load import formatters, load_formatter
from .results import ResultsCondition, ResultsConditionException

__all__ = ['ConsoleApplication']

class ConsoleApplication(BaseApplication):
    """
    Base application class for CLI applications.
    """

    SYNOPSIS = 'Usage: %prog [options (-h for help)] command [parameters...]'

    def __init__(self):
        option_parser = OptionParser(self.SYNOPSIS, version=self._get_optparse_version())
        app_options = OptionGroup(option_parser, '%s Options' % self.APPNAME.capitalize())
        self.add_application_options(app_options)
        option_parser.add_option_group(app_options)

        try:
            BaseApplication.__init__(self, option_parser=option_parser)
        except BackendsConfig.WrongPermissions, e:
            logging.error(u'Error: %s' % e)
            sys.exit(1)

        self._parser.format_description = lambda x: self._parser.description

        if self._parser.description is None:
            self._parser.description = ''
        self._parser.description += 'Available commands:\n'
        for name, arguments, doc_string in self._commands:
            command = '%s %s' % (name, arguments)
            self._parser.description += '   %-30s %s\n' % (command, doc_string)

        results_options = OptionGroup(self._parser, 'Results Options')
        results_options.add_option('-c', '--condition', help='filter result items to display given a boolean condition')
        results_options.add_option('-n', '--count', type='int', help='get a maximum number of results (all backends merged)')
        results_options.add_option('-f', '--formatter', choices=formatters, help='select output formatter (%s)' % u','.join(formatters))
        results_options.add_option('-s', '--select', help='select result item keys to display (comma separated)')
        self._parser.add_option_group(results_options)

        formatting_options = OptionGroup(self._parser, 'Formatting Options')
        formatting_options.add_option('--no-header', dest='no_header', action='store_true', help='do not display header')
        formatting_options.add_option('--no-keys', dest='no_keys', action='store_true', help='do not display item keys')
        self._parser.add_option_group(formatting_options)

    def add_application_options(self, group):
        # XXX why is it in ConsoleApplication and not BaseApplication? -romain
        pass

    def _handle_app_options(self):
        if self.options.formatter:
            formatter_name = self.options.formatter
        else:
            formatter_name = 'multiline'
        self.formatter = load_formatter(formatter_name)

        if self.options.no_header:
            self.formatter.display_header = False

        if self.options.no_keys:
            self.formatter.display_keys = False

        if self.options.select:
            self.selected_fields = self.options.select.split(',')
        else:
            self.selected_fields = None

        if self.options.condition:
            self.condition = ResultsCondition(self.options.condition)
        else:
            self.condition = None

    def _get_completions(self):
        return set(name for name, arguments, doc_string in self._commands)

    def ask(self, question, default=None, masked=False, regexp=None):
        """
        Ask a question to user.

        @param question  text displayed (str)
        @param default  optional default value (str)
        @param masked  if True, do not show typed text (bool)
        @param regexp  text must match this regexp (str)
        @return  entered text by user (str)
        """

        if default is not None:
            question = u'%s [%s]' % (question, default)
        hidden_msg = u'(input chars are hidden) ' if masked else ''
        question = u'%s%s: ' % (hidden_msg, question)

        correct = False
        while not correct:
            line = getpass.getpass(question) if masked else raw_input(question)
            if not line and default is not None:
                line = default
            correct = not regexp or re.match(regexp, unicode(line))

        return line

    def process_command(self, command=None, *args):
        if command is None:
            self._parser.print_help()
            return 0

        def f(x):
            return x.startswith('command_' + command)

        matching_commands = filter(f, dir(self))

        if len(matching_commands) == 0:
            sys.stderr.write("No such command: %s.\n" % command)
            return 1
        if len(matching_commands) != 1:
            sys.stderr.write("Ambiguious command %s: %s.\n" % (command, ', '.join(
                [s.replace('command_', '', 1) for s in matching_commands])))
            return 1

        func = getattr(self, matching_commands[0])

        _args, varargs, varkw, defaults = getargspec(func)
        nb_max_args = nb_min_args = len(_args) - 1
        if defaults:
            nb_min_args -= len(defaults)

        if len(args) > nb_max_args and not varargs:
            sys.stderr.write("Command '%s' takes at most %d arguments.\n" % (command, nb_max_args))
            return 1
        if len(args) < nb_min_args:
            if varargs or defaults:
                sys.stderr.write("Command '%s' takes at least %d arguments.\n" % (command, nb_min_args))
            else:
                sys.stderr.write("Command '%s' takes %d arguments.\n" % (command, nb_min_args))
            return 1

        try:
            command_result = func(*args)
        except CallErrors, errors:
            logging.error(errors)
            return 1

        self.formatter.flush()

        # Process result if value is returned by command
        if isinstance(command_result, str):
            print command_result
        elif isinstance(command_result, unicode):
            print command_result.encode('utf-8')
        elif isinstance(command_result, int):
            return command_result
        elif command_result is None:
            return 0
        else:
            try:
                print unicode(command_result).encode('utf-8')
            except ValueError:
                raise Exception(u'Command result type not expected: %s' % type(command_result))

        return 0

    _commands = []
    def register_command(f, doc_string, register_to=_commands):
        def get_arguments(func, skip=0):
            """
            Get arguments of a function as a string.
            skip is the number of skipped arguments.
            """
            skip += 1
            args, varargs, varkw, defaults = getargspec(func)
            cut = len(args)
            if defaults:
                cut -= len(defaults)
            args = ["<%s>" % a for a in args[skip:cut]] + \
                   ["[%s]" % a for a in args[cut:]]
            if varargs:
                args.append("[%s..]" % varargs)
            if varkw:
                raise TypeError('Command %s requests illegal keyword args (**%s)' % varkw)
            return " ".join(args)

        command_name = f.func_name.replace('command_', '')
        register_to.append((command_name, get_arguments(f), doc_string))
        return f

    def command(doc_string, f=register_command):
        return partial(f, doc_string=doc_string)

    def set_default_formatter(self, name):
        if not self.options.formatter:
            try:
                self.formatter = load_formatter(name)
            except ImportError:
                default_name = 'multiline'
                logging.error('Could not load default formatter "%s" for this command. Falling back to "%s".' % (
                    name, default_name))
                self.formatter = load_formatter(default_name)

    def set_formatter_header(self, string):
        self.formatter.set_header(string)

    def format(self, result, backend_name=None):
        try:
            self.formatter.format(obj=result, backend_name=backend_name,
                                  selected_fields=self.selected_fields, condition=self.condition)
        except ResultsConditionException, e:
            logging.error(e)

    # XXX why do not use staticmethod as a decorator? -romain
    register_command = staticmethod(register_command)
    command = staticmethod(command)

    def load_configured_backends(self, caps=None, names=None, *args, **kwargs):
        loaded_backends = BaseApplication.load_configured_backends(self, caps, names, *args, **kwargs)
        if not loaded_backends:
            logging.error(u'Cannot start application: no configured backend was found.\nHere is a list of all available backends:')
            from weboob.applications.weboobcfg import WeboobCfg
            weboobcfg = WeboobCfg()
            weboobcfg.options, args = weboobcfg._parser.parse_args([])
            weboobcfg._handle_app_options()
            if caps is not None:
                if not isinstance(caps, (list, tuple, set)):
                    caps = (caps,)
                caps = iter(cap.__name__ for cap in caps)
            weboobcfg.command_backends(*caps)
            logging.error(u'You can configure a backends using the "weboobcfg add" command:\nweboobcfg add <name> [options..]')
            sys.exit(0)

    def parse_id(self, _id):
        try:
            _id, backend_name = _id.rsplit('@', 1)
        except ValueError:
            backend_name = None
        return _id, backend_name

    @classmethod
    def run(klass, args=None):
        try:
            super(ConsoleApplication, klass).run(args)
        except BackendNotFound, e:
            logging.error(e)

    def do(self, function, *args, **kwargs):
        """
        Call Weboob.do(), after having filled the yielded object, if selected fields are given by user.
        """
        for i, (backend, result) in enumerate(self.weboob.do(function, *args, **kwargs)):
            if self.options.count and i == self.options.count:
                break
            fields = set(self.selected_fields) - set('*')
            if fields:
                try:
                    backend.browser.fillobj(result, fields)
                except Exception, e:
                    logging.warning(u'Could not retrieve required fields (%s): %s' % (','.join(fields), e))
            yield backend, result

    def do_caps(self, caps, function, *args, **kwargs):
        """
        Call Weboob.do_caps(), after having filled the yielded object, if selected fields are given by user.
        """
        for i, (backend, result) in enumerate(self.weboob.do_caps(caps, function, *args, **kwargs)):
            if self.options.count and i == self.options.count:
                break
            fields = set(self.selected_fields) - set('*')
            if fields:
                try:
                    backend.browser.fillobj(result, fields)
                except Exception, e:
                    logging.warning(u'Could not retrieve required fields (%s): %s' % (','.join(fields), e))
            yield backend, result

    def do_backends(self, backends, function, *args, **kwargs):
        """
        Call Weboob.do_backends(), after having filled the yielded object, if selected fields are given by user.
        """
        for i, (backend, result) in enumerate(self.weboob.do_backends(backends, function, *args, **kwargs)):
            if self.options.count and i == self.options.count:
                break
            fields = set(self.selected_fields) - set('*')
            if fields:
                try:
                    backend.browser.fillobj(result, fields)
                except Exception, e:
                    logging.warning(u'Could not retrieve required fields (%s): %s' % (','.join(fields), e))
            yield backend, result
<|endoftext|>


<commit_before>import argparse
import numpy as np
import copy
from compute_cv import compute_Z, get_energies
from src.cv_trapezoidal import  compute_cv_c
from itertools import chain, cycle
import matplotlib
from matplotlib import rc
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt

#######################SET LATEX OPTIONS###################
rc('text', usetex=True)
rc('font',**{'family':'serif','serif':['Computer Modern']})
#rc('text.latex',preamble=r'\usepackage{times}')
plt.rcParams.update({'font.size': 12})
plt.rcParams['xtick.major.pad'] = 8
plt.rcParams['ytick.major.pad'] = 8
##########################################################
#####################LINE STYLE CYCLER####################
lines = ["-","--","-.",":"]
linecycler = cycle(lines)
##########################################################

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="load energy intervals and compute Cv stdev",
                                     epilog="must write file name followed by a label string, otherwise raise the flag --nolabels")
    parser.add_argument("fname", nargs="+", type=str, help="filenames with heat capacity followed by label")
    parser.add_argument("--nolabels", action="store_true", help="turn on if do not want to insert labels",default=False)
    parser.add_argument("--show", action="store_true", help="show explorable plot preview",default=False)
    parser.add_argument("--leg_loc", type=int, help="define location of the legend (default upper right 1):"
                        " \"upper right=1\" \"upper left=2\" \"lower left=3\" \"lower right=4\" \"right=5\" "
                        "\"center left=6\" \"center right=7\" \"lower center=8\" \"upper center=9\" \"center=10\"",default=1)
    parser.add_argument("--xlabel", type=str, help="set x-label",default="T")
    parser.add_argument("--ylabel", type=str, help="set y-label",default="Cv")
    parser.add_argument("--title", type=str, help="set title",default=None)
    parser.add_argument("--linewidth", type=float, help="set line width",default=2.5)
    parser.add_argument("--grid", action="store_true", help="plot grid",default=False)

    args = parser.parse_args()
    print args.fname
    fname = args.fname
    nolabels = args.nolabels
    xlabel = args.xlabel
    ylabel = args.ylabel
    show = args.show
    title = args.title
    grid = args.grid
    linew = args.linewidth
    ####################################################################################################
    #deal with input

    if nolabels is False:
        all_data = [[] for i in xrange(len(fname)/2)]
        all_labels = np.array(["no_name" for i in xrange(len(fname)/2)])
        j = 0
        for name,i in zip(fname,xrange(len(fname))):
            if ((i+1) % 2) is not 0:
                data = np.genfromtxt(name)
                all_data[j] = copy.deepcopy(data.tolist())
            else:
                all_labels[j] = name
                j += 1
        print all_labels
    else:
        all_data = [[] for i in xrange(len(fname))]
        all_labels = np.array(["no_name" for i in xrange(len(fname))])
        for name,i in zip(fname,xrange(len(fname))):
            data = np.genfromtxt(name)
            all_data[i] = copy.deepcopy(data.tolist())

    all_data = np.array(all_data)
    ######################################################################################################

    #####################
    ####### PLOT ########
    #####################

    ####SET COLOUR MAP######
    cm = plt.get_cmap('jet')
    ########################
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_color_cycle([cm(1.*i/len(all_data)) for i in xrange(len(all_data))])

    for data, label, i in zip(all_data, all_labels, xrange(len(all_data))):
            color = cm(1.*i/5)
            ax.plot(data[:,0], data[:,1], next(linecycler), label = label, linewidth=linew)

    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    if grid is True:
        ax.grid(True,linestyle='--',color='0.75')
    if title is not None:
        ax.set_title(title)
    if nolabels is False:
        ax.legend(frameon=False)
    if show is True:
         plt.show()

    fig.savefig('cv_plot.eps')
    <commit_msg>improved cv_plot.py<commit_after>import argparse
import numpy as np
import copy
from itertools import cycle
import matplotlib
from matplotlib import rc
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt

#####################LINE STYLE CYCLER####################
lines = ["-","--","-.",":"]
linecycler = cycle(lines)
##########################################################

#######################SET LATEX OPTIONS###################
rc('text', usetex=True)
rc('font',**{'family':'serif','serif':['Computer Modern']})
#rc('text.latex',preamble=r'\usepackage{times}')
plt.rcParams.update({'font.size': 12})
plt.rcParams['xtick.major.pad'] = 8
plt.rcParams['ytick.major.pad'] = 8
##########################################################

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="load energy intervals and compute Cv stdev",
                                     epilog="must write file name followed by a label string, otherwise raise the flag --nolabels")
    parser.add_argument("fname", nargs="+", type=str, help="filenames with heat capacity followed by label")
    parser.add_argument("--leg_loc", type=int, help="define location of the legend (default upper right 1):"
                        " \"upper right=1\" \"upper left=2\" \"lower left=3\" \"lower right=4\" \"right=5\" "
                        "\"center left=6\" \"center right=7\" \"lower center=8\" \"upper center=9\" \"center=10\"",default=1)
    parser.add_argument("--xlabel", type=str, help="set x-label",default="T")
    parser.add_argument("--ylabel", type=str, help="set y-label",default="Cv")
    parser.add_argument("--xtop", type=float, help="set x-axis top",default=None)
    parser.add_argument("--xbot", type=float, help="set x-axis bottom",default=None)
    parser.add_argument("--ytop", type=float, help="set y-axis top",default=None)
    parser.add_argument("--ybot", type=float, help="set y-axis bottom",default=None)
    parser.add_argument("--title", type=str, help="set title",default=None)
    parser.add_argument("--linewidth", type=float, help="set line width",default=2.2)
    parser.add_argument("--colormap", type=str, help="set colormap (default spectral)",default='spectral')
    parser.add_argument("--ecolor", type=str, help="set error bars color (default light gray)",default='g')
    parser.add_argument("--ecap", type=float, help="set error bars cap size (default is None)",default=None)
    parser.add_argument("--output", type=str, help="set output name (default cv_plot)",default='cv_plot')
    parser.add_argument("--filetype", type=str, help="set output file format (default eps)",default='eps')
    parser.add_argument("--nolabels", action="store_true", help="turn on if do not want to insert labels",default=False)
    parser.add_argument("--show", action="store_true", help="show explorable plot preview",default=False)
    parser.add_argument("--ebar", action="store_true", help="plot error bars if in data file",default=False)
    parser.add_argument("--grid", action="store_true", help="plot grid",default=False)
    args = parser.parse_args()
    print args.fname
    fname = args.fname
    nolabels = args.nolabels
    xlabel = args.xlabel
    ylabel = args.ylabel
    show = args.show
    title = args.title
    grid = args.grid
    linew = args.linewidth
    xtop = args.xtop
    xbot = args.xbot
    ytop = args.ytop
    ybot = args.ybot
    colormap = args.colormap
    errcolor = args.ecolor
    ebar = args.ebar
    filename = args.output
    filetype = args.filetype
    ecap = args.ecap

    ####################################################################################################
    #deal with input

    if nolabels is False:
        all_data = [[] for i in xrange(len(fname)/2)]
        all_labels = np.array(["no_name" for i in xrange(len(fname)/2)])
        j = 0
        for name,i in zip(fname,xrange(len(fname))):
            if ((i+1) % 2) is not 0:
                data = np.genfromtxt(name)
                all_data[j] = copy.deepcopy(data.tolist())
            else:
                all_labels[j] = name
                j += 1
        print all_labels
    else:
        all_data = [[] for i in xrange(len(fname))]
        all_labels = np.array(["no_name" for i in xrange(len(fname))])
        for name,i in zip(fname,xrange(len(fname))):
            data = np.genfromtxt(name)
            all_data[i] = copy.deepcopy(data.tolist())

    all_data = np.array(all_data)
    ######################################################################################################

    #####################
    ####### PLOT ########
    #####################

    ####SET COLOUR MAP######
    cm = plt.get_cmap(colormap)
    ########################
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_color_cycle([cm(1.*i/len(all_data)) for i in xrange(len(all_data))])

    for data, label, i in zip(all_data, all_labels, xrange(len(all_data))):
            color = cm(1.*i/5)
            ax.plot(data[:,0], data[:,1], next(linecycler), label = label, linewidth=linew)
            if np.shape(data)[1] is 3 and ebar is True:
                ax.errorbar(data[:,0], data[:,1], yerr=data[:,2], ecolor=errcolor, capsize=ecap )
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    ax.set_xlim((xbot,xtop))
    ax.set_ylim((ybot,ytop))

    if grid is True:
        ax.grid(True,linestyle='--',color='0.75')
    if title is not None:
        ax.set_title(title)
    if nolabels is False:
        ax.legend(frameon=False)
    if show is True:
         plt.show()

    fig.savefig('{F}.{T}'.format(F=filename,T=filetype))
    <|endoftext|>