Exemple #1
0
def tablefromascii (tablename, asciifile,
                    headerfile='',
                    autoheader=False, autoshape=[],
                    columnnames=[], datatypes=[],
                    sep=' ',
                    commentmarker='',
                    firstline=1, lastline=-1,
                    readonly=True,
                    lockoptions='default', ack=True):
    import os.path
    filename = os.path.expandvars(asciifile);
    filename = os.path.expanduser(filename);
    if not os.path.exists(filename):
        s = "File '%s' not found" % (filename)
        raise IOError(s)
    if headerfile != '':
        filename = os.path.expandvars(headerfile);
        filename = os.path.expanduser(filename);
        if not os.path.exists(filename):
            s = "File '%s' not found" % (filename)
            raise IOError(s)
    tab = table(asciifile, headerfile, tablename, autoheader, autoshape,
                sep, commentmarker, firstline, lastline,
                columnnames, datatypes, _oper=1);
    print 'Input format: [' + tab._getasciiformat() +']';
    # Close table and reopen it in correct way.
    tab = '';
    return table(tablename, readonly=readonly, lockoptions=lockoptions,
                 ack=ack);
Exemple #2
0
def mainfun():
    a = input(
        "What operation do you want to do? [1]Fetch tweets from twitter. [2]See charts of the tweet. [3]Manual input. [4]show users in cluster table. [5]see database [q] Quit: "
    )

    if a == '1':
        twitterapicall.twitterapi()
        mainfun()
    elif a == '2':
        kmeans.kmeans()
        mainfun()
    elif a == '3':
        manual.manual()
        mainfun()
    elif a == '4':
        table.table()
        mainfun()
    elif a == '5':
        dbCreate.db()
        mainfun()
    elif a == 'q':
        quit()
        mainfun()
    else:
        print("sorry enter again.")
        mainfun()
Exemple #3
0
def tabledelete (tablename, checksubtables=False, ack=True):
    tabname = _remove_prefix(tablename);
    t = table(tabname, ack=False);
    if t.ismultiused(checksubtables):
        print 'Table', tabname, 'cannot be deleted; it is still in use';
    else:
        t = 0;
        table(tabname, readonly=False, _delete=True, ack=False);
        if ack:
            print 'Table', tabname, 'has been deleted';
def demNgayXaEm(dir):
    files = listFiles(dir)
    dnxe = []
    total = 0
    for file in files:
        x = CodeFile(file)
        fileType = x.getFileType()
        numOfEmptyLine = x.getCountEmptyLine()
        numOfTotalLine = x.getCountTotalLine()
        if (fileType == 'html'):
            numOfSingleCommentLine = x.getCountSingleLineCommentOfHtml()
            numOfMultiCommentLine = x.getCountMultiLineCommentOfHtml()
        elif (fileType == 'php'):
            numOfSingleCommentLine = x.getCountSingleLineCommentOfPhp()
            numOfMultiCommentLine = x.getCountMultiLineCommentOfPhp()
        elif (fileType == 'js'):
            numOfSingleCommentLine = x.getCountSingleLineCommentOfJs()
            numOfMultiCommentLine = x.getCountMultiLineCommentOfJs()
        elif (fileType == 'css'):
            numOfSingleCommentLine = x.getCountSingleLineCommentOfCss()
            numOfMultiCommentLine = x.getCountMultiLineCommentOfCss()
        elif (fileType == 'ctp'):
            numOfSingleCommentLine = x.getCountSingleLineCommentOfCtp()
            numOfMultiCommentLine = x.getCountMultiLineCommentOfCtp()
        elif (fileType == 'tpl'):
            numOfSingleCommentLine = x.getCountSingleLineCommentOfTpl()
            numOfMultiCommentLine = x.getCountMultiLineCommentOfTpl()
        else:
            numOfSingleCommentLine = 0
            numOfMultiCommentLine = 0
        finalTotal = numOfTotalLine - numOfSingleCommentLine - numOfMultiCommentLine - numOfEmptyLine
        total += finalTotal
        dataList = (file, numOfTotalLine, numOfEmptyLine,
                    numOfSingleCommentLine, numOfMultiCommentLine, finalTotal)
        dnxe.append(dataList)

    sys.stdout.write('State Capitals (source: Wikipedia)\n\n')
    headings = [
        'File', 'Total Line', 'Empty lines', 'Comment lines (single)',
        'Comment lines (multi)', 'Final total'
    ]
    fields = [0, 1, 2, 3, 4, lambda rec: rec[1] - rec[2] - rec[3] - rec[4]]
    align = [('^', '<'), ('^', '^'), ('^', '^'), ('^', '^'), ('^', '^'),
             ('^', '^')]
    table.table(sys.stdout, dnxe, fields, headings, align)
    print(
        "-------------------------------------------------------------------------------------------------------------"
    )
    print("Total lines of code exclude empty lines and comment lines: " +
          str(total))
