Exemple #1
0
def librosa_resample_test():
    sample, sr = librosa.load(fs[-1],
                              mono=False,
                              sr=SAMPLERATE,
                              duration=1,
                              res_type='polyphase')
    l = np.asfortranarray(sample[0])
    r = np.asfortranarray(sample[1])

    l = librosa.effects.pitch_shift(l, sr, n_steps=2.)
    r = librosa.effects.pitch_shift(r, sr, n_steps=2.)

    sample = np.column_stack((sample[0], sample[1])).ravel()
    sample *= 0x800000

    # resample, sr = sf.read(fs[0])
    # resample = resample.T
    resample = np.column_stack((l, r)).ravel()
    resample *= 0x800000

    note1 = Note.Note(sample, rate=sr, channel=CHANNELS, decay=decay)
    note2 = Note.Note(resample, rate=sr, channel=CHANNELS, decay=decay)
    note3 = Note.Note(resample, rate=sr, channel=CHANNELS, decay=decay)
    note4 = Note.Note(resample, rate=sr, channel=CHANNELS, decay=decay)

    player([note2, note3, note4])
Exemple #2
0
    def parseNotes(self):
        midiNotes = []
        for midiClip in self.arrangementClips:
            currentStart = midiClip.start
            currentEnd = midiClip.end
            loopStart = midiClip.loopStart
            loopEnd = midiClip.loopEnd
            startRelative = midiClip.startRelative
            length = currentEnd - currentStart
            loopLength = loopEnd - loopStart
            loop = midiClip.loop
            for note in midiClip.notes:
                start = currentStart + note.start - loopStart - startRelative
                if start >= currentStart and start < currentEnd:
                    n = Note(note.pitch, start, note.duration, note.velocity, note.isEnable)
                    midiNotes.append(n)
                    if loop and length > loopLength - startRelative and note.start >= loopStart and note.start < loopEnd:
                        #print('!clip is looping! Loop length:', loopLength)
                        while start < currentEnd:
                            #print('note Start:', start, 'end:', currentEnd)
                            n = Note(note.pitch, start, note.duration, note.velocity, note.isEnable)
                            midiNotes.append(n)
                            start += loopLength

                # case loop Note after start marker
                elif loop and note.start >= loopStart and note.start < loopEnd:
                    #print(note)
                    start = currentStart + note.start - loopStart - startRelative + loopLength
                    while start < currentEnd:
                        # print('note Start:', start, 'end:', currentEnd)
                        n = Note(note.pitch, start, note.duration, note.velocity, note.isEnable)
                        midiNotes.append(n)
                        start += loopLength

        return midiNotes
Exemple #3
0
    def __init__(self, size, m, xMax, yMax, ID, xmlFileName):

        self.x = randint(40, 960)
        self.y = randint(40, 560)
        
        self.radius = size
        self.mass = m

        self.xBound = xMax
        self.yBound = yMax

        self.ID = ID

        tree = ET.parse(xmlFileName)
        root = tree.getroot()

        self.noteList = []

        for note in root.findall('bubble'):
            if(note.attrib == self.ID):
                print(note.tag)
                print(self.ID)
                print('true')
                self.header = Note(30, 30, note.find('header').text)
                self.header.setTextSize(30)
                self.header.setFont('Arial')
                self.header.setColor((0, 0, 0))
                contents = Note(30, 75, note.find('text').text)
                contents.setTextSize(16)
                contents.setFont('Arial')
                contents.setColor((0,0,0))
                self.noteList.append(contents)

        self.randomMvmnt()
 def test_note_author():  
     test_note = Note()
     fn = FullName()
     fn.set_given_name("David")
     fn.set_middle_names(["Lee", "Roy", "Jenkins"])
     fn.set_surname("Baesmintdwaellor")
     fn.set_preferred_name("Dave")
     test_note.write_author(fn)
     assert test_note.get_author() == 'David Lee Roy Jenkins Baesmintdwaellor'
