Пример #1
0
 def test_rights_with_attributes(self):
     rights = r'''<rights type="arrangement">X.Y.</rights>'''
     xml = score(rights)
     printer = xml_to_printer_object(xml)
     expected = r'''\header {copyright = "Arrangement: X.Y." }'''
     result = printer.score_dict['header']
     assert trim(expected) == trim(result)
Пример #2
0
 def test_rights_without_attributes(self):
     rights = r'''<rights>Copyright by X.Y.</rights>'''
     xml = score(rights)
     printer = xml_to_printer_object(xml)
     expected = r'''\header {copyright = "Copyright by X.Y." }'''
     result = printer.score_dict['header']
     assert trim(expected) == trim(result)
Пример #3
0
 def get_segment_info(self, i):
     if 'segmentId' in i:
         if type(i['segmentId']) is not int:
             raise InputDomainError()
         search = self._dbw.execute("""
   SELECT * FROM Segment WHERE id = %d;
     """ % i['segmentId'])  # Q.6
         if len(search) == 0:
             raise NotFound("Segment %d does not exist" % i['segmentId'])
         else:
             match = search[0]
             return {
                 'segmentId': match[0],
                 'trackLength': match[1],
                 'condition': trim(match[2]),
                 'startStation': trim(match[3]),
                 'endStation': trim(match[4])
             }
     elif 'condition' in i:
         search = self._dbw.execute("""
   SELECT * FROM Segment WHERE condition = '%s';
     """ % i['condition'])  # Q.7
         results = []
         for s in search:
             sid = s[0]
             results.append(self.get_segment_info({'segmentId': sid}))
         return results
     else:
         raise MissingInput
 def test_rights_without_attributes(self):
     rights = r'''<rights>Copyright by X.Y.</rights>'''
     xml = score(rights)
     printer = xml_to_printer_object(xml)
     expected = r'''\header {copyright = "Copyright by X.Y." }'''
     result = printer.score_dict['header']
     assert trim(expected) == trim(result)
    def test_type_attribute(self):
        printer = xml_to_printer_object(self.xml)

        expected = r'''PartPOneVoiceOne = {a'1\shortfermata }'''
        result = printer.score_dict['voices']

        assert trim(expected) == trim(result)
Пример #6
0
 def get_segments(self, i):
     wid = None
     if 'workerId' in i:
         wid = i['workerId']
     data = []
     query = None
     if wid is None:
         query = """
   SELECT * FROM Segment;
   """
     else:
         query = ("""
   SELECT
     *
   FROM
     Segment INNER JOIN Works_On
     ON Works_On.segment_id = Segment.id
   WHERE
     Works_On.maintenance_worker_id = %d;
   """ % wid)  # Q.9
     for t in self._dbw.execute(query):
         data.append({
             'segmentId': t[0],
             'trackLength': t[1],
             'condition': trim(t[2]),
             'startStation': trim(t[3]),
             'endStation': trim(t[4])
         })
     return data
    def test_type_attribute(self):
        printer = xml_to_printer_object(self.xml)

        expected = r'''PartPOneVoiceOne = {a'1\shortfermata }'''
        result = printer.score_dict['voices']

        assert trim(expected) == trim(result)
Пример #8
0
def collective(fn):
    extra = trim("""
    This function is logically collective over MPI ranks, it is an
    error to call it on fewer than all the ranks in MPI communicator.
    """)
    fn.__doc__ = "%s\n\n%s" % (trim(fn.__doc__), extra) if fn.__doc__ else extra
    return fn
 def test_rights_with_attributes(self):
     rights = r'''<rights type="arrangement">X.Y.</rights>'''
     xml = score(rights)
     printer = xml_to_printer_object(xml)
     expected = r'''\header {copyright = "Arrangement: X.Y." }'''
     result = printer.score_dict['header']
     assert trim(expected) == trim(result)
 def font_size_test(self, fontsize, cmd):
     from string import Template
     xml = header + direction(fontsize=fontsize, fontstyle='italic') + footer
     printer = xml_to_printer_object(xml)
     expected = Template(r'''PartPOneVoiceOne = {| % 1 c'1
         -\markup { $cmd \italic {D.S. al Coda} } }''').substitute(cmd=cmd)
     result = printer.score_dict['voices']
     assert trim(expected) == trim(result)
