Example #1
0
 def getStatusBarHPAttribute(self):
     percentHealth = float(self.getHP())/self.getMaxHP()
     if (percentHealth <= 0.333):
         return Colors.getPairNumber('RED', 'BLACK')
     elif (percentHealth <= 0.666):
         return Colors.getPairNumber('YELLOW', 'BLACK')
     else: 
         return Colors.getPairNumber('GREEN', 'BLACK')
 def updateColor(self, fgColor, bgColor):
     self.attribute = Colors.getPairNumber(fgColor, bgColor)
     self.fgColor = fgColor
     self.bgColor = bgColor
     self.zDepthAttribute = self.attribute
     if (fgColor == bgColor): #Same color! Uh oh!
         if (bgColor != 'BLACK'):
             self.zDepthAttribute = Colors.getPairNumber(self.fgColor, 'BLACK')
         else:
             self.zDepthAttribute = Colors.getPairNumber(self.fgColor, 'WHITE')
Example #3
0
    def check_first_and_last_line(self):

        num_lines = sum(1 for line in self.fd)
        self.fd.seek(0)

        self.end_val = num_lines
        rows, self.bar_length = popen('stty size', 'r').read().split()
        self.bar_length = int(self.bar_length) - len('  00\rPercent: 100 {1}%')

        print Colors.change_color(
            '     Nombre de lignes au total: %s' % num_lines, 'OKGREEN')
Example #4
0
    def check_first_and_last_line(self):

        num_lines = sum(1 for line in self.fd)
        self.fd.seek(0)

        self.end_val = num_lines
        rows, self.bar_length = popen('stty size', 'r').read().split()
        self.bar_length = int(self.bar_length) - len('  00\rPercent: 100 {1}%')

        print Colors.change_color(
                '     Nombre de lignes au total: %s' % num_lines, 'OKGREEN')
Example #5
0
def annotate_covariation(ref_aligned_seq,
                         input_aligned_seq,
                         ref_aligned_dot,
                         anno_loop=False):
    """
    ref_aligned_seq             -- Reference aligned sequence
    input_aligned_seq           -- An input aligned sequence to annotate
    ref_aligned_dot             -- Reference aligned dotbracket structure
    anno_loop                   -- Will annotate loop mutations
    
    Use color to annotate mutate bases in stem loop
    """

    import Colors

    assert len(ref_aligned_seq) == len(input_aligned_seq) == len(
        ref_aligned_dot)
    ref_aligned_seq = ref_aligned_seq.replace('U', 'T')
    input_aligned_seq = input_aligned_seq.replace('U', 'T')

    anno_align_seq = list(input_aligned_seq)

    pair_bps = ['AT', 'TA', 'CG', 'GC', 'TG', 'GT']

    bp_list = dot2ct(ref_aligned_dot)
    for bp in bp_list:
        raw_bp = ref_aligned_seq[bp[0] - 1] + ref_aligned_seq[bp[1] - 1]
        new_bp = input_aligned_seq[bp[0] - 1] + input_aligned_seq[bp[1] - 1]
        assert raw_bp in pair_bps
        if new_bp in pair_bps:
            if raw_bp != new_bp:
                anno_align_seq[bp[0] - 1] = Colors.f(
                    anno_align_seq[bp[0] - 1], fc="cyan"
                )  #'\x1b[1;36;40m' + anno_align_seq[ bp[0]-1 ] + '\x1b[0m'
                anno_align_seq[bp[1] - 1] = Colors.f(
                    anno_align_seq[bp[1] - 1], fc="cyan"
                )  #'\x1b[1;36;40m' + anno_align_seq[ bp[1]-1 ] + '\x1b[0m'
        else:
            anno_align_seq[bp[0] - 1] = Colors.f(
                anno_align_seq[bp[0] - 1], fc="red"
            )  #'\x1b[1;31;40m' + anno_align_seq[ bp[0]-1 ] + '\x1b[0m'
            anno_align_seq[bp[1] - 1] = Colors.f(
                anno_align_seq[bp[1] - 1], fc="red"
            )  #'\x1b[1;31;40m' + anno_align_seq[ bp[1]-1 ] + '\x1b[0m'

    if anno_loop:
        for i in range(len(anno_align_seq)):
            if ref_aligned_dot[
                    i] == '.' and input_aligned_seq[i] != ref_aligned_seq[i]:
                anno_align_seq[i] = Colors.f(
                    anno_align_seq[i], fc="yellow"
                )  #'\x1b[1;33;40m' + anno_align_seq[ i ] + '\x1b[0m'

    return "".join(anno_align_seq)
Example #6
0
    def checkfile_shell(self, path):

        check_zip = \
            "file %s | sed 's/^.*gzip.*/gzip/'" % path
        check_ascii = \
            "file %s | sed 's/^.*ASCII.*/ASCII/'" % path
        check_sas = \
            "file %s | sed 's/^.*SAS.*/SAS/'" % path
        check_empty = \
            "file %s | sed 's/^.*empty.*/EMPTY/'" % path

        if self.check_path(path) is False:
            return False

        if self.execute.cmd(check_zip) == 'gzip':
            print Colors.change_color('     File Type: gzip', 'OKGREEN')
            self.fd = gzip.open(path, 'rb')
        elif (self.execute.cmd(check_ascii) == "ASCII"
              or self.execute.cmd(check_sas) == "SAS"):
            print Colors.change_color('     File Type: ASCII', 'OKGREEN')
            self.fd = open(path, 'r')
        elif (self.execute.cmd(check_empty) == 'EMPTY'):
            print Colors.change_color('\n     This File is Empty.', 'FAIL')
            return False
        else:
            print Colors.change_color('\n     Unrecognized file type ', 'FAIL')
            return False
        return True