Exemple #5
0
    def get_notes(self):
        user = self.setCredentialsForAnyUser()
        self.assertTrue(len(user.notes.all()) == 0)
        house = House.objects.all()[0]
        note = Note(user=user, text="0001", house=house)
        note.save()

        response = self.client.get(reverse('note-list'))

        self.assertTrue(response.status_code == status.HTTP_200_OK)
        self.assertTrue(json.loads(response.content)[0]['text'] == "0001")
Exemple #6
0
    def test_get_note(self):
        user = self.setCredentialsForAnyUser()
        self.assertTrue(len(user.notes.all()) == 0)

        house = House.objects.all()[0]
        note = Note(user=user, text="0001", house=house)
        note.save()
        response = self.requestNote(user, note.pk)
        self.assertEqual(response.status_code, 200)
        self.assertTrue(json.loads(response.content)[0]['text'] == "0001")
        self.assertTrue(len(user.notes.all()) == 1)
Exemple #7
0
 def get_all_notes(self, cur_user):
     note1 = Note.Note(
         "09/13/2018", "Westport",
         "THis is my first note on Scenic Route. I am probably going to quit this very soon."
     )
     note2 = Note.Note(
         "09/13/2018", "Westport",
         "THis is my second note on Scenic Route. I am very stoned right now"
     )
     note_list = [note1, note2]
     return note_list
Exemple #8
0
    def test_duplicates(self):
        user = self.setCredentialsForAnyUser()
        self.assertTrue(len(user.notes.all()) == 0)
        house = House.objects.all()[0]
        note = Note(user=user, text="0001", house=house)
        note.save()

        data = {"text": "0001", 'house': house.pk}
        response = self.client.post(reverse('note-list'), data, format='json')
        print response

        self.assertTrue(response.status_code == status.HTTP_201_CREATED)
        self.assertTrue(len(user.notes.all()) == 1)
        self.assertTrue(user.notes.all()[0].text == "0001")
Exemple #9
0
 def fetch_notes_for_version(self, m_version_obj, b_populate_playlists=False):
     notes_ret = []
     fields = ['id', 'subject', 'addressings_to', 'user', 'content', 'sg_note_type', 'note_links']
     filters = [
         ['project', 'is', {'type' : 'Project', 'id' : int(self.g_shotgun_project_id)}],
         ['note_links', 'is', {'type' : 'Version', 'id' : int(m_version_obj.g_dbid)}]
     ]
     sg_notes = self.g_sg.find("Note", filters, fields)
     for sg_note in sg_notes:
         t_id = sg_note['id']
         t_body = sg_note['content']
         t_from = self.fetch_artist_from_id(sg_note['user']['id'])
         t_to = self.fetch_artist_from_id(sg_note['addressings_to'][0]['id'])
         t_type = sg_note['sg_note_type']
         t_subject = sg_note['subject']
         t_links = []
         for link in sg_note['note_links']:
             if link['type'] == 'Shot':
                 t_links.append(self.fetch_shot_from_id(link['id']))
             elif link['type'] == 'Version':
                 t_links.append(self.fetch_version_from_id(link['id']))
             elif link['type'] == 'Playlist':
                 if b_populate_playlists:
                     t_links.append(self.fetch_playlist(link['name']))
                 else:
                     t_links.append(Playlist.Playlist(link['name'], [], link['id']))
         t_note_obj = Note.Note(t_subject, t_to, t_from, t_links, t_body, t_type, t_id)
         notes_ret.append(t_note_obj)
     return notes_ret
Exemple #10
0
			def read_note_on(x):

				global channel
				#check/set key/velocity
				key = int(data[fp:fp+2], 16)
				velocity = int(data[fp+2:fp+4], 16)
				#set channel
				if x == None:
					channel = int(data[fp-1], 16) + 1
					print_bytes(data[fp-2:fp+4], "Note off c nn vv")
				else:
					print_bytes(data[fp:fp+4], "nn vv")
				print "Channel:", channel
				note_tuple = (key, channel, total_delta_time)
				if velocity == 0:
					#if in list: create note object
					for nt in list_of_notes: 
						#create note object
						found = False
						if nt[0] == key and nt[1] == channel:
							duration = total_delta_time - nt[2]
							note = Note.Note(total_delta_time, duration, key, channel)
							print "Note created:", note.to_string(ticks_per_quarter_note)
							notes[channel].append(note)
							found = True
							list_of_notes.remove(nt) #remove from list_of_notes
					if not found:
						print "Note created with velocity of 0 at position"
				else:
					#add note to list
					list_of_notes.append(note_tuple)
				print "Add/Pop Note Command at fp:", fp
				advance(4)#add note event is 3 bytes long