Пример #11
0
def collective(fn):
    extra = trim("""
    This function is logically collective over MPI ranks, it is an
    error to call it on fewer than all the ranks in MPI communicator.
    """)
    fn.__doc__ = "%s\n\n%s" % (trim(fn.__doc__),
                               extra) if fn.__doc__ else extra
    return fn
 def font_size_test(self, fontsize, cmd):
     from string import Template
     xml = header + direction(fontsize=fontsize,
                              fontstyle='italic') + footer
     printer = xml_to_printer_object(xml)
     expected = Template(r'''PartPOneVoiceOne = {| % 1 c'1
         -\markup { $cmd \italic {D.S. al Coda} } }''').substitute(cmd=cmd)
     result = printer.score_dict['voices']
     assert trim(expected) == trim(result)
def test_work_number_and_work_title():

    xml = score(work_number="Op. 42",
                work_title="Work")
    printer = xml_to_printer_object(xml)
    expected = r'\header {opus = "Op. 42" title = "Work"}'
    result = printer.score_dict['header']

    assert trim(expected) == trim(result)
Пример #14
0
	def parseRecipeInstructions(self):
		try:
			instructions = self.soup.findAll(True, {"itemprop" : re.compile("recipeInstructions", re.IGNORECASE)})
			if (len(instructions) > 1):
				return [trim(instruction.get_text()) for instruction in instructions]
			else:
				return [trim(instruction) for instruction in instructions[0].stripped_strings]
		except:
			return []
def test_notehead_color():
    score = "".join([header, note_header, notehead("#FF0000"), note_footer, footer])
    printer = xml_to_printer_object(score)

    expected = r"""PartPOneVoiceOne = {
        \clef "treble" \key c \major \time 4/4
        \once \override NoteHead #'color = #(rgb-color 1.0 0.0 0.0) g'4}"""

    result = printer.score_dict["voices"]
    assert trim(expected) == trim(result)
Пример #16
0
 def test_default_font_size_A3(self):
     result = self.scaling_test(
         millimeters=7, tenths=40, page_format=self.A3)
     expected = r'''
         #(set-global-staff-size 20.0)
             \paper {
             paper-width = 29.7\cm
             paper-height = 42.0\cm
             indent = 1.32083333333\cm
             }'''
     assert trim(expected) == trim(result)
Пример #17
0
def test_multilined_headers():
    printer = xml_to_printer_object(score)

    expected = r'''
    \header {
     poet = \markup \column {
         \line { "German: Friedrich Heinrich Ranke (1798-1876) "}
         \line { "Latin: John Francis Wade (1711-1786)"} }
    composer = "John Francis Wade (1711-1786)"}'''

    result = printer.score_dict['header']
    assert trim(expected) == trim(result)
def test_multilined_headers():
    printer = xml_to_printer_object(score)

    expected = r"""
    \header {
     poet = \markup \column {
         \line { "German: Friedrich Heinrich Ranke (1798-1876) "}
         \line { "Latin: John Francis Wade (1711-1786)"} }
    composer = "John Francis Wade (1711-1786)"}"""

    result = printer.score_dict["header"]
    assert trim(expected) == trim(result)
Пример #19
0
def test_notehead_color():
    score = ''.join(
        [header, note_header,
         notehead('#FF0000'), note_footer, footer])
    printer = xml_to_printer_object(score)

    expected = r'''PartPOneVoiceOne = {
        \clef "treble" \key c \major \time 4/4
        \once \override NoteHead #'color = #(rgb-color 1.0 0.0 0.0) g'4}'''

    result = printer.score_dict['voices']
    assert trim(expected) == trim(result)
