Example #1
0
 def join(self, other_sorted, field, other_field=""):
     if not other_field:
         other_field=field
     pos, other_pos, pos_inside_block, other_pos_inside_block = 0, 0, 0, 0 #*_inside_block marks a record inside a block
     self.r_block.read(pos)
     while(self.r_block.records[0]):
         other_sorted.r_block.read(other_pos)
         while(other_sorted.r_block.records[0]):
             if not self.r_block.records[pos_inside_block]:
                 pos_inside_block=0
                 pos+=self.r_block.max_size*self.r_block.record_size
                 self.r_block.read(pos)
                 break
             if not other_sorted.r_block.records[other_pos_inside_block]:
                 other_pos_inside_block=0
                 other_pos+=other_sorted.r_block.max_size*other_sorted.r_block.record_size
                 other_sorted.r_block.read(pos)
                 break
             if(getattr(Record(self.r_block.records[pos_inside_block]),field)==getattr(Record(other_sorted.r_block.records[other_pos_inside_block]),other_field)):
                 print(self.r_block.records[pos_inside_block]+"\n"+other_sorted.r_block.records[other_pos_inside_block]+"\n")
                 pos_inside_block+=1 #pair found, moves left table's pointer
             else:
                 if(getattr(Record(self.r_block.records[pos_inside_block]),field)<getattr(Record(other_sorted.r_block.records[other_pos_inside_block]),other_field)):
                       pos_inside_block+=1 #moves left table's pointer
                 else:
                       other_pos_inside_block+=1 #moves right table's pointer
             if(pos_inside_block>=self.r_block.max_size): #loads left table's next block
                 pos_inside_block=0
                 pos+=self.r_block.max_size*self.r_block.record_size
                 self.r_block.read(pos)
             if(other_pos_inside_block>=other_sorted.r_block.max_size): #loads right table's next block
                 other_pos_inside_block=0
                 other_pos+=other_sorted.r_block.max_size*other_sorted.r_block.record_size
                 other_sorted.r_block.read(other_pos)
Example #2
0
    def loadDataBase(self, cp):
        path = cp
        loaddata = ["a"]
        if os.path.isfile(path):
            with open(path) as f:
                loaddata = [s.strip() for s in f.readlines()]

        def split_list(l, n):
            for idx in range(0, len(l), n):
                yield l[idx:idx + n]

        result = list(split_list(loaddata, 7))

        temp_record = [
            re.Record(result[0][0], result[0][1], result[0][2], result[0][3],
                      result[0][4], result[0][5])
        ]

        for i in range(len(result)):
            if i != 0:
                record = re.Record(result[i][0], result[i][1], result[i][2],
                                   result[i][3], result[i][4], result[i][5])
                temp_record.append(record)

        self.record = temp_record
        self.currentNum = len(self.record)
        self.currentFileName = path
Example #3
0
    def launch_mame(self):
        while self.out is None or self.out.poll() is not None:

            if self.item is None:
                return

            Record.timed_log(self.item.get_title())

            wait_loop = 15
            while wait_loop > 0:
                time.sleep(0.1)
                wait_loop = wait_loop - 1
                if self.is_running is False:
                    return

            if Config.dry_run is False:
                self.out = Mame.run(self.item)

                self.set_title()

                self.set_position()

            self.init_smart_sound()

            self.init_silence()

            self.init_date()

            self.first_launch = False

            self.get_command()

            self.send_keyboard_skip = True