Exemple #11
0
def resample_test2():
    w = wave.open(fs[-1], 'rb')
    da = np.array(wavdecode.from24le(w.readframes(w.getframerate()))).astype(
        np.float32)

    ns = wavdecode.pitchshift(da, w.getframerate(), 2, 1)

    note1 = Note.Note(da,
                      rate=w.getframerate(),
                      channel=w.getnchannels(),
                      decay=np.array([], dtype=np.float32))
    note2 = Note.Note(ns,
                      rate=w.getframerate(),
                      channel=w.getnchannels(),
                      decay=np.array([], dtype=np.float32))

    player([note1, note2])
Exemple #12
0
    def __init__(self, notes, volume=0.5):
        self.size = len(notes)

        note_arr = []
        for freq in notes:
            note_arr.append(Note.Note(freq, volume))

        self.chord = tuple(note_arr)
Exemple #13
0
def TestNoteCreateUser():
    uf = {
        'name': 'testuser',
        'password': "******",
        'mail': '*****@*****.**',
    }
    r = Note.CreateUser(uf)
    return r
Exemple #14
0
def TestCheckUser():
    shapassword = hashlib.sha256()
    shapassword.update(("admin").encode('utf-8'))
    #print(shapassword.hexdigest())
    return (Note.CheckUser({
        'name': "*****@*****.**",
        'password': shapassword.hexdigest()
    }))
Exemple #15
0
def twoPersonPlayTimerFired(data):
    #data.timerCounter == 650 is a whole song (60 seconds +5 countdown seconds)
    #so every minute+5sec it goes through a level
    #print(data.timerCounter) #10x is a hundreth of a second. 100 is a second
    if (data.timerCounter <= 2000 and data.currentLevel < len(data.levels)):
        #no more notes in the level then it moves to the next level
        #countdown
        if (data.timerCounter % 30 == 0):
            if (data.timerCounter < 150):  # 5 seconds
                data.countdown -= 1
            elif (data.countdown <= 1):  #after the countdown
                #adds the notes into the game
                if (len(data.notes) > 0):
                    secNote = data.notes.pop(0)
                    #making the notes
                    for i in range(len(secNote)):
                        if (secNote[i] == 1):
                            data.currentNotesP1.append(Note(i))
                            data.currentNotesP2.append(Note(i + 4))
        #movement of the fallingNotes
        for fallNote in data.currentNotesP1:
            fallNote.y += 5
            if (fallNote.y > data.height):
                if (fallNote.num < 4):
                    data.currentNotesP1.remove(fallNote)
        for fallNote2 in data.currentNotesP2:
            fallNote2.y += 5
            if (fallNote2.y > data.height):
                if (fallNote2.num < 4):
                    data.currentNotesP2.remove(fallNote2)
    else:
        #starts the next level
        #once all of the levels are done then create the space in the scoreboard
        data.currentLevel += 1
        if (data.currentLevel >= len(data.levels)):
            data.mode = 'end'
        else:
            data.notes[:] = []
            #print('in here')
            data.notes = copy.deepcopy(data.allSongs[data.currentLevel])
            print('data.notes', data.notes)
            #print('notes',data.notes)
            data.timerCounter = 0
            data.countdown = 5
    data.timerCounter += 1
