Best Python code snippet using avocado_python
modreader.py
Source:modreader.py  
1"""ModReaderGui - data processing for classic module format2"""3import sys4import collections5import logging6import readerapp.shared as shared7def log(inp):8    "local definition to allow for picking up module name in message format"9    logging.info(inp)10# de noten kloppen, maar de octaven worden in MilkyTracker 2 hoger weergegeven11# om gelijk te trekken met andere weergaven daarom maar aangepast12noteval = dict(zip([13    int(x) for x in """\141712 1616 1524 1440 1356 1280 1208 1140 1076 1016  960  90615 856  808  762  720  678  640  604  570  538  508  480  45316 428  404  381  360  339  320  302  285  269  254  240  22617 214  202  190  180  170  160  151  143  135  127  120  11318 107  101   95   90   85   80   75   71   67   63   60   5619""".split()], [20    x.replace('-', ' ') for x in """\21 C-2  C#2  D-2  D#2  E-2  F-2  F#2  G-2  G#2  A-2  A#2  B-222 C-3  C#3  D-3  D#3  E-3  F-3  F#3  G-3  G#3  A-3  A#3  B-323 C-4  C#4  D-4  D#4  E-4  F-4  F#4  G-4  G#4  A-4  A#4  B-424 C-5  C#5  D-5  D#5  E-5  F-5  F#5  G-5  G#5  A-5  A#5  B-525 C-6  C#6  D-6  D#6  E-6  F-6  F#6  G-6  G#6  A-6  A#6  B-626""".split()]))27maxpattlen = 6428def getstring(data):29    """convert data from file into a text string30    """31    result = ''32    for bytechar in data:33        if bytechar == b'\x00':34            continue35        result += str(bytechar)36    return result37def get_sample(data):38    """return data read from file as sample info39    """40    name = ''41    for bytechar in data[:22]:42        if int(bytechar) > 0:43            name += chr(bytechar)44    stats = [int(x) for x in data[22:]]45    return name, stats46def get_playseq(data, length):47    """return data read from file as a list of pattern numbers48    also return highest pattern number49    """50    result = []51    highpatt = 052    for bytechar in data[:length]:53        test = int(bytechar)54        result.append(test)55        if test > highpatt:56            highpatt = test57    return result, highpatt58def get_notedata(data):59    """return data read from file as note event information60    """61    sampnum = data[0] & 0xF062    sampnum += data[2] >> 463    period = data[0] & 0x0F64    period *= 25665    period += data[1]66    note = noteval[period] if period else 067    effectnum = data[2] & 0x0F68    effectparm = data[3]69    return sampnum, note, effectnum, effectparm70class ModFile:71    """Main processing class72    """73    def __init__(self, filename):74        self.filename = filename75        self.samples = {}76        self.patterns = {}77        ## self.patterns = collections.defaultdict(lambda: collections.defaultdict(list))78        self.read()79    def read(self):80        """read the file via structures into an internal data collection81        instead of repositioning while reading, why not read the entire file first82        and then (re)position in memory?83        """84        with open(self.filename, 'rb') as _in:85            self.name = str(_in.read(20), encoding='ascii')86            for x in range(31):87                name, stats = get_sample(_in.read(30))88                if name or stats[:2] not in ([0, 0], [1, 0], [1, 0]):89                    self.samples[x] = name, stats90            songlength = ord(_in.read(1))91            self.restart = ord(_in.read(1))92            self.playseq, self.highpatt = get_playseq(_in.read(128), songlength)93            self.modtype = str(_in.read(4), encoding='ascii')94            if self.modtype in ('M.K.', '4CHN', 'FLT4'):95                channelcount = 496            elif self.modtype in ('6CHN',):97                channelcount = 698            elif self.modtype in ('8CHN', 'FLT8'):99                channelcount = 8100            for i in range(self.highpatt + 1):101                pattern = []102                for j in range(maxpattlen):103                    track = []104                    for k in range(channelcount):105                        ## self.patterns[x][y].append([x for x in _in.read(4)])106                        track.append([x for x in _in.read(4)])107                    pattern.append(track)108                self.patterns[i] = pattern109        data = collections.defaultdict(lambda: collections.defaultdict(list))110        lentab = []111        for pattnum, pattern in self.patterns.items():112            ## log('pattern: {}'.format(pattnum))113            sample_list = set()114            last_event = False115            for ix, track in enumerate(pattern):116                ## log('  event {}'.format(ix))117                for event in track:118                    ## log('   track {}'.format(track.index(event)))119                    samp, note, effect, _ = get_notedata(event)120                    ## if samp or note or effect:121                        ## log('    notedata: {} {} {}'.format(samp, note, effect))122                    if note:123                        data[samp][pattnum].append((ix, note))124                        sample_list.add(samp)125                    if effect == 13:126                        leng = ix + 1127                        for samp in sample_list:128                            data[samp][pattnum].insert(0, leng)129                        last_event = True130                        break131                if last_event:132                    break133            if not last_event:134                leng = maxpattlen135                for samp in sample_list:136                    data[samp][pattnum].insert(0, leng)137            lentab.append((pattnum, leng))138        newlentab = {}139        self._pattern_data = collections.defaultdict(lambda: collections.defaultdict(list))140        ophogen = 0141        samples = [x for x in data.keys() if x]142        for pattnum, pattlen in lentab:143            # bepaal of pattern gesplitst moet worden144            split = pattlen > shared.per_line145            # zo ja, bepaal lengte v/h tweede deel146            if split:147                newlen = pattlen - shared.per_line148            for samp in samples:149                origpatt = data[samp][pattnum][1:]150                if split:151                    newlentab[pattnum] = [shared.per_line, newlen]152                    splitix = 0153                    for ix, event in enumerate(origpatt):154                        if event[0] >= shared.per_line:155                            splitix = ix156                            break157                    if not splitix:158                        if origpatt:159                            if origpatt[0][0] >= shared.per_line:  # wrschl is deze test niet nodig160                                origpatt = [(x - shared.per_line, y) for x, y in origpatt]161                            origpatt.insert(0, shared.per_line)162                            self._pattern_data[samp][pattnum + ophogen] = origpatt163                    else:164                        oldpatt, newpatt = origpatt[:splitix], origpatt[splitix:]165                        if oldpatt:166                            oldpatt.insert(0, shared.per_line)167                            self._pattern_data[samp][pattnum + ophogen] = oldpatt168                        if newpatt:169                            newpatt = [(x - shared.per_line, y) for x, y in origpatt[splitix:]]170                            newpatt.insert(0, newlen)171                            self._pattern_data[samp][pattnum + ophogen + 1] = newpatt172                else:173                    newlentab[pattnum] = [pattlen]174                    if data[samp][pattnum]:175                        self._pattern_data[samp][pattnum + ophogen] = data[samp][pattnum]176            if split:177                ophogen += 1178        self.lengths = []179        for x in self.playseq:180            self.lengths.extend(newlentab[x])181    def remove_duplicate_patterns(self, sampnum):182        """show patterns only once for incontiguous timelines183        """184        renumber = collections.defaultdict(dict)185        pattern_list = []186        for pattnum, patt in self._pattern_data[sampnum].items():187            try:188                new_pattnum = pattern_list.index(patt) + 1189            except ValueError:190                pattern_list.append(patt)191                new_pattnum = len(pattern_list)192            renumber[pattnum] = new_pattnum193        self.pattern_data[sampnum] = pattern_list194        for seq in self.playseq:195            if seq in renumber:196                self.playseqs[sampnum].append(renumber[seq])197            else:198                self.playseqs[sampnum].append(-1)199    def remove_duplicate_drum_patterns(self, samplist):200        """show patterns only once for incontiguous timelines201        """202        single_instrument_samples = [x for x, y in samplist if len(y) == 1]203        ## lookup = {y: x - 1 for x, y in samplist if len(y) == 1}204        samp2lett = {x: y for x, y in samplist}205        drumpatterns = collections.defaultdict(lambda: collections.defaultdict(list))206        pattlengths = {}207        for sampnum, sampdata in self._pattern_data.items():208            if sampnum not in single_instrument_samples:209                continue210            samplett = samp2lett[sampnum]211            for pattnum, patt in sampdata.items():212                drumpatterns[pattnum][samplett] = patt[1:]213                pattlengths[pattnum] = patt[0]214        for sampnum, sampdata in self._pattern_data.items():215            if sampnum in single_instrument_samples:216                continue217            try:218                instletters = samp2lett[sampnum]219            except KeyError:220                continue221            for pattnum, patt in sampdata.items():222                try:223                    if patt[0] > pattlengths[pattnum]:224                        pattlengths[pattnum] = patt[0]225                except KeyError:226                    pattlengths[pattnum] = patt[0]227                for letter in instletters:228                    drumpatterns[pattnum][letter].extend(patt[1:])229                    drumpatterns[pattnum][letter].sort()230        for pattnum in drumpatterns:231            drumpatterns[pattnum]['len'] = pattlengths[pattnum]232        renumber = collections.defaultdict(dict)233        pattern_list = []234        for pattnum, patt in drumpatterns.items():235            try:236                new_pattnum = pattern_list.index(patt) + 1237            except ValueError:238                pattern_list.append(patt)239                new_pattnum = len(pattern_list)240            renumber[pattnum] = new_pattnum241        self.pattern_data['drums'] = pattern_list242        for seq in self.playseq:243            if seq in renumber:244                self.playseqs['drums'].append(renumber[seq])245            else:246                self.playseqs['drums'].append(-1)247    def print_general_data(self, sample_list=None, full=False, _out=sys.stdout):248        """create the "overview" file (sample and pattern lists)249        sample_list is a list of pattern numbers associated with the drum samples250        to print on this event, e.g. ((1, 'b'), (2, 's'), (4, 'bs'), (7, 'bsh'))251        so this can be used to determine if it's a drum instrument252        printseq indicates the sequence to print these top to bottom e.g. 'hsb'253        stream is a file-like object to write the output to254        """255        if sample_list is None:256            sample_list = []257        drumsamples = [x for x, y in sample_list]258        data = shared.build_header("module", self.filename, self.name.rstrip(chr(0)))259        instruments = []260        self.pattern_data = {}261        self.playseqs = collections.defaultdict(list)262        for sampseq, sample_data in self.samples.items():263            sample_name = sample_data[0]264            sample_string = ''265            sample_number = sampseq + 1266            if sample_list:267                for sampnum, sampstr in sample_list:268                    if sampnum == sample_number:269                        sample_string = sampstr.join((' (', ')'))270            instruments.append((sample_number, sample_name + sample_string))271            if sample_number not in drumsamples:272                self.remove_duplicate_patterns(sample_number)273        self.remove_duplicate_drum_patterns(sample_list)274        data.extend(shared.build_inst_list(instruments))275        if not full:276            data.extend(shared.build_patt_header())277            for sample_number, sample_name in instruments:278                if sample_number not in drumsamples:279                    data.extend(shared.build_patt_list(sample_number, sample_name,280                                                       self.playseqs[sample_number]))281            if 'drums' in self.playseqs:282                data.extend(shared.build_patt_list('', 'Drums',283                                                   self.playseqs['drums']))284        for text in data:285            print(text.rstrip(), file=_out)286    def print_drums(self, printseq, _out=sys.stdout):287        """collect the drum sample events and print them together288        """289        for pattnum, pattern in enumerate(self.pattern_data['drums']):290            pattlen = pattern['len']291            empty_patt = pattlen * shared.empty_drums292            print(shared.patt_start.format(pattnum + 1), file=_out)293            for inst in printseq:294                for key, events in pattern.items():295                    if key != inst:296                        continue297                    events = [x[0] for x in events]298                    printable = ''299                    for i in range(pattlen):300                        new = inst if i in events else shared.empty_drums301                        printable += new302                    if printable != empty_patt:303                        print(''.join((shared.line_start, printable)), file=_out)304                    ## print('', file=_out)305            print('', file=_out)306    def print_instrument(self, sample, _out=sys.stdout):307        """print the events for an instrument as a piano roll308        sample is the number of the sample to print data for309        stream is a file-like object to write the output to310        """311        for pattnum, pattern in enumerate(self.pattern_data[sample]):312            pattlen = pattern.pop(0)313            print(shared.patt_start.format(pattnum + 1), file=_out)  # display starting with 1314            notes = collections.defaultdict(list)315            for timing, note in pattern:316                notes[note].append(timing)317            for notestr in reversed(sorted([x for x in notes],318                                           key=shared.getnotenum)):319                print(shared.line_start, end='', file=_out)320                events = notes[notestr]321                printable = []322                for tick in range(pattlen):323                    next_note = notestr if tick in events else shared.empty_note324                    printable.append(next_note)325                print(' '.join(printable), file=_out)326            print('', file=_out)327    def prepare_print_drums(self, printseq):328        """build complete timeline for drum instrument events329        sample_list is a list of pattern numbers associated with the instruments330        to print on this event, e.g. ((1, 'b'), (2, 's'), (4, 'bs'), (7, 'bsh'))331        printseq indicates the sequence to print these top to bottom e.g. 'hsb'332        stream is a file-like object to write the output to333        """334        self.all_drum_tracks = collections.defaultdict(list)335        ## interval, clear_empty = opts336        ## interval = 2 * opts[0]337        ## empty = interval * '.'338        for pattseq, pattnum in enumerate(self.playseqs['drums']):339            if pattnum == -1:340                pattlen = self.lengths[pattseq]341                for inst in printseq:342                    self.all_drum_tracks[inst].extend([shared.empty_drums] * pattlen)343                continue344            pattern = self.pattern_data['drums'][pattnum - 1]345            for inst in printseq:346                events = [x[0] for x in pattern[inst]]347                for i in range(pattern['len']):348                    to_append = inst if i in events else shared.empty_drums349                    self.all_drum_tracks[inst].append(to_append)350    def print_drums_full(self, printseq, opts, _out=sys.stdout):351        """output the drums timeline to a separate file/stream352        printseq indicates the top-to-bottom sequence of instruments353        opts indicates how many events per line and whether to print "empty" lines354        """355        total_length = sum(self.lengths)356        interval, clear_empty = opts357        interval *= 2358        ## empty = interval * shared.empty_drums359        for eventindex in range(0, total_length, interval):360            ## if eventindex + interval > total_length:361                ## empty = (total_length - eventindex) * shared.empty_drums362            not_printed = True363            for inst in printseq:364                tracks = self.all_drum_tracks[inst]365                line = ''.join(tracks[eventindex:eventindex + interval])366                test_empty_line = all([x == shared.empty_drums for x in367                                       tracks[eventindex:eventindex + interval]])368                ## if clear_empty and (line == empty or not line):369                if clear_empty and (test_empty_line or not line):370                    pass371                else:372                    print(line, file=_out)373                    not_printed = False374            if not_printed:375                print(shared.empty_drums, file=_out)376            print('', file=_out)377    def prepare_print_instruments(self, sample_list):378        """build complete timeline for all regular instrument events379        """380        self.all_note_tracks = collections.defaultdict(381            lambda: collections.defaultdict(list))382        self.all_notes = collections.defaultdict(set)383        ## interval, clear_empty = opts384        for sample, _ in sample_list:385            pattdict = collections.defaultdict(386                lambda: collections.defaultdict(list))387            pattdata = self.pattern_data[sample]388            for pattnum, pattern in enumerate(pattdata):389                for item in pattern:390                    try:391                        timing, note = item392                    except TypeError:393                        continue394                    pattdict[pattnum + 1][note].append(timing)395                    self.all_notes[sample].add(note)396            all_notes = [x for x in reversed(sorted(self.all_notes[sample],397                                                    key=shared.getnotenum))]398            playseq = self.playseqs[sample]399            for pattseq, pattnum in enumerate(playseq):400                pattlen = self.lengths[pattseq]401                if pattnum == -1:402                    ## for note in self.all_notes[sample]:403                    for note in all_notes:404                        self.all_note_tracks[sample][note].extend(405                            [shared.empty_note] * pattlen)406                    continue407                pattern = pattdict[pattnum]408                for note in all_notes:409                    events = pattern[note]410                    for i in range(pattlen):411                        to_append = note if i in events else shared.empty_note412                        self.all_note_tracks[sample][note].append(to_append)413    def print_instrument_full(self, sample, opts, _out=sys.stdout):414        """output an instrument timeline to a separate file/stream415        sample indicates the instrument to process416        opts indicates how many events per line and whether to print "empty" lines417        """418        total_length = sum(self.lengths)419        interval, clear_empty = opts420        if interval == -1:421            interval = total_length422        ## empty = ' '.join(interval * [shared.empty_note])423        for eventindex in range(0, total_length, interval):424            ## if eventindex + interval > total_length:425                ## empty = ' '.join((total_length - eventindex) * [shared.empty_note])426            not_printed = True427            for note in reversed(sorted(self.all_notes[sample],428                                        key=shared.getnotenum)):429                tracks = self.all_note_tracks[sample][note]430                line = ' '.join(tracks[eventindex:eventindex + interval])431                test_empty_line = all([x == shared.empty_note for x in432                                       tracks[eventindex:eventindex + interval]])433                if clear_empty and (test_empty_line or not line):434                    pass435                else:436                    print(line, file=_out)437                    not_printed = False438            if not_printed:439                print(shared.empty_note, file=_out)440            print('', file=_out)441    def print_all_instruments_full(self, instlist, druminst, drumseq, opts,442                                   stream=sys.stdout):443        """output all instrument timelines to the "general" file444        instlist indicates the top-to-bottom sequence of instruments445        drumseq indicates the top-to-bottom sequence of drum instruments446        opts indicates how many events per line and whether to print "empty" lines447        """448        total_length = sum(self.lengths)449        interval, clear_empty = opts450        ## inst_dict = {y:x for x, y in inst_list}451        ## instlist = [(inst_dict[y], y) for x, y in instlist_old]452        for eventindex in range(0, total_length, interval):453            sep = ' '454            ## if eventindex + interval > total_length:455                ## empty = sep.join((total_length - eventindex) * [shared.empty_note])456            for sample, instname in instlist:457                print('{}:'.format(instname), file=stream)458                not_printed = True459                for note in reversed(sorted(self.all_notes[sample],460                                            key=shared.getnotenum)):461                    tracks = self.all_note_tracks[sample][note]462                    line = sep.join(tracks[eventindex:eventindex + interval])463                    test_empty_line = all([x == shared.empty_note for x in464                                           tracks[eventindex:eventindex + interval]])465                    if clear_empty and (test_empty_line or not line):466                        pass467                    else:468                        print('  ', line, file=stream)469                        not_printed = False470                if not_printed:471                    print('  ', shared.empty_note, file=stream)472                print('', file=stream)473            sep = ''474            ## if eventindex + interval > total_length:475                ## empty = (total_length - eventindex) * shared.empty_drums476            print('drums:', file=stream)477            not_printed = True478            for _, instlett in sorted(druminst,479                                      key=lambda x: drumseq.index(x[1])):480                tracks = self.all_drum_tracks[instlett]481                line = sep.join(tracks[eventindex:eventindex + interval])482                test_empty_line = all([x == shared.empty_drums for x in483                                       tracks[eventindex:eventindex + interval]])484                if clear_empty and (test_empty_line or not line):485                    pass486                else:487                    print('  ', line, file=stream)488                    not_printed = False489            if not_printed:490                print('  ', shared.empty_drums, file=stream)491            print('', file=stream)...test_fcfs.py
Source:test_fcfs.py  
1import fcfs2import io3import test.helpers as h4class TestFCFS(h.TestHelper):5    def test_empty_line(self):6        PROCESSORS_NUM = 17        input = io.StringIO("\n")8        strategy = fcfs.FCFS(PROCESSORS_NUM, input)9        self.check_next_line(strategy, [-1])10    def test_one_processor_2procs(self):11        PROCESSORS_NUM = 112        input = io.StringIO("0 1 0 2\n" +13                            "1 2 0 1\n")14        strategy = fcfs.FCFS(PROCESSORS_NUM, input)15        self.check_next_line(strategy, [1])16        self.check_next_line(strategy, [1])17        self.check_next_line(strategy, [2])18    def test_two_processors_3procs(self):19        PROCESSORS_NUM = 220        input = io.StringIO("0 1 0 1 2 0 3\n" +21                            "1 3 0 2\n")22        strategy = fcfs.FCFS(PROCESSORS_NUM, input)23        self.check_next_line(strategy, [1, 2])24        self.check_next_line(strategy, [2, 3])25        self.check_next_line(strategy, [2, 3])26    def test_three_processors_1proc(self):27        PROCESSORS_NUM = 328        input = io.StringIO("0 1 0 1\n")29        strategy = fcfs.FCFS(PROCESSORS_NUM, input)30        self.check_next_line(strategy, [1, -1, -1])31class TestSimplePriorityFcfs(h.TestHelper):32    def test_empty_line(self):33        PROCESSORS_NUM = 134        input = io.StringIO("\n")35        strategy = fcfs.SimplePriorityFcfs(PROCESSORS_NUM, input)36        self.check_next_line(strategy, [-1])37    def test_one_processor_2procs(self):38        PROCESSORS_NUM = 139        input = io.StringIO("0 1 1 2\n" +40                            "1 2 0 1\n")41        strategy = fcfs.SimplePriorityFcfs(PROCESSORS_NUM, input)42        self.check_next_line(strategy, [1])43        self.check_next_line(strategy, [1])44        self.check_next_line(strategy, [2])45    def test_two_processors_3procs(self):46        PROCESSORS_NUM = 247        input = io.StringIO("0 1 2 1 2 1 3\n" +48                            "1 3 0 2\n")49        strategy = fcfs.SimplePriorityFcfs(PROCESSORS_NUM, input)50        self.check_next_line(strategy, [2, 1])51        self.check_next_line(strategy, [2, 3])52        self.check_next_line(strategy, [2, 3])53    def test_three_processors_1proc(self):54        PROCESSORS_NUM = 355        input = io.StringIO("0 1 0 1\n")56        strategy = fcfs.SimplePriorityFcfs(PROCESSORS_NUM, input)57        self.check_next_line(strategy, [1, -1, -1])58class TestPriorityFcfsWithDispossess(h.TestHelper):59    def test_empty_line(self):60        PROCESSORS_NUM = 161        input = io.StringIO("\n")62        strategy = fcfs.PriorityFcfsWithDispossess(PROCESSORS_NUM, input)63        self.check_next_line(strategy, [-1])64    def test_one_processor_2procs(self):65        PROCESSORS_NUM = 166        input = io.StringIO("0 1 1 2\n" +67                            "1 2 0 1\n")68        strategy = fcfs.PriorityFcfsWithDispossess(PROCESSORS_NUM, input)69        self.check_next_line(strategy, [1])70        self.check_next_line(strategy, [2])71        self.check_next_line(strategy, [1])72    def test_two_processors_3procs(self):73        PROCESSORS_NUM = 2...is_valid_msg.py
Source:is_valid_msg.py  
...37        """38        mock_log.return_value = True39        self.assertTrue(rmq_2_isse.is_valid_msg("One", mock_log))40    @mock.patch("rmq_2_isse.gen_class.Logger")41    def test_empty_line(self, mock_log):42        """Function:  test_empty_line43        Description:  Test is_valid_msg function for empty line.44        Arguments:45        """46        mock_log.return_value = True47        self.assertFalse(rmq_2_isse.is_valid_msg("", mock_log))48    @mock.patch("rmq_2_isse.gen_class.Logger")49    def test_multiple_entries(self, mock_log):50        """Function:  test_multiple_entries51        Description:  Test is_valid_msg function for multiple entries in line.52        Arguments:53        """54        mock_log.return_value = True55        self.assertFalse(rmq_2_isse.is_valid_msg("One Two", mock_log))...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!!