Example #4
0
 def join(self, other_heap, field, other_field=""):
     if not other_field:
         other_field=field
     pos, other_pos = 0, 0
     self.r_block.read(pos)
     while(self.r_block.records[0]):
         for i in self.r_block.records:
             if not i:
                 break
             if other_field in other_heap.indexes:  # if field is indexed
                 if other_heap.indexBPlusTree:
                     other_heap.r_block.read(int.from_bytes(other_heap.indexes[other_field].get(getattr(Record(i),field),byteorder)))
                 else:
                     if other_heap.indexBTree:
                         other_heap.r_block.read(other_heap.indexes[other_field].search(getattr(Record(i),field))[0].pos)
                     else:
                         other_heap.r_block.read(other_heap.indexes[other_field][getattr(Record(i), field)]*other_heap.r_block.record_size)
                 for j in other_heap.r_block.records:
                     if not j:
                         break
                     if getattr(Record(i), field) == getattr(Record(j), other_field):
                         print(i+"\n"+j+"\n")
             else:  # if field is NOT indexed
                 other_pos = 0
                 other_heap.r_block.read(other_pos)
                 while(other_heap.r_block.records[0]):
                     for j in other_heap.r_block.records:
                         if not j:
                             break
                         if getattr(Record(i), field) == getattr(Record(j), other_field):
                             print(i+"\n"+j+"\n")
                     other_pos += other_heap.r_block.max_size*other_heap.r_block.record_size
                     other_heap.r_block.read(other_pos)
         pos += self.r_block.max_size*self.r_block.record_size
         self.r_block.read(pos)
 def display_msg(self):
     # if rec.end:
     self.ui.text_box.setTextColor(QColor(200, 200, 200))
     self.ui.text_box.setText("Say something ....")
     self.ui.record_button.setText("Say")
     regex.reset_cmd()
     if rec.end:
         rec.record()
Example #6
0
    def editBook(self, content, Num, mylist):
        text1 = self.top.t1.get("1.0", "end-1c")
        text2 = self.top.t2.get("1.0", "end-1c")
        text3 = self.top.t3.get("1.0", "end-1c").rstrip()
        text3 = self.top.t3.get("1.0", "end-1c").replace("\n", "[newLine]")

        while (text3.endswith("[newLine]")):
            text3 = text3[0:(len(text3) - 9)]

        editString = text1 + "\t" + text2 + "\t" + text3 + "\n"

        content[int(Num) - 1] = editString
        #print content[int(Num)-1]

        thefile = open('a.txt', 'w')
        for item in content:
            #thefile.write("%s" % item.decode('utf-8').encode('utf-8') )
            thefile.write("%s" % item)
        thefile.close()

        self.mylist.config(state="normal")
        self.mylist.delete(1.0, END)
        #print "%s" % (mylist.get("1.0", "end-1c"))
        with open("a.txt") as f:
            content = f.readlines()

        Record.writeRecordToLog(datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                                "1", "gg", "Edit")

        self.mylist.insert(END,
                           "*************** reading list ***************\n")
        self.mylist.insert(END, "No.\tDate\tTitle\tReflection\n")

        count = 1
        for p in content:

            #========================================== debug
            items = p.split("\t")
            displayReflectionString = items[2]
            if (len(displayReflectionString) > 50):
                displayReflectionString = displayReflectionString[:49] + "...\n"

            displayString = items[0] + "\t" + items[
                1] + "\t" + displayReflectionString.replace("[newLine]", " ")
            self.mylist.insert(END, "%d\t%s" % (count, displayString))

            #self.mylist.insert(END,  "%d\t%s" % (count, displayString.decode("utf-8").encode("utf-8")))
            count += 1

    #========================================== debug

    #self.mylist.insert(END,  "%d\t%s" % (count, p))
    # count+=1

        self.wButton.config(state='normal')
        self.mylist.config(state="disabled")

        self.OnChildClose()