Example #7
0
    def checkfile_shell(self, path):

        check_zip = \
            "file %s | sed 's/^.*gzip.*/gzip/'" % path
        check_ascii = \
            "file %s | sed 's/^.*ASCII.*/ASCII/'" % path
        check_sas = \
            "file %s | sed 's/^.*SAS.*/SAS/'" % path
        check_empty = \
            "file %s | sed 's/^.*empty.*/EMPTY/'" % path

        if self.check_path(path) is False:
            return False

        if self.execute.cmd(check_zip) == 'gzip':
            print Colors.change_color('     File Type: gzip', 'OKGREEN')
            self.fd = gzip.open(path, 'rb')
        elif (self.execute.cmd(check_ascii) == "ASCII" or
                self.execute.cmd(check_sas) == "SAS"):
            print Colors.change_color('     File Type: ASCII', 'OKGREEN')
            self.fd = open(path, 'r')
        elif (self.execute.cmd(check_empty) == 'EMPTY'):
            print Colors.change_color('\n     This File is Empty.', 'FAIL')
            return False
        else:
            print Colors.change_color('\n     Unrecognized file type ', 'FAIL')
            return False
        return True
Example #8
0
	def __init__(self, dataSet):
		self.dataSet = dataSet
		
		self.cardType = CardType.createType(self.generateList('type'), self.model)
		self.cardTypes = CardTypes.createTypes(self.generateList('types'), self.model)
		self.cmc = Cmc.createCmc(self.generateList('cmc'), self.model)
		self.colorIdentity = ColorIdentity.createColorIdentity(self.generateList('colorIdentity'), self.model)
		self.colors = Colors.createColors(self.generateList('colors'), self.model)
		self.hand = Hand.createHand(self.generateList('hand'), self.model)
		self.imageName = ImageName.createImageName(self.generateList('imageName'), self.model)
		self.layouts = Layouts.createLayouts(self.generateList('layout'), self.model)
		self.legalities = Legalities.createLegalities(self.generateList('legalities'), self.model)
		self.life = Life.createLife(self.generateList('life'), self.model)
		self.loyalty = Loyalty.createLoyalty(self.generateList('loyalty'), self.model)
		self.manaCost = ManaCost.createManaCost(self.generateList('manaCost'), self.model)
		self.name = Name.createName(self.generateList('name'), self.model)
		self.names = Names.createNames(self.generateList('names'), self.model)
		self.power = Power.createPower(self.generateList('power'), self.model)
		self.printings = Printings.createPrintings(self.generateList('printings'), self.model)
		self.rulings = Rulings.createRulings(self.generateList('rulings'), self.model)
		self.source = Source.createSource(self.generateList('source'), self.model)
		self.starter = Starter.createStarter(self.generateList('starter'), self.model)
		self.cardSubTypes = CardSubTypes.createSubTypes(self.generateList('subtypes'), self.model)
		self.cardSuperTypes = CardSuperTypes.createSuperTypes(self.generateList('supertypes'), self.model)
		self.text = Text.createText(self.generateList('text'), self.model)
		self.toughness = Toughness.createToughness(self.generateList('toughness'), self.model)
Example #9
0
 def create_labels(self):
     """Create the labels for the socket."""
     Element.create_labels(self)
     self._bg_color = Colors.get_color(self.get_color())
     # create the layout
     layout = gtk.DrawingArea().create_pango_layout('')
     layout.set_markup(
         Utils.parse_template(PORT_MARKUP_TMPL, port=self, font=PORT_FONT))
     self.w, self.h = layout.get_pixel_size()
     self.W = 2 * PORT_LABEL_PADDING + self.w
     self.H = 2 * PORT_LABEL_PADDING + self.h * (3 if self.get_type()
                                                 == 'bus' else 1)
     self.H += self.H % 2
     # create the pixmap
     pixmap = self.get_parent().get_parent().new_pixmap(self.w, self.h)
     gc = pixmap.new_gc()
     gc.set_foreground(self._bg_color)
     pixmap.draw_rectangle(gc, True, 0, 0, self.w, self.h)
     pixmap.draw_layout(gc, 0, 0, layout)
     # create vertical and horizontal pixmaps
     self.horizontal_label = pixmap
     if self.is_vertical():
         self.vertical_label = self.get_parent().get_parent().new_pixmap(
             self.h, self.w)
         Utils.rotate_pixmap(gc, self.horizontal_label, self.vertical_label)
Example #10
0
 def create_shapes(self):
     """Precalculate relative coordinates."""
     Element.create_shapes(self)
     self._sink_rot = None
     self._source_rot = None
     self._sink_coor = None
     self._source_coor = None
     #get the source coordinate
     try:
         connector_length = self.get_source().get_connector_length()
     except:
         return
     self.x1, self.y1 = Utils.get_rotated_coordinate((connector_length, 0), self.get_source().get_rotation())
     #get the sink coordinate
     connector_length = self.get_sink().get_connector_length() + CONNECTOR_ARROW_HEIGHT
     self.x2, self.y2 = Utils.get_rotated_coordinate((-connector_length, 0), self.get_sink().get_rotation())
     #build the arrow
     self.arrow = [(0, 0),
         Utils.get_rotated_coordinate((-CONNECTOR_ARROW_HEIGHT, -CONNECTOR_ARROW_BASE/2), self.get_sink().get_rotation()),
         Utils.get_rotated_coordinate((-CONNECTOR_ARROW_HEIGHT, CONNECTOR_ARROW_BASE/2), self.get_sink().get_rotation()),
     ]
     source_domain = self.get_source().get_domain()
     sink_domain = self.get_sink().get_domain()
     self.line_attributes[0] = 2 if source_domain != sink_domain else 0
     self.line_attributes[1] = gtk.gdk.LINE_DOUBLE_DASH \
         if not source_domain == sink_domain == GR_MESSAGE_DOMAIN \
         else gtk.gdk.LINE_ON_OFF_DASH
     get_domain_color = lambda d: Colors.get_color((
         self.get_parent().get_parent().get_domain(d) or {}
     ).get('color') or Colors.DEFAULT_DOMAIN_COLOR_CODE)
     self._color = get_domain_color(source_domain)
     self._bg_color = get_domain_color(sink_domain)
     self._arrow_color = self._bg_color if self.is_valid() else Colors.CONNECTION_ERROR_COLOR
     self._update_after_move()