Пример #20
0
 def test_default_font_size_A3(self):
     result = self.scaling_test(millimeters=7,
                                tenths=40,
                                page_format=self.A3)
     expected = r'''
         #(set-global-staff-size 20.0)
             \paper {
             paper-width = 29.7\cm
             paper-height = 42.0\cm
             indent = 1.32083333333\cm
             }'''
     assert trim(expected) == trim(result)
Пример #21
0
 def test_keep_paper_size_proportions(self):
     # This seems obvious, but musicxml2ly used to behave in a very weird way
     # when changing the millimeters/tenth-ratio from e.g. 7/40 to 7000/40000
     result = self.scaling_test(
         millimeters=7000, tenths=40000, page_format=self.A3)
     expected = r'''
         #(set-global-staff-size 20.0)
             \paper {
             paper-width = 29.7\cm
             paper-height = 42.0\cm
             indent = 1.32083333333\cm
             }'''
     assert trim(expected) == trim(result)
Пример #22
0
 def test_keep_paper_size_proportions(self):
     # This seems obvious, but musicxml2ly used to behave in a very weird way
     # when changing the millimeters/tenth-ratio from e.g. 7/40 to 7000/40000
     result = self.scaling_test(millimeters=7000,
                                tenths=40000,
                                page_format=self.A3)
     expected = r'''
         #(set-global-staff-size 20.0)
             \paper {
             paper-width = 29.7\cm
             paper-height = 42.0\cm
             indent = 1.32083333333\cm
             }'''
     assert trim(expected) == trim(result)
Пример #23
0
 def get_trip_info(self, i):
     v = self.extract_fields(['tripId'], i)
     if type(v['tripId']) is not int:
         raise InputDomainError()
     search = self._dbw.execute("""
   SELECT * FROM Trip WHERE id = %d;
   """ % v['tripId'])
     if len(search) == 0:
         raise NotFound("Trip %d does not exist" % v['tripId'])
     else:
         match = search[0]
         return {
             'departureTime': trim(match[1]),
             'arrivalTime': trim(match[2])
         }
def test_stem_color_and_stem_direction():
    from musicxml2ly_conversion import conversion_settings

    conversion_settings.convert_stem_directions = True

    score = "".join([header, note_header, stem(color="#FF0000", direction="down"), note_footer, footer])
    printer = xml_to_printer_object(score)

    expected = r"""PartPOneVoiceOne = {
        \clef "treble" \key c \major \time 4/4
        \stemDown
        \once \override Stem #'color = #(rgb-color 1.0 0.0 0.0) g'4 }"""

    result = printer.score_dict["voices"]
    assert trim(expected) == trim(result)
Пример #25
0
def execute_amomax_w( s, inst ):
  addr  = s.rf[inst.rs1]
  value = s.mem.read( addr, 4 )
  new   = max( signed(value, 32), signed(s.rf[inst.rs2], 32) )
  s.mem.write( addr, 4, trim(new, 32))
  s.rf[inst.rd] = sext_32( value )
  s.pc += 4
Пример #26
0
 def __init__(self, plugins, xmpp, worker):
     self.name = self.__class__.__name__.lower()
     self._plugins = plugins
     self._xmpp = xmpp
     self._worker = worker
     # Compile handlers' regexs and create help
     self._handlers = []
     docs = [u"%s plugin help:" % self.name]
     for regex, handler in self.get_handlers():
         regex = u"\A%s\Z" % regex
         self._handlers.append((re.compile(regex), handler))
         if handler.__doc__:
             docs.append(trim(handler.__doc__))
     if hasattr(self, "about"):
         docs.append(trim(self.about))
     self._help_text = u"\n\n".join(docs)
Пример #27
0
 def __init__(self, plugins, xmpp, worker):
     self.name = self.__class__.__name__.lower()
     self._plugins = plugins
     self._xmpp = xmpp
     self._worker = worker
     # Compile handlers' regexs and create help
     self._handlers = []
     docs = [u"%s plugin help:" % self.name]
     for regex, handler in self.get_handlers():
         regex = u"\A%s\Z" % regex
         self._handlers.append((re.compile(regex), handler))
         if handler.__doc__:
             docs.append(trim(handler.__doc__))
     if hasattr(self, "about"):
         docs.append(trim(self.about))
     self._help_text = u"\n\n".join(docs)