Exemple #16
0
    def db_delete(self, use_transactions=1):
        """Delete this object record from the database.  Raises
        RecordLockedError exception if record is locked and unable to be
        deleted."""
        # Assume success
        result = 1
        try:
            # Initialize delete operation, begin transaction if necessary.
            (db, c) = self._db_start_delete(use_transactions)
            if (db == None):
                return      # Abort delete without even trying

            # Delete all Series-based Filter Configurations
            #   Delete Series Keyword Sequence Map records
            DBInterface.delete_filter_records(5, self.number)
            #   Delete Series Keyword Bar Graph records
            DBInterface.delete_filter_records(6, self.number)
            #   Delete Series Keyword Percentage Map records
            DBInterface.delete_filter_records(7, self.number)
            #   Delete Series Report records
            DBInterface.delete_filter_records(10, self.number)
            #   Delete Series Clip Data Export records
            DBInterface.delete_filter_records(14, self.number)

            # Detect, Load, and Delete all Series Notes.
            notes = self.get_note_nums()
            for note_num in notes:
                note = Note.Note(note_num)
                result = result and note.db_delete(0)
                del note
            del notes

            # Deletes Episodes, which in turn will delete Episode Transcripts,
            # Episode Notes, and Episode Keywords
            episodes = self.get_episode_nums()
            for episode_num in episodes:
                episode = Episode.Episode(episode_num)
                # Store the result so we can rollback the transaction on failure
                result = result and episode.db_delete(0)
                del episode
            del episodes

            # Delete the actual record.
            self._db_do_delete(use_transactions, c, result)

            # Cleanup
            c.close()
            self.clear()
        except RecordLockedError, e:
            # if a sub-record is locked, we may need to unlock the Series record (after rolling back the Transaction)
            if self.isLocked:
                # c (the database cursor) only exists if the record lock was obtained!
                # We must roll back the transaction before we unlock the record.
                c.execute("ROLLBACK")
                c.close()
                self.unlock_record()
            raise e    
Exemple #17
0
def produce(info, file, acename, temp, message_total):
    ENDFname = info.ENDFname
    input_path = info.input_path
    production_path = info.production_path
    note_path = info.note_path
    # 分离文件名,filename[0]就是分离后的文件名
    filename = os.path.splitext(file)
    global nuclide
    nuclide = filename[0]
    # 判断核素是否在裂变核素集合、true核素集合,是返回1,否返回0
    p_true = f.f_true(ENDFname, nuclide)
    p_fission = f.f_fission(ENDFname, nuclide)
    # 复制ENDF文件file_1到tape21
    file_i = input_path + file
    tape21 = production_path + 'tape21'
    f.copyfile(file_i, tape21)
    # 提取核素的MAT编号
    MAT = f.getMAT(tape21, ENDFname)
    # 写NJOY2016的输入卡
    n.Card_neutron(info, nuclide, acename, MAT, temp, p_fission)
    # note_card()函数的功能是建立存档文件card,备份NJOY输入卡
    Note.note_card(production_path, note_path, nuclide, temp)
    # note_message()函数的功能是建立存档文件message,备份输入卡和加工过程中的报错信息
    Note.note_message(production_path, note_path, nuclide, temp)

    message = Note.message

    # 写bat命令行
    writebat(production_path, p_true)
    # 调用cmd,运行run.bat,从而运行NJOY
    os.chdir(production_path)
    p = subprocess.Popen("cmd.exe /c" + production_path + "run.bat abc",
                         stdout=subprocess.PIPE,
                         stderr=subprocess.STDOUT)
    # 输出NJOY程序窗口返回的信息
    curline = p.stdout.readline()
    while (curline != b''):
        print(curline)
        message_total.write(str(curline) + '\n')
        message.write(str(curline) + '\n')
        curline = p.stdout.readline()
    p.wait()
    print(p.returncode)
    return 0
Exemple #18
0
 def makeNote(self, istart):
     note = Note.Note(istart)
     note.idur = self.idur
     note.iattack = self.iattack
     note.ipan = self.ipan
     note.ifreq1 = self.ifreq1
     note.ifreq2 = self.ifreq2
     note.ihness = self.ihness
     note.idist = self.idist
     return note
Exemple #19
0
def get_notes(songs_data):
    notes = []

    for song_data in songs_data:
        note_vect = song_data.seg_pitches

        for i in xrange(len(note_vect)):
            notes.append(str(Note.Note(note_vect[i])))

    return notes