Exemple #5
0
class translator:
    INSTRUCTION = ""
    tokenify = t.token()
    tablify = tab.table()
    syntaxify = s.syntaxis()
    stackify = tab.table()
    semanticfy = sem.semantic()
    IS_INTERPRETING = True

    def start(self):
        print(Fore.GREEN + "    ___(                     )\n" +
              "   (      THUNDER-flask      _)\n" +
              "  (_                       __)\n" +
              "    ((                _____)\n" + "      (_________)----'\n" +
              "         _/  /\n" + "        /  _/\n" + "      _/  /\n" +
              "     / __/\n" + "   _/ /\n" + "  /__/\n" + " //\n" + "/'\n")

    def listen(self):
        while self.IS_INTERPRETING:
            self.INSTRUCTION = raw_input(Fore.MAGENTA + 'thunder>')
            self.INSTRUCTION = self.INSTRUCTION.strip()  #quitar espacios
            # Sacar los tokens
            tokens = self.tokenify.tokenize(self.INSTRUCTION)
            # Agregar tokens a la tabla
            ok = True  #variable validadora de errores
            for token in tokens:
                if (token[1] == "error"):
                    print(Fore.CYAN + "(X_X)Invalid Token: " + token[2] +
                          " in index " + str(token[0]))
                    ok = False  #informar de error
                else:
                    self.tablify.add(token)
            #no hay error continuar a syntaxis
            if ok:
                #sacar el top de instrucciones
                tab = self.tablify.top()  #to improve
                #verificar validez sintactica del comando
                if self.syntaxify.syntaxize(tab) != None:
                    self.stackify.data = self.syntaxify.syntaxize(tab)
                    #analizar por clave la semantica
                    #print(self.stackify.data)
                    status = self.semanticfy.semanticize(self.stackify.data)
                    self.IS_INTERPRETING = status[0]
                    print(status[1])
                else:
                    print(Fore.RED + "(X_X) invalid comand: " +
                          ' '.join(str(x[2]) for x in tab) +
                          '\n(X_X) unknown syntaxis: ' +
                          ' '.join(str(x[1]) for x in tab))
 def logfile(self):
     from table import table
     from os.path import basename,exists
     from time_string import date_time
     from numpy import concatenate
     if exists(self.log_filename): logfile = table(self.log_filename)
     else:
         logfile = table()
         logfile["date time"] = [date_time(t) for t in self.start_time+self.scan_T]
         logfile["filename"] = [basename(f) for f in self.image_filenames]
         DX,DY = concatenate([self.scan_DXDY.T]*self.repeat_number).T
         logfile["X[mm]"] = DX
         logfile["Y[mm]"] = DY
     logfile.filename = self.log_filename
     return logfile
Exemple #7
0
    def inventory(self):
        if self.tracker.bin[0] == '0':
            messagebox.showwarning("showwarning",
                                   "Your account doesn't have this privilege")
            return
        for widget in self.table_frame.winfo_children():
            widget.destroy()
        self.Table_ = table(frame=self.table_frame,
                            tree_row=3,
                            tree_col=5,
                            column_id=("historyID", "Action Type", "User ID",
                                       "Action", "Date", "Time"),
                            rowheight=40,
                            height=10,
                            font_size=12,
                            font='Helvetica',
                            tablecol_width=180,
                            headingfont=30)
        list_his = CRUD.retrieve_history_byaction('inventory')
        list_his.reverse()
        self.Table_.tree.bind("<<TreeviewSelect>>", self.select_row)
        self.Table_.tree.bind("<Double-1>", self.OnDoubleClick)

        for x in list_his:
            self.Table_.tree.insert('', 'end', values=(x))
Exemple #8
0
def tableexists(tablename):
    result = True
    try:
        t = table(tablename, ack=False)
    except:
        result = False
    return result
Exemple #9
0
def openProject():
    cls()
    print(messeges['open_project'])
    objP = project(__sqlite)
    result = objP.get_list_proyect()
    selectTrue = False
    data_project = ''
    while not (selectTrue):
        headers = ('ID', 'NOMBRE', 'RUTA')
        tab = table(len(headers))
        tab.setMaxWidth(30)
        tab.setHeaders(headers)
        tab.setBody(result)
        tab.print_table()
        #for i in result:
        #    print(styles['result'].format(i))
        select_project = input(lines['input_option'])
        if select_project.isnumeric():
            select_project = int(select_project)
            for tupla in result:
                if select_project == tupla[0]:
                    selectTrue = True
                    objP = None
                    work_projec(tupla)
        else:
            print('Ingrese un valor valido, un ID')

    input('Salio')
Exemple #10
0
def tabledelete (tablename, checksubtables=False, ack=True):
    """Delete a table on disk.

    It is the same as :func:`table.delete`, but without the need to open
    the table first.

    """
    tabname = _remove_prefix(tablename)
    t = table(tabname, ack=False)
    if t.ismultiused(checksubtables):
        six.print('Table', tabname, 'cannot be deleted; it is still in use')
    else:
        t = 0
        table(tabname, readonly=False, _delete=True, ack=False)
        if ack:
            six.print('Table', tabname, 'has been deleted')
Exemple #11
0
    def read_file(self):
        "Check log file for changes and reread it"
        from os.path import exists, getmtime
        from table import table

        if not exists(self.filename):
            self.T, self.DT = zeros(0), zeros(0)
            self.timestamp = 0
            self.loaded_filename = ""
        else:
            current_timestamp = getmtime(self.filename)
            if abs(current_timestamp - self.timestamp) > 2 or \
                self.filename != self.loaded_filename:
                if self.timestamp != 0:
                    print "log file changed by %g s" % \
                        (current_timestamp - self.timestamp)
                status("Reading %s..." % self.filename)
                try:
                    logfile = table(self.filename, separator="\t")
                    self.T = array(map(timestamp, logfile.date_time))
                    self.DT = logfile.delay
                    self.timestamp = current_timestamp
                    self.loaded_filename = self.filename
                except Exception, details:
                    print "%s unreadable: %s" % (self.filename, details)
                    if self.loaded_filename != self.filename:
                        self.T, self.DT = zeros(0), zeros(0)
                        self.timestamp = current_timestamp
                        self.loaded_filename = self.filename
                status("Reading %s... done" % self.filename)