Example #7
0
 def display_msg(self):
     if rec.end:
         rec.end = False
         self.ui.label.setText("Hãy nói gì đó!")
         self.ui.record_button.setText("Dừng")
         rec.record()
     else:
         rec.end = True
         self.ui.label.setText("Dừng")
         self.ui.record_button.setText("Ghi âm")
    def __init__(self, command_line_arguments):
        pdb.set_trace()
        Record.__init__(self, 'control')

        if len(command_line_arguments) > 1:
            raise RuntimeError('command line arguments ignored')

        me = 'model_ols_regression_test'

        self.path_out_log = '../data/working/' + me + '.txt'
        self.num_features = 1
        self.num_train_samples = 1000
        self.num_test_samples = 100
        self.true_theta = np.array([10, 1, -2])
    def __init__(self, root):
        a = 60
        b = 80
        l = 50
        self.choose = False
        self.choosed_chess = False
        self.xing_qi = True

        self.root = root
        self.Board = Board.Board(root, a, b, l)
        self.front_display()
        self.Board.canvas.bind('<Button-1>', self.move)
        self.che_record = Record.CHE_Record(self.Board)
        self.log_record = Record.FEN_Record()
        self.fen = ''
Example #10
0
def parse(handle):
    record = None
    for line in handle:
        line = line.strip('\n').strip('\r')
        if not line: continue  # Ignore empty lines
        c = line[0]
        if c == '^':
            if record: yield record
            record = Record.Record()
            record.entity_type, record.entity_id = _read_key_value(line)
        elif c == '!':
            if line in ('!Sample_table_begin', '!Sample_table_end',
                        '!Platform_table_begin', '!Platform_table_end'):
                continue
            key, value = _read_key_value(line)
            if key in record.entity_attributes:
                if type(record.entity_attributes[key]) == list:
                    record.entity_attributes[key].append(value)
                else:
                    existing = record.entity_attributes[key]
                    record.entity_attributes[key] = [existing, value]
            else:
                record.entity_attributes[key] = value
        elif c == '#':
            key, value = _read_key_value(line)
            assert key not in record.col_defs
            record.col_defs[key] = value
        else:
            row = line.split("\t")
            record.table_rows.append(row)
    yield record
Example #11
0
    def Remove(self, content, addOrEdit, Num, mylist):
        thefile = open('a.txt', 'w')
        for item in content:
            #thefile.write("%s" % item.decode('utf-8').encode('utf-8') )
            thefile.write("%s" % item)
        thefile.close()

        self.mylist.config(state="normal")
        self.mylist.delete(1.0, END)

        with open("a.txt") as f:
            content = f.readlines()

        Record.writeRecordToLog(datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                                "1", "gg", "Remove")
        display
Example #12
0
 def __init__(self,
              record=re.Record(),
              currentNum=-1,
              currentFileName=None):
     self.record = [record]
     self.currentNum = currentNum
     self.currentFileName = currentFileName
Example #13
0
def start():
    from Project import Project
    import Record

    project = Project()
    record = Record.Record()

    Proxy.begin_catch(
        #callback = record.add_hit,
        callback=callback,
        filter=lambda x: True,
        hittype=HitData,
    )
    proxy = Proxy.thread_start()

    while True:
        c = raw_input('Enter stop to stop > ')
        if c == 'stop':
            break

    Proxy.stop()
    proxy.join()

    print 'Recording finished'
    print
Example #14
0
def main(filename):

    g = open('./text/' + filename + '.sbg', 'r', encoding='utf8')
    sbg_list = re.split('-' * 50 + '\n', g.read().strip())[1:]
    records = Record.ProduceRecords(sbg_list)
    print("Processing %d records in total" % len(records))

    with open('./intermediate/feature_template.pkl', 'rb') as p:
        featCombination = pickle.load(p)

    data, idmap = feature.process(records, featCombination)
    binder = predict(data)
    with open('./text/' + filename + '.kng', 'w', encoding='utf8') as f:
        knowledge_list = []
        cn = 0
        for e in binder:
            cn += 1
            r, y_pred = e
            if y_pred == 1:
                uniid = idmap[str(int(r[0]))]
                articleId, sentenceId = uniid.split('-')
                graph = [
                    record.graph for record in records
                    if record.articleId == articleId
                    and record.sentenceId == sentenceId
                ]
                assert len(graph) == 1
                knowledge_list.append((articleId, sentenceId, graph[0]))
        knowledge_list = sorted(knowledge_list,
                                key=lambda x: (int(x[0]), int(x[1])))
        for knowledge in knowledge_list:
            f.write(knowledge[0] + '-' + knowledge[1] + '\n' + knowledge[2] +
                    '\n')

    g.close()