Exemple #20
0
 def __init__(self, parent, id, seriesNum=0, episodeNum=0, transcriptNum=0, collectionNum=0, clipNum=0, snapshotNum=0, documentNum=0, quoteNum=0):
     obj = Note.Note()
     obj.author = DBInterface.get_username()
     obj.series_num = seriesNum
     obj.episode_num = episodeNum
     obj.transcript_num = transcriptNum
     obj.collection_num = collectionNum
     obj.clip_num = clipNum
     obj.snapshot_num = snapshotNum
     obj.document_num = documentNum
     obj.quote_num = quoteNum
     NotePropertiesForm.__init__(self, parent, id, _("Add Note"), obj)
Exemple #21
0
 def get_map_dict(self):
     mappings = {
         # Default mappings
         str(Note('A', 4)): 'w',
         str(Note('B', 4)): 'a',
         str(Note('C', 5)): 's',
         str(Note('D', 5)): 'd',
         str(Note('D', 4)): 'k',
         str(Note('E', 4)): 'l',
         str(Note('G', 5)): 'spacebar'
     }
     return mappings
Exemple #22
0
def startTimerFired(data):
    for note in data.startScreenNotes:
        if (note.y > data.height):
            data.startScreenNotes.remove(note)
        else:
            note.y += 20

    if (data.start.fill == 'white'):
        data.start.fill = 'PeachPuff2'
    else:
        data.start.fill = 'white'

    num = random.randint(0, 7)
    data.startScreenNotes.append(Note(num))
Exemple #23
0
 def ajouterNote(self, idEtudiant, idCours, note):
     etudiantsId = []
     for e in self._etudiants:
         etudiantsId.append(e.numero)
     coursId = []
     for c in self._cours:
         coursId.append(c.code)
     
     if idEtudiant in etudiantsId and idCours in coursId:
         n = Note(idEtudiant, idCours, note)
         self._notes.append(n)
         print("la note a bien ete ajoutee")
     else:
         print("Le cours ou l'etudiant n'existe pas")
Exemple #24
0
    def play(self, idx, is_on):
        notes = self.on if is_on else self.off

        if idx in self.playing:
            if idx in self.ending:
                self.ending[idx].close()
                del self.ending[idx]
            self.ending[idx] = self.playing[idx]
            self.ending[idx].end()
            del self.playing[idx]

        if idx in notes.keys():
            if isinstance(notes[idx][0], str):
                self.playing[idx] = Note.WavNote(
                    notes[idx][self.group % len(notes[idx])],
                    decay=self.decay,
                    out_samplerate=self.out_samplerate)
                self.group += 1
            else:
                self.playing[idx] = Note.Note(
                    *notes[idx],
                    decay=self.decay,
                    out_samplerate=self.out_samplerate)
Exemple #25
0
def onePersonPlayTimerFired(data):
    #data.timerCounter == 650 is a whole song (60 seconds +5 countdown seconds)
    #so every minute+5sec it goes through a level
    #print(data.timerCounter) #10x is a hundreth of a second. 100 is a second
    if (data.timerCounter <= 2000 and data.currentLevel < len(data.levels)):
        #no more notes in the level then it moves to the next level
        #countdown
        if (data.timerCounter % 30 == 0):
            if (data.timerCounter < 150):  # 5 seconds
                data.countdown -= 1
            elif (data.countdown <= 1):  #after the countdown
                #adds the notes into the game
                if (len(data.notes) > 0):
                    secNote = data.notes.pop(0)
                    #making the notes
                    for i in range(len(secNote)):
                        if (secNote[i] == 1):
                            data.currentNotes.append(Note(i))

        #movement of the fallingNotes
        for fallNote in data.currentNotes:
            fallNote.y += 5
            if (fallNote.y > data.height):
                data.currentNotes.remove(fallNote)
    else:
        #starts the next level
        #once all of the levels are done then create the space in the scoreboard
        data.currentLevel += 1
        if (data.currentLevel >= len(data.levels)):
            #insert the value
            tempScore = data.score
            if (len(data.scoreboard) == 0):
                data.scoreboard.append((data.score, 'you'))
            else:
                for indexPerson in range(len(data.scoreboard)):
                    person = data.scoreboard[indexPerson]
                    if (tempScore >= person[0]):
                        data.scoreboard.insert(indexPerson,
                                               (data.score, 'you'))
                        tempScore = -1
            data.mode = 'end'
        else:
            data.notes[:] = []
            #print('in here')
            data.notes = copy.deepcopy(data.allSongs[data.currentLevel])
            #print('notes',data.notes)
            data.timerCounter = 0
            data.countdown = 5
    data.timerCounter += 1