Exemple #12
0
    def read_file(self):
        "Check log file for changes and reread it"
        with self.lock:  # Allow only one thread at a time inside this function.
            from os.path import exists, getmtime
            from table import table

            if not exists(self.filename):
                ##debug("file %r not found" % self.filename)
                self.T, self.VALUE = zeros(0), zeros(0)
                self.timestamp = 0
                self.loaded_filename = ""
            else:
                current_timestamp = getmtime(self.filename)
                if abs(current_timestamp - self.timestamp) > 2 or \
                    self.filename != self.loaded_filename:
                    if self.timestamp != 0:
                        dt = (current_timestamp - self.timestamp)
                        ##debug ("log file changed by %g s" % dt)
                    ##debug("Reading %s" % self.filename)
                    status("Reading %s..." % self.filename)
                    try:
                        logfile = table(self.filename, separator="\t")
                        self.T = array(map(timestamp, logfile.date_time))
                        self.VALUE = logfile.value
                        self.timestamp = current_timestamp
                        self.loaded_filename = self.filename
                    except Exception, details:
                        ##debug("%s unreadable: %s" % (self.filename,details))
                        if self.loaded_filename != self.filename:
                            self.T, self.VALUE = zeros(0), zeros(0)
                            self.timestamp = current_timestamp
                            self.loaded_filename = self.filename
                    status("Reading %s... done" % self.filename)
    def __getattr__(self, name):
        """Get the keyword value.

        | The value of a column keyword is returned if it names a keyword.
          If the keyword is a subtable, it opens the table and returns a
          table object.
        | The values of all column keywords is returned if name equals _ or keys.

        An AttributeError is raised if the name is not a keyword.

        For example::

          print tc.MEASINFO         # print the column's measure info
          print tc._                # print all column keywords

        """
        # Try if it is a keyword.
        try:
            val = self.getkeyword(name)
            # See if the keyword represents a subtable and try to open it.
            if val != _do_remove_prefix(val):
                try:
                    return table(val, ack=False)
                except:
                    pass
            return val
        except:
            pass
        # _ or keys means all keywords.
        if name == '_'  or  name == 'keys':
            return self.getkeywords()
        # Unknown name.
        raise AttributeError("table has no attribute/keyword " + name)
Exemple #14
0
def main(screen):
    screen.clear()
    screen = curses.newpad(500, 500)
    curses.cbreak()
    screen.nodelay(True)
    screen.keypad(True)
    curses.curs_set(0)
    main_page = page(screen)
    for j in range(1, 10):
        arr = [[0] * 5 for i in range(3)]
        for i in range(5):
            v = i + j
            arr[0][i] = '1000 divided by {} is {}'.format(v, 1000 / v)
        for i in range(5):
            v = i + j + 10
            arr[1][i] = '1000 divided by {} is {}'.format(v, 1000 / v)
        for i in range(5):
            v = i + j + 15
            arr[2][i] = '1000 divided by {} is {}'.format(v, 1000 / v)
        new_arr = [[arr[j][i] for j in range(3)] for i in range(5)]
        Table = table.table(new_arr)
        main_page.add_table(Table)
    main_page.redraw()
    main_page.refresh(point(curses.LINES, curses.COLS))
    mainloop(screen, main_page)
Exemple #15
0
def start_game():
    """
    this runs the game
    :return: nothing
    """
    print("Welcome to the game of life(Semi-Poker)")
    game_state = 0
    YOU_LOSE = 1
    new_deck = deck.Deck()
    new_deck_size = new_deck.size()

    while game_state != YOU_LOSE:
        score = 0
        for num in range(int(new_deck_size / 9)):

            community_hand = table.table(new_deck, 5)
            hand_a = hand.StudHand(new_deck, community_hand, 2)
            hand_b = hand.StudHand(new_deck, community_hand, 2)

            print_cards(community_hand, hand_a, hand_b)

            actual_winner = hand_a.compare_to(hand_b)

            predicted_winner = print_input()

            if is_not_correct(actual_winner, predicted_winner):
                game_state = YOU_LOSE
                print_loser(score)
                return
            score += 1
        print("You win!")
        return
Exemple #16
0
def tabledelete (tablename, checksubtables=False, ack=True):
    """Delete a table on disk.

    It is the same as :func:`table.delete`, but without the need to open
    the table first.

    """
    tabname = _remove_prefix(tablename)
    t = table(tabname, ack=False)
    if t.ismultiused(checksubtables):
        print 'Table', tabname, 'cannot be deleted; it is still in use'
    else:
        t = 0
        table(tabname, readonly=False, _delete=True, ack=False)
        if ack:
            print 'Table', tabname, 'has been deleted'
Exemple #17
0
    def _tostr(self, fn=str, includeHeader=True, props=None):
        import functools

        def getattr(obj, attr, *args):
            def rgetattr(obj, attr):
                if obj:
                    return builtins.getattr(obj, attr, *args)
                return None
            return functools.reduce(rgetattr, [obj] + attr.split('.'))

        tbl = table()

        if props:
            props = ('ix', 'id') + tuple(props)
        else:
            props = ('ix', 'id')


        if includeHeader:
            r = tbl.newrow()
            for prop in props:
                r.newfield(prop)
            
        for p in self:
            r = tbl.newrow()
            for prop in props:
                if prop == 'ix':
                    v = self.getindex(p)
                else:
                    v = getattr(p, prop)
                    v = v if v else ''
                r.newfield(v)
        return str(tbl)
Exemple #18
0
def tablerename(tablename, newtablename):
    """Rename a table.

    The table with the given name is renamed (or moved) to the new name.

    """
    t = table(tablename, ack=False)
    t.rename (newtablename)
Exemple #19
0
    def initialize(self):
        print "Parsing inputfiles..."
        self.samples = plotfromoptree.parseInputfiles(self.options.inputfile)
        print "Parsing plotvariables..."
        self.allHistos = plotfromoptree.parsePlotvariables(self.options.plotvariables, self.samples)
        print "Writing inputfiles Tree..."
        self.inputfiletree = plotfromoptree.inputfileTree(self.samples)
        print "Writing plotvariables Tree..."
        self.plotvariabletree = plotfromoptree.plotvariableTree(self.allHistos)

        self.wsProducer = WSProducer()
        if (self.options.mode == "highestSumpt"):
            self.counter = table.table(2, 9)
            self.wsProducer.prepareDataSets(3)
        elif (self.options.mode == "allPairs"):
            self.counter = table.table(2, 1)
            self.wsProducer.prepareDataSets(3)
Exemple #20
0
def tableiswritable(tablename):
    result = True
    try:
        t = table(tablename, readonly=False, ack=False)
        result = t.iswritable()
    except:
        result = False
    return result
Exemple #21
0
def tableexists(tablename):
    """Test if a table exists."""
    result = True
    try:
        t = table(tablename, ack=False)
    except:
        result = False
    return result
 def show_table(self):
     tab = table(self.df)
     text = "\nMatriz de adyacencia\n" + str(tab)
     self.result.setText(text)
     self.send.setEnabled(False)
     self.graph.setEnabled(True)
     self.kruskal.setEnabled(True)
     self.prim.setEnabled(True)