Пример #28
0
def execute_amominu_w( s, inst ):
  addr  = s.rf[inst.rs1]
  value = s.mem.read( addr, 4 )
  new   = min( value, s.rf[inst.rs2] )
  s.mem.write( addr, 4, trim(new, 32))
  s.rf[inst.rd] = sext_32( value )
  s.pc += 4
Пример #29
0
def execute_amominu_w(s, inst):
    addr = s.rf[inst.rs1]
    value = s.mem.read(addr, 4)
    new = min(value, s.rf[inst.rs2])
    s.mem.write(addr, 4, trim(new, 32))
    s.rf[inst.rd] = sext_32(value)
    s.pc += 4
Пример #30
0
def execute_amomax_w(s, inst):
    addr = s.rf[inst.rs1]
    value = s.mem.read(addr, 4)
    new = max(signed(value, 32), signed(s.rf[inst.rs2], 32))
    s.mem.write(addr, 4, trim(new, 32))
    s.rf[inst.rd] = sext_32(value)
    s.pc += 4
def scrapingIndex(url):

    urls = {}

    if not url:
        print("Error: URL is empty.")
        return ""

    #get URL content
    req = requests.get(url)

    statusCode = req.status_code
    if statusCode == 200:
        print("Get URL", url, statusCode, "OK")
        html = BeautifulSoup(req.text, "html.parser")

        #<div class="caixa-enllacos">
        #   <div class="FW_BoxSimple">
        #       <h3>Title of section (nº of iterms)</h3>
        #   </div>
        #   <ul>
        #       <li>
        #           <a href=""></a>
        #       </li>
        #   </ul>
        #</div>
        contents = html.find_all('div', 'caixa-enllacos')
        for content in contents:

            title = content.find('h3')
            if title:
                anchor = content.find('a')
                if anchor:
                    title = trim(removeNumberOfItems(anchor.getText()))

            if title:
                lis = content.find_all('li')
                for li in lis:
                    anchor = li.find('a')
                    if anchor:
                        href = getUrlDomain(url) + anchor.get('href')
                        subtitle = trim(removeNumberOfItems(anchor.getText()))

                        #add item to dictionary of urls
                        urls[title + "\t" + subtitle] = href

    return urls
Пример #32
0
 def get_passenger_info(self, i):
     v = self.extract_fields(['passengerId'], i)
     if type(v['passengerId']) is not int:
         raise InputDomainError()
     search = self._dbw.execute("""
   SELECT * FROM Passenger WHERE id = %d;
   """ % v['passengerId'])
     if len(search) == 0:
         raise NotFound("Passenger %d does not exist" % v['passengerId'])
     else:
         match = search[0]
         return {
             'passengerId': v['passengerId'],
             'name': ("%s %s" % (trim(match[1]), trim(match[2]))),
             'phoneNumber': trim(match[3]),
             'email': trim(match[4])
         }
Пример #33
0
	def parseRecipeUrl(self):
		try:
			url = trim(self.soup.findAll("link", {"rel" : re.compile("canonical", re.IGNORECASE)})[0].get("href"))
			logging.info("found canonical url: %s", url)
			return url
		except:
			logging.info("couldn't find canonical url")
			return ""
Пример #34
0
def test_stem_color_and_stem_direction():
    from musicxml2ly_conversion import conversion_settings
    conversion_settings.convert_stem_directions = True

    score = ''.join([
        header, note_header,
        stem(color='#FF0000', direction='down'), note_footer, footer
    ])
    printer = xml_to_printer_object(score)

    expected = r'''PartPOneVoiceOne = {
        \clef "treble" \key c \major \time 4/4
        \stemDown
        \once \override Stem #'color = #(rgb-color 1.0 0.0 0.0) g'4 }'''

    result = printer.score_dict['voices']
    assert trim(expected) == trim(result)