Example #11
0
    def waitForStatusLineUpdateConfirmation(self, inputHandler = None):

        if (inputHandler == None):
            inputHandler = InputHandler.SingletonKeyboardInputHander(self.screen)

        promptMessage = 'PRESS A KEY'
        promptMessageLength = len(promptMessage)

        y = self.getTerminalHeight() - 1
        x = self.getTerminalWidth() - self.maxSideBarLen - 1
        promptMessageAttr = Colors.BLINK | Colors.getPairNumber('BLACK', 'YELLOW')

        self.screen.addnstr(y, x, promptMessage, promptMessageAttr)
        
        self.draw()

        curses.flash() #Visual bell

        keyPressed = inputHandler.waitForKey()

        Logger.put(' key found: %s' % (str(keyPressed)))

        self.resetStatusLinesAppended()
        #erase the prompt message
        self.screen.addnstr(y, x, ' ' * promptMessageLength, promptMessageAttr)

        self.draw()
def launchGame(screenParam):
    global screen
    screen = screenParam
    Colors.init()
    curses.curs_set(1)
    screen.keypad(1)
    screen.nodelay(1)

    doIntro(screenParam)

    #val = k.getKey()

    #screen.addstr(2, 1, "%d" % (val))

    w = World.World(screen, 80, 30)
    w.doEventLoop()
    def __init__(self,
                 entity_property: EntityProperty,
                 property_value: float = None,
                 parent: EntityGroup = None,
                 children: List[EntityGroup] = None) -> None:

        self._entity_property = entity_property
        self._property_value = property_value
        # all entities in the group
        self._entities = []

        # #todo new update, if works, delete later
        if parent is not None:
            self._parent: EntityGroup = parent
            # self._has_parent = True
        self._has_parent: bool = parent is not None

        if children is not None:
            self._children: List[EntityGroup] = children
            self._has_children: bool = True
        else:
            self._children: List[EntityGroup] = []
            self._has_children: bool = False

        # default blue line
        self._color_line: str = Colors.RGBColor([0, 128, 255]).to_hex().hex
Example #14
0
    def generateXml(self, contourDB, contourFile, mapfile):
        config = Config.get()
        regionClusters = Utils.read_features(
            config.get("MapData", "clusters_with_region_id"))
        regionIds = sorted(
            set(
                int(region['cluster_id'])
                for region in regionClusters.values()))
        regionIds = map(str, regionIds)
        countryBorders = Utils.read_features(
            config.get("GeneratedFiles", "country_borders"))
        colorFactory = Colors.ColorSelector(countryBorders,
                                            Config.getColorWheel())
        colors = colorFactory.optimalColoring()

        ms = MapStyler(config, colors)
        imgfile = config.get("MapOutput", "img_src_name")

        ms.addCustomFonts(config.get("MapResources", "fontDir"))

        ms.makeMap(contourFile, config.get("MapData", "countries_geojson"),
                   regionIds, contourDB)
        ms.saveMapXml(config.get("MapData", "countries_geojson"), mapfile)
        ms.saveImage(mapfile, imgfile + ".png")
        ms.saveImage(mapfile, imgfile + ".svg")
Example #15
0
def cmalign(CMFile,
            seqdbFn,
            outFn,
            cpu=0,
            glocal=False,
            outformat='Stockholm',
            mxsize=1028.0,
            verbose=True,
            showCMD=True,
            use_LSF=False,
            LSF_parameters={}):
    """
    Search CM model from sequence database
    CMFile              -- CM file
    seqdbFn             -- File name of sequence database
    outFn               -- Output file
    cpu                 -- How many threads to use
    glocal              -- Configure CM for global alignment [default: local]
    outformat           -- Output alignment in format <s>  [Stockholm]
                           Stockholm, Pfam, AFA (aligned FASTA), A2M, Clustal, PHYLIP
    mxsize              -- Set maximum allowable DP matrix size to <x> Mb  [1028.0]  (x>0.)
    verbose             -- Show command and log information
    showCMD             -- Print the command
    use_LSF             -- Submit to LSF if True
    LSF_parameters      -- { 'queue': 'Z-ZQF', 'cpu': 20, 'job_name': 'cmalign', 'logFn': '/dev/null', 'errFn': '/dev/null' }
    
    Require: cmalign
    """
    import General
    import shutil

    cmalign_exe = General.require_exec("cmalign", exception=True)
    cmd = f"{cmalign_exe} "
    if cpu > 0:
        cmd += f"--cpu {cpu} "
    if glocal:
        cmd += "-g "
    cmd += f"--outformat {outformat} --mxsize {mxsize} -o {outFn} {CMFile} {seqdbFn}"

    if not verbose:
        cmd += " > /dev/null"
    if showCMD:
        import Colors
        print(Colors.f(cmd, fc='yellow'))

    if use_LSF:
        import Cluster
        job = Cluster.new_job(command=cmd,
                              queue=LSF_parameters.get('queue', 'Z-ZQF'),
                              cpu=LSF_parameters.get('cpu', 20),
                              job_name=LSF_parameters.get(
                                  'job_name', 'cmsearch'),
                              logFn=LSF_parameters.get('logFn', '/dev/null'),
                              errFn=LSF_parameters.get('errFn', '/dev/null'))
        #print(job.get_submit_command())
        job.submit()
        return job
    else:
        os.system(cmd)
 def __init__(self):
     CreatureWithInventory.__init__(self)
     self.description = 'outlaw'
     self.representation = 'T'
     self.speed = 220
     self.attribute = Colors.getPairNumber("RED", "BLACK")
     "Outlaws cannot see in the dark well."
     self.minimumLightToSeeThreshold = self.minimumLightToSeeThreshold + 1
 def __init__(self):
     CreatureWithInventory.__init__(self)
     self.description = 'deputy'
     self.representation = '@'
     self.speed = 200
     self.attribute = Colors.getPairNumber("WHITE", "BLACK")
     w = BaseItems.Revolver()
     self.addToInventory(w)
     self.setWeapon(w)
Example #18
0
 def showtext(self, text, fontsize):
     self.clearscreen()
     font = pygame.font.Font(None, fontsize)
     fontWidth = font.size(text)[0]
     fontHeight = font.size(text)[1]
     midX = self.windowsize[0] / 2 - fontWidth / 2
     midY = self.windowsize[1] / 2 - fontHeight / 2
     screentext = font.render(text, True, Colors.randomcolor_rgb())
     self.screen.blit(screentext, (midX, midY))
     self.updatescreen()