Exemple #23
0
def tableexists(tablename):
    """Test if a table exists."""
    result = True
    try:
        t = table(tablename, ack=False)
    except:
        result = False
    return result
Exemple #24
0
def tablerename(tablename, newtablename):
    """Rename a table.

    The table with the given name is renamed (or moved) to the new name.

    """
    t = table(tablename, ack=False)
    t.rename (newtablename)
Exemple #25
0
def tableinfo(tablename):
    """Get type info of a table.

    It is the same as :func:`table.info`, but without the need to open
    the table first.

    """
    t = table(tablename, ack=False)
    return t.info()
Exemple #26
0
def tablesummary(tablename):
    """Get the summary of a table.

    It is the same as :func:`table.summary`, but without the need to open
    the table first.

    """
    t = table(tablename, ack=False)
    t.summary()
Exemple #27
0
def tablesummary(tablename):
    """Get the summary of a table.

    It is the same as :func:`table.summary`, but without the need to open
    the table first.

    """
    t = table(tablename, ack=False)
    t.summary()
Exemple #28
0
def tableinfo(tablename):
    """Get type info of a table.

    It is the same as :func:`table.info`, but without the need to open
    the table first.

    """
    t = table(tablename, ack=False)
    return t.info()
Exemple #29
0
 def __init__(self):
     self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.sock_number = 0
     self.available = 0
     self.initSocket()
     self.table = table()
     self.queue = Queue(maxsize=0)
     self.pool = self.start_pool()
     self.start_monitor()
     self.listen()
Exemple #30
0
def tablecopy(tablename, newtablename, deep=False, valuecopy=False, dminfo={},
              endian='aipsrc', memorytable=False, copynorows=False):
    """Copy a table.

    It is the same as :func:`table.copy`, but without the need to open
    the table first.

    """
    t = table(tablename, ack=False)
    return t.copy (newtablename, deep=deep, valuecopy=valuecopy)
Exemple #31
0
def table_overview(table_name):
    result = execute_command("""select * from "%s" limit 1;""" % table_name)
    overview = []
    if result:
        for col_name, example_value in result[0].iteritems():
            row = OrderedDict()
            row['Column name'] = col_name
            row['Example value'] = example_value
            overview.append(row)
        return table.table(overview)
Exemple #32
0
def table_overview(table_name):
    result = execute_command("""select * from "%s" limit 1;""" % table_name)
    overview = []
    if result:
        for col_name, example_value in result[0].iteritems():
            row = OrderedDict()
            row['Column name'] = col_name
            row['Example value'] = example_value
            overview.append(row)
        return table.table(overview)
Exemple #33
0
def tablestructure(tablename, dataman=True, column=True, subtable=False,
                   sort=False):
    """Print the structure of a table.

    It is the same as :func:`table.showstructure`, but without the need to open
    the table first.

    """
    t = table(tablename, ack=False)
    six.print(t.showstructure(dataman, column, subtable, sort))
Exemple #34
0
def tablecopy(tablename, newtablename, deep=False, valuecopy=False, dminfo={},
              endian='aipsrc', memorytable=False, copynorows=False):
    """Copy a table.

    It is the same as :func:`table.copy`, but without the need to open
    the table first.

    """
    t = table(tablename, ack=False)
    return t.copy (newtablename, deep=deep, valuecopy=valuecopy)
Exemple #35
0
def removeImagingColumns (msname):
    # Open the MS
    t = table (msname, readonly=False, ack=False)
    # Remove if the column exists.
    cnames = t.colnames()
    removeNames = []
    for col in ['MODEL_DATA', 'CORRECTED_DATA', 'IMAGING_WEIGHT']:
        if col in cnames:
            removeNames.append (col)
    if len(removeNames) > 0:
        t.removecols (removeNames)
        t.flush()
 def get_crystal_IJ(self):
     """coordinates of crystal centers
     I: 0-based horizontal pixel coordinates, from left
     J: 0-based vertical pixel coordinates, from top
     """
     from table import table
     from numpy import array
     if self.has_crystal_IJ:
         data = table(self.crystal_IJ_filename,separator="\t")
         IJ = data["I","J"].asarray
     else: IJ = array([[],[]],dtype=int)
     return IJ
Exemple #37
0
def database_overview():
    result = execute_command("select type, name, sql from sqlite_master;")
    if result:
        # Calculate row counts only if db file is less than 1GB
        if os.path.getsize(db_file) < 1024 ** 3:
            for thing in result:
                if thing['type'] in ['table', 'view']:
                    r2 = execute_command("""select count(*) as n from "%s";""" % thing['name'])
                    thing['rows'] = int(r2[0]['n'])
                else:
                    thing['rows'] = None
        return table.table(result)
Exemple #38
0
 def make_move(self, game):
     start = time.time()
     self.distance = 1
     self.max_q = 11
     hash = self.get_hashkey(game)
     self.table = table()
     self.count = game.fullmove_number
     while time.time() < start + self.time_limit:
         move = self.iterative_root(game, start + self.time_limit, hash)
         self.distance += 1
         self.max_q += 1
     return move