Пример #35
0
	def parseRecipeDescription(self):
		try:
			description = super(HRecipeParser, self).parseRecipeDescription()
			if not description or description == "":
				return trim(self.soup.findAll(True, {"class" : re.compile("summary", re.IGNORECASE)})[0].get_text())
			else:
				return description
		except:
			return ""
Пример #36
0
    def predict_prob(self, X):
        sample_rate, signal = wav.read(X)
        signal = trim(signal)
        coefs = mfcc(signal, samplerate=sample_rate, winlen=0.025, winstep=0.01,
            ncoef=13, nfilter=26, nfft=2048, lof=0, hif=None, preem=0.97, lift=22)
        test = np.mean(coefs, axis=0)
        test = test.reshape(1, -1)

        return self.clf.predict_proba(test)[0]
Пример #37
0
 def get_songs_page_url(page_data, song):
     search_name_list = []
     search_href_list = []
     soup = BeautifulSoup(page_data, "html.parser")
     for link in soup.select('div.single-songs figcaption h3 a'):
         search_name_list.append(trim(link.get_text()))
         search_href_list.append(link.get('href'))
     best_match_index = BestMatchService.get_best_match(search_name_list, song)
     return search_href_list[best_match_index]
Пример #38
0
def regular_tweet():
    tweet = ''.join([
        choice(mochimochi.level1 + mochimochi.level2 + mochimochi.level3 +
               mochimochi.level4) for _ in range(1, randint(2, 11))
    ])
    tweet = utils.trim(tweet)
    api.update_status(tweet)
    print('regular tweet success!')
    print(tweet)
    print('-' * 20)
Пример #39
0
    def __init__(self, words, source=None):
        if words == None or len(words) == 0 or words == " ":
            raise AttributeError("Property [words] is required")

        self.source = source
        self._words = []
        words = trim(words)
        for w in words.split(" "):
            if w != None and w != "":
                self._words.append(w.lower())
Пример #40
0
	def parseRecipeDescription(self):
		try:
			description = super(SchemaOrgParser, self).parseRecipeDescription()
			if not description or description == "":
				return trim(self.soup.findAll(True, {"itemprop" : re.compile("description", re.IGNORECASE)})[0].get_text())
			else:
				return description
		except Exception, e:
			logging.info(e)
			return ""
Пример #41
0
def parse_containers(containers):
    # Parse an AirAsia price container and returns a list of flights
    for container in containers:
        rows = container.findAll(
            'tr', {'class': ['fare-light-row', 'fare-dark-row']})
        list_of_flights = []
        for row in rows:
            rowOfFare = row.findAll(
                'tr', {'class': ['fare-light-row', 'fare-dark-row']})
            trip = {}
            if len(rowOfFare) > 0:
                flights = row.findAll('td', {'class': 'avail-table-detail'})
                for depart, arrive in pairs(flights):
                    d, a = trim(depart.getText()), trim(arrive.getText())
                    flight = {'origin': f'{d}', 'destination': f'{a}'}
                    trip.setdefault('flights', []).append(flight)
                price = row.findAll(
                    'div', {'class': 'avail-fare-price'})[0].getText()
                trip['price'] = trim(price)
                list_of_flights.append(trip)
        yield list_of_flights
Пример #42
0
def getImage(CHARS, font_name, image_height, font_length, font_size,
             word_dict):
    text = ''
    n = random.random()
    if n < 0.1:
        for i in range(font_length):
            text += random.choice(
                "123456789012345678901234567890-./$,:()+-*=><")
    elif n < 0.5 and n >= 0.1:
        for i in range(font_length):
            text += random.choice(CHARS)
    else:
        while len(text) < font_length:
            word = random.choice(word_dict)
            _word = ""
            for c in word:
                if c in CHARS:
                    _word += c
            text = text + " " + _word.strip()
    text = text.strip()

    params = {}
    params['text'] = text
    params['fontname'] = font_name
    params['fontsize'] = font_size
    # params['fontmode'] = random.choice([0,1,2,4,8])
    params['fontmode'] = random.choice([0, 1, 2, 4])
    params['fonthint'] = random.choice([0, 1, 2, 3, 4, 5])

    r = http('http://192.168.2.113:8888/', params)
    _img = Image.open(io.BytesIO(r))
    img = Image.new("RGB", _img.size, (255, 255, 255))
    img.paste(_img, (0, 0), _img)
    img = utils.trim(img)
    w, h = img.size
    _h = random.randint(9, 64)
    _w = round(w * _h / h)
    img = img.resize((_w, _h), Image.ANTIALIAS)
    img = np.asarray(img)
    img = utils.clearBackgroundColor(img)
    img = 1 - utils.img2gray(img) / 255.
    img = utils.dropZeroEdges(img)

    filter = np.random.random(img.shape) - 0.9
    filter = np.maximum(filter, 0)
    img = img + filter * 5
    imin, imax = img.min(), img.max()
    img = (img - imin) / (imax - imin)

    img = utils.resize(img, image_height)
    return text, img