Exemple #26
0
def resample_test():
    w = wave.open(fs[-1], 'rb')
    da = np.array(wavdecode.from24le(w.readframes(w.getframerate()))).astype(
        np.float32)

    shift = 100
    left, right = da[0::2], da[1::2]
    lf, rf = np.fft.rfft(left), np.fft.rfft(right)
    lf, rf = np.roll(lf, shift), np.roll(rf, shift)
    lf[0:shift], rf[0:shift] = 0, 0

    nl, nr = np.fft.irfft(lf), np.fft.irfft(rf)
    ns = np.column_stack((nl, nr)).ravel().astype(np.float32)

    note1 = Note.Note(da,
                      rate=w.getframerate(),
                      channel=w.getnchannels(),
                      decay=np.array([], dtype=np.float32))
    note2 = Note.Note(ns,
                      rate=w.getframerate(),
                      channel=w.getnchannels(),
                      decay=np.array([], dtype=np.float32))

    player([note1, note2])
Exemple #27
0
    def addnote_clicked(self, event):
        myclient = pymongo.MongoClient(
            "mongodb+srv://Jonpc042:[email protected]/test?retryWrites=true"
        )
        mydb = myclient["NoteAppDataBase"]
        mycol = mydb["NoteCollection"]

        #theid = str(event.GetEventObject().myname)

        mytime = datetime.datetime.now()

        print("ADD NOTE")

        mydict = {
            "UserID": self.username,
            "UniqueID": "",
            "Date": str(mytime.date()),
            "Title": "",
            "Details": "",
            "IsChecked": "False"
        }
        x = mycol.insert_one(mydict)

        getback = mycol.find_one({"UserID": self.username},
                                 sort=[("_id", pymongo.DESCENDING)])

        mydict = {
            "UserID": getback.get("UserID"),
            "UniqueID": str(getback.get("_id")),
            "Date": getback.get("Date"),
            "Title": getback.get("Title"),
            "Details": getback.get("Details"),
            "IsChecked": getback.get("IsChecked")
        }
        x = mycol.update_one({"_id": ObjectId(getback.get("_id"))},
                             {'$set': mydict},
                             upsert=True)
        note = Note.Note(self)
        note.uniqueID = getback.get("_id")
        note.date = getback.get("Date")
        note.title = getback.get("Title")
        note.details = getback.get("Details")
        note.isChecked = getback.get("IsChecked")
        self.myNotes.append(note)
        sizer = self.buildNote(note)
        self.notePanelSizer.Add(sizer, flag=wx.EXPAND | wx.ALL, border=10)
        self.notePanelSizer.Layout()
Exemple #28
0
    def set_stamp(self):
        #### TODO: If custom chord, we need to order this series first
        ##
        #
        self.set_id()

        notes = self.notes

        #convert to list of values (0-11) and sort
        notes = [note.value for note in notes]
        notes = sorted(notes)

        #convert to list of strings representing notes in order from A-G#
        notes = [str(Note(note)) for note in notes]

        #convert list of strings into one string separated by comma such as "B,E,G"
        self.stamp = ",".join(notes)