Example #19
0
    def __init__(self, semObject, className, modelPath=None):

        # Use the AToM3 Tkinter root window
        self.className = className
        root = self.rootInitilization(semObject, modelPath)
        if (not root): return

        self.root = root
        self.mainHandler = MainHandler.MainHandler(self)
        root.bind("<Key>", self.mainHandler.onKey)
        root.bind("<Shift-Key>", self.mainHandler.onShiftKey)
        root.bind("<Control-Key>", self.mainHandler.onControlKey)
        zoom = 1.0
        self.menuBar = Tools.MenuBar(root, self,
                                     self.mainHandler)  #goes to top by itself
        self.statusBar = Tools.StatusBar(root, "", zoom, 0,
                                         0)  #goes to bottom by itself

        self.colorSelector = Colors.ColorSelector(
            root, self.mainHandler)  #goes to bottom by itself

        self.toolFrame = Tkinter.Frame(root, relief=Tkinter.RAISED, bd=1)
        self.toolSelector = Tools.ToolSelector(self.toolFrame,
                                               self.mainHandler, Tkinter.TOP)
        self.outlineFillOptionSelector = Tools.OutlineFillOptionSelector(
            self.toolFrame, self.mainHandler, Tkinter.TOP)
        self.lineWidthSelector = Tools.LineWidthSelector(
            self.toolFrame, self.mainHandler, Tkinter.TOP)
        self.toolFrame.pack(side=Tkinter.LEFT)
        self.workspace = Workspace(self, self.CANVAS_SIZE_TUPLE[2],
                                   self.CANVAS_SIZE_TUPLE[3],
                                   self.CANVAS_SIZE_TUPLE[2],
                                   self.CANVAS_SIZE_TUPLE[3], self.mainHandler,
                                   zoom)  #goes to the right by itself
        self.workspace.setZoom(zoom, 0, 0)
        self.canvas = self.workspace.getCanvas()

        self.scripting = Scripting()
        ## self.GFs = self.open()
        self.GFs = []
        self.extendedInitilization(semObject)

        self.clipboardList = []
        self.undoStack = []
        self.mainHandler.start()
        self.compositionVisitor = GFVisitors.CompositionVisitor(self)
        self.colorVisitor = GFVisitors.ColorVisitor()
        self.widthVisitor = GFVisitors.WidthVisitor()
        self.optionVisitor = GFVisitors.OptionVisitor(self)

        # Carefully try to load the GF model (may fail for random reasons)
        try:
            self.GFs = self.open()
        except:
            raise
Example #20
0
    def __init__(self, screen, width = None, height = None):
        self.screen = screen
        self.width = width
        self.height = height
        self.statusLinesHeight = 5
        self.maxSideBarLen = 11
        self.time = 0
        self.eventHeap = []
        self.shouldPause = False
        self.lightSources = []

        self.defaultOverlay = Overlay.Overlay(self)
        self.overlay = self.defaultOverlay

        self.setDrawMode(World.DRAW_DETAIL_PHYSICAL)
        self.setViewMode(World.VIEW_VIEWER_INFORMATION)

        #self.world is referenced by x first, then y
        self.world = []

        if (self.width == None):
            self.width = self.screen.getmaxyx()[1]
        if (self.height == None):
            self.height = self.screen.getmaxyx()[0] - 5

        #self.makeForestMap()
        self.loadMapFromFile('testMap.txt')

        playerA = BaseCreatures.Deputy()
        playerB = BaseCreatures.Sheriff()

        playerA.makePlayerControlled()
        playerB.makePlayerControlled()

        self.team = TeamViewer(self, [playerA, playerB])
        self.currentViewer = self.team.getTeamMember(0)
        for i in range(0, len(self.team.getTeamList())):
            self.placeItem(self.team.getTeamMember(i), i, 0)

        #initialize some static data if not already initialized
        if (World.cannotSeeAttribute == None):
            World.cannotSeeAttribute = Colors.getPairNumber('WHITE', 'BLACK')
            for k in World.zHeightLookupTable.keys():
                result = WorldState.WorldRepresentation.convertString(World.zHeightLookupTable[k])
                if (k < 0):
                    World.zHeightLookupTable[k] = result
                else:
                    World.zHeightLookupTable[k] = result

    
        self.statusLinesAttribute = 0

        self.statusLines = []
        self.statusOffset = 11-6
        self.statusLinesAppended = 0
 def __init__(self):
     CreatureWithInventory.__init__(self)
     self.description = 'thieving bandito'
     self.representation = 'B'
     self.speed = 180
     self.attribute = Colors.getPairNumber("YELLOW", "BLACK")
     w = BaseItems.Revolver()
     self.addToInventory(w)
     self.setWeapon(w)
     "Banditos can see in the dark pretty well."
     self.minimumLightToSeeThreshold = self.minimumLightToSeeThreshold - 1
Example #22
0
def askQuestion(question, lChoices):
    """
	Ask a question to the user, and return his answer.
	"""
    mess = "\n%s\n%s" % (colorQ(question), '\n'.join([
        " [%s] %s" % (colorC(i + 1), lChoices[i]) for i in range(len(lChoices))
    ]))
    mess += "\n [%s] Quit\nChoice: %s" % (colorC('Q'),
                                          txt.buildColor(fgColor="Red"))
    choice = raw_input(mess)
    sys.stdout.write(txt.reset())
    sys.stdout.flush()

    if choice.lower() == 'q':
        sys.exit(0)

    if choice not in map(str, range(1, len(lChoices) + 1)):
        print "Your choice \"%s\" doesn't exist." % choice
        return askQuestion(question, lChoices)

    return int(choice) - 1