Пример #43
0
 def get_ticket_info(self, i):
     v = self.extract_fields(['tripId', 'seatNumber'], i)
     search = self._dbw.execute("""
   SELECT * FROM (Ticket
   INNER JOIN
   Passenger
   On
   Passenger.id = Ticket.passenger_id)
   INNER JOIN
   Class
   on
   Class.type = Ticket.class_type
   WHERE 
     Ticket.seat_number = %d
     AND
     Ticket.trip_id = %d
   """ % (v['seatNumber'], v['tripId']))  # Q.9
     if len(search) == 0:
         raise NotFound("Requested ticket does not exist")
     else:
         match = search[0]
         # passenger = self.get_passenger_info({'passengerId': pid})
         # ticketclass = self.get_class_info({'classType': ctype})
         return {
             'seatNumber': match[0],
             'passenger': {
                 'passengerId': match[4],
                 'name': ("%s %s" % (trim(match[5]), trim(match[6]))),
                 'phoneNumber': trim(match[7]),
                 'email': trim(match[8])
             },
             'class': {
                 'classType': trim(match[2]),
                 'refundable': match[11],
                 'priorityBoarding': match[12],
                 'freeFood': match[13]
             }
         }
Пример #44
0
 def get_station(self, i):
     if 'sname' in i:
         search = self._dbw.execute("""
   SELECT * FROM Station WHERE name = '%s';
     """ % i['sname'])
         if len(search) == 0:
             raise NotFound("Station %s does not exist" % i['sname'])
         else:
             match = search[0]
             return {
                 'sname': trim(match[0]),
                 'location': trim(match[1]),
                 'trainCapacity': match[2]
             }
     else:
         search = self._dbw.execute("""
   SELECT * FROM Station;
     """)
         results = []
         for s in search:
             sname = s[0]
             results.append(self.get_station({'sname': sname}))
         return results
Пример #45
0
    def start(self):
        plugins_str = u", ".join(
            [p.name for p in self._plugins if p.show_help])
        self._help_text = trim(u"""Help:

            Help [plugin]
            Show this message or plugin help.
            List of plugins: %s

            All commands could be typed with or without
            initial cap i.e. 'Help' = 'help'.
            Spaces between arguments are not significant
            i.e. it's ok to type '   S     url    '.
            """ % plugins_str)
Пример #46
0
def benchmark(clf):
    needsDense=[RandomForestClassifier, AdaBoostClassifier, Pipeline]
    print('_' * 80)
    print("Training: ")
    print(clf)
    t0 = time()
    if type(clf) in needsDense:
        clf.fit(X_train.todense(), y_train)
    else:
        clf.fit(X_train, y_train)
    train_time = time() - t0
    print("train time: %0.3fs" % train_time)

    t0 = time()
    if type(clf) in needsDense:
        pred = clf.predict(X_test.todense())
    else:
        pred = clf.predict(X_test)
    test_time = time() - t0
    print("test time:  %0.3fs" % test_time)

    score = metrics.f1_score(y_test, pred)
    print("f1-score:   %0.3f" % score)

    if hasattr(clf, 'coef_'):
        print("dimensionality: %d" % clf.coef_.shape[1])
        print("density: %f" % density(clf.coef_))

        if print_topX:
            print("top feature per class:")
            for i, category in enumerate(categories):
                # topX = np.min(clf.coef_.shape[1], print_topX)
                topX = np.argsort(clf.coef_[i])[-print_topX:][::-1]
                print(trim("%s: %s"
                           % (category, " | ".join(feature_names[topX]))))
        print()

    if print_report:
        print("classification report:")
        print(metrics.classification_report(y_test, pred))
                                            # target_names=categories))

    if print_cm:
        print("confusion matrix:")
        print(metrics.confusion_matrix(y_test, pred))

    print()
    clf_descr = str(clf).split('(')[0]
    return clf_descr, score, train_time, test_time, clf, pred