Exemple #29
0
def main():
    args = parse_args()
    if args.run_tests:
        return run_tests()
    # list FIGURES: [(str voice, [(str note, int octave/None)/None, ...]), ...]
    pair = parse_problemfile(args.problem)
    if not pair:
        print "  Exiting."
        return 1
    chords = pair[0]
    figures = pair[1]
    print "(Info) Initializing harmony problem..."
    t = time.time()
    problem = init_problem(constraint.Problem(), chords, figures)
    print "(Info) Finished initialization ({0:.4f}s)".format(time.time() - t)
    print "(Info) Solving Harmony Problem"
    t = time.time()
    solutions_iter = solve(problem)
    dur = time.time() - t
    print "(Info) Done Solving ({0:.4f}s)".format(dur)
    print "  Displaying solutions:"
    flag_continue = False
    solutions = []
    for sol in solutions_iter:
        solutions.append(sol)
    print "    {0} Solutions Total.".format(len(solutions))
    for i, solution in enumerate(solutions):
        if flag_continue:
            continue
        tmax = len(solution) / 4
        for t in xrange(tmax):
            print "Time={0}:    [{1}]".format(t, chords[t])
            for voice in VOICE_PREFIXES:
                var = make_var(voice, t)
                pitchnum = solution[var]
                print "    {0}: {1}".format(voice,
                                            Note.numToPitch_absolute(pitchnum))
        s = raw_input(
            "({0}/{1}) Press enter to continue, 'c' to skip, or 'q' to exit.".
            format(i,
                   len(solutions) - 1))
        if s == 'c':
            flag_continue = True
        elif s == 'q':
            break
Exemple #30
0
    def db_delete(self, use_transactions=1):
        """Delete this object record from the database."""
        result = 1
        try:
            # Initialize delete operation, begin transaction if necessary
            (db, c) = self._db_start_delete(use_transactions)

            # Delete the QuotePosition data, if it exists
            query = "DELETE FROM QuotePositions2 WHERE QuoteNum = %s"
            # Adjust the query for sqlite if needed
            query = DBInterface.FixQuery(query)
            # Execute the query
            c.execute(query, (self.number, ))

            notes = []

            # Detect, Load, and Delete all Quote Notes.
            notes = self.get_note_nums()
            for note_num in notes:
                note = Note.Note(note_num)
                result = result and note.db_delete(0)
                del note
            del notes

            # Delete all related references in the ClipKeywords table
            if result:
                DBInterface.delete_all_keywords_for_a_group(
                    0, 0, 0, self.number, 0)

            # Delete the actual record.
            self._db_do_delete(use_transactions, c, result)

            # Cleanup
            c.close()
            self.clear()
        except RecordLockedError, e:
            # if a sub-record is locked, we may need to unlock the Transcript record (after rolling back the Transaction)
            if self.isLocked:
                # c (the database cursor) only exists if the record lock was obtained!
                # We must roll back the transaction before we unlock the record.
                c.execute("ROLLBACK")
                c.close()
                self.unlock_record()
            raise e
Exemple #31
0
def main():
    args = parse_args()
    if args.run_tests:
        return run_tests()
    # list FIGURES: [(str voice, [(str note, int octave/None)/None, ...]), ...]
    pair = parse_problemfile(args.problem)
    if not pair:
        print "  Exiting."
        return 1
    chords = pair[0]
    figures = pair[1]
    print "(Info) Initializing harmony problem..."
    t = time.time()
    problem = init_problem(constraint.Problem(), chords, figures)
    print "(Info) Finished initialization ({0:.4f}s)".format(time.time() - t)
    print "(Info) Solving Harmony Problem"
    t = time.time()
    solutions_iter = solve(problem)
    dur = time.time() - t
    print "(Info) Done Solving ({0:.4f}s)".format(dur)
    print "  Displaying solutions:"
    flag_continue = False
    solutions = []
    for sol in solutions_iter:
        solutions.append(sol)
    print "    {0} Solutions Total.".format(len(solutions))
    for i, solution in enumerate(solutions):
        if flag_continue:
            continue
        tmax = len(solution) / 4
        for t in xrange(tmax):
            print "Time={0}:    [{1}]".format(t, chords[t])
            for voice in VOICE_PREFIXES:
                var = make_var(voice, t)
                pitchnum = solution[var]
                print "    {0}: {1}".format(voice, Note.numToPitch_absolute(pitchnum))
        s = raw_input("({0}/{1}) Press enter to continue, 'c' to skip, or 'q' to exit.".format(i, len(solutions) - 1))
        if s == 'c':
            flag_continue = True
        elif s == 'q':
            break