Example #15
0
def readPerson(file_path):

    with open(file_path) as fp:
        contents = fp.readlines()

        isFirstLine = True
        person = Person.Person()
        person.delMsgList()
        person.delRecordList()

        for line in contents:
            record = Record.Record()

            if "e029d1bf418527382ef2247e4d95a6a3" in line:
                line = line.replace("e029d1bf418527382ef2247e4d95a6a3",
                                    "Beibei    ")
            if not ("---" in line or "ID" in line
                    or "Wechat messages" in line):
                # get a valid record
                while line.replace("   ", "  ") != line:
                    line = line.replace("   ", "  ")
                fields = line.split("  ")

                if "<" in fields[0] and "/>" in fields[0]:
                    print "8888"
                    break

                # parse the record
                # fields 0:ID, 1:dateAndTime, 2:name, 4:sndRcv, 6:msg

                record.setDateAndTime(fields[1])
                record.setSndRcv(fields[4])
                record.setMsg(fields[6])

                if True == isFirstLine and "Beibei" not in fields[0]:
                    person.setID(fields[0])
                    person.setName(fields[2])
                    person.setTimeBeFriends(fields[1])
                    isFirstLine = False

                person.addMsgList(fields[6])
                person.addRecordList(record)

        #print "------- msgList -------"
        numRecord = 0
        msgList = person.getMsgList()
        for msg in msgList:
            #print msg
            numRecord += 1
        print "###### total", numRecord
        person.setNumRecord(numRecord)
        personList.append(person)
        #print "******* recordList ******"
        #recordList = person.getRecordList()
        #for record in recordList:
        #print record
    status = 0

    return status, person
Example #16
0
def record_and_graph(show=False):
    name = input("Name to save files as: ")
    time = input("Time of sample to take in seconds: ")
    rec.recordThis(name, int(time))

    plt.subplot(211)
    plt.title("Decibel Level")
    amp.graphThis(name)

    plt.subplot(212)
    plt.title("Frequency Graph")
    freq.frequencyThis(name)

    plt.tight_layout()
    save(name)
    if show:
        plt.show()
 def put_chess(self):
     self.fen = Record.FEN_Record(self.read())
     state = self.fen._import()[1]
     for col in range(10):
         for row in range(9):
             chess_kind = state[row][col]
             if chess_kind != -1:
                 # print chess_kind, row, col
                 self.pack((row, col), chess_kind)
Example #18
0
def readParamFile(filename):
    file = open(filename, 'r')
    lines = file.readlines()
    records = []
    for line in lines:
        records.append(Record(line))
    p = ParamComposite()
    p.read(records, 0)
    return p
Example #19
0
def postRecord():
    req_data = request.get_json()
    #record_genre = req_data['record_genre']
    artist_name = req_data['artist_name']
    record_name = req_data['record_name']    
    id = req_data['id']
    new_record = Record(artist_name, record_name)
    my_dict[id] = new_record
    return 'post works or put works'
Example #20
0
 def __init__(self, master=None, height=0, width=0):
     tkinter.Canvas.__init__(self, master, height=height, width=width)
     self.step_record_chess_board = Record.Step_Record_Chess_Board()
     # 初始化記步器
     self.init_chess_board_points()  # 畫點
     self.init_chess_board_canvas()  # 畫棋盤
     self.board = MCTS.Board()
     self.AI = MCTS.MonteCarlo(self.board, 2)
     self.clicked = 0
    def __init__(self, teacherList, subjectsList, roomN):
        self.teacherList = teacherList
        self.subjectsList = subjectsList
        self.roomN = roomN
        self.records = []

        for el in subjectsList:
            for i in range(el.timesPerWeek):
                self.records.append(Record(self.teacherList, roomN, el.id))
        self.conflicts = 0