Exemple #39
0
def menu_header(fenetre, db, canvas, vbar):
    font = ("times new roman", 14)

    mainmenu = Menu(fenetre, background="#59C38D", font=font, activebackground="#2FB5A3", relief="flat")

    mtable = Menu(mainmenu, tearoff=0, activebackground="#2FB5A3", background="#59C38D", font=font, relief="flat")
    mtable.add_command(label="abdominaux", command=lambda choix="abdominaux": table.table(db, choix, fenetre, canvas, vbar))
    mtable.add_command(label="pectoraux", command=lambda choix="pectoraux": table.table(db, choix, fenetre, canvas, vbar))
    mtable.add_command(label="dos", command=lambda choix="dos": table.table(db, choix, fenetre, canvas, vbar))
    mtable.add_command(label="biceps", command=lambda choix="biceps": table.table(db, choix, fenetre, canvas, vbar))
    mtable.add_command(label="triceps", command=lambda choix="triceps": table.table(db, choix, fenetre, canvas, vbar))
    mtable.add_command(label="jambes", command=lambda choix="jambes": table.table(db, choix, fenetre, canvas, vbar))

    mupdateexercise = Menu(mainmenu, tearoff=0, activebackground="#2FB5A3", background="#59C38D", font=font, relief="flat")
    mupdateexercise.add_command(label="ajouter exercice", command=lambda: ajoutexercice.main(db, fenetre, canvas, vbar))
    mupdateexercise.add_command(label="supprimer exercice", command=lambda: supprexercice.main(db, fenetre, canvas, vbar))
    mupdateexercise.add_command(label="modifier exercice", command=lambda: modifexercice.main(db, fenetre, canvas, vbar))

    mupdateprogram = Menu(mainmenu, tearoff=0, activebackground="#2FB5A3", background="#59C38D", font=font, relief="flat")
    mupdateprogram.add_command(label="ajouter programme", command=lambda: ajoutprogramme.main(db, fenetre, canvas, vbar))
    mupdateprogram.add_command(label="supprimer programme", command=lambda: supprprogramme.main(db, fenetre, canvas, vbar))
    mupdateprogram.add_command(label="modifier programme", command=lambda: modifprogramme.main(db, fenetre, canvas, vbar))

    mainmenu.add_command(label="accueil", font=font, command=lambda: accueil.accueil(db, fenetre, canvas, vbar))
    mainmenu.add_cascade(label="table", font=font, menu=mtable)
    mainmenu.add_cascade(label="exercice", font=font, menu=mupdateexercise)
    mainmenu.add_cascade(label="programme", font=font, menu=mupdateprogram)

    mainmenu.add_command(label="seance", command=lambda: seance.seance(db, fenetre, canvas, vbar))

    mainmenu.add_command(label="démarrer", command=lambda: demarrer.demarrer(db, fenetre, canvas, vbar))

    fenetre.config(menu=mainmenu)
Exemple #40
0
async def handle_message_tags(message, client):
    if "-h" in message.content:
        await send_message(message.channel, "generate a list of tags")
        return
    results = get_tags()
    fname = "tags.txt"
    file = open(fname, "w")
    tab = table(("Tag", "Prob #"), results, False)
    file.write(tab)
    file.close()
    fil = discord.File(fname)
    await message.channel.send(file=fil)
    os.remove(fname)
def load_table(tbl_name):
    with open(tbl_name.lower().replace(" ", "_") + ".bin", mode='rb') as f:
        table_name = pickle.load(f)
        attribute_names = pickle.load(f)
        attribute_types = pickle.load(f)
        records = pickle.load(f)

    tbl = table(table_name)
    tbl.create(attribute_names, attribute_types)
    for record in records:
        tbl.addRow(record)
        
    return tbl
Exemple #42
0
    def initialize(self):
        print "Parsing inputfiles..."
        self.samples, self.generalInfo = plotfromoptree.parseInputfiles(self.options.inputfile)
        print "Parsing plotvariables..."
        self.allHistos = plotfromoptree.parsePlotvariables(self.options.plotvariables, self.samples)
        print "Writing inputfiles Tree..."
        self.inputfiletree = plotfromoptree.inputfileTree(self.samples)
        print "Writing plotvariables Tree..."
        self.plotvariabletree = plotfromoptree.plotvariableTree(self.allHistos)

        self.signalSamples = plotfromoptree.getSignalSamples(self.samples)
        self.wsProducer = WSProducer(self.options)
        self.counter = table.table(2, 5)
        self.wsProducer.prepareDataSets(11, self.signalSamples)
Exemple #43
0
def show_tables():
	global has_created
	if not has_created:
		has_created = True		
		t_idx = 0
		tables_list.clear()
		show_list.clear()
		while t_idx < TABLES:
			t_id = 'table%i' % t_idx
			new_table = table(t_id)
			tables_list[t_id] = new_table
			show_list[t_id] = new_table.get_funds()
			t_idx += 1
	return jsonify(show_list)
Exemple #44
0
    def getContent(self):        
        import suit.core.sc_utils as sc_utils
        import suit.core.keynodes as keynodes
        session = core.Kernel.session()
        _addr = self._getSheet()._getScAddr()
        if _addr is not None:
            fmt = sc_utils.getContentFormat(session, _addr)
            
            if fmt.this == keynodes.ui.format_string.this or fmt.this == keynodes.ui.format_term.this:
                value = session.get_content_str(_addr)
            elif fmt.this == keynodes.ui.format_int.this or fmt.this == keynodes.ui.format_real.this:
                value = str(session.get_content_real(_addr))
            
            if value is None:
                return ""
            
            return value            
        ob = table.table("information")

        return ob.makeTextTable() #"Text\nAnd Text"
Exemple #45
0
    def table(self, x, header = False):
        r"""
        Print a nested list as a HTML table.  Strings of html
        will be parsed for math inside dollar and double-dollar signs.
        2D graphics will be displayed in the cells.  Expressions will
        be latexed.


        INPUT:

        - ``x`` -- a list of lists (i.e., a list of table rows)
        - ``header`` -- a row of headers.  If ``True``, then the first
          row of the table is taken to be the header.

        EXAMPLES::

            sage: html.table([(i, j, i == j) for i in [0..1] for j in [0..1]])
            <html>
            <div class="notruncate">
            <table class="table_form">
            <tbody>
            <tr class ="row-a">
            <td><script type="math/tex">0</script></td>
            <td><script type="math/tex">0</script></td>
            <td><script type="math/tex">\mathrm{True}</script></td>
            </tr>
            <tr class ="row-b">
            <td><script type="math/tex">0</script></td>
            <td><script type="math/tex">1</script></td>
            <td><script type="math/tex">\mathrm{False}</script></td>
            </tr>
            <tr class ="row-a">
            <td><script type="math/tex">1</script></td>
            <td><script type="math/tex">0</script></td>
            <td><script type="math/tex">\mathrm{False}</script></td>
            </tr>
            <tr class ="row-b">
            <td><script type="math/tex">1</script></td>
            <td><script type="math/tex">1</script></td>
            <td><script type="math/tex">\mathrm{True}</script></td>
            </tr>
            </tbody>
            </table>
            </div>
            </html>

            sage: html.table([(x,n(sin(x), digits=2)) for x in [0..3]], header = ["$x$", "$\sin(x)$"])
            <html>
            <div class="notruncate">
            <table class="table_form">
            <tbody>
            <tr>
            <th><script type="math/tex">x</script></th>
            <th><script type="math/tex">\sin(x)</script></th>
            </tr>
            <tr class ="row-a">
            <td><script type="math/tex">0</script></td>
            <td><script type="math/tex">0.00</script></td>
            </tr>
            <tr class ="row-b">
            <td><script type="math/tex">1</script></td>
            <td><script type="math/tex">0.84</script></td>
            </tr>
            <tr class ="row-a">
            <td><script type="math/tex">2</script></td>
            <td><script type="math/tex">0.91</script></td>
            </tr>
            <tr class ="row-b">
            <td><script type="math/tex">3</script></td>
            <td><script type="math/tex">0.14</script></td>
            </tr>
            </tbody>
            </table>
            </div>
            </html>

        """
        from table import table
        table(x, header_row=header)._html_()