Example #23
0
def R_scape(StoFn,
            outDir,
            outname=None,
            maxIdentity=0.985,
            minIndentity=0.500,
            F=0.5,
            gapthresh=0.5,
            two_set_test=True,
            fold=False,
            acceptE=0.05,
            nseqmin=5,
            verbose=False,
            showCMD=True):
    """
    StoFn                           -- Stockholm file
    outDir                          -- Output the file to this directory
    outname                         -- File prefix
    maxIdentity                     -- require seqs to have < <x> id  [1.0]  (0<x<=1.0)
    minIndentity                    -- require seqs to have >= <x> id  (0<=x<1.0)
    F                               -- filter out seqs <x*seq_cons residues  (0<x<=1.0)
    gapthresh                       -- keep columns with < <x> fraction of gaps  [0.75]  (0<=x<=1)
    two_set_test                    -- two-set test: basepairs / all other pairs. Requires a given structure
    fold                            -- obtain the structure with maximum covariation
    acceptE                         -- Eval: max expected number of covNBPs allowed  [0.05]  (x>=0)
    nseqmin 						-- minimum number of sequences in the alignment  (n>0)
    verbose                         -- Show command and log information
    showCMD                         -- Print the command
    
    Require: R-scape
    """
    import General
    import shutil

    R_scape_exe = General.require_exec("R-scape", exception=True)
    if not os.path.exists(outDir):
        os.mkdir(outDir)
    cmd = f"{R_scape_exe} --outmsa --r2rall --outtree --roc --voutput --outnull --consensus "
    cmd += f"--outdir {outDir} -I {maxIdentity} -i {minIndentity} -F {F} --gapthresh {gapthresh} -E {acceptE} --nseqmin {nseqmin} "
    if outname:
        cmd += f"--outname {outname} "
    if two_set_test:
        cmd += "-s "
    if fold:
        cmd += "--fold "
    cmd += f" {StoFn} "

    if not verbose:
        cmd += "> /dev/null"
    if showCMD:
        import Colors
        print(Colors.f(cmd, fc='yellow'))

    os.system(cmd)
Example #24
0
def showRNAStructure(transFeature, sequence, bias=0):
    
    cds_start = transFeature['cds_start']
    cds_end = transFeature['cds_end']
    UTR5 = sequence[:cds_start-1]
    Start_codon = sequence[cds_start-1:cds_start+2]
    CDS = sequence[ cds_start+2:cds_end-3+bias ]
    Stop_codon = sequence[ cds_end-3+bias:cds_end+bias ]
    UTR3 = sequence[cds_end+bias:]
    
    if len(CDS)%3 != 0:
        print >>sys.stderr, "Warning: The length of the CDS is not an integer multiple of 3"
    
    formatCDS = ""
    i = 0; j = 0
    while i<len(CDS):
        if j % 2 == 0:
            formatCDS += Colors.f(CDS[i:i+3], fc='black', bc='yellow', ft='normal')
        else:
            formatCDS += Colors.f(CDS[i:i+3], fc='black', bc='lightyellow', ft='normal')
        i += 3
        j += 1
    
    UTR5 = Colors.f(UTR5, fc='green', bc='default', ft='normal')
    Start_codon = Colors.f(Start_codon, fc='lightred', bc='default', ft='bold')
    Stop_codon = Colors.f(Stop_codon, fc='lightred', bc='default', ft='bold') 
    UTR3 = Colors.f(UTR3, fc='green', bc='default', ft='normal')
    
    return UTR5+Start_codon+formatCDS+Stop_codon+UTR3
Example #25
0
 def run(self):
     config = Config.get()
     colorWheel = Config.getColorWheel()
     countryBorders = Utils.read_features(
         config.get("GeneratedFiles", "country_borders"))
     colorFactory = Colors.ColorSelector(countryBorders, colorWheel)
     colors = colorFactory.optimalColoring()
     ms = MapStyler(config, colors)
     ms = MapStyler(config, colorWheel)
     ms.saveImage(config.get("MapOutput", "map_file_density"),
                  config.get("MapOutput", "img_src_name") + ".png")
     ms.saveImage(config.get("MapOutput", "map_file_density"),
                  config.get("MapOutput", "img_src_name") + ".svg")
Example #26
0
def you_lost():
    exit_game = False
    temp_color = Colors.rand_col()
    while not exit_game:
        gameWindow.fill(temp_color)
        text_screen("press x to restart" , Colors.black , 350 , 300)
        pygame.display.update()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit_game = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_x:
                    game_loop()
Example #27
0
 def question_safe(self, question):
     while True:
         try:
             try_input = raw_input(question)
             if (len(try_input) > 0):
                 return try_input
             else:
                 Message = "\n     No Input Detected"
                 exit(Colors.change_color(Message, 'FAIL'))
         except EOFError:
             self.quit_gracefully()
         except KeyboardInterrupt:
             self.quit_gracefully()
Example #28
0
 def question_safe(self, question):
     while True:
         try:
             try_input = raw_input(question)
             if (len(try_input) > 0):
                 return try_input
             else:
                 Message = "\n     No Input Detected"
                 exit(Colors.change_color(Message, 'FAIL'))
         except EOFError:
             self.quit_gracefully()
         except KeyboardInterrupt:
             self.quit_gracefully()
Example #29
0
 def __processinput(self, inputvalue):
     line = Line.Line()
     choices = inputvalue.split(" ")
     if len(choices) != self.nbcolor:
         print "Il faut ", self.nbcolor , " couleurs"
         return False
     for colorname in choices:
         color = Colors.getcolorfromname(colorname)
         if color == 0:
             print "la couleur ", colorname, " n'existe pas"
             return False
         line.addcolor(color)
     self.line = line
     return True
Example #30
0
 def __processinput(self, inputvalue):
     line = Line.Line()
     choices = inputvalue.split(" ")
     if len(choices) != self.nbcolor:
         print "Il faut ", self.nbcolor, " couleurs"
         return False
     for colorname in choices:
         color = Colors.getcolorfromname(colorname)
         if color == 0:
             print "la couleur ", colorname, " n'existe pas"
             return False
         line.addcolor(color)
     self.line = line
     return True
Example #31
0
def cmcalibrate(CMFn,
                cpu=0,
                verbose=True,
                showCMD=True,
                use_LSF=False,
                LSF_parameters={}):
    """
    Calibrate the CM model
    CMFn                -- CM file
    cpu                 -- How many CPU to use
    verbose             -- Show command and log information
    showCMD             -- Print the command
    use_LSF             -- Submit to LSF if True
    LSF_parameters      -- { 'queue': 'Z-ZQF', 'cpu': 20, 'job_name': 'cmcalibrate', 'logFn': '/dev/null', 'errFn': '/dev/null' }
    
    Return:
        Return job object if use_LSF==True
        Return None if use_LSF==False

    Require: cmcalibrate
    """
    import General
    import shutil

    cmcalibrate_exe = General.require_exec("cmcalibrate", exception=True)
    cmd = f"{cmcalibrate_exe} "
    if cpu > 0:
        cmd += f"--cpu {cpu} "

    cmd += CMFn
    if not verbose:
        cmd += " > /dev/null"
    if showCMD:
        import Colors
        print(Colors.f(cmd, fc='yellow'))

    if use_LSF:
        import Cluster
        job = Cluster.new_job(command=cmd,
                              queue=LSF_parameters.get('queue', 'Z-ZQF'),
                              cpu=LSF_parameters.get('cpu', 20),
                              job_name=LSF_parameters.get(
                                  'job_name', 'cmcalibrate'),
                              logFn=LSF_parameters.get('logFn', '/dev/null'),
                              errFn=LSF_parameters.get('errFn', '/dev/null'))
        job.get_submit_command()
        job.submit()
        return job
    else:
        os.system(cmd)