Пример #47
0
def esa( abar, ans, onto ) :
  #print ""
  #print "... entering esa ..."
  #print ""

  conExtList = utils.getSets( abar, onto )
  #print "getSets: " + str(conExtList)
  x = utils.getX( abar, ans, onto, conExtList)
  #print "getX: " + str(x)
  x = utils.trim( x, onto)

  #print ""
  #print "... exiting esa ..."
  #print ""
  return x
Пример #48
0
  def set_csr( self, csr_id, val ):
    # TODO: permission check
    if   csr_id == csr_map[ "fcsr" ]:
      # only the low 8 bits of fcsr should be non-zero
      self.state.fcsr = trim( val, 8 )
    elif csr_id == csr_map[ "mepc" ]:
      self.state.mepc = val
    elif csr_id == csr_map[ "mtohost" ]:
      if val & 0x1 and self.state.testbin:
        status = val >> 1
        if status:
          print "  [ FAILED ] %s (test #%s)" % (self.state.exe_name, status )
        else:
          print "  [ passed ] %s" % self.state.exe_name
        self.state.running = False

    else:
      print "WARNING: can't set csr %x" % csr_id
def expand_to_semantic_unit(string, startIndex, endIndex):
  symbols = "([{)]}"
  breakSymbols = ",;=&|\n"
  lookBackBreakSymbols = breakSymbols + "([{"
  lookForwardBreakSymbols = breakSymbols + ")]}"
  symbolsRe = re.compile(r'(['+re.escape(symbols)+re.escape(breakSymbols)+'])')

  counterparts = {
    "(":")",
    "{":"}",
    "[":"]",
    ")":"(",
    "}":"{",
    "]":"["
  }

  symbolStack = []

  searchIndex = startIndex - 1;
  while True:
    if(searchIndex < 0):
      newStartIndex = searchIndex + 1
      break
    char = string[searchIndex:searchIndex+1]
    result = symbolsRe.match(char)
    if result:
      symbol = result.group()

      if(symbol in lookBackBreakSymbols and len(symbolStack) == 0):
        newStartIndex = searchIndex + 1
        break

      if symbol in symbols:
        if len(symbolStack) > 0 and symbolStack[len(symbolStack) - 1] == counterparts[symbol]:
          symbolStack.pop()
        else:
          symbolStack.append(symbol)

    # print(char, symbolStack)
    searchIndex -= 1

  searchIndex = endIndex;
  while True:
    char = string[searchIndex:searchIndex+1]
    result = symbolsRe.match(char)
    if result:
      symbol = result.group()

      if len(symbolStack) == 0 and symbol in lookForwardBreakSymbols:
        newEndIndex = searchIndex;
        break

      if symbol in symbols:
        if len(symbolStack) > 0 and symbolStack[len(symbolStack) - 1] == counterparts[symbol]:
          symbolStack.pop()
        else:
          symbolStack.append(symbol)

    if searchIndex >= len(string) - 1:
      return None

    # print(char, symbolStack, searchIndex)
    searchIndex += 1

  s = string[newStartIndex:newEndIndex]
  trimResult = utils.trim(s)
  if trimResult:
    newStartIndex = newStartIndex + trimResult["start"];
    newEndIndex = newEndIndex - (len(s) - trimResult["end"]);

  try:
    if newStartIndex == startIndex and newEndIndex == endIndex:
      return None

    if newStartIndex > startIndex or newEndIndex < endIndex:
      return None

    return utils.create_return_obj(newStartIndex, newEndIndex, string, "semantic_unit")
  except NameError:
    return None