Exemple #46
0
    def table(self, x, header=False):
        r"""
        Generate a HTML table.  

        See :class:`~sage.misc.table.table`.

        INPUT:

        - ``x`` -- a list of lists (i.e., a list of table rows)

        - ``header`` -- a row of headers.  If ``True``, then the first
          row of the table is taken to be the header.

        OUTPUT:
     
        A :class:`HtmlFragment` instance.

        EXAMPLES::

            sage: pretty_print(html.table([(i, j, i == j) for i in [0..1] for j in [0..1]]))
            doctest:...: DeprecationWarning: use table() instead of html.table()
            See http://trac.sagemath.org/18292 for details.
            <div class="notruncate">
            <table class="table_form">
            <tbody>
            <tr class ="row-a">
            <td><script type="math/tex">0</script></td>
            <td><script type="math/tex">0</script></td>
            <td><script type="math/tex">\mathrm{True}</script></td>
            </tr>
            <tr class ="row-b">
            <td><script type="math/tex">0</script></td>
            <td><script type="math/tex">1</script></td>
            <td><script type="math/tex">\mathrm{False}</script></td>
            </tr>
            <tr class ="row-a">
            <td><script type="math/tex">1</script></td>
            <td><script type="math/tex">0</script></td>
            <td><script type="math/tex">\mathrm{False}</script></td>
            </tr>
            <tr class ="row-b">
            <td><script type="math/tex">1</script></td>
            <td><script type="math/tex">1</script></td>
            <td><script type="math/tex">\mathrm{True}</script></td>
            </tr>
            </tbody>
            </table>
            </div>

            sage: pretty_print(html(table(
            ....:     [(x,n(sin(x), digits=2)) for x in range(4)],
            ....:     header_row=["$x$", "$\sin(x)$"])))
            <div class="notruncate">
            <table class="table_form">
            <tbody>
            <tr>
            <th><script type="math/tex">x</script></th>
            <th><script type="math/tex">\sin(x)</script></th>
            </tr>
            <tr class ="row-a">
            <td><script type="math/tex">0</script></td>
            <td><script type="math/tex">0.00</script></td>
            </tr>
            <tr class ="row-b">
            <td><script type="math/tex">1</script></td>
            <td><script type="math/tex">0.84</script></td>
            </tr>
            <tr class ="row-a">
            <td><script type="math/tex">2</script></td>
            <td><script type="math/tex">0.91</script></td>
            </tr>
            <tr class ="row-b">
            <td><script type="math/tex">3</script></td>
            <td><script type="math/tex">0.14</script></td>
            </tr>
            </tbody>
            </table>
            </div>
        """
        from sage.misc.superseded import deprecation
        deprecation(18292, 'use table() instead of html.table()')
        from table import table
        return table(x, header_row=header)._html_()
Exemple #47
0
 def run(self):
     return [table.table(
         head=self.export_headers(),
         body=map(self.export_project, self.get_and_clear_projects())
     )]
def main(argv):
    startTime = None; endTime = None; outPut = None; configFile = None
    global _debug
    _debug = None;
    #parse the arguments
    try:
        opts, args = getopt.getopt(argv[1:],
                                  "c:de:hs:o:V",
                                  ["config=", "debug","end=", "help", "start=",
                                   "output", "version"])
    except getopt.GetoptError:
        usage()
        sys.exit(2)
    #Deal with the arguments
    for opt, arg in opts:
        if   opt in ("-h",   "--help"):
            usage()
            sys.exit()
        elif opt in ('-d',  "--debug"):
            _debug = 1
        elif opt in ("-s",  "--start"):
            startTime = makeInt(arg)
        elif opt in ("-e",    "--end"):
            endTime = makeInt(arg)
        elif opt in ("-o", "--output"):
            outPut = arg
        elif opt in ("-c", "--config"):
            configFile = arg
            print("Sorry, config files are not supported yet!")
            sys.exit(2)
        elif opt in ("-V", "--version"):
            version()
            sys.exit()

    if configFile != None: # Deal with config file.
        pass
    elif len(args) != 1: # the host must be defined in the args
        usage()
        sys.exit(2)
    else:
        host = args[0]

    if startTime == None: # Define the off-peak start time
        startTime = 0 # TODO: Think about what these defaults should be
    if endTime   == None: # Define the off-peak end time
        endTime   = 0
    if outPut    == None:
        outPut    = "../www/index.html"
    
    myTable = table.table()
    users = {}
    interface = webInterface.webInterface()
    # Final program loop!
    while True:
        print("Currently updating data from router " + host)
        myTable.updateTable(host)
        if _debug == 1 : print("DEBUG: updated table")
        # Check if we are currently on or off peak

        curTime = datetime.time(time.localtime().tm_hour,time.localtime().tm_min)
        if  curTime > datetime.time(startTime,0) \
        and curTime < datetime.time(endTime  ,0):
                peak = 'off'
        else:
            peak = 'on'

        while myTable.hasLines():
            line = myTable.getLine()
            
            if line["address"] not in users:
                users[line["address"]] = user.user()
            myUser = users[line["address"]]
            myUser.addData(data = line["bytes"], pkts = line["pkts"],
                           peak = peak, direction = line["upOrDown"])

        interface.outputIndex(outPut, users)
        
        time.sleep(time.localtime(time.time())[3])