Example #32
0
def welcome():
    exit_game = False
    temp_color = Colors.rand_col()
    while not exit_game:
        gameWindow.fill(temp_color)
        text_screen("Press space to start" , Colors.black , 350 , 300)
        pygame.display.update()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit_game = True
                pygame.quit()
                quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    return 0
Example #33
0
    def __init__(self, parent=None, tab_title='Batch.io', isStatic=False):
        super(AssetListWidget, self).__init__(parent)

        self.setGeometry(0, 0, 240, 0)
        self.assetWidgets = {}
        self.tab_dict = {}
        self.isDroppable = True
        self.titleLbl = QLabel(tab_title)
        self.tab_title = tab_title
        self.animWaitingColor = False
        self.log = None
        self.colors = Colors()
        self.isStatic = isStatic

        self.initUI()
Example #34
0
    def _setup(self, host, task):
        """
        Implementation specific setup for outputting to the CLI.

        :Parameters:
           - `host`: name of the host
           - `task`: name of the task
        """
        import Colors
        import sys
        self._c = Colors.Colors()
        self._sys = sys
        self._sys.stdout.write('%s:\n' % (self._c.format_string(host, 'blue')))
        self._sys.stdout.write(
            '%s Starting Task[%s]\n' %
            (self.timestamp, self._c.format_string(task, 'white')))
Example #35
0
 def create_shapes(self):
     """Precalculate relative coordinates."""
     Element.create_shapes(self)
     self._sink_rot = None
     self._source_rot = None
     self._sink_coor = None
     self._source_coor = None
     #get the source coordinate
     try:
         connector_length = self.get_source().get_connector_length()
     except:
         return
     self.x1, self.y1 = Utils.get_rotated_coordinate(
         (connector_length, 0),
         self.get_source().get_rotation())
     #get the sink coordinate
     connector_length = self.get_sink().get_connector_length(
     ) + CONNECTOR_ARROW_HEIGHT
     self.x2, self.y2 = Utils.get_rotated_coordinate(
         (-connector_length, 0),
         self.get_sink().get_rotation())
     #build the arrow
     self.arrow = [
         (0, 0),
         Utils.get_rotated_coordinate(
             (-CONNECTOR_ARROW_HEIGHT, -CONNECTOR_ARROW_BASE / 2),
             self.get_sink().get_rotation()),
         Utils.get_rotated_coordinate(
             (-CONNECTOR_ARROW_HEIGHT, CONNECTOR_ARROW_BASE / 2),
             self.get_sink().get_rotation()),
     ]
     source_domain = self.get_source().get_domain()
     sink_domain = self.get_sink().get_domain()
     self.line_attributes[0] = 2 if source_domain != sink_domain else 0
     self.line_attributes[1] = gtk.gdk.LINE_DOUBLE_DASH \
         if not source_domain == sink_domain == GR_MESSAGE_DOMAIN \
         else gtk.gdk.LINE_ON_OFF_DASH
     get_domain_color = lambda d: Colors.get_color(
         (self.get_parent().get_parent().get_domain(d) or {}).get(
             'color') or Colors.DEFAULT_DOMAIN_COLOR_CODE)
     self._color = get_domain_color(source_domain)
     self._bg_color = get_domain_color(sink_domain)
     self._arrow_color = self._bg_color if self.is_valid(
     ) else Colors.CONNECTION_ERROR_COLOR
     self._update_after_move()
Example #36
0
    def __init__(self, parent=None):
        super(AssetWidget, self).__init__(parent)

        self.isDraggable = False
        self.isDroppable = False
        self.isAssetWidget = True
        self.isTrigger = False
        self.isHeader = False
        self.asset_width = 210
        self.asset_height = 50
        self.button_size = self.asset_height / 2
        self.hasProgressBar = False
        self.hasContextMenu = False
        self.isInterative = True
        self.colors = Colors()
        self.asset_btn_list = []
        self.type = None

        self.initUI()
Example #37
0
def _color_command_heatmap(base_score,
                           gradient_list,
                           min_score=0,
                           max_score=1):
    import numpy as np
    if base_score == 'NULL':
        return "0.51 0.51 0.51 setrgbcolor"
    else:
        v = np.clip(float(base_score), min_score, max_score)
        ind = int(
            (v - min_score) / (max_score - min_score) * len(gradient_list))
        #print(ind)
        ind = int(np.clip(ind, 0, len(gradient_list) - 1))
        color = gradient_list[ind]
        #print(color)
        r, g, b = Colors._hex_to_RGB(color)
        r, g, b = r / 255, g / 255, b / 255
        #print(r,g,b)
        return f"{r:.2f} {g:.2f} {b:.2f} setrgbcolor"
Example #38
0
	def _create_labels(self):
		"""Create the labels for the socket."""
		self._bg_color = Colors.get_color(self.get_color())
		#create the layout
		layout = gtk.DrawingArea().create_pango_layout('')
		layout.set_markup(Utils.parse_template(PORT_MARKUP_TMPL, port=self))
		self.w, self.h = layout.get_pixel_size()
		self.W, self.H = 2*PORT_LABEL_PADDING+self.w, 2*PORT_LABEL_PADDING+self.h
		#create the pixmap
		pixmap = self.get_parent().get_parent().new_pixmap(self.w, self.h)
		gc = pixmap.new_gc()
		gc.set_foreground(self._bg_color)
		pixmap.draw_rectangle(gc, True, 0, 0, self.w, self.h)
		pixmap.draw_layout(gc, 0, 0, layout)
		#create the images
		self.horizontal_label = image = pixmap.get_image(0, 0, self.w, self.h)
		if self.is_vertical():
			self.vertical_label = vimage = gtk.gdk.Image(gtk.gdk.IMAGE_NORMAL, pixmap.get_visual(), self.h, self.w)
			for i in range(self.w):
				for j in range(self.h): vimage.put_pixel(j, self.w-i-1, image.get_pixel(i, j))