Example #22
0
def post_record():
    artist_name = request.json['artist_name']
    record_name = request.json['record_name']

    new_record = Record(artist_name, record_name)

    db.session.add(new_record)
    db.session.commit()

    return jsonify(record_schema.dump(new_record))
Example #23
0
    def get_command(self):
        self.item = Mode.get()
        while self.item is not None and self.item.get_machine_xml() is None:
            self.item = Mode.get()

        if self.item is None:
            if Config.end_text is not None or Config.end_background is not None:
                display_end()

                if Config.end_duration is not None:
                    if Config.record is not None:
                        Record.create_time_file()

            print("No more software for window", self.index)
            Display.print_machine_and_soft(None, self.position)
            return False
        else:
            if self.first_launch is True:
                Record.reset_log_time()

                if Config.title_text is not None or Config.title_background is not None:
                    display_title()

                    if Config.record is not None:
                        Display.record_title()

                    self.execute_start_command()

                    time.sleep(4.0)
                else:
                    self.execute_start_command()

                Display.print_machine_and_soft(self.item, self.position)

            else:
                Display.print_machine_and_soft(self.item, self.position)

            if Config.record is not None:
                Display.record_marquee()

            print("Next for window", self.index, ": ",
                  self.item.get_soft_description(), self.item.get_soft_info())
            return True
Example #24
0
def main():
    # Create LED
    record_led = Record.LED()

    # Blinking Test
    print("Start blinking LED at {}".format())
    record_led.blink()
    time.sleep(10)
    record_led.stop()
    print("Finished blinking.")
Example #25
0
 def insertData(self):
     while True:
         recordInp = re.Record()
         if self.putRecord(recordInp): break
         else:
             if self.currentNum < 0:
                 self.currentNum = 0
                 self.record[0] = recordInp
             else:
                 self.record.append(recordInp)
                 self.currentNum += 1
Example #26
0
def main():
    """ Main program function """
    # Blank list for customer recorde
    database = []

    # Get 3 records using this for-loop
    for i in range(0, 3):
        # Create a new Record Object and get information
        new_record = Record()

        # Add to the database
        database.append(new_record.get_record())

        # Delete the record
        del new_record

        print("\n")

    # Save the records to customers.dat
    save_records(database)
Example #27
0
def addSalesRecords(product):
	filename = "spreadsheets/" + product.name + "_sales.csv"
	row_count = getFileRows(filename)

	data = pd.read_csv(filename, parse_dates=['Date'], usecols = ['Date','Sales'],  nrows = row_count-1)
	for row in data.itertuples():
		try:
			sale_epoch = getEpochTime(row[1])
			product.addSales(Record(sale_epoch,row[2]))
		except:
			break
Example #28
0
 def non_branch_metabolite( self, content ):
     for metabolite in content:
         items = metabolite.split()
         name = items[ 0 ]
         consumed = int( items[ 1 ] )
         built = int( items[ 2 ] )
         vector = items[ 4 ].replace( 'r', '0' )
         vector = vector.replace( 'i', '1' )
         vector = list( vector )
         entry = Record.MetaboliteRole( name, consumed, built, vector )
         self.data.non_branch_metabolites.append( entry )
Example #29
0
    def metabolite_line( self, content ):
        self.data.external_metabolites = []
        self.data.internal_metabolites = []
        for metabolite in content:
            items = metabolite.split()
            entry = Record.Metabolite( int( items[ 0 ] ), items[ 2 ] )

            if( items[ 1 ] == "external" ):
                self.data.external_metabolites.append( entry )
            else:
                self.data.internal_metabolites.append( entry )