Exemple #49
0
#!/usr/bin/python2
# -*- coding: utf-8 -*-
import sys
from table import table

if __name__ == "__main__":
    if len(sys.argv) == 2:
        t = table.load(sys.argv[1])
        print t.generatePage()
        quit()
        
    f*g = ""
    print "Velkomin í stundatöfluvélina"
    tafla = table()
    print tafla
    while f*g != "q":
        print "Sladu inn f*g til ad baeta vid, 'q' til ad haetta"
        f*g = raw_input("F*g: ")
        if f*g == 'q':
            print tafla
        else:
            fulltNafn = raw_input("Fullt nafn námskeiðs: ")
            adalkennari = raw_input("Kennari námskeiðs (upphafsstafir): ")
            litur = raw_input("HTML litur: ")
            print "Sláðu inn gerð tíma (f, d1, etc) og veldu tímasetningu, gerð 'q' til að hætta: "
            gerd = None
            while gerd != "q":
                gerd = raw_input("Gerð: ")
                if gerd == "q":
                    break
                lengd = raw_input("Fjoldi tima (1,2,etc): ")
Exemple #50
0
def tablerename(tablename, newtablename):
    t = table(tablename, ack=False)
    t.rename (newtablename)
Exemple #51
0
def tableinfo(tablename):
    t = table(tablename, ack=False)
    return t.info()
Exemple #52
0
def tablesummary(tablename):
    t = table(tablename, ack=False)
    t.summary()
 def next (self):
     # next returns a Table object, so turn that into table.
     return table (self._next(), _oper=3);
Exemple #54
0
                exit()
            elif a.strip().lower().startswith('show tables'):
                print database_overview()
            elif a.strip().lower().startswith('help'):
                print shell_help
            elif a.strip().lower().startswith('describe'):
                try:
                    table_name = a.strip().lower().split()[1]
                except IndexError, e:
                    print 'Which table would you like to describe?'
                else:
                    print table_overview(table_name)
            else:
                result = execute_command(a)
                if isinstance(result, list) and len(result):
                    print table.table(result)


def execute_command(command):
    conn = sqlite3.connect(db_file)
    cursor = conn.cursor()
    try:
        result = cursor.execute(command)
    except sqlite3.OperationalError, e:
        print 'Invalid query'
        print e
        return False
    else:
        c = command.lower().strip()
        if result.description:
            column_names = [ col[0] for col in result.description ]