Пример #50
0
if __name__ == '__main__':
    # Here we examine the difference in the waveform produced by the
    # StandardOscillator vs. the waveform produced by the ResamplingOscillator.
    fs = 44100
    duration = 1
    size = fs * duration
    saw_type = wavetable.WaveType.SAWTOOTH

    x = np.linspace(0, size, size)

    ss = np.zeros(size, dtype='d')
    StandardOscillator(saw_type, 43.65, 3.0, 1.0).render(ss)

    rs = np.zeros(size, dtype='d')
    ResamplingOscillator(saw_type, 43.65, 3.0, 1.0).render(rs)

    plt.plot(x, trim(rs - ss, pow(2, 3 / 1200.0)))
    plt.show()

    # Now, to show that we can introduce the same artifacts in real time, we'll
    # show that the output of the ResamplingOscillator and the
    # RealTimeResamplingOscillator are actually the same.
    rt = np.zeros(size, dtype='d')
    RealTimeResamplingOscillator(saw_type, 43.65, 3.0, 1.0).render(rt)

    trim(rt, pow(2, 3 / 1200.0))

    assert np.allclose(rs, rt)
    plt.plot(x, rs - rt)
    plt.show()
Пример #51
0
def execute_amoand_w( s, inst ):
  addr  = s.rf[inst.rs1]
  value = s.mem.read( addr, 4 )
  s.mem.write( addr, 4, trim(value & s.rf[inst.rs2], 32))
  s.rf[inst.rd] = sext_32( value )
  s.pc += 4
Пример #52
0
            # for f in faces:
            #     x, y, w, h = [ v*SCALE_FACTOR for v in f ] # scale the bounding box back to original frame size
            #     cv2.rectangle(frame, (x,y), (x+w,y+h), (0,255,0))
            #     cv2.putText(frame, "Training Face", (x,y), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0,255,0))

            if len(faces):
                for f in faces:
                    x, y, w, h = [v for v in f]  # scale the bounding box back to original frame size
                    cropped_face = rotated_frame[y : y + h, x : x + w]  # img[y: y + h, x: x + w]
                    cropped_face = cv2.resize(cropped_face, FACE_DIM, interpolation=cv2.INTER_AREA)
                    cv2.rectangle(rotated_frame, (x, y), (x + w, y + h), (0, 255, 0))
                    cv2.putText(rotated_frame, "Training Face", (x, y), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 255, 0))

                # rotate the frame back and trim the black paddings
                processed_frame = ut.trim(ut.rotate_image(rotated_frame, rotation * (-1)), frame_scale)

                # reset the optmized rotation map
                current_rotation_map = get_rotation_map(rotation)

                faceFound = True

                break

        if faceFound:
            frame_skip_rate = 0
            # print "Face Found"
        else:
            frame_skip_rate = SKIP_FRAME
            # print "Face Not Found"
def test_breathing_sign():
    printer = xml_to_printer_object(score)
    expected = r'''PartOneVoiceNone = {\numericTimeSignature\time 4/4  c'8 [ d'8 ] \breathe }'''
    result = printer.score_dict['voices']

    assert trim(expected) == trim(result)
Пример #54
0
    def parse(self, crawley_dsl):
        
        action_section, get_section = utils.trim(crawley_dsl).split(self.QUERY_SEPARATOR)
        action, properties = action_section.lower().split(self.ACTION_SEPARATOR)

        return self.get_final_query(action, properties)
Пример #55
0
 def updater_info(self, user_jid, our_jid):
     return utils.trim(u"""Updater plugin info:
         current connections count: %d
         """ % self._conn_count)
Пример #56
0
def execute_sh( s, inst ):
  addr = trim_64( s.rf[inst.rs1] + inst.s_imm )
  s.mem.write( addr, 2, trim( s.rf[inst.rs2], 16 ) )
  s.pc += 4