Example #30
0
 def join2(self, other_heap, field, other_field=""):
     if not other_field:
         other_field=field
     pos, other_pos = 0, 0
     self.r_block.read(pos)
     while(self.r_block.records[0]):
         for i in self.r_block.records:
             if not i:
                 break
             other_pos = 0
             other_heap.r_block.read(other_pos)
             while(other_heap.r_block.records[0]):
                 for j in other_heap.r_block.records:
                     if not j:
                         break
                     if getattr(Record(i), field) == getattr(Record(j), other_field):
                         print(i+"\n"+j+"\n")
                 other_pos += other_heap.r_block.max_size*other_heap.r_block.record_size
                 other_heap.r_block.read(other_pos)
         pos += self.r_block.max_size*self.r_block.record_size
         self.r_block.read(pos)
Example #31
0
 def insert(self, string):
     rec = Record(string)
     for i in self.indexes:
         if self.indexBPlusTree:
             self.indexes[i].insert(getattr(rec,i),self.w_block.disk.tell().to_bytes(4,byteorder),True) #True for replacing node, if already existant
         else:
             if self.indexBTree:
                 self.indexes[i].insert(getattr(rec,i))
                 self.indexes[i].search(getattr(rec,i))[0].pos=self.w_block.disk.tell()
             else:
                 self.indexes[i].update({getattr(rec,i):self.w_block.disk.tell()})
     self.w_block.write(self.w_block.disk.tell(), rec)
Example #32
0
File: GUI.py Project: yccai/Gomoku
 def __init__(self, master=None, height=0, width=0):
     '''
     棋盘类初始化
     :param master: 画到那个对象
     :param height: 棋盘的高度
     :param width: 棋盘的宽度
     '''
     Tkinter.Canvas.__init__(self, master, height=height, width=width)
     self.step_record_chess_board = Record.Step_Record_Chess_Board()
     #初始化计步器对象
     self.init_chess_board_points()  #画点
     self.init_chess_board_canvas()  #绘制棋盘
    def parse_substance_lines( self, multiline ):
        lines = multiline.splitlines()
        line_no = 0
        for line in lines:
            line_dict = self._make_line_dict( line )
            try:
                if( not _is_valid_substance( line_dict ) ):
                    raise ECellError( "quantity and concentration are mutually exclusive" )
            except ECellError, e:
                print sys.stderr, e.message

            qty = Record.get_entry( line_dict, 'qty' )
            conc = Record.get_entry( line_dict, 'conc' )
            if( ( qty.lower() != 'fix' ) and ( conc.lower() != 'fix' ) ):
                self.data.num_substances = self.data.num_substances + 1
            else:
                line_no = line_no + 1
            if( line.lower().startswith( 'substance' ) ):
                _set_defaults( line_dict )
                self._convert_conc( line_dict )

            self._build_substance_entry( line_dict, line_no )
Example #34
0
File: fqSou.py Project: 23niu/fqSou
 def get(self, page='1', count='100'):
     logs = Record.get_page(r'/var/log/port-ip-monitor.log', int(page), int(count))
     self.render('log.html', logs=logs, page=page, count=count)
Example #35
0
        # Analysis
        rs = RuleSet(ruleset)
        curindex = 0
        ruleinstances = []
        (curindex, ruleinstances) = rs.run(ruletree, buff, curindex, ruleinstances)

	print "----------------------------------------------------------------------------------------"
	print "Results:"
	print ""

        matched = 1
	has_empty = 0
	confidence_sum = 0
	confidence_cnt = 0
        newrecord = Record()

	header_start_pos = 0
	header_end_pos = 0
	body_start_pos = 0
	body_end_pos = 0
	for r in ruleinstances:
                m = r.getMatchedKeys()
		if len(m.keys()) < 1:
			has_empty = 1
			continue

		array = m[r.getRule().getType()]
                date = [0,0,0]
                timerange = [0,0,0,0]