Best Python code snippet using slash
printgalore.py
Source:printgalore.py  
...18    profit = []19    skipknap = False20    #analyze for duplicates/ same properties21    for i in range(n):22      duration.append(tasks[i].get_duration())23      deadline.append(tasks[i].get_deadline())24      profit.append(tasks[i].get_max_benefit())25        26    print(sum(profit)/len(profit))27    if int(sum(profit)/len(profit)) == int(profit[1]) == int(profit[50]):28        skipknap = True29    #all same duration:30    # if avg(duration) == duration[1]:31    #     skipknap = True32    deadprof = {}     #deadline profit chunks:33    durprof = {}     #deadline profit chunks:34    deaddurprof = {}35    for i in range(n):36        if (deadline[i], profit[i]) not in deadprof:37            deadprof[(deadline[i], profit[i])] = 138        else:39            deadprof[(deadline[i], profit[i])] += 140        41        if (deadline[i], duration[i], profit[i]) not in deaddurprof:42            deaddurprof[(deadline[i], duration[i], profit[i])] = 143        else:44            deaddurprof[(deadline[i], duration[i], profit[i])] += 145        if (duration[i], profit[i]) not in durprof:46            durprof[(duration[i], profit[i])] = 147        else:48            durprof[(duration[i], profit[i])] += 149    for key in deadprof:50        if deadprof[key] / n >= .8:51            skipknap = True52            break53    for key in durprof:54        if durprof[key] / n >= .8:55            skipknap = True56            break57    58    for key in deaddurprof:59        if deaddurprof[key] / n >= .4:60            skipknap = False61            print('CHANGED SKIPKNAP BACK TO FALSE')62            break63        #print('d :' + str(deaddurprof[key]))64        if deaddurprof[key] > 6:65            skipknap = True66            break67    #print(len(durprof))68    if len(durprof) < 8:69        print('TOO FEW KEYS----------------------')70        skipknap = True71    72    if skipknap:73        print("skipknap------------------------------")74    75    # if not special:76    if not skipknap:77        for size in range(n//8,n//2+1,n//8):78            id_ordering, profit, tasks_ordering = knapsack_solver(tasks,size)79            assert profit == get_profit(tasks_ordering)80            if profit > best_profit:81                best_profit = profit82                best_result = id_ordering83                best_ordering = tasks_ordering84    count = 085    for id_ordering, profit, tasks_ordering in [greedy_profit_duration(tasks), greedy_duration_deadline(tasks), greedy_duration_deadline(tasks), greedy_critical_time(tasks),86                                                greedy_min_slack(tasks), greedy_decay(tasks), greedy_decay_profit_duration(tasks)]: #backtrack_profit_duration(tasks)]:87        assert profit == get_profit(tasks_ordering)88        if profit > best_profit:89            #used_greedy = True90            #print(profit)91            #print(id_ordering)92            best_profit = profit93            best_result = id_ordering94            best_ordering = tasks_ordering95            print('USED GREEDY: ' + str(count))96            if count > 5:97                print('USED MADDY --------------------------')98            if count > 6:99                print('USED JESSIE -------------------------')100        count += 1101    102    dp_ordering = dp(tasks)103    dp_profit = get_profit(dp_ordering)104    if dp_profit > best_profit:105        best_profit = dp_profit106        best_ordering = dp_ordering107        best_result = [t.get_task_id() for t in dp_ordering]108        print('USED DP---------------------------')109    #if not used_greedy:110        #print('USED KNAPSACK')111    print('profit: ' + str(best_profit))112    #print(best_result)113    #print(best_profit)114    assert best_profit == get_profit(best_ordering)115    assert best_result == [t.get_task_id() for t in best_ordering]116    assert check_validity(best_result, tasks)117    return best_result118def knapsack_solver(tasks, knapsack_size, total_time=1440, recurse=1):119    solver = pywrapknapsack_solver.KnapsackSolver(120        pywrapknapsack_solver.KnapsackSolver.121        KNAPSACK_MULTIDIMENSION_BRANCH_AND_BOUND_SOLVER, 'KnapsackExample')122    #sort by deadline123    tasks_sorted_deadline = sorted(tasks, key=lambda task: task.get_deadline())124    ordering = []125    current_start = 0126    #elementary counter here127    #start clock128    for i in range(0, len(tasks), knapsack_size):129        tasks_group = tasks_sorted_deadline[i:min(i+knapsack_size,len(tasks_sorted_deadline))]130        values = [t.get_max_benefit() for t in tasks_group]131        weights = [[t.get_duration() for t in tasks_group]]132        capacities = [min(tasks_group[-1].get_deadline(), total_time) - current_start]133        solver.Init(values, weights, capacities)134        #https://stackoverflow.com/questions/366682/how-to-limit-execution-time-of-a-function-call135        # try:136        #     with time_limit(10):137        #         computed_value = solver.Solve()138        # except TimeoutException as e:139            # return [], 0140        computed_value = solver.Solve()141        packed_items = []142        for i in range(len(tasks_group)):143            if solver.BestSolutionContains(i):144                packed_items.append(tasks_group[i])145        group_ordering = sorted(packed_items, key=lambda task: task.get_deadline())146        current_start = current_start + sum([t.get_duration() for t in group_ordering])147        ordering += group_ordering148    remaining_tasks = [t for t in tasks if t not in ordering]149    time_remaining = total_time - current_start150    if remaining_tasks and recurse == 1 and time_remaining >= remaining_tasks[0].get_duration():151        second_result, second_profit, second_ordering = knapsack_solver(remaining_tasks, knapsack_size, time_remaining, 2)152        ordering += second_ordering153        time_remaining = time_remaining - sum([t.get_duration() for t in second_ordering])154        remaining_tasks = [t for t in remaining_tasks if t not in ordering]155    #after knapsack, greedily fill in remaining time156    ordering += fill_remaining(remaining_tasks, time_remaining)157    result = [t.get_task_id() for t in ordering]158    total_profit = get_profit(ordering)159    #print(sum([t.get_duration() for t in ordering]))160    return result, total_profit, ordering161def get_profit(ordering, start_time=0):162    total_profit = 0163    current_time = start_time164    for task in ordering:165        current_time += task.get_duration()166        if current_time <= task.get_deadline():167            total_profit += task.get_max_benefit()168        else:169            total_profit += task.get_late_benefit(current_time - task.get_deadline())170        #if testing:171            #print(current_time)172            #print(str(task.get_task_id()) + ': ' + str(total_profit))173    return total_profit174    175def fill_remaining(tasks_remaining, time_remaining, from_decay=False):176    # compares two different methods of filling in remaining time:177    # tries fill in backwards from 1440, latest deadline first, and tries greedy_decay178    tasks_sorted = sorted(tasks_remaining, key=lambda task: (-task.get_deadline(), -task.get_max_benefit()))179    ordering = []180    temp_time = time_remaining181    #orig_remain = True182    while time_remaining > 0 and tasks_sorted:183        if tasks_sorted[0].get_duration() <= time_remaining:184            ordering.append(tasks_sorted[0])185            time_remaining -= tasks_sorted[0].get_duration()186        tasks_sorted.pop(0)187    profit = get_profit(ordering, 1440 - temp_time)188    if not from_decay:189        if temp_time > 0 and tasks_remaining:190            other_id_result, other_profit, other_task_ordering = greedy_decay(tasks_remaining, temp_time)191            if other_profit > profit:192                #orig_remain = False193                ordering = other_task_ordering194    return ordering195def greedy_decay(tasks, time_remaining=1440):196    # different from other greedys because it allows you to go past deadline197    profit_duration = sorted(tasks, key=lambda task: (-task.get_max_benefit()/task.get_duration(), task.get_deadline()))198    profit_forwards = sorted(tasks, key=lambda task: (-task.get_max_benefit(), task.get_deadline()))199    sorted_deadline = sorted(tasks, key=lambda task: (task.get_deadline(), -task.get_max_benefit()))200    sorted_duration = sorted(tasks, key=lambda task: (task.get_duration(), task.get_deadline()))201    #count = 0202    best_ordering = []203    best_profit = 0204    for sorted_tasks in [profit_duration, profit_forwards, sorted_deadline, sorted_duration]:205        current_time = 1440 - time_remaining206        ordering = []207        while sorted_tasks and current_time < time_remaining:208            if current_time + sorted_tasks[0].get_duration() <= time_remaining:209                ordering.append(sorted_tasks[0])210                current_time += sorted_tasks[0].get_duration()211            sorted_tasks.pop(0)212        remaining_tasks = [t for t in tasks if t not in ordering]213        reverse_ordering = ordering.copy()214        reverse_ordering.reverse()215        deadline_ordering = sorted(ordering, key=lambda task: task.get_deadline())216        for array in [deadline_ordering, ordering, reverse_ordering]:217            array += fill_remaining(remaining_tasks, time_remaining - current_time, True)218            profit = get_profit(array, 1440 - time_remaining)219            if profit > best_profit:220                best_profit = profit221                best_ordering = array222     223    result = [t.get_task_id() for t in best_ordering]224    return result, get_profit(best_ordering), best_ordering225                                     226def backtrack_profit_duration(tasks):227    # when to backtrack? 228    # when we find another task that has greater profit/duration that we can't take due to time constraints229    # eg. if current_start + task.get_duration() > task.get_deadline(), remove the previous task from 230    # both our list and choice of options 231    counter_backtrack = 0232    233    tasks_sorted = sorted(tasks, key=lambda task: task.get_max_benefit() / task.get_duration())[::-1]234    previous_task = tasks_sorted[0]235    current_start = tasks_sorted[0].get_duration()236    ordering = [tasks_sorted[0]]237    238    for i in range(1, len(tasks_sorted)):239        task = tasks_sorted[i]240        unit_prof = task.get_max_benefit() / task.get_duration()241        if current_start + task.get_duration() > task.get_deadline() and unit_prof >= previous_task.get_max_benefit()/previous_task.get_duration():242            while ordering and current_start + task.get_duration() > task.get_deadline():243                temp = ordering.pop()244                current_start -= temp.get_duration()245            counter_backtrack += 1246        #else if current_start + task.get_duration() <= task.get_deadline():247        ordering.append(task)248        current_start += task.get_duration()249        previous_task = task250    remaining_tasks = [t for t in tasks if t not in ordering]251    ordering += fill_remaining(remaining_tasks, 1440 - current_start)252    result = [t.get_task_id() for t in ordering]253    return result, get_profit(ordering), ordering                                254def greedy_profit_duration(tasks):255    tasks_sorted = sorted(tasks, key=lambda task: task.get_max_benefit() / task.get_duration())[::-1]256    current_start = 0257    ordering = []258    for task in tasks_sorted:259        if (current_start + task.get_duration() <= task.get_deadline()):260            ordering.append(task)261            current_start += task.get_duration()262    remaining_tasks = [t for t in tasks if t not in ordering]263    ordering += fill_remaining(remaining_tasks, 1440 - current_start)264    result = [t.get_task_id() for t in ordering]265    return result, get_profit(ordering), ordering266def greedy_decay_profit_duration(tasks):267    tasks_sorted = sorted(tasks, key=lambda task: task.get_max_benefit() / task.get_duration())[::-1]268    current_start = 0269    ordering = []270    while len(tasks_sorted) > 0:271        task = tasks_sorted[0]272        if current_start + task.get_duration() <= 1440:273            ordering.append(task)274            current_start += task.get_duration()275        tasks_sorted = tasks_sorted[1:]276        tasks_sorted = sorted(tasks_sorted, key=lambda task: task.get_late_benefit(max(0, task.get_duration() - task.get_deadline())) / task.get_duration())[::-1]277    remaining_tasks = [t for t in tasks if t not in ordering]278    ordering += fill_remaining(remaining_tasks, 1440 - current_start)279    result = [t.get_task_id() for t in ordering]280    return result, get_profit(ordering), ordering281    282def greedy_duration_deadline(tasks):283    tasks_sorted = sorted(tasks, key=lambda task: (task.get_deadline(), task.get_duration())) 284    current_start = 0285    ordering = []286    for task in tasks_sorted:287        if (current_start + task.get_duration() <= task.get_deadline()):288            ordering.append(task)289            current_start += task.get_duration()290    remaining_tasks = [t for t in tasks if t not in ordering]291    ordering += fill_remaining(remaining_tasks, 1440 - current_start)292    result = [t.get_task_id() for t in ordering]293    return result, get_profit(ordering), ordering294def greedy_deadline_profit(tasks):295    tasks_sorted = sorted(tasks, key=lambda task: (task.get_deadline(), -task.get_max_benefit())) 296    current_start = 0297    ordering = []298    for task in tasks_sorted:299        if (current_start + task.get_duration() <= task.get_deadline()):300            ordering.append(task)301            current_start += task.get_duration()302    remaining_tasks = [t for t in tasks if t not in ordering]303    ordering += fill_remaining(remaining_tasks, 1440 - current_start)304    result = [t.get_task_id() for t in ordering]305    return result, get_profit(ordering)306def greedy_critical_time(tasks):307    #deadline / duration308    tasks_sorted = sorted(tasks, key=lambda task: (task.get_deadline()/task.get_duration())) 309    current_start = 0310    ordering = []311    for task in tasks_sorted:312        if (current_start + task.get_duration() <= task.get_deadline()):313            ordering.append(task)314            current_start += task.get_duration()315    remaining_tasks = [t for t in tasks if t not in ordering]316    ordering += fill_remaining(remaining_tasks, 1440 - current_start)317    result = [t.get_task_id() for t in ordering]318    return result, get_profit(ordering), ordering319def greedy_min_slack(tasks):320    #deadline - duration321    tasks_sorted = sorted(tasks, key=lambda task: (task.get_deadline() - task.get_duration())) 322    current_start = 0323    ordering = []324    for task in tasks_sorted:325        if (current_start + task.get_duration() <= task.get_deadline()):326            ordering.append(task)327            current_start += task.get_duration()328    remaining_tasks = [t for t in tasks if t not in ordering]329    ordering += fill_remaining(remaining_tasks, 1440 - current_start)330    result = [t.get_task_id() for t in ordering]331    return result, get_profit(ordering), ordering332def check_validity(results, tasks):333    time = 0334    used = []335    for i in results:336        if i in used: # no repeats337            print('repeat')338            return False339        time += tasks[i-1].get_duration()340        used.append(i)341        #print(i)342        #print(time)343    if time > 1440: # don't go past 1440344        print('overtime')345        return False346    return True347def dp(tasks):348  n = len(tasks)349  arr = [[0 for t in range(1440)] for i in range(n)]350  #print(arr)351  #arr(i,t) = a feasible schedule in which only jobs from [1, i] are scheduled and all jobs finish by time t.352  for t in range(1440):353    arr[0][t] = 0354  deadline_sorted = sorted(tasks, key=lambda task: (task.get_deadline()))355  356  #tp = min(t, d_i) - t_i357  #if tp < 0 then arr[i][t] = arr[i-1][t]358  #if tp >= 0 then arr[i][t] = max(arr[i-1][t], p_i + arr[i-1][tp])359  360  def printopt(i, t, lst):361    task = deadline_sorted[i]362    t_i = task.get_duration()363    d_i = task.get_deadline()364    if i == 0:365      #print([t.get_task_id() for t in lst])366      #print(get_profit(lst))367      #print(lst)368      #print(lst == None)369      return  #, get_profit(lst), [t.get_task_id() for t in lst]370    if arr[i][t] == arr[i-1][t]:371      printopt(i-1, t, lst)372    else:373      tp = min(t, d_i) - t_i374      lst.append(task)375      printopt(i-1, tp, lst)376  377  for i in range(n):378    task = deadline_sorted[i]379    t_i = task.get_duration()380    d_i = task.get_deadline()381    p_i = task.get_max_benefit()382    #task1 = tasks[i+1]383    #t1 = task1.get_duration()384    #d1 = task1.get_deadline()385    #p1 = task1.get_max_benefit()386    for t in range(1440):387      tp = min(t, d_i) - t_i388      if tp < 0:389        arr[i][t] = arr[i-1][t]390      else:391        #print(i, t, i-1, tp)392        arr[i][t] = max(arr[i-1][t], p_i + arr[i-1][tp])393      #if(arr[i][t] != -1 and t + t1 <= d1):394        #arr[i+1][t+t1] = max(arr[i+1][t+t1], arr[i][t] + p1)395  lst = []396  printopt(n-1, 1439, lst)397  lst = lst[::-1]...chords.py
Source:chords.py  
...8LENKICKHEAVY = 0.7160090702959LENHIHAT = 0.24163265306110LENCLAP = 0.24163265306111# clap, sr = librosa.load("drums/clap.wav")12# print librosa.get_duration(clap, sr)13# snare, sr = librosa.load("drums/snare.wav")14# print librosa.get_duration(snare, sr)15# kick, sr = librosa.load("drums/kick-big.wav")16# print librosa.get_duration(kick, sr)17# kick, sr = librosa.load("drums/kick-heavy.wav")18# print librosa.get_duration(kick, sr)19# hat, sr = librosa.load("drums/hihat.wav")20# print librosa.get_duration(hat, sr)21#Piano22cScale = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B']23yC, srC = librosa.load("piano/wav/c.wav")24#yC = librosa.effects.time_stretch(yC, librosa.get_duration(yC, srC))25yCs, srCs = librosa.load("piano/wav/cs.wav")26#yCs = librosa.effects.time_stretch(yCs, librosa.get_duration(yCs, srCs))27yD, srD = librosa.load("piano/wav/d.wav")28#yD = librosa.effects.time_stretch(yD, librosa.get_duration(yD, srD))29yDs, srDs = librosa.load("piano/wav/ds.wav")30#yDs = librosa.effects.time_stretch(yDs, librosa.get_duration(yDs, srDs))31yE, srE = librosa.load("piano/wav/e.wav")32#yE = librosa.effects.time_stretch(yE, librosa.get_duration(yE, srE))33yF, srF = librosa.load("piano/wav/f.wav")34#yF = librosa.effects.time_stretch(yF, librosa.get_duration(yF, srF))35yFs, srFs = librosa.load("piano/wav/fs.wav")36#yFs = librosa.effects.time_stretch(yFs, librosa.get_duration(yFs, srFs))37yG, srG = librosa.load("piano/wav/g.wav")38#yG = librosa.effects.time_stretch(yG, librosa.get_duration(yG, srG))39yGs, srGs = librosa.load("piano/wav/gs.wav")40#yGs = librosa.effects.time_stretch(yGs, librosa.get_duration(yGs, srGs))41yA, srA = librosa.load("piano/wav/a.wav")42#yA = librosa.effects.time_stretch(yA, librosa.get_duration(yA, srA))43yAs, srAs = librosa.load("piano/wav/as.wav")44#yAs = librosa.effects.time_stretch(yAs, librosa.get_duration(yAs, srAs))45yB, srB = librosa.load("piano/wav/b.wav")46#yB = librosa.effects.time_stretch(yB, librosa.get_duration(yB, srB))47srPiano = srC48cScaleNotesP = [yC, yCs, yD, yDs, yE, yF, yFs, yG, yGs, yA, yAs, yB, librosa.effects.pitch_shift(yC, srPiano, n_steps=12), librosa.effects.pitch_shift(yCs, srPiano, n_steps=12), librosa.effects.pitch_shift(yD, srPiano, n_steps=12), librosa.effects.pitch_shift(yDs, srPiano, n_steps=12), librosa.effects.pitch_shift(yE, srPiano, n_steps=12), librosa.effects.pitch_shift(yF, srPiano, n_steps=12), librosa.effects.pitch_shift(yFs, srPiano, n_steps=12), librosa.effects.pitch_shift(yG, srPiano, n_steps=12), librosa.effects.pitch_shift(yGs, srPiano, n_steps=12), librosa.effects.pitch_shift(yA, srPiano, n_steps=12), librosa.effects.pitch_shift(yAs, srPiano, n_steps=12), librosa.effects.pitch_shift(yB, srPiano, n_steps=12), librosa.effects.pitch_shift(yC, srPiano, n_steps=24), librosa.effects.pitch_shift(yCs, srPiano, n_steps=24)]49#Bass50yC, srC = librosa.load("Octaver/Octaver-c1.wav")51yDs, srDs = librosa.load("Octaver/Octaver-d#1.wav")52yFs, srFs = librosa.load("Octaver/Octaver-f#1.wav")53yA, srA = librosa.load("Octaver/Octaver-a1.wav")54yC2, srC = librosa.load("Octaver/Octaver-c2.wav")55yDs2, srDs = librosa.load("Octaver/Octaver-d#2.wav")56yFs2, srFs = librosa.load("Octaver/Octaver-f#2.wav")57yA2, srA = librosa.load("Octaver/Octaver-a2.wav")58yC3, srC = librosa.load("Octaver/Octaver-c3.wav")59yDs3, srDs = librosa.load("Octaver/Octaver-d#3.wav")60yFs3, srFs = librosa.load("Octaver/Octaver-f#3.wav")61yA3, srA = librosa.load("Octaver/Octaver-a3.wav")62srBass = srC63cScaleNotesB = [yC, librosa.effects.pitch_shift(yC, srBass, n_steps=1), librosa.effects.pitch_shift(yC, srBass, n_steps=2), yDs, librosa.effects.pitch_shift(yDs, srBass, n_steps=1), librosa.effects.pitch_shift(yDs, srBass, n_steps=2), yFs, librosa.effects.pitch_shift(yFs, srBass, n_steps=1), librosa.effects.pitch_shift(yFs, srBass, n_steps=2), yA, librosa.effects.pitch_shift(yA, srBass, n_steps=1), librosa.effects.pitch_shift(yA, srBass, n_steps=2), yC2, librosa.effects.pitch_shift(yC2, srBass, n_steps=1), librosa.effects.pitch_shift(yC2, srBass, n_steps=2), yDs2, librosa.effects.pitch_shift(yDs2, srBass, n_steps=1), librosa.effects.pitch_shift(yDs2, srBass, n_steps=2), yFs2, librosa.effects.pitch_shift(yFs2, srBass, n_steps=1), librosa.effects.pitch_shift(yFs2, srBass, n_steps=2), yA2, librosa.effects.pitch_shift(yA2, srBass, n_steps=1), librosa.effects.pitch_shift(yA2, srBass, n_steps=2), yC3, librosa.effects.pitch_shift(yC3, srBass, n_steps=1), librosa.effects.pitch_shift(yC3, srBass, n_steps=2), yDs3, librosa.effects.pitch_shift(yDs3, srBass, n_steps=1), librosa.effects.pitch_shift(yDs3, srBass, n_steps=2), yFs3, librosa.effects.pitch_shift(yFs3, srBass, n_steps=1), librosa.effects.pitch_shift(yFs3, srBass, n_steps=2), yA3, librosa.effects.pitch_shift(yA3, srBass, n_steps=1), librosa.effects.pitch_shift(yA3, srBass, n_steps=2)]64#COMMENTS on stuff that confuse me65#spb means how long before every beat66#Drums67#each x is 1/16th of a measure68#hat    |xxxx|xxxx|xxxx|xxxx|69#snare  |xxxx|xxxx|xxxx|xxxx|70#kick   |xxxx|xxxx|xxxx|xxxx|71#standard break beat?72# |x x |x x |xxx |x x |73# |    |x   |    |x   |74# |x   |    |  x |    |75def makeStandardBreaks(bpm):76	spb = 60.0 / bpm77	measure = 4.0 * spb78	timeBeat = ((measure / 16.0) * 1000)79	canvas = AudioSegment.silent(measure * 1000 * 2)80	oneBeat = AudioSegment.silent(spb * 1000)81	snare = AudioSegment.from_file("drums/snare.wav")82	kickBig = AudioSegment.from_file("drums/kick-big.wav")83	kickHeavy = AudioSegment.from_file("drums/kick-heavy.wav")84	hihat = AudioSegment.from_file("drums/hihat.wav")85	hihat = hihat86	hatBeat1 = hihat + AudioSegment.silent(2 * timeBeat - (LENHIHAT * 1000)) + hihat + AudioSegment.silent(2 * timeBeat - (LENHIHAT * 1000)) + hihat + AudioSegment.silent(2 * timeBeat - (LENHIHAT * 1000)) + hihat + AudioSegment.silent(2 * timeBeat - (LENHIHAT * 1000)) + hihat + AudioSegment.silent(2 * timeBeat - (LENHIHAT * 1000)) + hihat + AudioSegment.silent(2 *timeBeat - (LENHIHAT * 1000)) + hihat + AudioSegment.silent(2 * timeBeat - (LENHIHAT * 1000)) + hihat + AudioSegment.silent(2 * timeBeat - (LENHIHAT * 1000)) + hihat + AudioSegment.silent(2 * timeBeat - (LENHIHAT * 1000))87	hatBeat2 = hihat + AudioSegment.silent(2 * timeBeat - (LENHIHAT * 1000)) + hihat + AudioSegment.silent(2 * timeBeat - (LENHIHAT * 1000)) + hihat + AudioSegment.silent(2 * timeBeat - (LENHIHAT * 1000)) + hihat + AudioSegment.silent(timeBeat - (LENHIHAT * 1000)) + hihat + AudioSegment.silent(timeBeat - (LENHIHAT * 1000)) + hihat + AudioSegment.silent(2 *timeBeat - (LENHIHAT * 1000)) + hihat + AudioSegment.silent(4 * timeBeat - (LENHIHAT * 1000)) + hihat88	snareKickBeat1 = kickBig + AudioSegment.silent(4 * timeBeat - (LENKICKBIG * 1000)) + snare + AudioSegment.silent(6 * timeBeat - (LENSNARE * 1000)) + kickHeavy + AudioSegment.silent(2 * timeBeat - (LENKICKHEAVY * 1000)) + snare89	oneMeasure = canvas.overlay(hatBeat1).overlay(hatBeat2, position = measure * 1000).overlay(snareKickBeat1).overlay(snareKickBeat1, position = measure * 1000)90	twoMeasures = oneMeasure + oneMeasure91	twoMeasures.export("drumsStandardBreaks.wav", format = "wav")92# 2 and 4 beat93# | x x| x x|94# |xxxx|xxxx|95# |x x |x x |96def make2and4Beat(bpm):97	spb = 60.0 / bpm98	measure = 4.0 * spb99	timeBeat = (measure / 4) * 1000100	canvas = AudioSegment.silent(measure * 1000)101	oneBeat = AudioSegment.silent(spb * 1000)102	snare = AudioSegment.from_file("drums/snare.wav")103	kick = AudioSegment.from_file("drums/kick-big.wav")104	hihat = AudioSegment.from_file("drums/hihat.wav")105	hihat = hihat + 5106	snareBeat = snare + AudioSegment.silent(timeBeat - (LENSNARE * 1000)) + snare + AudioSegment.silent(timeBeat - (LENSNARE * 1000)) + snare + AudioSegment.silent(timeBeat - (LENSNARE * 1000)) + snare107	kickHihatBeat = kick + AudioSegment.silent(timeBeat - (LENKICKBIG * 1000)) + hihat + AudioSegment.silent(timeBeat - (LENHIHAT * 1000)) + kick + AudioSegment.silent(timeBeat - (LENKICKBIG * 1000)) + hihat108	oneMeasure = canvas.overlay(snareBeat).overlay(kickHihatBeat)109	twoMeasures = oneMeasure + oneMeasure110	twoMeasures.export("drums24.wav", format="wav")111# this makes like | 1 4 | 5 |112def makeBasic145(key, bpm):113	#Piano114	spb = 60.0 / bpm115	measure = BEATSPERMEASURE * spb116	scaleIndex = cScale.index(key)117	tempNote = cScaleNotesP[scaleIndex]118	note1_1 = librosa.effects.time_stretch(tempNote, (librosa.get_duration(tempNote, srPiano) / measure) * 2.0)119	tempNote = cScaleNotesP[scaleIndex + 4]120	note1_2 = librosa.effects.time_stretch(tempNote, (librosa.get_duration(tempNote, srPiano) / measure) * 2.0)121	tempNote = cScaleNotesP[scaleIndex + 7]122	note1_3 = librosa.effects.time_stretch(tempNote, (librosa.get_duration(tempNote, srPiano) / measure) * 2.0)123	librosa.output.write_wav("noteP1_1.wav", note1_1, srPiano)124	librosa.output.write_wav("noteP1_2.wav", note1_2, srPiano)125	librosa.output.write_wav("noteP1_3.wav", note1_3, srPiano)126	audioSegment1_1 = AudioSegment.from_file("noteP1_1.wav")127	audioSegment1_2 = AudioSegment.from_file("noteP1_2.wav")128	audioSegment1_3 = AudioSegment.from_file("noteP1_3.wav")129	audioSegment1 = audioSegment1_1.overlay(audioSegment1_2).overlay(audioSegment1_3)130	tempNote = cScaleNotesP[scaleIndex + 5]131	note4_1 = librosa.effects.time_stretch(tempNote, (librosa.get_duration(tempNote, srPiano) / measure) * 2.0)132	tempNote = cScaleNotesP[scaleIndex + 9]133	note4_2 = librosa.effects.time_stretch(tempNote, (librosa.get_duration(tempNote, srPiano) / measure) * 2.0)134	tempNote = cScaleNotesP[scaleIndex + 12]135	note4_3 = librosa.effects.time_stretch(tempNote, (librosa.get_duration(tempNote, srPiano) / measure) * 2.0)136	librosa.output.write_wav("noteP4_1.wav", note4_1, srPiano)137	librosa.output.write_wav("noteP4_2.wav", note4_2, srPiano)138	librosa.output.write_wav("noteP4_3.wav", note4_3, srPiano)139	audioSegment4_1 = AudioSegment.from_file("noteP4_1.wav")140	audioSegment4_2 = AudioSegment.from_file("noteP4_2.wav")141	audioSegment4_3 = AudioSegment.from_file("noteP4_3.wav")142	audioSegment4 = audioSegment4_1.overlay(audioSegment4_2).overlay(audioSegment4_3)143	tempNote = cScaleNotesP[scaleIndex + 7]144	note5_1 = librosa.effects.time_stretch(tempNote, (librosa.get_duration(tempNote, srPiano) / measure))145	tempNote = cScaleNotesP[scaleIndex + 11]146	note5_2 = librosa.effects.time_stretch(tempNote, (librosa.get_duration(tempNote, srPiano) / measure))147	tempNote = cScaleNotesP[scaleIndex + 14]148	note5_3 = librosa.effects.time_stretch(tempNote, (librosa.get_duration(tempNote, srPiano) / measure))149	librosa.output.write_wav("noteP5_1.wav", note5_1, srPiano)150	librosa.output.write_wav("noteP5_2.wav", note5_2, srPiano)151	librosa.output.write_wav("noteP5_3.wav", note5_3, srPiano)152	audioSegment5_1 = AudioSegment.from_file("noteP5_1.wav")153	audioSegment5_2 = AudioSegment.from_file("noteP5_2.wav")154	audioSegment5_3 = AudioSegment.from_file("noteP5_3.wav")155	audioSegment5 = audioSegment5_1.overlay(audioSegment5_2).overlay(audioSegment5_3)156	audio145 = audioSegment1 + audioSegment4 + audioSegment5157	audio145.export("piano145.wav", format="wav")158	#Bass159	tempNote = cScaleNotesB[scaleIndex]160	note1_1 = librosa.effects.time_stretch(tempNote, (librosa.get_duration(tempNote, srBass) / measure) * 2.0)161	tempNote = cScaleNotesB[scaleIndex + 5]162	note4_1 = librosa.effects.time_stretch(tempNote, (librosa.get_duration(tempNote, srBass) / measure) * 2.0)163	tempNote = cScaleNotesB[scaleIndex + 7]164	note5_1 = librosa.effects.time_stretch(tempNote, (librosa.get_duration(tempNote, srBass) / measure))165	librosa.output.write_wav("noteB1_1.wav", note1_1, srBass)166	librosa.output.write_wav("noteB4_1.wav", note4_1, srBass)167	librosa.output.write_wav("noteB5_1.wav", note5_1, srBass)168	audioSegment1_1 = AudioSegment.from_file("noteB1_1.wav")169	audioSegment4_1 = AudioSegment.from_file("noteB4_1.wav")170	audioSegment5_1 = AudioSegment.from_file("noteB5_1.wav")171	audio145 = (audioSegment1_1 + 10) + (audioSegment4_1 + 10) + (audioSegment5_1 + 10)172	audio145.export("bass145.wav", format="wav")173def make1456(key, bpm):174	#Piano175	spb = 60.0 / bpm176	measure = BEATSPERMEASURE * spb177	scaleIndex = cScale.index(key)178	tempNote = cScaleNotesP[scaleIndex + 7]179	note1_1 = librosa.effects.time_stretch(tempNote, (librosa.get_duration(tempNote, srPiano) / measure) * 2.0)180	tempNote = cScaleNotesP[scaleIndex + 12]181	note1_2 = librosa.effects.time_stretch(tempNote, (librosa.get_duration(tempNote, srPiano) / measure) * 2.0)182	tempNote = cScaleNotesP[scaleIndex + 16]183	note1_3 = librosa.effects.time_stretch(tempNote, (librosa.get_duration(tempNote, srPiano) / measure) * 2.0)184	librosa.output.write_wav("2noteP1_1.wav", note1_1, srPiano)185	librosa.output.write_wav("2noteP1_2.wav", note1_2, srPiano)186	librosa.output.write_wav("2noteP1_3.wav", note1_3, srPiano)187	audioSegment1_1 = AudioSegment.from_file("2noteP1_1.wav")188	audioSegment1_2 = AudioSegment.from_file("2noteP1_2.wav")189	audioSegment1_3 = AudioSegment.from_file("2noteP1_3.wav")190	audioSegment1 = audioSegment1_1.overlay(audioSegment1_2).overlay(audioSegment1_3)191	tempNote = cScaleNotesP[scaleIndex + 7]192	note4_1 = librosa.effects.time_stretch(tempNote, (librosa.get_duration(tempNote, srPiano) / measure) * 2.0)193	tempNote = cScaleNotesP[scaleIndex + 11]194	note4_2 = librosa.effects.time_stretch(tempNote, (librosa.get_duration(tempNote, srPiano) / measure) * 2.0)195	tempNote = cScaleNotesP[scaleIndex + 14]196	note4_3 = librosa.effects.time_stretch(tempNote, (librosa.get_duration(tempNote, srPiano) / measure) * 2.0)197	librosa.output.write_wav("2noteP4_1.wav", note4_1, srPiano)198	librosa.output.write_wav("2noteP4_2.wav", note4_2, srPiano)199	librosa.output.write_wav("2noteP4_3.wav", note4_3, srPiano)200	audioSegment4_1 = AudioSegment.from_file("2noteP4_1.wav")201	audioSegment4_2 = AudioSegment.from_file("2noteP4_2.wav")202	audioSegment4_3 = AudioSegment.from_file("2noteP4_3.wav")203	audioSegment4 = audioSegment4_1.overlay(audioSegment4_2).overlay(audioSegment4_3)204	tempNote = cScaleNotesP[scaleIndex + 9]205	note5_1 = librosa.effects.time_stretch(tempNote, (librosa.get_duration(tempNote, srPiano) / measure) * 2.0)206	tempNote = cScaleNotesP[scaleIndex + 12]207	note5_2 = librosa.effects.time_stretch(tempNote, (librosa.get_duration(tempNote, srPiano) / measure) * 2.0)208	tempNote = cScaleNotesP[scaleIndex + 16]209	note5_3 = librosa.effects.time_stretch(tempNote, (librosa.get_duration(tempNote, srPiano) / measure) * 2.0)210	librosa.output.write_wav("2noteP5_1.wav", note5_1, srPiano)211	librosa.output.write_wav("2noteP5_2.wav", note5_2, srPiano)212	librosa.output.write_wav("2noteP5_3.wav", note5_3, srPiano)213	audioSegment5_1 = AudioSegment.from_file("2noteP5_1.wav")214	audioSegment5_2 = AudioSegment.from_file("2noteP5_2.wav")215	audioSegment5_3 = AudioSegment.from_file("2noteP5_3.wav")216	audioSegment5 = audioSegment5_1.overlay(audioSegment5_2).overlay(audioSegment5_3)217	tempNote = cScaleNotesP[scaleIndex + 9]218	note6_1 = librosa.effects.time_stretch(tempNote, (librosa.get_duration(tempNote, srPiano) / measure) * 2.0)219	tempNote = cScaleNotesP[scaleIndex + 12]220	note6_2 = librosa.effects.time_stretch(tempNote, (librosa.get_duration(tempNote, srPiano) / measure) * 2.0)221	tempNote = cScaleNotesP[scaleIndex + 17]222	note6_3 = librosa.effects.time_stretch(tempNote, (librosa.get_duration(tempNote, srPiano) / measure) * 2.0)223	librosa.output.write_wav("2noteP6_1.wav", note6_1, srPiano)224	librosa.output.write_wav("2noteP6_2.wav", note6_2, srPiano)225	librosa.output.write_wav("2noteP6_3.wav", note6_3, srPiano)226	audioSegment6_1 = AudioSegment.from_file("2noteP6_1.wav")227	audioSegment6_2 = AudioSegment.from_file("2noteP6_2.wav")228	audioSegment6_3 = AudioSegment.from_file("2noteP6_3.wav")229	audioSegment6 = audioSegment6_1.overlay(audioSegment6_2).overlay(audioSegment6_3)230	audio145 = audioSegment1 + audioSegment4 + audioSegment5 + audioSegment6231	audio145.export("piano1456.wav", format="wav")232	#Bass233	tempNote = cScaleNotesB[scaleIndex + 12]234	note1_1 = librosa.effects.time_stretch(tempNote, (librosa.get_duration(tempNote, srBass) / measure) * 2.0)235	tempNote = cScaleNotesB[scaleIndex + 11]236	note4_1 = librosa.effects.time_stretch(tempNote, (librosa.get_duration(tempNote, srBass) / measure) * 2.0)237	tempNote = cScaleNotesB[scaleIndex + 9]238	note5_1 = librosa.effects.time_stretch(tempNote, (librosa.get_duration(tempNote, srBass) / measure) * 2.0)239	tempNote = cScaleNotesB[scaleIndex + 5]240	note6_1 = librosa.effects.time_stretch(tempNote, (librosa.get_duration(tempNote, srBass) / measure) * 2.0)241	librosa.output.write_wav("2noteB1_1.wav", note1_1, srBass)242	librosa.output.write_wav("2noteB4_1.wav", note4_1, srBass)243	librosa.output.write_wav("2noteB5_1.wav", note5_1, srBass)244	librosa.output.write_wav("2noteB6_1.wav", note5_1, srBass)245	audioSegment1_1 = AudioSegment.from_file("2noteB1_1.wav")246	audioSegment4_1 = AudioSegment.from_file("2noteB4_1.wav")247	audioSegment5_1 = AudioSegment.from_file("2noteB5_1.wav")248	audioSegment6_1 = AudioSegment.from_file("2noteB6_1.wav")249	audio145 = (audioSegment1_1 + 10) + (audioSegment4_1 + 10) + (audioSegment5_1 + 10) + (audioSegment6_1 + 10)250	audio145.export("bass1456.wav", format="wav")251#puts together drums, piano (all two measures)252def putTogether():253	drumsT = AudioSegment.from_file("drums24.wav")254	pianoT = AudioSegment.from_file("piano145.wav")...solver2.py
Source:solver2.py  
...5def find_best_schedule(tasks, schedule, start_time, total_time=0):6        if not tasks:7            return schedule, calc_benefit(schedule, start_time, start_time + 288), start_time + total_time8        task = tasks[0]9        return max(find_best_schedule(tasks[1:], schedule + [task], start_time, total_time + task.get_duration()), 10                   find_best_schedule(tasks[1:], schedule, start_time, total_time), 11                   key = lambda k: k[1])12def find_schedule(tasks, schedule=[]):13    if not tasks:14        return schedule, calc_benefit(schedule, 0, 1440)15    return max(find_schedule(tasks[1:], schedule + [tasks[0]]), 16               find_schedule(tasks[1:], schedule), 17               key = lambda k: k[1])18def calc_benefit(tasks, start_time, max_time=1440):19    benefit = 020    time = start_time21    for task in tasks: 22        if time + task.get_duration() < max_time:23            latest_start = task.get_deadline() - task.get_duration()24            mins_late = max(0, time - latest_start)25            benefit += task.get_late_benefit(mins_late)26            time = time + task.get_duration()27        else:28            return 029    return benefit30def zero_calibrate(tasks):31    for task in tasks:32        latest_start = task.get_deadline() - task.get_duration()33        if latest_start >= 0:34            break35        else: 36            task.perfect_benefit = task.get_late_benefit(-latest_start)37            task.deadline = task.get_duration()38    return tasks39def remove_weak(tasks):40    benefit = 041    for task in tasks:42        benefit += task.get_max_benefit()43    average_benefit = benefit/len(tasks)44    return [task for task in tasks if task.get_max_benefit() > average_benefit * .1]45<<<<<<< HEAD46def checkDeadline(currTime, task2):47    if(task2.get_deadline()-task2.get_duration() < currTime):48        return False49    return True50def getInitialGreedySoln(tasks):51    currTime = 0;52    schedule = []53    notinschedule = []54    while(len(tasks)>0):55        if(checkDeadline(currTime, tasks[0])):56            schedule.append(tasks[0])57            currTime+=tasks[0].get_duration()58        else:59            notinschedule.append(tasks[0])60        del tasks[0]61    return schedule, notinschedule62def calcProfit(schedule):63    sum = 064    for task in schedule: sum+=task.get_max_benefit()65    return sum66def calc_task_heuristic(task):67    return (task.get_deadline() - task.get_duration()) - 0.2 * task.get_max_benefit()68def solve(tasks):69    """70    Args:71        tasks: list[Task], list of igloos to polish72    Returns:73        output: list of igloos in order of polishing  74    """75    tasks = sorted(tasks, key=lambda x: calc_task_heuristic(x))76    tasks = zero_calibrate(tasks)77    tasks = remove_weak(tasks)78    schedule_optimal, benefit_opt = find_schedule(tasks)79    print("OPTIMAL_SCHEDULE")80    printSchedule(schedule_optimal)81    print(benefit_opt)82    schedule, notinschedule = getInitialGreedySoln(tasks)83    print("SCHEDULE_GREEDY")84    printSchedule(schedule)85    print(calcProfit(schedule))86    heap = []87    for task in notinschedule: hq.heappush(heap, task)88    #print("HEAP")89    #printSchedule(heap)90    maxIter = 100091    for i in range(0,maxIter):92        if(len(heap)==0):93            break;94        schedule_opt, popped = replace(schedule, hq.heappop(heap))95        if(calcProfit(schedule_opt) > calcProfit(schedule)):96            schedule = schedule_opt97            for t in popped:98                hq.heappush(heap, t)99        else:100            hq.heappop(heap)101    print("FINAL SCHEDULE")102    printSchedule(schedule)103    print(calcProfit(schedule))104    print(checkSchedule(schedule))105def printSchedule(schedule):106    for task in schedule: print(task)107def replace(schedule, task):108    currentTime = 0109    before = 0110    latest_Time = task.get_deadline()-task.get_duration()111    for t in schedule:112        if(currentTime + t.get_duration()>latest_Time):113            projectedTime = currentTime + task.get_duration()114            break;115        currentTime += t.get_duration()116        before += 1117    scheduleF = schedule[:before]118    scheduleF.append(task)119    poppedItems = []120    for i in range(before, len(schedule)):121        if(schedule[i].get_deadline() - schedule[i].get_duration() > projectedTime):122            scheduleF.append(schedule[i])123        else:124            poppedItems.append(schedule[i])125    return scheduleF, poppedItems126    #tasks = remove_weak(tasks)127    big_schedule = []128    big_benefit = 0129    leftovers = []130    start_time = 0131    for i in range(5):132        bucket = [tasks.pop(0) for i in range(17)]133        buffer = [tasks.pop(0) for i in range(3)]134        schedule, benefit, start_time = find_best_schedule(bucket, [], start_time)135        big_schedule += schedule136        big_benefit += benefit137        duration = sum([task.get_duration() for task in schedule])138        leftovers.append(Task.Task(100 + i, start_time, int(duration), float(benefit)))139        leftovers += buffer140        for task in schedule:141            print(task)142        print("dur:", duration)143        print("ben:", benefit)144        print()145    final_schedule, benefit = find_schedule(leftovers) 146    for task in final_schedule:147        print(task)148    print(benefit)149    print(sum([task.get_duration() for task in final_schedule]))150def checkSchedule(schedule):151    currTime = 0152    while(len(schedule)>1):153        currTime += schedule[0].get_duration()154        if(schedule[1].get_deadline()-schedule[1].get_duration()<currTime):155            return False156        del schedule[0]157    return True158def main():159    for input_path in os.listdir('inputs/'):160        output_path = 'outputs/' + input_path[:-3] + '.out'161        tasks = read_input_file('inputs/' + input_path)162        output = solve(tasks)163        #write_output_file(output_path, output)164if __name__ == "__main__":165    main()166# Here's an example of how to run your solver.167# if __name__ == '__main__':168#     for input_path in os.listdir('inputs/'):...utils_test.py
Source:utils_test.py  
2from unittest import TestCase3from utils.time import get_duration4class DurationParserTestCase(TestCase):5    def test_get_secs(self):6        self.assertEqual(get_duration("20s"), timedelta(seconds=20))7    def test_get_mins(self):8        self.assertEqual(get_duration("20m"), timedelta(minutes=20))9    def test_get_hours(self):10        self.assertEqual(get_duration("20h"), timedelta(hours=20))11    def test_get_days(self):12        self.assertEqual(get_duration("3d"), timedelta(days=3))13    def test_get_week(self):14        self.assertEqual(get_duration("28w"), timedelta(weeks=28))15    def test_get_mix(self):16        self.assertEqual(17            get_duration("2h 30m 10s"), timedelta(hours=2, minutes=30, seconds=10)18        )19        self.assertEqual(20            get_duration("2d 4h 45m 5s"),21            timedelta(22                days=2,23                hours=4,24                minutes=45,25                seconds=5,26            ),27        )28        self.assertEqual(29            get_duration("1w 2d 3h 4m 5s"),30            timedelta(31                days=9,32                hours=3,33                minutes=4,34                seconds=5,35            ),36        )37        self.assertEqual(get_duration("2w 4d"), timedelta(weeks=2, days=4))38    def test_wrong_order(self):39        self.assertEqual(get_duration("4m 3w"), timedelta(weeks=3, minutes=4))40    def test_get_default(self):41        self.assertEqual(get_duration("600"), timedelta(minutes=600))42    def test_get_bad_raw_duration(self):43        self.assertEqual(get_duration("php sucks!"), timedelta(0))44        self.assertEqual(get_duration("php 20s sucks!"), timedelta(seconds=20))45        self.assertEqual(46            get_duration("php 20s sucks 40m !"), timedelta(seconds=20, minutes=40)47        )48    def test_get_duration_lt_10(self):49        self.assertEqual(get_duration("9"), timedelta(minutes=9))50        self.assertEqual(get_duration("900"), timedelta(minutes=900))51        self.assertEqual(get_duration("1"), timedelta(minutes=1))52    def test_get_duration_with_dots(self):53        self.assertEqual(get_duration("666.666"), timedelta(minutes=0))54    def test_trailing_whitespace(self):55        self.assertEqual(get_duration("20s  "), timedelta(seconds=20))56        self.assertEqual(get_duration("     20s  "), timedelta(seconds=20))57        self.assertEqual(get_duration("20m  "), timedelta(minutes=20))58        self.assertEqual(get_duration("     20m  "), timedelta(minutes=20))59        self.assertEqual(get_duration("20h  "), timedelta(hours=20))60        self.assertEqual(get_duration("     20h  "), timedelta(hours=20))61        self.assertEqual(62            get_duration("2h   30m 10s"), timedelta(hours=2, minutes=30, seconds=10)63        )64        self.assertEqual(65            get_duration("     2h   30m 10s"),66            timedelta(hours=2, minutes=30, seconds=10),67        )68        self.assertEqual(get_duration("600  "), timedelta(minutes=600))...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