Example #39
0
	def create_labels(self):
		"""Create the labels for the socket."""
		Element.create_labels(self)
		self._bg_color = Colors.get_color(self.get_color())
		#create the layout
		layout = gtk.DrawingArea().create_pango_layout('')
		layout.set_markup(Utils.parse_template(PORT_MARKUP_TMPL, port=self))
		self.w, self.h = layout.get_pixel_size()
		self.W, self.H = 2*PORT_LABEL_PADDING+self.w, 2*PORT_LABEL_PADDING+self.h
		#create the pixmap
		pixmap = self.get_parent().get_parent().new_pixmap(self.w, self.h)
		gc = pixmap.new_gc()
		gc.set_foreground(self._bg_color)
		pixmap.draw_rectangle(gc, True, 0, 0, self.w, self.h)
		pixmap.draw_layout(gc, 0, 0, layout)
		#create vertical and horizontal pixmaps
		self.horizontal_label = pixmap
		if self.is_vertical():
			self.vertical_label = self.get_parent().get_parent().new_pixmap(self.h, self.w)
			Utils.rotate_pixmap(gc, self.horizontal_label, self.vertical_label)
Example #40
0
 def __init__(self):
     super(Background, self).__init__(
         (getGameDimension()[0], getGameDimension()[1]))
     # the rect is the score table of this game
     pygame.draw.rect(self,
                      Colors().FloralWhite,
                      (0, 0, getGameDimension()[2], getGameDimension()[3]))
     backgroundImg = pygame.image.load(
         './assets/images/field/soccer-field.png')
     backgroundImg2 = pygame.image.load(
         './assets/images/background/WechatIMG174.png')
     backgroundImg3 = pygame.image.load(
         './assets/images/background/WechatIMG173.png')
     resizedbackgroundImg2 = pygame.transform.scale(backgroundImg2,
                                                    (1100, 60))
     resizedbackgroundImg3 = pygame.transform.scale(backgroundImg3,
                                                    (300, 60))
     self.blit(backgroundImg, (0, getGameDimension()[3]))
     self.blit(resizedbackgroundImg2, (0, 0))
     self.blit(resizedbackgroundImg3, (800, 0))
Example #41
0
def ssecFromPDB(pdb, clean=True, verbose=False):
    """
    pdb                     -- A PDB id or PDB file, for example, 5CD1, /tmp/5CD1.cif
                               If you provide a PDB ID, it will download pdf file automaticly
    clean                   -- Clean the directory
    verbose                 -- Print the command to the screen
    
    Return:
        { 'm1_chain_L5': {'bseq': 'ACTAGTCAGCTAGC', 'sstr': '....((((..))))...'}, ... }
    """
    import tempfile, shutil, os, Colors
    import json, General
    
    tmpdir = tempfile.mkdtemp(prefix="PDB_", dir='/tmp/')
    tmp_result_json = os.path.join(tmpdir, "result.json")
    
    if len(pdb)==4:
        import Bio
        from Bio.PDB import PDBList
        pdbl = PDBList(verbose=False)
        pdbFn = pdbl.retrieve_pdb_file(pdb, pdir=tmpdir, overwrite=True)
    else:
        pdbFn = pdb
    
    cmd = f'x3dna-dssr -i={pdbFn} -o={tmp_result_json} --json 2>/dev/null'
    if verbose:
        print( Colors.f(cmd, 'yellow') )
    os.system(cmd)
    
    x3dna_result = json.load(open(tmp_result_json))
    ssec = {}
    for key in x3dna_result['dbn']:
        if key != 'all_chains':
            ssec[key] = { 'bseq':x3dna_result['dbn'][key]['bseq'], 'sstr':x3dna_result['dbn'][key]['sstr'] }
    
    if clean:
        shutil.rmtree(tmpdir)
    
    return ssec
Example #42
0
def printWin(w):
    ''' TODO: For Testing
    for r in range(len(w)):
        print(' '.join(str(n) for n in w[r]))
    '''
    ret = ''
    colors = Colors.getColors()[::-1]
    length = len(colors)
    for r in range(len(w)):
        for c in range(len(w[r])):
            if w[r][c] == 0: ret += colors[0] + '  '
            if w[r][c] == 1: ret += colors[1] + '. '
            if w[r][c] == 2: ret += colors[2] + '- '
            if w[r][c] == 3: ret += colors[3] + '~ '
            if w[r][c] == 4: ret += colors[4] + '+ '
            if w[r][c] == 5: ret += colors[5] + '* '
            if w[r][c] == 6: ret += colors[6] + '# '
            if w[r][c] == 7: ret += colors[7] + '% '
            if w[r][c] == 8: ret += colors[8] + '$ '
            if w[r][c] == 9: ret += colors[9] + '& '
        ret += '\n'
    print(ret)
Example #43
0
    def __init__(self):
        Item.LocationAwareItem.__init__(self)
        self.x = None
        self.y = None
        self.world = None
        self.speed = 100
        self.description = 'uninherited-from creature'
        self.representation = 't'
        self.foreGroundColorName = 'YELLOW'
        self.attribute = Colors.BOLD | Colors.getPairNumber(self.foreGroundColorName, "BLACK")
        self.inputHandler = InputHandler.SingletonKeyboardInputHander(ToastWrangler.screen)
        Logger.put(str(self.inputHandler))

        self.minimumLightToSeeThreshold = 3

        self.seeDistance = 99
        self.fov = None

        self.light = None

        self.moveActionDistance = 3
        self.moveDistanceThisTurn = 0

        self.didAttack = False

        self.maxHP = 10
        self.hp = 10

        self.horizontalAttackDistance = 1
        self.verticalAttackDistance = 1

        self.attackDamage = 1

        self.toggleLightCost = 1

        self.team = 0

        self.originalThink = self.doThink