Exemple #55
0
def tablefromascii (tablename, asciifile,
                    headerfile='',
                    autoheader=False, autoshape=[],
                    columnnames=[], datatypes=[],
                    sep=' ',
                    commentmarker='',
                    firstline=1, lastline=-1,
                    readonly=True,
                    lockoptions='default', ack=True):
    """Create a table from an ASCII file.

    Create a table from a file in ASCII format. Columnar data as well as
    table and column keywords may be specified.
    Once the table is created from the ASCII data, it is opened in the
    specified mode and a table object is returned.

    The table columns are filled from a file containing the data values
    separated by a separator (one line per table row). The default
    separator is a blank. Blanks before and after the separator are ignored.
    If a non-blank separator is used, values can be empty. Such values
    default to 0, empty string, or F depending on the data type. E.g.
    1,,2, has 4 values of which the 2nd and 4th are empty and default to 0.
    Similarly if fewer values are given than needed, the missing values
    get the default value.

    Either the data format can be explicitly specified or it can be found
    automatically. The former gives more control in ambiguous situations.
    Both scalar and array columns can be generated from the ASCII input.
    The format string determines the type and optional shape.

    It is possible to give the column names and their data types in
    various ways:

    - Using 2 header lines (as described below) as the first two lines
      in the data file or in a separate header file. This is the default way.
    - Derive them automatically from the data (`autoheader=True`).
    - Using the arguments `columnnames` and
      `datatypes` (as non-empty vectors of strings).
      It implies (`autoheader=False`). The data types should be
      given in the same way as done in headers.

    In automatic mode (`autoheader=True`) the first line
    of the ASCII data is analyzed
    to deduce the data types. Only the types I, D, and A can be
    recognized. A number without decimal point or exponent is I (integer),
    otherwise it is D (double). Any other string is A (string).
    Note that a number may contain a leading sign (+ or -).
    The `autoshape` argument can be used to specify if the input
    should be stored as multiple scalars (the default) or as a single
    array. In the latter case one axis in the shape can be defined as
    variable length by giving it the value 0. It means that the actual
    array shape in a row is determined by the number of values in the
    corresponding input line.
    Columns get the names `Column1`, `Column2`, etc..
    For example:

    1. `autoshape=[]` (which is the default) means that all values
       are to be stored as scalar columns.
    2. `autoshape=0` means that all values in a row are to be stored as
       a variable length vector.
    3. `autoshape=10` defines a fixed length vector. If an input
       line contains less than 10 values, the vector is filled with default
       values. If more than 10 values, the latter values are ignored.
    4. `autoshape=[5,0]` defines a 2-dim array of which the 2nd axis is
       variable. Note that if an input line does not contain a multiple of 5
       values, the array is filled with default values.

    If the format of the table is explicitly specified, it has to be done
    either in the first two lines of the data file (named by the
    argument filename), or in a separate header file (named by the
    argument headerfile). In both forms, table keywords may also be
    specified before the column definitions.
    The column names and types can be described by two lines:

    1. The first line contains the names of the columns.
       These names may be enclosed in quotes (either single or double). 
    2. The second line contains the data type and optionally the shape
       of each column. Valid types are: 

       - S for Short data 
       - I for Integer data 
       - R for Real data 
       - D for Double Precision data 
       - X for Complex data (Real followed by Imaginary) 
       - Z for Complex data (Amplitude then Phase) 
       - DX for Double Precision Complex data (Real followed by Imaginary) 
       - DZ for Double Precision Complex data (Amplitude then Phase) 
       - A for ASCII data (a value must be enclosed in single or double quotes
         if it contains whitespace) 
       - B for Boolean data (False are empty string, 0, or any string
         starting with F, f, N, or n).

    If a column is an array, the shape has to be given after the data type
    without any whitespace. E.g. `I10` defines an integer vector
    of length 10. `A2,5` defines a 2-dim string array with shape
    [2,5]. Note that `I` is not the same as `I1` as the
    first one defines a scalar and the other one a vector with length 1.
    The last column can have one variable length axis denoted by the value 0.
    It "consumes" the remainder of the input line.

    If the argument headerfile is set then the header information is
    read from that file instead of the first lines of the data file.

    To give a simple example of the form where the header information
    is located at the top of the data file::

      COLI   COLF   COLD       COLX        COLZ       COLS
        I      R      D          X           Z          A
        1      1.1    1.11       1.12 1.13   1.14 1.15  Str1
        10     11     12         13   14     15   16    ""

    Note that a complex number consists of 2 numbers.
    Also note that an empty string can be given.

    Let us now give an example of a separate header file that one might use to
    get interferometer data into casacore::

      U     V      W         TIME        ANT1       ANT2      DATA
      R     R      R          D           I          I        X1,0

    The data file would then look like::

      124.011 54560.0  3477.1  43456789.0990    1      2        4.327 -0.1132
      34561.0 45629.3  3900.5  43456789.0990    1      3        5.398 0.4521

    Note that the DATA column is defined as a 2-dim array of 1
    correlation and a variable number of channels, so the actual number of
    channels is determined by the input. In this example both rows will
    have 1 channel (note that a complex value contains 2 values).

    Tables may have keywords in addition to the columns. The keywords
    are useful for holding information that is global to the entire
    table (such as author, revision, history, etc.).
    The keywords in the header definitions must preceed the column descriptions.
    They must be enclosed between a line that starts with ".key..." and
    a line that starts with ".endkey..." (where ... can be anything).
    A table keywordset and column keywordsets can be specified.
    The latter can be specified by specifying the column name after
    the .keywords string.
    Between these two lines each line should contain the following:

    - The keyword name, e.g., ANYKEY 
    - The datatype and optional  shape of the keyword
      (cf. list of valid types above) 
    - The value or values for the keyword (the keyword may contain 
      a scalar or an array of values). e.g., 3.14159 21.78945 

    Thus to continue the example above, one might wish to add keywords
    as follows::

      .keywords
      DATE        A  "97/1/16"
      REVISION    D 2.01
      AUTHOR      A "Tim Cornwell"
      INSTRUMENT  A "VLA"
      .endkeywords
      .keywords TIME
      UNIT A "s"
      .endkeywords
      U     V      W         TIME        ANT1       ANT2      DATA
      R     R      R          D           I          I        X1,0

    Similarly to the column format string, the keyword formats can also
    contain shape information. The only difference is that if no shape is
    given, a keyword can have multiple values (making it a vector).

    It is possible to ignore comment lines in the header and data file
    by giving the `commentmarker`. It indicates that lines
    starting with the given marker are ignored. Note that the marker can
    be a regular expression (e.g. `' *//'` tells that lines starting
    with // and optionally preceeded by blanks have to be ignored).

    With the arguments `firstline` and `lastline` one can
    specify which lines have to be taken from the input file. A negative value
    means 1 for `firstline` or end-of-file for `lastline`.
    Note that if the headers and data are combined in one file,
    these line arguments apply to the whole file. If headers and data are in
    separate files, these line arguments apply to the data file only.

    Also note that ignored comment lines are counted, thus are used to
    determine which lines are in the line range.

    The number of rows is determined by the number of lines read from the data
    file.

    """
    import os.path
    filename = os.path.expandvars(asciifile)
    filename = os.path.expanduser(filename)
    if not os.path.exists(filename):
        s = "File '%s' not found" % (filename)
        raise IOError(s)
    if headerfile != '':
        filename = os.path.expandvars(headerfile)
        filename = os.path.expanduser(filename)
        if not os.path.exists(filename):
            s = "File '%s' not found" % (filename)
            raise IOError(s)
    tab = table(asciifile, headerfile, tablename, autoheader, autoshape,
                sep, commentmarker, firstline, lastline,
                _columnnames=columnnames, _datatypes=datatypes, _oper=1)
    six.print('Input format: [' + tab._getasciiformat() +']')
    # Close table and reopen it in correct way.
    tab = 0
    return table(tablename, readonly=readonly, lockoptions=lockoptions,
                 ack=ack)
Exemple #56
0
#==========================================================================#
#                         Initialize surfaces                              #
#==========================================================================#
screen         = pg.display.set_mode((tb.BLOCK_SIZE*tb.WIDTH,tb.BLOCK_SIZE*tb.HEIGHT+INFO_SURFACE_HEIGHT))
tablesurface   = screen.subsurface((0,INFO_SURFACE_HEIGHT,tb.BLOCK_SIZE*tb.WIDTH,tb.BLOCK_SIZE*tb.HEIGHT))
infosurface    = screen.subsurface((0,0,tb.BLOCK_SIZE*tb.WIDTH,INFO_SURFACE_HEIGHT))

#==========================================================================#
#                        Block spawn position                              #
#==========================================================================#
BLOCK_SPAWN_POS = (0,(tb.WIDTH/2)-1)

#==========================================================================#
#               Create the table and an initial block                      #
#==========================================================================#
t     = tb.table(tablesurface)
b     = bk.block(BLOCK_SPAWN_POS)
nextb = bk.block(BLOCK_SPAWN_POS)

#==========================================================================#
#                 Draw initial information surface                         #
#==========================================================================#
updateInfo(nextb)

#==========================================================================#
#                            Main loop                                     #
#==========================================================================#
running = True

while running:
	clock.tick_busy_loop(FPS)