Example #44
0
def cmbuild(inStoFn, outCMFn, verbose=False, showCMD=True):
    """
    Build a cm file from stockholm file
    inStoFn                     -- Input stockholm file
    outCMFn                     -- Output CM file
    verbose                     -- Show command and log information
    showCMD                     -- Print the command

    Require: cmbuild
    """
    import General
    import shutil
    
    cmbuild_exe = General.require_exec("cmbuild", exception=True)
    cmd = f"{cmbuild_exe} -F "
    if not verbose:
        cmd += '-o /dev/null '
    cmd += f"{outCMFn} {inStoFn}"
    
    if showCMD:
        import Colors
        print( Colors.f(cmd, fc='yellow') )
    os.system(cmd)
Example #45
0
 def create_dock_windows(self):
     self.dockManager = TkUtil.DockManager.DockManager(
             left=self.leftDockArea, right=self.rightDockArea)
     self.colorsDock = Colors.Dock(self.master, self.dockManager)
     self.colorsDock.dock_right()
     self.dockWindows.append(self.colorsDock)
     self.colorsDock.bind("<<ForegroundChange>>", lambda *args:
             self.editor.text.config(
                 foreground=self.colorsDock.foreground))
     self.colorsDock.bind("<<BackgroundChange>>", lambda *args:
             self.editor.text.config(
                 background=self.colorsDock.background))
     self.displayDock = Display.Dock(self.master, self.dockManager)
     self.displayDock.dock_right()
     self.dockWindows.append(self.displayDock)
     self.displayDock.bind("<<WordWrapChanged>>", lambda *args:
             self.editor.text.config(wrap=self.displayDock.word_wrap))
     self.displayDock.bind("<<BlockCursorChanged>>", lambda *args:
             self.editor.text.config(
                 blockcursor=self.displayDock.block_cursor))
     self.displayDock.bind("<<LineSpacingChanged>>", lambda *args:
             self.editor.text.config(
                 spacing3=self.displayDock.line_spacing))
Example #46
0
def cd_hit_est(id2seq,
               identity=0.9,
               global_align=False,
               band_width=20,
               memory=800,
               cpu=0,
               word_length=10,
               cluster_mode=0,
               alignment_mode=1,
               clean=True,
               verbose=False):
    """
    id2seq                  -- {id1:seq1, ...}
    identity                -- sequence identity threshold. 
                               this is the default cd-hit's "global sequence identity" calculated as:
                               number of identical amino acids or bases in alignment
                               divided by the full length of the shorter sequence
    global_align            -- use global sequence identity
    band_width              -- band_width of alignment
    memory                  -- memory limit (in MB) for the program, 0 for unlimited
    cpu                     -- number of threads, with 0, all CPUs will be used
    word_length             -- word_length, default 10, see user's guide for choosing it
    cluster_mode            -- 1 or 0.
                               by cd-hit's default algorithm, a sequence is clustered to the first
                               cluster that meet the threshold (fast cluster). If set to 1, the program
                               will cluster it into the most similar cluster that meet the threshold
                               (accurate but slow mode)
    alignment_mode          -- 1 or 0, default 1, by default do both +/+ & +/- alignments
                               if set to 0, only +/+ strand alignment
    clean                   -- Delete all tmp files
    verbose                 -- Print command
    
    Remove duplicated sequence from sequence
    
    Return:
        {id1:seq1,...}
    
    Require: cd-hit-est
    """
    import General, Colors
    import shutil, tempfile

    exe = General.require_exec("cd-hit-est", exception=True)

    ROOT = tempfile.mkdtemp(prefix="cd_hit_est_")

    #ROOT = "/tmp/predict_structure_%s/" % (randID, )
    #os.mkdir(ROOT)
    fa_file = os.path.join(ROOT, "input.fa")
    output_file = os.path.join(ROOT, "output.fa")

    General.write_fasta(id2seq, fa_file)
    CMD = f"{exe} -i {fa_file} -o {output_file} -c {identity} -b {band_width} -M {memory} -T {cpu} -n {word_length} -g {cluster_mode} -r {alignment_mode} "
    if global_align:
        CMD += " -G "

    if verbose:
        print(Colors.f(CMD, fc='yellow'))

    CMD += ' > /dev/null'
    os.system(CMD)

    cleaned_fasta = General.load_fasta(output_file)
    if clean:
        shutil.rmtree(ROOT)

    return cleaned_fasta
Example #47
0
 def printNormalUsage(self):
     print Colors.change_color(NormalUsage, 'OKGREEN')
Example #48
0
 def __init__(self, world, creature):
     Overlay.__init__(self, world)
     self.creature = creature
     self.cursorPosX = 0
     self.cursorPosY = 0
     self.attackAttribute = Colors.getPairNumber('WHITE', 'RED') | curses.A_BOLD
	def _processNeuron(self, file, neuron, options = {}):
		"""
		Part of the graphviz visualisation routines
		Adds a single neuron and its connections into the graph
		
		@type	file:	filehandle
		@param	file:	handle of the graph file
		
		@type	neuron:	neuron
		@param	neuron:	the neuron
		
		@type	options:	set
		@param	options: 	Set of options for visualisation
			Further documentation: L{visualize}
		"""
		if (neuron != 0):
			mass = normalize(neuron.getMass())
			if (mass < 0):
				mass_p = round(100+(mass*100))
			else:
				mass_p = round(100-(mass*100))
			if 'useColor' in options:
				color = int(neuron.getName().split('.')[1])
				file.write('\t%s [shape="box" color="grey%i" penwidth="3" style="filled" fillcolor="%s"]\n' % (neuron.getName(),mass_p,Colors.getColor(color)))
			else:
				file.write('\t%s [shape="box" color="grey%i" penwidth="3"]\n' % (neuron.getName(),mass_p))
			for x in range (0, neuron.getLinkCount()):
				weight = normalize(neuron.getWeight(x))
				if (weight < 0):
					weight_p = round(100+(weight*100))
				else:
					weight_p = round(100-(weight*100))
				file.write("\t%s -> %s " % (neuron.getName(),neuron.getLink(x)))
				file.write(' [')
				if 'showLabel' in options:
					file.write('label="%.2f" ' % (weight))
				if 'showHead' not in options:
					file.write('arrowhead="none" ')
				file.write('color="grey%i"] /* weight: %.2f */' % (weight_p,weight))
				file.write('\n')
			file.write('\n')